19 minute read

Compare MISRA C with SPARK for Safe and Secure Programming

By Yannick Moy, AdaCore

As part of the Linux Security Summit Europe last October, I participated in a panel around the question, “Would Abandoning the C Language Really Help?” C, which is the main language used in the Linux kernel, is notorious for having an endless source of vulnerabilities. Just look at the long list of open bugs automatically reported by the fuzzing robot syzbot that are still waiting for a fix.1

The panel discussion revolved around alternative, safer languages that are suitable for kernel development like Ada and Rust, as well as the need for formal verification to go beyond the guarantees that a compiler can provide. Indeed, many memory and safety vulnerabilities currently reported on the Linux kernel would stop the program altogether in Ada or Rust, which is only slightly better. Looking at kernel patches reveals that many issues could be detected by specifying simple properties on the code, like what calls are legal in which mode, the types of data invariants that should be preserved, and how to verify them statically using appropriate tools. it has established itself as a must-have in a number of industries to protect against fallibilities of the C language. MISRA C appeared in 1998 as a coding standard for C, initially for the automotive industry, and has been revised twice. The current version is MISRA C:2012. It focuses on avoiding error-prone features of the C programming language rather than enforcing a particular programming style. A study of coding standards for C, written by Les Hatton, found that, compared to ten typical coding standards for C, MISRA C was the only one to focus exclusively on error avoidance rather than style enforcement, and by a very large margin.2

The popularity of the C programming language, as well as its many traps and pitfalls, have led to the huge success of MISRA C in domains where C is used for high-integrity software. This success has driven tool vendors to propose many competing implementations of MISRA C checkers.3 Tools compete, in particular, on the coverage of MISRA C guidelines that they help enforce, as it is impossible to enforce all of the 16 directives and 143 rules (collectively referred to as guidelines) of MISRA C.

In particular, 27 rules out of 143 are not decidable, so no tool can always detect all violations of these rules without, at the same time, reporting “false alarms” on code that does not constitute a violation. An example of an undecidable rule is rule 1.3: “There shall be no occurrence of undefined or critical unspecified behavior.”

Appendix H of MISRA C:2012 lists hundreds of cases of undefined and critical unspecified behavior in the C programming language standard, a majority of which is not individually decidable. For the most part, MISRA C checkers ignore undecidable rules such as rule 1.3, although violations of these rules are known to have a dramatic impact on software quality.

However, for other programming languages, static-analysis technology is available that can tackle this challenge without inundating users with false alarms. One example is the SPARK toolset developed by AdaCore, Altran, and Inria, which is based on four principles:

› The base language Ada provides a solid foundation for static analysis through a well-defined language standard, strong typing, and rich specification features. › The SPARK subset of Ada restricts the base language in essential ways to support static analysis, by controlling sources of ambiguity such as side-effects in functions and aliasing of names.

SAFETY & SECURITY STANDARDS

Effort & Skills

Toward implementation guidance

Platinum: Full functional requirements

Gold: Key integrity properties

Silver: Runtime errors & CWE

Only for a subset of the code subject to speci c key integrity properties (functional safety, security)

The default target for critical software (subject to costs and limitations)

For the largest part of the code as possible

An intermediate level during adoption

Bronze: Flow constraints

Stone: Safer, analysable Stone: Safer, analyzable language subset language subset

FIGURE 1 The five levels of SPARK adoption.

› The static analysis tools work mostly at the granularity of an individual function, making the analysis more precise and minimizing the possibility of false alarms. › The static analysis tools are interactive, allowing users to guide the analysis if necessary or desired, and providing counter-examples when user-supplied contracts cannot be proved.

As shown in Figure 1, SPARK can be incrementally adopted in a C codebase, progressively gaining assurance through the five levels of SPARK adoption and by supporting “hybrid verification” that combines formal analysis (SPARK) with traditional testingbased methods (C).4

SPARK Stone Level – Basic Guarantees

The first level of SPARK adoption is called the Stone Level. It corresponds to code that conforms to the SPARK subset of Ada. Just adopting this level guarantees many consistency properties that cannot be enforced for C. These include:

› The use of a proper package system as opposed to C’s use of textual-based inclusion of files with no consistency requirements across translation units. › Strict and readable syntax that emphasizes clarity and minimizes “gotchas” as opposed to C’s very permissive syntax which makes it easy to write programs whose effect is not what was intended. › Adherence to the strong typing rules of Ada and SPARK, as opposed to C’s

“poor type safety [that] permits a wide range of implicit type conversions to take place [which] can compromise safety as their implementation-defined aspects can cause developer confusion.” (MISRA C:2012, Annex C).

MISRA C attempts to tame these possible inconsistencies of the C language with a variety of guidelines. It defines, in particular, stronger typing rules (“The essential type model”) and restricts the use of function parameters/results and control structures. While these avoid common sources of developer confusion, they are intentionally not bulletproof, as they would otherwise make most C programs illegal.

These basic guarantees are easily achieved in SPARK with a simple compiler-like analysis by a tool called GNATprove, thanks to the stronger rules that define the SPARK subset of Ada.

SPARK Silver Level – Strong Safety & Security Guarantees

MISRA C guidelines also aim at preventing more subtle errors, reads of uninitialized data, conflicting side-effects in expressions, and undefined behavior such as division

by zeros or buffer overflows (which can have safety as well as security consequences). All of this falls into the category of undecidable rules, for which few MISRA C checkers provide complete detection.

These are completely prevented at the Silver level of SPARK adoption, which corresponds to analyzing the program with both flow analysis (reaching the second level of SPARK adoption called Bronze), and proof of the absence of runtime errors (reaching the third level, i.e. Silver). To reach this level, a developer will generally need to define types with the specific constraints that they are designed to support and supply contracts on functions exported between files – using so-called preconditions for specifying the obligations on the caller, and postconditions for specifying the obligations on the callee.

The process for reaching the Silver level involves interaction with the IDE. The developer runs the GNATprove tool (possibly on a subset of the program), investigates the GNATprove diagnostics, updates the program accordingly, and repeats. Such interactions are facilitated by the detailed information provided by GNATprove at every step to guide developers.

Figure 2 shows an example of a message displayed by GNATprove.

After locating the addition operation, which may cause an overflow, GNATprove gives an example of a value triggering the problem – here the largest Integer value (denoted Integer’Last in SPARK). The “reason for check” explains clearly that the result of the addition should fit in a machine integer, which is not the case if X is the largest integer value before the addition. Then, GNATprove suggests that adding a suitable precondition to the function Incr might solve the problem by specifying here that X cannot be that largest value.

SPARK Beyond the Silver Level

There are further benefits of using SPARK that go well beyond what MISRA C checkers can provide. At the Gold and Platinum levels, a developer specifies properties of the program through

FIGURE 2 A message displayed by GNATprove.

SPARK contracts and can then use GNATprove to guarantee that these properties will be met. A developer can also enable GNATprove warnings to detect dead code (also an objective pursued by MISRA C) and inconsistencies in the code, using the powerful proof technology that forms the basis of GNATprove analysis.

Conclusion

Essentially, all objectives pursued by MISRA C are best achieved in SPARK, with a combination of a stronger base language (Ada) and a powerful analysis tool (GNATprove). Developers who are planning to use MISRA C rules can achieve increased assurance by adopting SPARK for part of their applications.

The rules in MISRA C represent an impressive collective effort to improve the reliability of C code in critical applications, with a focus on avoiding error-prone features rather than enforcing a particular programming style. At a fundamental level, however, MISRA C is still built on a base language that was not really designed with the goal of supporting large high-assurance applications. It’s hard to retrofit reliability, safety, and security into a language that did not have these as goals from the start.

As C will remain the base language for large programs like the Linux kernel, we can foresee the coexistence of two trends to protect better against fallibilities in C programs where MISRA C can play a role, and to replace C with safer languages like Rust and SPARK Ada for part of the code. Major actors in the automotive industry have already started on this latter path, like NVIDIA5 and JTEKT.6

A detailed comparison of SPARK and MISRA-C, as well as various courses to learn Ada and SPARK, can be found at AdaCore’s learn.adacore.com site.

Guidance for adoption of SPARK can be found at https://www.adacore.com/books/ implementation-guidance-spark/.

The GNATprove tool is freely available as part of the GNAT Community Edition at https://www.adacore.com/download.

Yannick Moy is SPARK Product Manager at AdaCore and co-director of the ProofInUse joint laboratory with Inria. He leads the development of SPARK and previously worked on source code analyzers for PolySpace (now The MathWorks) and at Université Paris-Sud.

References:

1. Syzbot. https://syzkaller.appspot.com/upstream. 2. Hatton, L. (2004). Safer Language Subsets: An Overview and a Case History, MISRA C.

Information and Software Technology, 46(7), 465–472. https://doi.org/10.1016/j. infsof.2003.09.016. 3. MISRA C. Wikipedia. https://en.wikipedia.org/wiki/MISRA_C 4. Climbing the Software Assurance Ladder – AdaCore. https://www.adacore.com/papers/climbingthe-software-assurance-ladder. 5. AdaCore Enhances Security-Critical Firmware with NVIDIA. AdaCore. https://www.adacore.com/ press/adacore-enhances-security-critical-firmware-with-nvidia. 6. Electric Power Steering System Supplier JTEKT Selects SPARK Pro for Safety-Critical Automotive

Software. AdaCore. https://www.adacore.com/press/jtekt-spark-pro-automotive.

The Era of 5G, Industry 5.0, and AI Comes with Challenges

Interview with Stefan Skarin, CEO of IAR Systems

How has the pandemic affected your business, and what do you expect the “new normal” to look like?

SKARIN: I always try to see potential instead of problems. And however counterintuitive it might sound, the pandemic has given us the potential to get to know our colleagues and customers on a personal level even though we are not meeting in person. With everyone attending virtual meetings from home, you get to interact on a new level, with the person in their home, and sometimes even meet their cat.

Another challenge that can bring potential is the need for efficient workflows and problem solving over long distances. I believe this added flexibility is what we will keep as the new normal.

With reports of hacks and breaches occurring on a regular basis, why are we still having such a difficult time convincing the embedded community that security must be baked into their designs right from the start?

SKARIN: I think it’s a combination of a few different factors. As humans, we are creatures of habit, and change can be hard. Developers are just not in the habit of working with security and they will need a strong reason to change that. In addition, everyone is busy, and wants to save time as well as money. When cutting corners to save resources, security is often taken out of the equation. Why? Well, it could have to do with a lack of liability. However, that is changing and with legislation rapidly coming in place, security is becoming a personal liability for CEOs and CISOs, among others. This will make it harder to cut security out.

Another factor is the fact that security in MCUs is mainly available in high-end (expensive) devices. Many of our customers are not ready to move from their current device. We believe there is still plenty to be done, perhaps not reaching the maximum level of security, but security that could be “good enough” for the application at hand. Security should not be all or nothing; the important thing right now is to get started, and reach a higher level than we have today.

Will 2021 be the year that RISC-V gains a significant market share? Why or why not?

SKARIN: Yes and no. I do believe that 2021 will be a breakout year for RISC-V. The ecosystem continues to grow and we are seeing smaller customers starting to use it, but we are also seeing R&D groups at some larger companies starting to explore the architecture, and there are few large companies committed to using it in at least some business units. However, the architecture is still young, and there is definitely a lot of caution around new technology, especially among larger corporations.

What’s the biggest challenge developers face as we move into the era of Industry 5.0, 5G, and extensive use of artificial intelligence?

SKARIN: Those technologies you mention are all the keys to our future. However, none of them will be realized to their full potential if we don’t improve our code quality. We will need to push out quality software as fast as possible. This is a really tricky problem, because if you go too fast you tend to make mistakes, and if you get something wrong in your embedded code, it can render the system inoperable. This challenge is more and more being solved through the use of continuous integration and continuous deployment. These techniques help to improve efficiency, but also quality, if done right. By implementing code quality checks and automated testing, it’s possible to easily verify that the created software conforms to safe and reliable coding practices, and behaves the way it’s supposed to.

Addressing Security Challenges in an Increasingly Connected World

By Mike Balow, Americas Vice President of Connected Secure Systems, Infi neon Technologies

What’s the latest IoT security horror story that you’ve heard? How did it happen, what did it cost, and how could it have been prevented?

BALOW: There have been quite a few troubling incidents, but I see them more as wakeup calls than true horror stories. As for the cost of incidents, actual damage is often kept confi dential.

Dollar value is just one way to measure loss though, and as the IoT extends into consumer-facing products, the impact of a security breach can be much greater than lost production. To start, incidents get a lot more public exposure. When security researchers successfully attacked automated driver assist systems a few years back it made worldwide headlines. We’ve also repeatedly seen reports of connected home devices being attacked.

One example among many is a 2019 case in Tennessee, where a family discovered that an in-home connected camera was accessed by outside intruders. It turns out that the household Wi-Fi was not appropriately secured and the family didn’t use two-factor authentication, but that explanation raises a serious issue for suppliers of IoT products. Succeeding in smart homes and other emerging areas means making security both strong and easy to implement. Ideally, it should be built-in from the beginning and in a comprehensive, ideally automated, way that needs little or even no interaction by the user.

We’ve all heard the saying that the good guys have to get it right “every time” when it comes to security, but the bad guys only have to get it right once. Taking that statement at face value for a moment, security breaches and vulnerabilities are inevitable. So, does this mean that, moving forward, technology organizations will have to integrate dedicated security departments or organizations regardless of their position in the supply chain to ensure they can be “right” as close to “every time” as possible?

BALOW: As I mentioned, the incidents that have occurred have woken up the industry to security risks. Today’s focus on developing “smart” products, which of course means connected products, has made system-level and end-to-end security a top design priority.

A part of the change in priority has been a recognition of how to embed security into every design. Security is built on authentication, encryption, and integrity at every access point to a system. Since the early 2000s, Infi neon has supplied Trusted Platform Module-compliant (TPM-compliant) devices, which are certifi ed security microcontrollers that provide a Root of Trust (RoT) as the basis for security architectures in computing devices. Hardware-based security has proven to be far more resilient than software-only approaches and this approach to RoT is now incorporated into nearly every type of embedded system security design.

At Infi neon, hardware RoT is implemented in a family of stand-alone security processors, our OPTIGA™ portfolio, as well as in trusted microcontrollers with integrated security hardware that include the AURIX™ and PSoC® 64 microcontrollers. Beyond security controllers, we provide the highly secured NOR Flash memory devices and secured Wi-Fi/Bluetooth connectivity ICs.

Our security chips are based on decades of expertise and work to advance the stateof-the-art, and are produced in secured and certifi ed environments. Certifi cation extends throughout the value chain, so customers don´t need to secure and audit the complete value chain separately. Device manufacturers benefi t from our investment in R&D and extensive production and logistics infrastructure.

In an era where sales are often driven by low cost and short time to market, security offers little conspicuous ROI and adds development time. What strategies, tools, tips, or techniques are available to development organizations that can help them streamline robust security implementations and meet their goals?

BALOW: What we’ve seen is that the industry’s move to security by design recognizes that there is an ROI. Look at authentication, even in non-connected products. In consumer electronics products, authentication is about product integrity. In ink jet printers and digital cameras, adding an authentication IC to ink cartridges and batteries assures that counterfeit products of potentially low quality or even user risk cannot be used. It’s hard to measure the value of protecting integrity. For the printer manufacturer, the same feature also protects recurring revenue from sale of consumables, and that’s an easy value to calculate.

FIGURE 1 A broad range of defenses exist to protect IoT devices

With connected devices, authentication is the basis for encryption and for guarding security keys that are essential to protecting the system. It’s why we are seeing the concept being incorporated into regulatory frameworks, such as the UK Code of Practice, ETSI standards, and state regulations recently rolled-out in California and Oregon.

Reference designs and pre-certifi ed solutions help manufacturers meet their own goals and emerging requirements for built-in security (Figure 1). These involve more than just a module delivered to a manufacturing site. OPTIGA and our other security controllers include a unique cryptographic key pair and certifi cate stored in hardware. Behind the hardware is a trusted process to deliver it to the customer, from design environments and manufacturing sites to protected key programming, with security certifi cation at every step.

Security has been a challenge since the inception of the Internet of Things, but in that time a rash of new technologies have become poised to upend traditional approaches to security. These include Differential Power Analysis (DPA), AI, and quantum cryptography. How do, or should, these developments impact the security posture of technology organizations looking to protect themselves in the near-, mid-, and long-term?

BALOW: You’re right. As long as there are bad actors trying to penetrate security, the science behind security will keep advancing. Protections against DPA and other types of “side-channel” attack techniques were specifi cally addressed in our security controllers even before such attacks were made public. This was possible as we are constantly pushing the boundaries of countermeasures research with our own internal teams and in cooperation with the global security community. For instance, Infi neon is active in development of next-generation cryptography and algorithms related to quantum cryptography, including a global competition to establish standards sponsored by the US National Institutes of Science and Technology (NIST). The company also was recognized as early as 2017 for its work in implementing post-quantum cryptography on contactless security chips like those used in bank cards.

In addition to helping drive the state-of-the-art in crypto, we are working to extend the scope of hardware-based protection across all classes of devices and connectivity. We did that last year for cellular connectivity of IoT devices with the launch of OPTIGA Connect IoT, a turnkey embedded SIM (eSIM) that supports carrier-agnostic coverage in more than 200 countries and territories. It’s simple, fast, and secured Internet connectivity that let’s IoT system builders focus on what they do best, knowing that security is built in.

Based on your interaction with customers, do you think the adoption rate of sufficiently robust security architectures and practices in the connected device industry is sufficient today, at least at a company/ organizational level? Why so high or so low, and what’s needed to move that needle?

BALOW: I talked already about how we’ve seen security move to the top of priority lists for any company that’s building connected products, which means just about every company. In the industrial IoT in particular, new systems are implemented with very solid architectures. There are likely still some vulnerabilities in legacy systems, but awareness and proactive approaches are the norm, not the exception.

In the consumer IoT, comprehensive approaches and implementations of security are now like table stakes to enter the market. Consumers are growing more aware of the need to secure these systems and starting to think about their own vulnerability. And the industry is responding. A major example is the Connected Home over IP (CHIP) project that’s going on under the auspices of the Zigbee Alliance. It will be a standard, on track for publication in the fi rst part of this year, that enables Zero-Touch Provisioning for the Smart Home.

Essentially, when a consumer buys any device certified as compliant, like a smart coffeemaker, that device has a hardware RoT protecting pre-loaded secured software and credentials. Out of the box, the consumer scans a QR code, presses a pairing button and the smart home network verifi es the credentials and admits the device. That’s it. It’s a really exciting initiative with wide support across the smart home ecosystem that we think will defi nitely move the needle.

Infi neon Technologies www.Infi neon.com

This article is from: