wiki:RustInTor

Rust in Tor

What & why

We are currently investigating integrating Rust as a first-class language in Tor. We decided upon Rust due to the benefits of memory safety and the ability to directly integrate Rust and C. To read more about how and why this started, see our meeting notes from the 2017 meeting in Amsterdam.

https://lists.torproject.org/pipermail/tor-dev/2017-March/012088.html

Current status

In Tor 0.3.3.x, we include a Rust implementation of our "protover" module. It is not enabled by default, but we encourage people to try it.

Starting with Tor 0.3.4.x, we will accept Rust-only features, if they can be safely merged to the network with only some Tor instances supporting them.

We will continue to build out our modularity efforts, and our Rust infrastructure, to make it easier to write modules in rust and replace parts of Tor.

We encourage ALL downstream packagers to try building Tor with Rust enabled, to help identify any compatibility or usability issues as soon as possible.

Future steps

At some point in the future, when we judge that our Rust support is sufficiently mature, we will announce a release and release date after which Rust will be required. We have not picked such a release or date yet.

What we are currently working on

  1. Understand alignment between Rust and Tor supported platforms. This is a list of which platforms we aim to support, it would be helpful to understand the intersection with Rust. (#22771
  2. Adding automated tooling for code quality tools. (#22156)
  3. Build Tor with Rust for Windows. (#22839)
  4. Investigate the reproducibility of Rust binaries. (#22769)
  5. Implementing existing submodules in Rust as a proof of concept. Two that are currently in progress are consdiff (#24609) and protover (#22840).
  6. Add Rust-enabled build to the Tor CI. (#22636 and #22768)

Interested in helping out?

Please see doc/HACKING/GettingStartedRust.md (rendered) in the tor.git repo.

Coding Standards

Please see doc/HACKING/CodingStandardsRust.md (rendered) in the tor.git repo.

All current, non-closed, Rust in Tor tickets

Ticket Summary
#24265 Fuzz all rust functions that are used by authorities to make sure they match C
Description

We could break consensus if some authorities are running the rust version of the code, and some are running the C version of the code, and their outputs differ on any input.

This is like #24029, but with arbitrary inputs that may or may not be UTF-8.

#22776 Implement the remaining cryptographic protocols for Hyphae
Description

We'll need:

1) Back-Maxwell Rangeproofs (requires Borromean Ring Signatures) 2) A ZKP compiler 3) Testvectors for Ristretto (a.k.a. Decaf for curve25519)

#26265 A proposal and demo for a fuzzing system that works with Rust through C code
Description

I've implemented a demo for fuzzing Rust code and C code at the same time. I hope I can address #25386 with that by using cargo afl. Though I would like to have this system approved first before I write code for a PR.

#25669 Privcount: blinding and encryption should be finished up
Description

We're supposed to do this in 0.3.4. I don't know if there is anything here left to do, but in case there is (like merging to tor, testing more, etc) this is the master ticket.

#24249 Create automated mechanism for C/Rust types to stay in sync
Description

In transitioning parts of tor to Rust, some parts of the code will either need to temporarily exist in both C and Rust (such as protover), or will be highly coupled (such as enums that are passed between the FFI boundary).

It would be good to automatically verify these areas of the code don't get out of sync. This could either be a post-hoc verifier, or a generator that takes a higher-level specification and generates both C and Rust types.

Ideally, the coupling between C and Rust will be as minimal as possible, so this probably does not need to be a heavyweight solution.

#25841 Write test for Rust fragile hardening
Description

We should write some tests to ensure that asan is working to check memory leaks, dangling pointers, and so on. I know that #25386 links asan, but I don't know if it actually checks stuff that we want checked. We should check that it checks what we want checked.

I envision this looking like a test_fragile_hardening.c (or a series of such files) and some helper Rust code that does some bad behavior and a wrapper that ensures that it crashes.

Landing this requires #25386, but writing it does not; just assume that Rust and C can arbitrarily call each other (with the proper boilerplate), and asan is supposed to catch everything that it catches in C.

#23351 Create a rustfmt.toml defining our whitespace/formatting standards
Description

We currently have no style consensus for Rust code. It would be good to agree on something! We could agree on whatever the Rust people like (still a WIP last I checked) or we could modify that by creating a `rustfmt.toml`.

We should also probably add a pre-commit hook for running rustfmt, since we have a pretty clean slate and we should keep it clean. :)

#22816 Run tests for single Rust module
Description

In Tor, we currently have the ability to run tests for a single C module (or even a single unit test). As specified in doc/HACKING/WritingTests, running tests for the cell format module (for example) can be done via ./src/test/test cellfmt/..

Rust modules should have a similar option. Currently 'cargo test' can be run within a single Rust module, but this will not link against C modules. It would be good to be able to do this and retain the ability to test a single Rust module. Also, it would be nice to make this similar to running single C module tests, to minimize developer confusion.

#24609 consdiff implementation in Rust
Description

in my public repo in branch rust4, there's a pretty much complete consdiff implementation in Rust (only missing some logging and testing from the C side iirc). I won't have time to pick it up anytime soon I'm afraid but I hope someone finds it useful. Note it looks a bit different compared to the C code as we were trying very hard to come up with something without any unsafe code and no external dependencies, as this was some of the first rust code ever written for tor. It should be straight-forward, though.

#26038 Misc Rust/Cargo improvements (incl. use global cargo cache)
Description

https://cgit.alxu.ca/tor.git/log/?h=misc-rust

for discussion (since nobody cared on #tor-dev): should we use the global cargo cache? I think most C+Rust projects still use the global cache. I tried searching GitHub (https://github.com/search?q=%22CARGO_HOME%22+extension%3Aam&type=Code). I found that tor is the only project that does not. for users who do not care, using the global cache will save download time and bandwidth on repeat builds, and for those who do care, my patch prints a warning so they will know. (maybe it should be downgraded to NOTICE?)

#22769 Investigate the reproducibility of Rust binaries
Description

If we are going to start writing more Tor things in Rust, it would be nice to understand the reproducibility of binaries created with rustc. I suspect the Tor Browser Team would also be interested in having these results, since parts of Firefox are now written in Rust, and soon (ESR 58?) it will no longer be optional to use them.

Note: this ticket is not about the reproducibility of rustc iteself. That is an extremely deep rabbit hole (trust me, I have a rustc chained back to the OCaml days). Someday we may need to explore that, but that time is not now.

My approach for this task would be probably be to create a Docker instance which builds some trivial Rust program, and then run the Docker instance on different machines and compare the hashes of the binaries (then optionally investigate the differences using whatever tools like running strings and moving up to Ida or whatever).

#25504 Find more generic ways to handle smartlist_t/Vec<T> between C and Rust
Description

From #25368, we discussed having a possibly more generic and/or more rusty way to handle our smartlist_ts in C (and whatever underlying types the smartlist contains). Right now we have a Stringlist type in src/rust/smartlist/smartlist.rs, which is a Rust representation of smartlist_t using C types, and then we have a conversion between that and a Vec<String>:

pub trait Smartlist<T> {
    fn get_list(&self) -> Vec<T>;
}

#[repr(C)]
pub struct Stringlist {
    pub list: *const *const c_char,
    pub num_used: c_int,
    pub capacity: c_int,
}

impl Smartlist<String> for Stringlist {
    fn get_list(&self) -> Vec<String> {
        // [...]
    }
}

I have not thought about this nearly as much as komlo has, but maybe one way to do it is to have direct conversion between a smartlist_t and a Vec<T>, where T is probably an opaque pointer to whatever type in C, or T is only allowed to be a String which we've copied from a non-NULL char* (e.g. impl From<Stringlist> for Vec<String>, or something, and then keep Stringlist private since internally it's a bunch of C types that we don't want propagating into our more Rusty code).

Another idea might be to only handle Vec<T>-like things in Rust (if/when we move to the Rust-is-required phase), since we already have a nice datatype there, and then provide safe interfaces for C code to do all the things with/to the vectors that it currently does. (This sounds easier and more maintainable to me.)

We should probably brainstorm other ideas of how we're going to do this generically moving forward, because our C code uses smartlists everywhere.

#25269 Set codegen-units to 1 in src/rust/Cargo.toml to eke out every last drop of performance
Description

Rust 1.24 now sets codegen-units to 16 by default to speed up compilation time but it makes the final binary slower https://blog.rust-lang.org/2018/02/15/Rust-1.24

For maximum speed, setting codegen-units to 1 in your Cargo.toml is needed to eke out every last drop of performance.

So src/rust/Cargo.toml should be changed with that to squeeze the most perf.

#23880 Build tor with --enable-rust in Orbot and OnionBrowser
Description

Hello! During our Rust discussions at the Montréal meeting, we discussed that it would be extremely useful to know — before we enable Rust by default — if doing so will cause issues for our packagers and downstreams, particularly on mobile. Would it be possible, please, for someone to create an experimental build of Orbot (and OnionBrowser!) building with ./configure --enable-rust [--enable-cargo-online-mode], and let us know any issues you encounter here?

#23882 Investigate implementing a Rust allocator wrapping tor_malloc
Description

We should look into implementing the Rust alloc::allocator::Alloc trait as a wrapper around tor_malloc as a way to have a cleaner allocator interface in Rust moving forward (which still works with our current legacy C code).

This is what the Rust code in Firefox has done, and the alloc crate is supposed to stabilised "soon" (as in, within the next six months) because FF is using it.

#23886 Write FFI bindings and function pointers for ed25519-dalek
Description

As part of our efforts to get a few modules in Tor written in Rust for 0.3.3, an exceptionally easy candidate is our ed25519 code, given that the current code is already highly modularised, taking function pointers to implement an interface. I wrote ed25519-dalek, and I recently revised the API to be a very close match to what tor expects, so I believe this task should be extremely easy, and a prime candidate for someone newer to Rust who wishes to learn about writing FFI. (I'm happy to pair program on this too! Also on anything else, but this too.)

#26257 tor-browser-builder might want to not build rustc
Description

As part of #25977, teor and I were looking into how rustc is being called and built, and we noticed that the binary for 1.24.1 is downloaded and then used to compile 1.25.0. The network team's current policy is to continue using whatever rustc is the current stable until "some distro we care about" releases a new OS version which freezes the rustc they distribute. Additionally, as of eight months or so (sometime between 1.19 and 1.20) ago, the latest nightly is used to compile the next night's nightly, so it's no longer always the case that the last version will compile the current version (meaning you're probably going to end up rabbitholing each time a new stable is released to figure out which nightly you need to somehow get a copy of to build with). Additionally, on a more theoretical note, I'm not certain what we're getting in terms of Trusting Trust attacks by building the compiler only once, versus just downloading the one we need to use.

#26337 make rust error types use the failure crate
Description

As our Rust code increases, we'll eventually want a nicer way to convert between error types than we currently have. We'll probably want to use boats's failure crate. They mentioned a while ago that they were going to make a 1.0.0 release soon, and afaict there's not really anything about the current release that is expected to change, so we can probably start working on this now-ish.

#26373 test_rust.sh should detect when it's being invoked improperly and error out
Description

While attempting to test #26258, I noticed that running src/test/test_rust.sh from the top of the source tree exited with status 0 and no output. It should probably detect that it failed to find any Cargo.toml files and exit with a failure status with an error message. (This seems to happen because some necessary environment variables aren't set.)

Prior to #26258, the find invocation failing would probably have taken care of this, so this change should probably get back ported to the same releases.

#25341 Remove now-unnecessary Rust linking workaround
Description

We've got the following stanza in our configure.ac:

  dnl This is a workaround for #46797                                                                           
  dnl (a.k.a https://github.com/rust-lang/rust/issues/46797 ).  Once the                                        
  dnl upstream bug is fixed, we can remove this workaround.                                                     
  case "$host_os" in                                                                                            
      darwin*)                                                                                                  
        TOR_RUST_EXTRA_LIBS="-lresolv"                                                                          
    ;;                                                                                                          
  esac

It looks like https://github.com/rust-lang/rust/issues/46797 has been resolved as of 22 January 2018, so we can probably remove this workaround now! (Someone who is on MacOS should probably test this, I don't have access to any Macs right now.)

#26497 set CARGO_HOME correctly or stop using it
Description

It looks like we set CARGO_HOME incorrectly for invocations of both cargo build and cargo test. The cargo build invocations work because we first cd to the directory containing the .cargo directory. The cargo test invocations don't work for out-of-source-tree builds. #26455 contains a more minimal fix.

The setting of CARGO_HOME is redundant if we cd to the correct directory first. Or we could stop changing directories and instead set CARGO_HOME correctly. We probably shouldn't do both because it's confusing and possibly inconsistent.

#25628 Document our Rust coding standards for error/failure types
Description

Every crate which returns Result<T, E>s or Option<T> anywhere in its public interface should have an errors.rs module containing error types which implement either Display or Debug, and also ::failure::Fail for making errors easier to work with between crates. See the errors.rs addition to the protover crate from #24031 for an example (doesn't have the ::failure::Fail impl yet, because the failure crate is about to become 1.0.0 any day now).

We should probably wait on this until failure is 1.0.0.

#25386 Link Rust Tests to C Dependencies in Tor (allow integration testing from Rust to C)
Description

currently, it is not possible to call C Tor, directly or indirectly, from rust tests. one of the following must be done:

  1. provide rust stubs for all C functions that may be needed for tests (impractical)
  1. test rust functions from C (so we will have C tests calling Rust functions calling C functions)
  1. link C functions into rust doctests (preferred)
  1. never call C-using rust functions in tests (leads to poor test coverage, very bad)

my branch https://cgit.alxu.ca/tor.git/commit/?h=fix-rust-tests implements option 3 poorly. this is a bad solution firstly because it is very ugly, and secondly because it does not properly pass the system linking arguments, e.g. -L/opt/ssl. thirdly, it may hide problems in or cause to be compiled incorrectly dependency crates.

this ticket blocks a number of rust improvements, since of course we would like to actually test the improvements, and doctests are the best way to do it in rust.

#26398 feature gate testing C code from Rust for now
Description

Any tests which call C code from Rust should be feature gated, by default off for now, and then re-enabled when we have a satisfiable fix for the linker issues in #25386.

#23878 Attempt rewriting buffers.c in Rust
Description

In buffers.c, we define buf_t, which is essentially a doubly-linked list comprised of chunks of contiguously-allocated memory. During the Montréal meeting, we identified buf_t as a potentially good candidate datatype for reimplementation in Rust.

My understanding of possibly the ideal way to do this (after talking with Alex Crichton, without boats, nickm, and Nika Layzell) would be to entirely rethink the implementation in terms of a VecDeque<Bytes> using VecDeque from the stdlib and Bytes or another buffer type from the bytes crate. If this is something which works out, we could then (hopefully!) expose a similar API as to the C interface. (If that doesn't work out, there's only a couple points in the code which appear to rely on the current implementation of buf_t.)

#24033 Require all directory documents to be utf-8
Description

There are only a few places that directory documents can have arbitrary bytes today, and almost nobody is using them to encode anything besides UTF-8. let's standardize on UTF-8 while we still can.

Step one will be for the authorities to start rejecting these documents. Once they're rejecting them, everybody else can begin rejecting them too.

#26161 Design and implement a Rust dirauth module
Description

Some of our protoceratops* functions are only used when dirauths vote:

  • protover_compute_vote
  • protover_compute_for_old_tor

This function is implemented in Rust and C:

  • protover_compute_vote

We should work out how to split protover in Rust and C, and put the dirauth parts in a separate module.

* I blame autocorrect

#25441 Occasional timing? failures in hs_descriptor/validate_cert unit test
Description

I see failures like this occasionally on a macOS VM when using Rust. Is there some weird timing issue, or is the Rust code interfering with the validation?

hs_descriptor/validate_cert: [forking] 
  FAIL ../src/test/test_hs_descriptor.c:710: assert(ret OP_EQ 1): 0 vs 1
  [validate_cert FAILED]
#25381 Add crypto_rand_double_sign() in C and Rust
Description

We need a function that returns 1.0 or -1.0 with equal probability, so we can avoid weird tricks that waste floating point precision.

Since we want to use this in the laplace and guassian distributions, it needs to be implemented in both C and Rust.

#24116 Torsocks deadlocks every Rust program
Description

Any Rust program that is run with torsocks will deadlock. This has nothing to do with networking, even the program 'fn main() { }' compiled with a recent rustc will deadlock when run as 'torsocks ./rust_torsocks'.

This is a backtrace I got when attaching to the deadlocked process:

#0  0xb7713cf9 in __kernel_vsyscall ()
#1  0xb76b9d92 in __lll_lock_wait ()
  at ../sysdeps/unix/sysv/linux/i386/lowlevellock.S:144
#2  0xb76b38de in __GI___pthread_mutex_lock (mutex=0xb770d024)
  at ../nptl/pthread_mutex_[lock.c:80 lock.c:80]
#3  0xb77001ed in tsocks_mutex_lock ()
  from /usr/lib/i386-linux-gnu/torsocks/libtorsocks.so
#4  0xb7700334 in tsocks_once ()
  from /usr/lib/i386-linux-gnu/torsocks/libtorsocks.so
#5  0xb76fa25e in tsocks_initialize ()
  from /usr/lib/i386-linux-gnu/torsocks/libtorsocks.so
#6  0xb76fd02d in syscall ()
  from /usr/lib/i386-linux-gnu/torsocks/libtorsocks.so
#7  0x004a5049 in os_overcommits_proc ()
  at /checkout/src/liballoc_jemalloc/../jemalloc/src/pages.c:252
#8  je_pages_boot ()
  at /checkout/src/liballoc_jemalloc/../jemalloc/src/pages.c:297
#9  0x004745dd in malloc_init_hard_a0_locked ()
  at /checkout/src/liballoc_jemalloc/../jemalloc/src/jemalloc.c:1366
#10 0x00474768 in malloc_init_hard ()
  at /checkout/src/liballoc_jemalloc/../jemalloc/src/jemalloc.c:1493
#11 0x00489b95 in malloc_init ()
  at /checkout/src/liballoc_jemalloc/../jemalloc/src/jemalloc.c:317
#12 ialloc_body (slow_path=true, usize=<synthetic pointer>,
  tsdn=<synthetic pointer>, zero=true, size=20)at /checkout/src/liballoc_jemalloc/../jemalloc/src/jemalloc.c:1583
#13 calloc (num=1, size=20)
  at /checkout/src/liballoc_jemalloc/../jemalloc/src/jemalloc.c:1824
#14 0xb76d23ec in _dlerror_run (
  operate=operate@entry=0xb76d1b80 <dlopen_doit>, args=args@entry=0xbfb8cd10)
#15 0xb76d1c9e in __dlopen (file=0xb7703345 "libc.so.6", mode=1) at dlopen.c:87
#16 0xb76fa44f in ?? () from /usr/lib/i386-linux-gnu/torsocks/libtorsocks.so
#17 0xb7700352 in tsocks_once ()__
  from /usr/lib/i386-linux-gnu/torsocks/libtorsocks.so
#18 0xb76fa25e in tsocks_initialize ()
  from /usr/lib/i386-linux-gnu/torsocks/libtorsocks.so
#19 0xb7724c65 in call_init (l=<optimized out>, argc=argc@entry=1,
  argv=argv@entry=0xbfb8ce74, env=0xbfb8ce7c) at dl-init.c:72
#20 0xb7724d8e in call_init (env=0xbfb8ce7c, argv=0xbfb8ce74, argc=1,
  l=<optimized out>) at dl-init.c:30
#21 _dl_init (main_map=<optimized out>, argc=1, argv=0xbfb8ce74,
  env=0xbfb8ce7c) at dl-init.c:120
#22 0xb7715a5f in _dl_start_user () from /lib/ld-linux.so.2

It looks like tsocks_initialize() is called when libtorsocks is loaded, it calls tsocks_once() which locks a mutex and then calls dlopen() to get the libc symbols, dlopen() tries to allocate some memory which leads jemalloc (the default allocator for Rust programs) to try to call syscall() (it wants to open a proc file to see if the system overcommits memory or not), which is intercepted by libtorsocks, which leads to another call to tsocks_initialize()... and since the mutex is already locked, it deadlocks.

One way to fix this might be to just let through any syscall() calls that happen during bootstrapping, but i don't know the torsocks code well enough to know if this could cause any dangerous leaks.

#25727 Add bool types to Rust coding standards guidelines
Description

Similar to #25368, we can once again expand upon which Rust types are safe to send over the FFI boundary without conversion/serialisation/translation, because Rust's bool type and C99's bool type are directly compatible. (I think this also makes an even larger argument moving forward for using bools in C wherever it makes sense, since otherwise we need to convert between the libc uint8_t type and the native u8 in Rust.)

Last modified 4 months ago Last modified on Mar 20, 2018, 11:56:10 AM