Repository navigation
Description
Right now the actix-web code contains 100+ uses of unsafe. Presumably this is in order to achieve the best possible performance in hot parts of the code.
However, web servers often face the public Internet, so security is extremely important for web server implementations. This issue is especially critical for organizations that intend to use the software in large-scale production environments. One of the main reasons to choose a Rust-based HTTP implementation is the guaranteed memory safety that safe Rust provides. Unfortunately this guarantee is eroded for every use of unsafe in the codebase. Performance isn't worth much if it comes at the cost of critical security vulnerabilities due to unsafe memory access. It's also nice to know for certain that your web server won't segfault in production.
I propose that we leave this open as a tracking issue to track design and implementation issues concerning the use of unsafe code. Some of the items that should be explored:
- Is it possible to remove any of the current uses of
unsafewithout significantly impacting performance? - Is it appropriate to remove some uses of
unsafeeven if there's a performance impact? - Is there a long-term plan to reduce or eliminate the use of unsafe code?
- Security analysis, testing, and fuzzing of the codebase
- Profiling and performance analysis to assess the impact of converting unsafe to safe code
Activity
DoumanAsh commentedon Jun 8, 2018
@axon-q First of all if your concern is
unsafecode then you cannot use even Rust's standard library which is the biggest collection ofunsafecode.Most likely no, but it should be investigated on per case basis, not overall
No, I don't believe it is right approach to problem.
Just because code is
unsafedoesn't mean it is going to to segfault or cause memory corruption.Note that Rust has strong guarantees about UB and it is really difficult to write code that would unexpectedly cause problems (applicable for most
unsafecode aside from raw pointers)P.s. Of course if code is not correct it should be corrected
AFAIK there is no long-term plan, but nothing stops you from eliminating it on per case basis(as long as it doens't impact performance significantly)
But overall goal should not be to remove 100% of unsafe code
fafhrd91 commentedon Jun 8, 2018
unsafe code is used mostly for two reasons:
in any case we have to evaluate every use case for unsafe. i used unsafe for the reason, in most cases i couldnt come up with safe solution. also you need to take into account size of the codebase, at the moment actix-web is ~27k loc
axon-q commentedon Jun 8, 2018
@DoumanAsh The point is to reduce risk and the attack surface. Of course the entire stack, including
std, rustc, LLVM and the kernel can potentially have vulnerabilities. The Rust foundations are considered very solid, however, due to their maturity and the amount of use and scrutiny they receive. The question is how much risk actix-web adds on top of that, and how to minimize it. This is something that everyone considering using it in production has to evaluate.I agree that
unsafeisn't necessarily bad, and that some kinds ofunsafecode are better than others. But from the perspective of risk, the lessunsafethe better.axon-q commentedon Jun 8, 2018
@fafhrd91 Makes sense! Good to know that it might be possible to work toward removing some of the non-performance-critical usages. Also, some uses of
unsafeare more problematic than others: having a bit ofunsafesealed inside an internal component is not so bad, butunsafehandling of things like memory buffers and parsing that are directly affected by untrusted input is a red flag from a security perspective.memoryruins commentedon Jun 12, 2018
If anyone would like to try fuzzing, these will come in handy:
seanmonstar commentedon Jun 15, 2018
After noticing this issue, and then noticing #301, I figured I'd do a more in-depth analysis of the
unsafeusages here. I've so far found ~15 cases where a user can "safely" trigger memory bugs. I first offered to send this in a private email, but it was preferred I just post this here.I haven't done a complete review. I first looked in public API files, and so have not analyzed
client/*,server/*, orpipeline.rs, all of which do happen to contain a large amount ofunsafecode as well.The two main classes of issues I have found are:
Send, allowing memory unsafety to occur if the affected code every moves to another thread.While a couple
unsafeusages can be fine, I'd strongly recommend to remove as much as possible. Consider:The issues I've found so far:
Actix core
Box<Future>(note, not Box<Future + Send>).F: Futurebounds, so a user can safely insert !Send futures into the items list. If thatContextImplever crosses to another thread, it can easily trigger memory unsafety (double-free or use-after-free).Context::create(new_actor)to create a new Context. After grabbing a&Tof something on their Actor (&mut self), they canmem::replace(context, new_context). When the returned old_context drops, it will have invalidated the memory of&T.Writer::new(some_io, ctx)will spawn a clone of the UnsafeWriter to be costantly flushing its buffer on the io&self.bufferto pass tostd::io::Write::writejust before the second thread causes the buffer to re-allocate to grow, theWritewill try to copy freed memory.Actix-web
let header = req1.headers().get("connection"), and then invalidate the memory it points to, by doingreq2.headers_mut() = HeaderMap::new().req.connection_info()save static references from the current HeaderMap and Urireq.headers_mut().insert("x-forward-for", "woopsies").req.connection_info()will access cached "static" strs that have had their memory freed.req.query()req.extensions_mut().HttpRequest.req.query()will return the cached but likely freed "static" references.ActormethodPredicatePredicatethat could accidentally free the Uri.Predicate::check(&mut req), via*req = my_sub_request.&mut selfctx.actor(Woopsies::new()Box<Identity>(notBox<Identity + Send>)Identity, such as usingRcClone, andDerefMut, without synchronization, meaning a user can have multiple mutable references to the sameConfigfafhrd91 commentedon Jun 16, 2018
@seanmonstar thanks for analysis. i will think about this.
fafhrd91 commentedon Jun 16, 2018
@seanmonstar thanks again for pointing.
last is header_mut(), i need to think how to fix it
fafhrd91 commentedon Jun 17, 2018
fixed most of the problems. let's open new ticket for each new case.
closing this one
seanmonstar commentedon Jun 18, 2018
I'm glad that some of the issues could be fixed, that's great!
However, I think it's early to close this issue, as "most of the problems" are not actually fixed. Some of the holes have been filled in, but the underlying unsafety still exists, and several of the "fixes" actually still leave a public API that is unsound.
unsafe impl Sendhas been removed (though, I was a little shocked to read one of the patches add a brand newunsafe impl Send, instead of removing all of them. I haven't yet analyzed the new one.).&'a strinto&'static str. However, several others still remain. The Contexts still have ways to trigger memory bugs. HttpRequest still has was for a user to trigger memory bugs. The URI issue is not fixed.The biggest problem is there several different versions of code like this:
This is a very unsafe thing to do! True, it's possible for the
do_something_mutmethod to not trigger memory unsafey, but doing the above has completely disable the compiler from helping you notice when you do! And, this pattern is actually the root of most of the unsound APIs that are available. I'd beg that instead of trying to fill in more holes, the root of the unsoundness be fixed instead.For that reason, I'm not spelling out exactly how to trigger the memory bugs that still exist (though I have exact steps), since it's not my goal to have the ones I find fixed. It's my goal to have people using and writing safe software. Instead, I can write up some steps on how to fix the roots.
The
HttpRequestcontinues to have just anRc<InnerHttpMessage>, and yet thanks toHttpRequest::as_mut()simply transmuting to a&mut InnerHttpMessage, references can still be invalidated. Theas_mutmethod should add a check that there is only 1 reference, and panic otherwise.The
Scopetakes an unsafe reference to the path, and then passes a mutable reference to each predicate (memory bugs are still possible with the fixes so far). It should not do this. Instead, it should only grab a temporary reference when it is needed.Instead, this should be done:
The various Contexts,
ContextImpl,Context,HttpContext,WebsocketContext, all do the mutable alias example I mentioned above:This still has several unsound holes, and they could all be fixed by not doing the above. Since the
Contextis passed a&mut Contextto allActorandHandlermethods, the structure should be changed. TheContextshould stop holding the actualActor, so that a mutable alias isn't required to pass theContextto an actor method.Besides the unsoundness that I've been able to identify, there may exist other instances that I haven't noticed yet. Instead of fixing the individual issues, fixing the root makes any unnoticed issues go away too. I'd expect this issue to remain open so users of Actix can track how to know that the code they rely on is safe, until everything has been resolved.
(An example of number 2 is how
server::TransferEncodingholds a*mut BytesMut. This is unsafe, but it's unsafety has been wrapped up in a couple of debug assertions. While analyzing the code, it doesn't appear that memory bugs are triggered, there is absolutely no need to have this unsafety, but allows for future code to accidently violate some invariants. Instead of keeping a*mut BytesMutinside theTransferEncoding, a&mut BytesMutcould be passed toTransferEncoding::encode, likeencoder.encode(&mut self.buffer, bytes).)I believe Actix users would want these to be addressed. If not by reopening this issue, then by opening a new one with that objective.
hayd commentedon Jun 18, 2018
Also, the issue's headline is:
This is still the case. Being able to track this is useful...
fafhrd91 commentedon Jun 19, 2018
@seanmonstar i can not see how to trigger memory unsafety with
req.uri().path()and predicates. could you elaborate?gnzlbg commentedon Jun 19, 2018
Each use of
unsafein thestdlibrary contains a comment "proving"/explaining why the unsafe operations performed are safe. The explanations typically list the invariants that, when violated, could lead to undefined behavior, and the code typicallyasserts these, such that the program will abort or unwind instead of running into undefined behavior.OTOH
unsafeinsideactix-webappears to be used nitty-willy, without any explanations of why eachunsafeoperation is actually safe. That's a completely different bar.Do you mean that you couldn't come up with a safe solution in safe Rust? Because
unsafeis a tool to write safe code that the compiler cannot prove correctly, not a tool to write code that is not safe (EDIT: that is, that has undefined behavior).ZerothLaw commentedon Jun 19, 2018
So I'm a newish Rust developer (but long time developer in other stuff). Will efforts to start refactoring the API/Code to remove reliance on
unsafebe accepted if sound and clean?9 remaining items
mitsuhiko commentedon Jun 20, 2018
I think for now I want to land some changes that mark functions as unsafe that should need that or tag them to be only there for internal test uses. That should make it clearer which ones are okay and which ones are not. And add markers to indicate why things are unsafe.
fafhrd91 commentedon Jun 20, 2018
Let’s not rush. We need to play with different approaches. In general, I am inclined to remove unsafe rather than making unsafe fn. I am not very happy about this shitstorm atm
kamek-pf commentedon Jun 24, 2018
For anyone keeping track of this, last week
actix-webhad over 120unsafes, as of today I only count 38.Shout out to the team !
botev commentedon Jun 25, 2018
@mitsuhiko first I want to say that I'm not really an expert on web development or any of the such so my understanding of these issues is relatively low. However, I did have several times have to spend time in Rust developing things which were very counter-intuitive to do with the borrow checker as they required various mutations which are not allowed. As such I'm quite curious what exactly is the issue/use-case/problem here. Is it possible for you to describe a bit the flow of the API and where/why this is required and which bits make it harder? Again for someone not so familiar with HTTP libraries.
Pzixel commentedon Jun 25, 2018
@botev unsafe can make safe Rust to perform an UB operation which would lead to anything, including data corruption or panic. Here is an example on playground. Although it compiles it crashes at runtime (best outcome). However, UB says that it could silently corrupt your data or send your credit card number to African drug dealers (not so nice outcome).
DoumanAsh commentedon Jun 25, 2018
@Pzixel Please don't be misleading, unsafe code may lead to UB(in a very rare occasions) or memory corruption. But it doesn't mean that all unsafe code equals to UB or corruption or segfault
Pzixel commentedon Jun 25, 2018
@DoumanAsh plase, reread my sentence carefully. That's what I have written:
botev commentedon Jun 25, 2018
@Pzixel maybe I reference the wrong part, but I intended this towards the issue of removing 'Clone' and in general allowing productive mutations when passing object around. I think there have been enough discussion on 'unsafe' and UB and I can't add anything to that.
fafhrd91 commentedon Jul 5, 2018
UB should be fixed. some unsafe are still there but should not bring UB. if anyone what to review code re-open ticket or create new one
berkus commentedon Jul 14, 2018
@fafhrd91 is there a commit id/range with regards to fixes related to this ticket?
fafhrd91 commentedon Jul 14, 2018
@berkus there is no any specific commit, changes are too large. Most of commits for the last two weeks are related to fixes
berkus commentedon Jul 14, 2018
Okay, I'll look through those, thanks!
laciferin2024 commentedon Aug 25, 2024