Skip to content

Writing Sturdy C – Greatest Practices for Discovering and Stopping Vulnerabilities


For EIP-4844, Ethereum shoppers want the flexibility to compute and confirm KZG commitments. Fairly than every shopper rolling their very own crypto, researchers and builders got here collectively to write down c-kzg-4844, a comparatively small C library with bindings for higher-level languages. The concept was to create a strong and environment friendly cryptographic library that each one shoppers might use. The Protocol Safety Analysis crew on the Ethereum Basis had the chance to overview and enhance this library. This weblog put up will talk about some issues we do to make C tasks safer.


Fuzz

Fuzzing is a dynamic code testing approach that includes offering random inputs to find bugs in a program. LibFuzzer and afl++ are two fashionable fuzzing frameworks for C tasks. They’re each in-process, coverage-guided, evolutionary fuzzing engines. For c-kzg-4844, we used LibFuzzer since we had been already well-integrated with LLVM venture’s different choices.

Here is the fuzzer for verify_kzg_proof, one in every of c-kzg-4844’s features:

#embody "../base_fuzz.h"

static const size_t COMMITMENT_OFFSET = 0;
static const size_t Z_OFFSET = COMMITMENT_OFFSET + BYTES_PER_COMMITMENT;
static const size_t Y_OFFSET = Z_OFFSET + BYTES_PER_FIELD_ELEMENT;
static const size_t PROOF_OFFSET = Y_OFFSET + BYTES_PER_FIELD_ELEMENT;
static const size_t INPUT_SIZE = PROOF_OFFSET + BYTES_PER_PROOF;

int LLVMFuzzerTestOneInput(const uint8_t* knowledge, size_t dimension) {
    initialize();
    if (dimension == INPUT_SIZE) {
        bool okay;
        verify_kzg_proof(
            &okay,
            (const Bytes48 *)(knowledge + COMMITMENT_OFFSET),
            (const Bytes32 *)(knowledge + Z_OFFSET),
            (const Bytes32 *)(knowledge + Y_OFFSET),
            (const Bytes48 *)(knowledge + PROOF_OFFSET),
            &s
        );
    }
    return 0;
}

When executed, that is what the output seems like. If there have been an issue, it will write the enter to disk and cease executing. Ideally, it is best to have the ability to reproduce the issue.

There’s additionally differential fuzzing, which is a way which fuzzes two or extra implementations of the identical interface and compares the outputs. For a given enter, if the output is completely different, and also you anticipated them to be the identical, you already know one thing is flawed. This system may be very fashionable in Ethereum as a result of we wish to have a number of implementations of the identical factor. This diversification gives an additional stage of security, figuring out that if one implementation had been flawed the others could not have the identical situation.

For KZG libraries, we developed kzg-fuzz which differentially fuzzes c-kzg-4844 (by way of its Golang bindings) and go-kzg-4844. Up to now, there have not been any variations.

Protection

Subsequent, we used llvm-profdata and llvm-cov to generate a protection report from working the assessments. It is a nice technique to confirm code is executed (“coated”) and examined. See the protection goal in c-kzg-4844’s Makefile for an instance of generate this report.

When this goal is run (i.e., make protection) it produces a desk that serves as a high-level overview of how a lot of every operate is executed. The exported features are on the high and the non-exported (static) features are on the underside.

There may be quite a lot of inexperienced within the desk above, however there’s some yellow and pink too. To find out what’s and is not being executed, confer with the HTML file (protection.html) that was generated. This webpage exhibits the whole supply file and highlights non-executed code in pink. On this venture’s case, a lot of the non-executed code offers with hard-to-test error circumstances equivalent to reminiscence allocation failures. For instance, this is some non-executed code:

Originally of this operate, it checks that the trusted setup is large enough to carry out a pairing examine. There is not a check case which gives an invalid trusted setup, so this does not get executed. Additionally, as a result of we solely check with the right trusted setup, the results of is_monomial_form is all the time the identical and would not return the error worth.

Profile

We do not advocate this for all tasks, however since c-kzg-4844 is a efficiency crucial library we expect it is essential to profile its exported features and measure how lengthy they take to execute. This will help determine inefficiencies which might doubtlessly DoS nodes. For this, we used gperftools (Google Efficiency Instruments) as an alternative of llvm-xray as a result of we discovered it to be extra feature-rich and simpler to make use of.

The next is an easy instance which profiles my_function. Profiling works by checking which instruction is being executed on occasion. If a operate is quick sufficient, it will not be observed by the profiler. To cut back the prospect of this, chances are you’ll have to name your operate a number of occasions. On this instance, we name my_function 1000 occasions.

#embody <gperftools/profiler.h>

int task_a(int n) {
    if (n <= 1) return 1;
    return task_a(n - 1) * n;
}

int task_b(int n) {
    if (n <= 1) return 1;
    return task_b(n - 2) + n;
}

void my_function(void) {
    for (int i = 0; i < 500; i++) {
        if (i % 2 == 0) {
            task_a(i);
        } else {
            task_b(i);
        }
    }
}

int fundamental(void) {
    ProfilerStart("instance.prof");
    for (int i = 0; i < 1000; i++) {
        my_function();
    }
    ProfilerStop();
    return 0;
}

Use ProfilerStart(“<filename>”) and ProfilerStop() to mark which components of your program to profile. When re-compiled and executed, it should write a file to disk with profiling knowledge. You’ll be able to then use pprof to visualise this knowledge.

Right here is the graph generated from the command above:

Here is a much bigger instance from one in every of c-kzg-4844’s features. The next picture is the profiling graph for compute_blob_kzg_proof. As you may see, 80% of this operate’s time is spent performing Montgomery multiplications. That is anticipated.

Reverse

Subsequent, view your binary in a software program reverse engineering (SRE) device equivalent to Ghidra or IDA. These instruments will help you perceive how high-level constructs are translated into low-level machine code. We expect it helps to overview your code this fashion; like how studying a paper in a special font will power your mind to interpret sentences in another way. It is also helpful to see what kind of optimizations your compiler makes. It is uncommon, however generally the compiler will optimize out one thing which it deemed pointless. Preserve an eye fixed out for this, one thing like this truly occurred in c-kzg-4844, a few of the assessments had been being optimized out.

Whenever you view a decompiled operate, it is not going to have variable names, complicated sorts, or feedback. When compiled, this info is not included within the binary. It is going to be as much as you to reverse engineer this. You will typically see features are inlined right into a single operate, a number of variables declared in code are optimized right into a single buffer, and the order of checks are completely different. These are simply compiler optimizations and are typically tremendous. It might assist to construct your binary with DWARF debugging info; most SREs can analyze this part to supply higher outcomes.

For instance, that is what blob_to_kzg_commitment initially seems like in Ghidra:

With a bit work, you may rename variables and add feedback to make it simpler to learn. Here is what it might appear to be after a couple of minutes:

Static Evaluation

Clang comes built-in with the Clang Static Analyzer, which is a superb static evaluation device that may determine many issues that the compiler will miss. Because the title “static” suggests, it examines code with out executing it. That is slower than the compiler, however lots quicker than “dynamic” evaluation instruments which execute code.

Here is a easy instance which forgets to free arr (and has one other downside however we are going to speak extra about that later). The compiler is not going to determine this, even with all warnings enabled as a result of technically that is utterly legitimate code.

#embody <stdlib.h>

int fundamental(void) {
    int* arr = malloc(5 * sizeof(int));
    arr[5] = 42;
    return 0;
}

The unix.Malloc checker will determine that arr wasn’t freed. The road within the warning message is a bit deceptive, but it surely is smart if you concentrate on it; the analyzer reached the return assertion and observed that the reminiscence hadn’t been freed.

Not the entire findings are that easy although. Here is a discovering that Clang Static Analyzer present in c-kzg-4844 when initially launched to the venture:

Given an sudden enter, it was attainable to shift this worth by 32 bits which is undefined conduct. The answer was to limit the enter with CHECK(log2_pow2(n) != 0) in order that this was unimaginable. Good job, Clang Static Analyzer!

Sanitize

Santizers are dynamic evaluation instruments which instrument (add directions) to applications which may level out points throughout execution. These are notably helpful at discovering widespread errors related to reminiscence dealing with. Clang comes built-in with a number of sanitizers; listed below are the 4 we discover most helpful and simple to make use of.

Deal with

AddressSanitizer (ASan) is a quick reminiscence error detector which may determine out-of-bounds accesses, use-after-free, use-after-return, use-after-scope, double-free, and reminiscence leaks.

Right here is identical instance from earlier. It forgets to free arr and it’ll set the sixth aspect in a 5 aspect array. It is a easy instance of a heap-buffer-overflow:

#embody <stdlib.h>

int fundamental(void) {
    int* arr = malloc(5 * sizeof(int));
    arr[5] = 42;
    return 0;
}

When compiled with -fsanitize=deal with and executed, it should output the next error message. This factors you in a great route (a 4-byte write in fundamental). This binary may very well be considered in a disassembler to determine precisely which instruction (at fundamental+0x84) is inflicting the issue.

Equally, this is an instance the place it finds a heap-use-after-free:

#embody <stdlib.h>

int fundamental(void) {
    int *arr = malloc(5 * sizeof(int));
    free(arr);
    return arr[2];
}

It tells you that there is a 4-byte learn of freed reminiscence at fundamental+0x8c.

Reminiscence

MemorySanitizer (MSan) is a detector of uninitialized reads. Here is a easy instance which reads (and returns) an uninitialized worth:

int fundamental(void) {
    int knowledge[2];
    return knowledge[0];
}

When compiled with -fsanitize=reminiscence and executed, it should output the next error message:

Undefined Conduct

UndefinedBehaviorSanitizer (UBSan) detects undefined conduct, which refers back to the scenario the place a program’s conduct is unpredictable and never specified by the langauge normal. Some widespread examples of this are accessing out-of-bounds reminiscence, dereferencing an invalid pointer, studying uninitialized variables, and overflow of a signed integer. For instance, right here we increment INT_MAX which is undefined conduct.

#embody <limits.h>

int fundamental(void) {
    int a = INT_MAX;
    return a + 1;
}

When compiled with -fsanitize=undefined and executed, it should output the next error message which tells us precisely the place the issue is and what the situations are:

Thread

ThreadSanitizer (TSan) detects knowledge races, which may happen in multi-threaded applications when two or extra threads entry a shared reminiscence location on the identical time. This example introduces unpredictability and might result in undefined conduct. Here is an instance wherein two threads increment a worldwide counter variable. There are no locks or semaphores, so it is solely attainable that these two threads will increment the variable on the identical time.

#embody <pthread.h>

int counter = 0;

void *increment(void *arg) {
    (void)arg;
    for (int i = 0; i < 1000000; i++)
        counter++;
    return NULL;
}

int fundamental(void) {
    pthread_t thread1, thread2;
    pthread_create(&thread1, NULL, increment, NULL);
    pthread_create(&thread2, NULL, increment, NULL);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    return 0;
}

When compiled with -fsanitize=thread and executed, it should output the next error message:

This error message tells us that there is a knowledge race. In two threads, the increment operate is writing to the identical 4 bytes on the identical time. It even tells us that the reminiscence is counter.

Valgrind

Valgrind is a strong instrumentation framework for constructing dynamic evaluation instruments, however its greatest identified for figuring out reminiscence errors and leaks with its built-in Memcheck device.

The next picture exhibits the output from working c-kzg-4844’s assessments with Valgrind. Within the pink field is a sound discovering for a “conditional leap or transfer [that] is dependent upon uninitialized worth(s).”

This recognized an edge case in expand_root_of_unity. If the flawed root of unity or width had been offered, it was attainable that the loop will break earlier than out[width] was initialized. On this scenario, the ultimate examine would depend upon an uninitialized worth.

static C_KZG_RET expand_root_of_unity(
    fr_t *out, const fr_t *root, uint64_t width
) {
    out[0] = FR_ONE;
    out[1] = *root;

    for (uint64_t i = 2; !fr_is_one(&out[i - 1]); i++) {
        CHECK(i <= width);
        blst_fr_mul(&out[i], &out[i - 1], root);
    }
    CHECK(fr_is_one(&out[width]));

    return C_KZG_OK;
}

Safety Overview

After improvement stabilizes, it has been totally examined, and your crew has manually reviewed the codebase themselves a number of occasions, it is time to get a safety overview by a good safety group. This may not be a stamp of approval, but it surely exhibits that your venture is at the very least considerably safe. Take into account there is no such thing as a such factor as good safety. There’ll all the time be the danger of vulnerabilities.

For c-kzg-4844 and go-kzg-4844, the Ethereum Basis contracted Sigma Prime to conduct a safety overview. They produced this report with 8 findings. It comprises one crucial vulnerability in go-kzg-4844 that was a very good discover. The BLS12-381 library that go-kzg-4844 makes use of, gnark-crypto, had a bug which allowed invalid G1 and G2 factors to be sucessfully decoded. Had this not been fastened, this might have resulted in a consensus bug (a disagreement between implementations) in Ethereum.

Bug Bounty

If a vulnerability in your venture may very well be exploited for features, like it’s for Ethereum, take into account establishing a bug bounty program. This enables safety researchers, or anybody actually, to submit vulnerability stories in trade for cash. Usually, that is particularly for findings which may show that an exploit is feasible. If the bug bounty payouts are cheap, bug finders will notify you of the bug quite than exploiting it or promoting it to a different occasion. We advocate beginning your bug bounty program after the findings from the primary safety overview are resolved; ideally, the safety overview would value lower than the bug bounty payouts.

Conclusion

The event of strong C tasks, particularly within the crucial area of blockchain and cryptocurrencies, requires a multi-faceted method. Given the inherent vulnerabilities related to the C language, a mix of greatest practices and instruments is crucial for producing resilient software program. We hope our experiences and findings from our work with c-kzg-4844 present invaluable insights and greatest practices for others embarking on related tasks.

continue reading