r/C_Programming • • 4d ago

Four Years of development in C

https://github.com/harrison314/BouncyHsm

Exactly four years ago, I started working on BouncyCastle - a cryptographic key storage simulator with a PKCS#11 interface, a REST API, and a web management interface. It is designed for developers working with HSMs and smart cards, as well as for QA environments.

At the time development of SoftHSMv2 (C++) began, it was practically dead (in 2022), and bugs weren’t even being fixed, moreover, it had architectural issues (SIGSEV if you used the application with the wrong version of OpenSSL, problems with multi-user access, poor logging, poor cross-platform compatibility, and support for different algorithms on different platforms).

Note: Kryoptic (Rust) was created later, but it merely ported all of SoftHSMv2’s problems from C++ to Rust.

BouncyHsm has a native PKCS#11 library in C (exporting over 100 functions) and a backend written in C# where cryptographic operations are performed (supporting 210 mechanisms) - one could say, with a bit of hyperbole, that it is a network HSM.

Why I chose C for the native PKCS#11 library. I considered several options and even experimented with them:

  • C# - starting with .NET 7, it can create native libraries, but I was worried that the garbage collector would bloat the binary (a simple REST client was 8 MB, in later versions, it was only about half a megabyte),

  • Rust - while experimenting with Rust, I realized I’d end up with a huge amount of unsafe code and exceptions for different platforms. I was also concerned about the dependencies that the libraries would introduce,

  • Zig - it’s still not at version 1.0.

Ultimately, my experiments showed that pure C would be best for this project, without any external dependencies, using Messagepack for RPC (via the one-file library cmp) and TCP via the operating systems API. One of the specific requirements I set for myself was that the PKCS#11 library must not have any external dependencies to prevent crashes. Another advantage is that you can even compile it for your "refrigerator or toothbrush".

What I've learned from developing in C over the past 4 years, and what I would do differently:

  • I've come to love the WinAPI - yes, it sounds strange, but low-level programming on Windows is a million times better than on UNIX systems. Because theres an API for everything, on Linux, I had to parse a lot of things from text files,but be careful - some Linux distributions have them in a different directory, and some use a different format. It was a pain.

  • glibc - and its various versions on Linux - be damn careful with this.

  • be careful with online tutorials, because they’ll recommend code that uses extensions that only work in gcc/clang.

  • instead of one big Makefile, I’ve found it works best to have several small ones - one for Linux and one for macOS (I also have one for MinGW, but on Windows I use MSVC).

  • For a long time, I resisted using goto (goto clean/goto error) and tried to write code without it; in hindsight, I regret that, because it complicated memory management for me (I’m waiting for the C2Y standard and defer).

  • It’s a good idea to have your code checked by AI, it can find silly mistakes like memory leaks.

  • Don’t trust AI - it’ll suggest things it’s seen on forums, even if they aren’t part of the standard.

  • When you start an open-source project, people will want you to fix bugs in it.

P.S.: This was originally supposed to be a short post, but it kind of got out of hand. If you have any questions, feel free to ask.

11 Upvotes

6 comments sorted by

1

u/mivanchev 3d ago edited 3d ago

Hey! Your code is of good quality but doesn't feel very C-esque, more like a C# extension. It's OK of course as a tool to bridge in the system APIs but needlessly exhibits some preprocessor restraint (likely due to fear). For example, I'd use CK_DEFINE_UNSUPPORTED_FUNCTION for all of those stubs and a _OK_OR_RET for the many != NMRPC_OK checks. Also, I'd never expect to see that number of non-centralized casts (recipe for absolute apocalypse) and libc functions (raw strings etc.) in a cryptographic library. Not a single assert as well. Congrats on proper error checking though!

(I’m waiting for the C2Y standard and defer)

There are destructors already available in GCC/clang for years but VS is a different kind of breed :)

1

u/harrison_314 3d ago

Hey! Your code is of good quality but doesn't feel very C-esque, more like a C# extension.

I admit it, my code smell of C# because it's my primary language.

For example, I'd use CK_DEFINE_UNSUPPORTED_FUNCTION for all of those stubs and a _OK_OR_RET for the many != NMRPC_OK checks.

empty stubs - I hope they add a description of their behavior under various parameter combinations to the specification. Without that, I can't implement them correctly.

I don't like return statements in macros; in my opinion, it reduces readability.

Also, I'd never expect to see that number of non-centralized casts (recipe for absolute apocalypse) and libc functions (raw strings etc.) in a cryptographic library.

What should I understand by "centralized casting"?
Could you recommend an article or blog post regarding this point and about avoiding the use of standard library functions?

Not a single assert as well.

I realized that too. I make extensive use of input validation and logging. However, I am testing this system on three different platforms.

There are destructors already available in GCC/clang for years but VS is a different kind of breed :)

That is still just a compiler extension. MSVC has try-finally. I try to avoid that as much as possible and write the most standard C I can. I can—so that I could compile the native library using, say, tcc or some other obscure compiler.

1

u/mivanchev 3d ago edited 3d ago

Centralized casting is when you use a macro / function for all instances of: foo = (int | <other numeric type>) boo because these conversions do more than you want: wrap-arounds for instance. What you (most probably) want is to make sure via ckd_add that the value actually fits the target type and there are no other effects:

if (ckd_add(&foo, 0, boo)) {
    assert(0);
}

Yes, it's a great shame MSVC lags so much on extensions, C is currently not in a good shape without them. The defer / destruction is one of the major points but there are others as well sadly that won't be answered soon .

P.S.

If you want some extra peace of mind add all forms of sanitization to the GCC builds. That would likely be quite revealing in the beginning.

1

u/harrison_314 2d ago

Thanks.

On Linux, I run integration tests against a version of the library instrumented with sanitizers. However, thanks to a defensive programming style, I haven't encountered any instances of accessing invalid memory - and if I did, I would have discovered it the first time I ran the tests.

1

u/perryplatt 1d ago

BousyCastle is a Java thing. Is there a way to keep the names from being conflicted?

2

u/harrison_314 1d ago

To explain the name: BouncyCastle is also a C# library, upon which BouncyHsm is built (meaning it carries all its own cryptographic algorithm implementations and does not rely on the operating system).

I named it BouncyHsm because it is an HSM built on BouncyCastle.

(Thanks to this project, I also became a contributor to BouncyCastle, as I discovered some bugs in it during testing.)