This task is copied from my blog, where I wrote about Zero Cost Abstractions once.

As the digital landscape continues to evolve, programming languages have raced to keep up with the ever-increasing demands for efficiency and speed. One such language, Rust, has proven itself to be a front-runner in this race, offering a feature that might seem like something out of a developer’s dream – Zero Cost Abstractions. But what exactly is this intriguing concept, and how does it play a role in revolutionizing the way we code? Let’s dive into the world of Rust and explore how Zero Cost Abstractions, combined with the marvel of iterators, can significantly elevate your programming experience.

A Glimpse into Zero Cost Abstractions

Zero Cost Abstractions embody the principle that programming efficiency shouldn’t come at the cost of unnecessary performance overhead. In simpler terms, “What you don’t use, you don’t pay for. And what you do use, you couldn’t do any better if you coded by hand.” This two-fold idea encapsulates the essence of this feature.

The first part – “What you don’t use, you don’t pay for” – emphasizes the elimination of global costs associated with unused features. Imagine a scenario where a programming language carries around unnecessary baggage, like a massive 1GB file that hampers performance. Even if certain features aren’t utilized, the price is still paid for them. Zero Cost Abstractions challenge this convention, ensuring that you’re not burdened by unnecessary costs.

The second part – “And what you do use, you couldn’t do any better if you coded by hand” – highlights the optimization achieved by this feature. Consider writing a function to calculate Fibonacci numbers. If you were to manually code this function in assembly, you might not achieve any performance improvements, or worse, you might even compromise performance. Zero Cost Abstractions enable you to write abstracted code, preserving or even enhancing performance, akin to hand-written assembly. It’s a remarkable testament to the power of Rust’s design philosophy.

The Intricacies of Iterators

In the realm of Rust, iterators emerge as a pivotal tool for processing series of items. Think of them as a more versatile sibling of the traditional for loop. Iterators, however, exhibit a unique trait – they are lazy. This means they won’t spring into action until explicitly instructed to do so, distinguishing them from their eager for loop counterparts.

Let’s illustrate this with an example. Say we have a vector ‘a’ containing integers [1, 2, 3]. To utilize the iterator, we create ‘a_iter’ using ‘a.iter()’. But here’s the twist – this alone won’t accomplish anything tangible. It’s akin to setting the stage without the performance unfolding.

To truly activate the iterator and extract values from it, we rely on a for loop. Take this snippet as an instance:

fn main() {
    let a = vec![1, 2, 3];
    let a_iter = a.iter();
    for val in a_iter {
        println!("The value is {}", val);
    }
}

By employing the iterator in the for loop, we finally set the gears in motion and observe the values being processed.

Merging Abstractions and Iterators

Now that we’ve delved into the intricacies of Zero Cost Abstractions and the wonders of iterators, let’s explore how these concepts interweave to supercharge your Rust programming endeavors.

Iterators, with their zero cost abstraction nature, offer a remarkable advantage over traditional for loops. When you choose iterators, you’re tapping into Rust’s optimization prowess, accelerating your program’s performance. This synergistic relationship between iterators and zero cost abstractions empowers developers to achieve speed and efficiency that wasn’t easily attainable before.

In summary, Rust’s Zero Cost Abstractions revolutionize the way we perceive programming efficiency, enabling us to wield powerful abstractions without incurring performance penalties. When combined with the elegance and utility of iterators, this duo becomes a force to be reckoned with, propelling Rust to the forefront of modern programming languages.

So, whether you’re a seasoned Rustacean or just embarking on your journey with the language, take a moment to appreciate the elegance of Zero Cost Abstractions and the versatility of iterators. These features aren’t merely technical nuances; they are the building blocks of a faster, more efficient, and more enjoyable coding experience.

Writing Hello World in Rust

Create a new folder, and in the terminal type:

cargo init

This makes Cargo initialise a new Rust repository. Cargo will take care of most of the work for you.

The file structure is as follows:

- Cargo.toml
- src/
    - main.rs

cargo.toml is the configuration file for our Rust project. It includes our dependencies, project name, authors, the version of Rust we are using and more.

When we have just ran cargo init, our file will look like this:

[package]
name = "Hello_world"
version = "0.1.0"
authors = ["bee <bee@fake.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

Our main.rsfile in the folder src is the main file where we write our code. Every single Rust project must have a main file, and every main file must have a main function.

fn main() {
    println!("Hello, world!");
}

In Rust, we use curly braces to denote blocks of code. And a semi-colon to express the end of an expression.

To print in Rust, we use the macro println!.

We know println is a macro, as it is called with an exclamation mark. Macros, in a nutshell, allow us to write code that writes more code. To put it even simpler, we can create our own syntax that translate to different code.

To directly run this program, we execute:

cargo run

This should result in:

➜ cargo run
   Compiling hello_world v0.1.0 (/tmp/hello_world)
    Finished dev [unoptimized + debuginfo] target(s) in 0.21s
     Running `target/debug/hello_world`
Hello, world!

This command:

  • Compiles the code with the unoptimised build (to increase the speed of compilation)
  • Runs the code

You’ll also notice a new folder has been created, target.

target contains the binaries for our project.

- Cargo.toml
- src/
    - main.rs
- target/
    - debug/
        = build/
        - deps/
        - examples/
        - hello_world
        - hello_world.d
        - incremental/

Right now, the only important file is hello_world

This file is actually the binary for our program.

We can tell its a binary by running file on the target file or by running ls -l in the directory

drwxr-xr-x    - bee 31 Jul 23:35 build
drwxr-xr-x    - bee 31 Jul 23:35 deps
drwxr-xr-x    - bee 31 Jul 23:35 examples
.rwxr-xr-x 2.9M bee 31 Jul 23:35 hello_world
.rw-r--r--   72 bee 31 Jul 23:35 hello_world.d
drwxr-xr-x    - bee 31 Jul 23:35 incremental

To build our project without running it, run:

cargo build

And now we can run the binary directly.

./target/debug/hello_world

This is exactly the same as cargo run, but 2 commands.

When we want to build our project and optimise it, run it with the release profile:

cargo build --release

Use the normal cargo build for quick checking of the code. Use the release argument to optimise the code to the maximum possible that the Rust compiler will allow.

We call --release a profile, specifically the release profile. The Rust compiler has different levels of optimisation depending on what you want.

What is Rust?

Introduction

Rust is a programming language created in 2015 by a small team of people, and later adopted by Mozilla.

It is a compiled low-level language, which aims to be as fast as C or C++, while incorporating some features from high-level languages such as Go, Python, or JavaScript.

Rust has three main goals:

  • Performance
  • Safety
  • Productivity

Performance

Rust aims to achieve performance similar to C or C++.

Rust is statically typed, which means the data type of a variable is known at compile time. This allows the compiler to optimize the code further than if we didn’t know the types.

Rust does not use garbage collection (despite being a low-level programming language). Garbage collection is where the program attempts to reclaim memory from objects no longer in use by the program.

Unlike languages like Python and JavaScript, Rust avoids these abstractions to minimize issues, making it a preferred choice for low-level programming.

Safety

Rust is designed to be completely memory safe. This means that memory-related exploits aren’t possible in Rust, unless you explicitly specify unsafe Rust code.

The Microsoft Security Response Centre reports that 70% of all CVEs assigned are memory safety issues. Microsoft states:

“This means that if that software had been written in Rust, 70% of these security issues would most likely have been eliminated. And we’re not the only company to have reported such findings.”

Rust provides tools to wrap unsafe actions, enabling static enforcement of unsafe code by the Rust compiler.

The memory safety is guaranteed by the concept of ownership, governed by these rules:

  • Each value has a variable, called an owner.
  • There can only be one owner at a time.
  • When the owner goes out of scope, the value will be dropped.

Values can be moved or borrowed between variables, but no value can have more than one owner.

Consider an example in Python:z

squares = (val * val for val in range(100))
print(min(squares))
print(max(squares))

What we want is:

0
9801

But what we get is:

>>> print(min(squares))
0
>>> print(max(squares))
Traceback (most recent call last):
  File "", line 1, in 
ValueError: max() arg is an empty sequence

This is because min alters the variable squares. It’s strange, because we just wanted the minimum — not to alter the whole variable!

In Rust, the same code is:

fn main()
   let squares = (0..100).map(|val| val * val);
   println!("{:?}", squares.min());
   println!("{:?}", squares.max());
}

When we try to compile this, Rust tells us:

error[E0382]: use of moved value: `squares`
 --> ownership.rs:4:21
  |
3 |    println!("{:?}", squares.min());
  |                     ------- value moved here
4 |    println!("{:?}", squares.max());
  |                     ^^^^^^^ value used here after move
  |
  = note: move occurs because `squares` has type `std::iter::Map<std::ops::Range, [closure@ownership.rs:2:31: 2:40]>`, which does not implement the `Copy` trait

The important part here is that Python allows functions to alter variables they do not own, whereas Rust doesn’t.

Productivity

Rust’s third major goal is productivity, and it provides a rich set of tools to support developers.

Note: The below list is read as:

  • Tool

Explanation of the above tool.

Some of these tools include:

  • Cargo

Rust’s version of NPM or PyPi. Download packages others have created.

  • Clippy

Microsoft Clippy, but re-imagined for Rust to aid with development.

  • RustFmt

Automatically formats Rust code.

  • Cargo Test

A built-in testing application created by the Rust developers.

  • Cargo docs

Automatically generates documentation for your code using documentation comments (written in Markdown). This documentation is then sent to docs.rs upon publishing to Cargo. Moreover, examples in documentation are automatically tested for you, eliminating untested documentation examples.

  • Rust-Analyzer

Rust Analyzer is like an intelligent IDE. It clearly labels what’s wrong with your code, explains why it’s wrong, points out the exact characters causing errors, and often provides an “auto-fix” function that rectifies errors automatically.

  • The Rust Book & Docs

Rust offers a comprehensive book called The Book, which covers everything you need to know about Rust. Neatly divided into chapters, it’s easily searchable and available for free. Additionally, due to Rust’s documentation comments, most libraries you use will have extensive documentation online.

With these tools at your disposal, compiling a Rust program and encountering bugs is incredibly rare. The tooling and language usually catch issues long before you hit the compile button.

Conclusion

If you are seeking exceptional speed, memory safety, and enhanced productivity, Rust is the language you’ve been looking for.

As Pentesters, part of our job is to provide solutions to developers. While suggesting a low-level language like Rust to Python developers might seem unconventional initially, Rust offers robust support, even allowing calls from functions written in other languages through foreign function interfacing.

We can leverage Rust to rewrite security or performance-critical code that seamlessly integrates with our existing codebase.

Here’s an example of calling C code:

extern "C" {
    fn abs(input: i32) -> i32;
}

fn main() {
    unsafe {
        println!("C believes that the absolute value of -3 is: {}", abs(-3));
    }
}