Repository navigation
Improve connection loop and handling of request timeouts - #77
Conversation
This prevents errors such as
tcp-read: error reading
system error: Connection reset by peer; errno=54
errortrace...:
context...:
/Applications/Racket v7.4/collects/racket/port.rkt:1160:4: try-again
from appearing in application output after clients terminate their
connections abruptly (without sending a FIN packet).
This code can be used to exercise the problem:
#lang racket
(require racket/tcp)
(for ([_ (in-range 100)])
(define-values (in out)
(tcp-connect "127.0.0.1" 8000))
(parameterize ([current-output-port out])
(displayln "GET / HTTP/1.1")
(displayln "")
(flush-output))
(read-string 100 in)
(tcp-abandon-port in)
(tcp-abandon-port out))
The previous implementation was susceptible to three issues: 1. a timing issue whereby a request on a persistent connection could come in at the same time as the initial connection timeout expired, making the request fail, 2. a timing issue whereby a response could be terminated prematurely because the initial connection timeout expired and 3. a slowloris attack whereby the client could open many connections to the server, each sending large values in the Content-Length header and never sending any data. The new implementation resets the connection timeout on every new request to a pre-set value that the programmer controls (no more slowloris) and subsequently resets it again for every response chunk returned by the application.
It can sometimes happen that a connection's timeout will expire in the middle of us reading the request data. When that happens, we need to silence the exception and ensure that the connection is killed.
|
This seems like a good change to me. Do you anticipate needing to do any other things? The code is definitely simpler and I believe that it solves the sloworis attack. When I look at the graphs, it was not obvious to me that the new one is better, but then I noticed the Y-axis and see that the spikes are much less severe. |
I would like to take a deeper look at how timeouts are handled for file responses as well as try and profile memory use over time so I'll do that in the coming days and ping you when I think this is ready so I don't spam everybody with PR notifications. |
|
Seeing those consistent spikes in the second plot, I wonder if they're something that could be address, and might be a GC issue. Is it possible to annotate the plot based on gc logging? Also, I wonder if using the incremental gc after each request is handled would help. |
|
I'm embarrassed I didn't notice this yesterday, but I took a deeper look at the load test today and there are a couple problems with it:
I think 2. is OK because it just means that the application gets hit harder during the load test and had it not been for this "flaw", then we probably wouldn't have caught the problem in the first place. We just have to keep that in mind when we interpret the graphs. The reason you see the spikes at the end in the graphs above, though, is because I failed to properly run the go server that the application calls yesterday so all the external requests that the application was making were silently failing (because of 1.). I've forked the load test and cleaned it up here: https://github.com/bogdanp/racket-test-server (diff) In particular, I've modified the application itself so that it's as efficient as I know how to make it while preserving its original behavior and I've split the load test into two separate ones:
With all that in mind here are the results of running 1-minute load tests with Flawed load test (note the different Y-axis scales)
|
|
I realized I could convert the result data to JSON and then make plots (using the
Flawed load testLoad test at 100 req/sLoad test at 200 req/sI've committed the result JSON files as well as the Racket code to generate the plots to my fork of the load test repo in case anyone wants to play with the charts in DrRacket. |
|
When I look at the graphs, I don't see a meaningful improvement in the new branch, except that the code is simpler. Am I missing something? |
|
@jeapostrophe performance wise, there is a meaningful improvement in the new branch when the application code has slow request handlers (for whatever reason: waiting on external services, GC, un-optimized code, etc.). Here's what happens if I add a 2-second sleep to the load test application's request handler: As before, red is the master branch and green is this branch. The smaller spikes (which I believe are GC related) appear on both branches, but the larger ones only appear on master and are directly related to connection timeouts. Apart from performance, the other improvements I mention in my PR description still apply so I think these changes are definitely worth adding. EDIT: Here is the same test with GC pauses plotted: The GC data is collected separately so the the x-axis may be shifted a little bit, but it seems fairly accurate. Code and result data for this plot (run with EDIT 2: And here is the same test again, with memory use as reported by the GC plotted: EDIT 3: Here's a plot of memory usage during a slowloris attack: This is with a request read timeout of 15 seconds. Pink is the master branch and blue is this one. As you can see at the end, this branch eventually reclaims memory for the attacking connections, while master doesn't. While I was testing the slowloris attack I realized there are a couple other open vectors that ought to be plugged so I'll try and fix those tomorrow. |
|
Yes, that is very convincing. Thank you. Let me know if you need any pointers with file responses. |
Without this change, a malicious client could keep sending the server data until it runs out of memory. Improvements still need to be made to the multipart parser, which is currently completely unsafe, and to how these limits are handled. Currently, any time such a limit is reached, an exception is raised which immediately terminates the connection. Instead, HTTP responses (eg. HTTP 413 Request Entity Too Large) should be returned detailing the issue.
|
@jeapostrophe this last commit was fairly large and I anticipate at least two more that are going to be at least as large (one to make the multipart parser safer and the other to handle these limits more gracefully). If you think that'll be too much to review in one go, then I can split this into multiple PRs instead. |
Previously, (parse-bindings #"a&b=") would result in (list (make-binding:form #"a" #"b=")) which was wrong. This commit re-works parse-bindings so that it can handle that particular case as well as a couple of other interesting ones. Un-provides parse-bindings and read-headers. These seem to have been provided so they could be tested, but they really shouldn't be a part of the public interface so I've removed the toplevel provides and re-provided them from the `internal-test' submodule.
This variant allocates a lot less memory every time it's called and it's generally within 15% of read-bytes-line as far as runtime on medium-long lines.
Previously, clients could DoS the server by requesting large files
without ever reading them from the output socket because the timeout
was set based upon the size of the files being requested. This change
adds a rolling send timeout such that for every chunk of data that is
read by the client, the timeout resets. If the client is too slow,
then the connection is eventually terminated.
To test this change you can set up a file server with a low send timeout:
#lang racket/base
(require (prefix-in files: web-server/dispatchers/dispatch-files)
web-server/dispatchers/filesystem-map
web-server/web-server)
(define shutdown
(serve
#:dispatch (files:make #:url->path (make-url->path "."))
#:port 9000
#:response-send-timeout 5))
(with-handlers ([exn:break? (lambda _
(shutdown))])
(sync never-evt))
create a large file in the directory that the server is running in:
# creates a 100MB file called test.dat filled with zeros
# replace "bs=1M" with "bs=1m" on macOs
dd if=/dev/null of=test.dat count=100 bs=1M
and try to read that file using a client that's intentionally slower
than that send timeout:
#lang racket/base
(require racket/format
racket/tcp)
(define-values (in out)
(tcp-connect "127.0.0.1" 9000))
(parameterize ([current-output-port out])
(display "GET /test.dat HTTP/1.1\r\n")
(display "\r\n")
(flush-output))
(define st (current-inexact-milliseconds))
(define n 0)
(let loop ()
(printf "delta: ~ams and ~amb\n"
(- (current-inexact-milliseconds) st)
(~r (/ n 1024 1024)))
(define bs (read-bytes (* 1 1024 1024) in))
(unless (eof-object? bs)
(set! n (+ n (bytes-length bs)))
(sleep 10)
(loop)))
Following this sequence of steps on my machine, the client gets
disconnected within about 20 seconds:
$ racket client.rkt
delta: 0.075927734375ms and 0mb
delta: 10009.180908203125ms and 1mb
delta: 20015.35791015625ms and 1.5544mb
$
Before this change, the client would only get disconnected after 100
million seconds (1 second per every byte in the requested file).
Previously, the call to `read-bytes' would pre-allocate a buffer of size `size-in-bytes' regardless of whether or not that much data was available on the input port. That was a potential attack vector.
`read-bytes' pre-allocates a buffer of however many bytes it expects to read. This presents a potential attack vector where someone can send a request with a large `Content-Length' and never send the server any data. The server/read-bytes will happily allocate that buffer and wait for data to come in. If the attacker spawns enough requests like this then the server will eventually run out of memory. `read-bytes/lazy' as implemented here peeks into the input port until it's sure that there is enough data available on the port before allocating the final bytes buffer.
Previously, if you had called `read-bytes/lazy' with n=100, then the final call to `read-bytes' would end up allocating a 100 byte buffer even when the input port only contained 10 bytes. This change makes it so that read-bytes/lazy will allocate the minimum number of bytes it needs to to satisfy the call.
This change minimizes the overhead of read-bytes/lazy versus read-bytes, while maintaining the reduced memory use during an attack.
I also refactored the Request tests to extract request data into fixtures and make it easy for individual tests to only match on the data that matters for them.
It wasn't buying us much over a plain let-loop.
|
I'm reading along and you're doing a great job! |
| (or f00 f01) | ||
| headers | ||
| ;; FIXME | ||
| (port->bytes contents))])]))) |
There was a problem hiding this comment.
@jeapostrophe I'm nearly done but I'm not sure how to proceed here. Uploaded files now get written to disk if they are large enough so binding:file's contents should really just be the input port for its associated file. Obviously, that would be a breaking change so that's problematic. I could introduce a new binding type (say binding:file-port) and a flag to create binding:file-ports instead of binding:files, but that would end up not being secure by default and it would introduce a bunch of cruft.
The best option I can think of is limiting the scope of the breaking change by renaming the contents field of binding:file to in and then adding a new function called binding:file-contents which just applies port->bytes to in and memoizes the result. I think this would be mostly backwards-compatible except in cases where someone is matching on (struct binding:file (id fname headers contents)).
What do you think?
There was a problem hiding this comment.
The best option I can think of is limiting the scope of the breaking change by renaming the contents field of binding:file to in and then adding a new function called binding:file-contents which just applies port->bytes to in and memoizes the result. I think this would be mostly backwards-compatible except in cases where someone is matching on (struct binding:file (id fname headers contents)).
The latest commit I pushed does this. Let me know if you want me to take a different approach.
I'm still not super happy with how the mime parser ended up (in particular, in-http-lines is probably not necessary and it's definitely not as safe as it could be) so I'm going to try and improve it tomorrow and add a few more test cases. I think once that's done, this'll be good to go.
There was a problem hiding this comment.
There are a few ways to limit the backwards incompatibility here. One that might be easy is to provide an impersonated version of the binding:file instance that does the port->bytes (and memoization) in the impersonator code.
There was a problem hiding this comment.
@samth thanks for the tip! I have never used impersonators before, but I was able to sketch this up pretty quickly:
#lang racket/base
(require racket/match
racket/port)
(struct binding:file (id name headers [content #:mutable])
#:transparent)
(struct binding:file/port binding:file (in)
#:transparent)
(define (make-binding:file id name headers content [in #f])
(impersonate-struct
(binding:file/port id name headers #f (or in (open-input-string content)))
struct:binding:file
binding:file-content
(let ([mem #f]
[sem (make-semaphore 1)])
(lambda (b c)
(unless mem
(call-with-semaphore sem
(lambda _
(unless mem
(set! mem (port->string (binding:file/port-in b)))))))
mem))))
(define b (make-binding:file "a" "a" null "a"))
(binding:file-content b)
(binding:file-content b)
(match b
[(struct binding:file (id name headers content))
content])Is this along the lines of what you were thinking? It does seem like this would be more backwards-compatible than what I've done. Anything I should watch out for in particular with impersonators?
There was a problem hiding this comment.
I like this strategy for dealing with the memory limits and the impersonator trick is a nice one I would not have thought of.
There was a problem hiding this comment.
This is almost exactly what I was thinking of. One suggestion I'd make is to use the content field instead of mem -- it already has to be mutable, and that means there's less allocation. If you put the semaphore in a field as well, you can make the impersonator handler not a closure at all.
This opens up use cases where the size of the uploaded files in a request can exceed the available memory. Additionally, validate fields and files separately within multipart requests.
This keeps the amount of data that gets buffered into memory low regardless of how large the uploaded files are.
|
I think this is nearly ready to go now. I'm going to look at all the changes again this weekend and see if I can think up a few more tests to add, but given all the new unit tests and the fact that matchacha.ro (and its tests) runs without issue on the new branch, I'm pretty confident that I didn't break anything. Here's what all the graphs look like this morning:
100 requests/s to a slow request handler6000 concurrent connection slowloris with 15s read timeout100 concurrent connections each uploading a 10MB file |
|
Those graphs are very impressive! One question: why do the pink lines end earlier than the blue ones in the second two graphs? |
|
The slowloris attack on the master branch never ends because the attacking connections are never terminated by the server so memory usage grows and grows as new attacking connections are made and then it plateaus once new connections stop being created. After about a minute and a half, I manually stopped this attack and that's where you can see the memory spike up again (for whatever reason) at the end. So from about the 60s mark until the end there, the server was using about 6GB of memory. When attacking this branch, I had used a 15 second read timeout so the attacking connections were each dropped by the server after living for about 15 seconds. This branch also no longer trusts the content length it receives from the client, so it never even tries to allocate the 6GB worth of buffers (1MB per attacking connection) that the master branch does. Here's the source for the slowloris attack. The upload attack against the master branch finishes quicker because the server reads all the uploaded data into memory with minimal buffering. This branch buffers file upload data in 64k chunks into memory up until they hit 1MB in size and it then starts writing them to disk (still in 64k chunks) once they go over the 1MB threshold so it is much safer re. memory usage, but also slower. The extra buffering buys us
Here's the source code for the file upload attack. |
|
This is awesome! |
Also, fix an off-by-one issue in read-bytes/lazy.
|
@jeapostrophe these changes are good to go! |
|
Thank you very much, I'm going to merge and run the tests locally for myself to double check. This is such a great job and you were so thorough. Thank you again! |
|
I'm very enthusiastic about these improvements, but I have some concerns about backward-compatibility. The default values for the new timeouts and length limits are reasonable ones, but adding limits will break some programs that were designed without them, and the contracts for the new arguments don't provide a way to opt in to the old, unlimited behavior (e.g. by supplying Concretely, I think this would break Digital Ricoeur. While I need to review both these changes and my own code more closely, parts of our application do or have used request bodies and file uploads well over 10 MB, large numbers of file uploads, and long-running request handler functions. Again, I think these are great changes overall, and providing sensible defaults may well be worth requiring some porting for the (probably small) set of existing programs for which these limits might be a problem. My concerns are about providing a smooth migration path and not limiting the programs it's possible to write. I will try to contribute some implementation work toward those ends, once I've understood these changes more deeply. |
|
@LiberalArtist I think all of the limits I added can be safely updated to use a contract like the one I added in this commit. That should make it so that applications that depended on the old behavior can opt back into it. Let me know if you want to go ahead and do that yourself or if I should. I'd be happy to answer any questions you have about any of the changes I've made here or over email (visible on my GH profile). I think improving security is worth making breaking changes so I would like to keep the new defaults (or slightly more lax versions of each of them) despite them being breaking to some applications. Without these limits, certain attack vectors are exploitable even when you run an application behind a reverse proxy like nginx. |
|
I definitely agree about safety, and I think the great majority of applications don't need or want to accept the complete works of a prolific philosopher in one HTTP At first glance, your |
| [#:max-waiting max-waiting integer? 511] | ||
| [#:initial-connection-timeout initial-connection-timeout integer? 60]) | ||
| [#:initial-connection-timeout initial-connection-timeout integer? 60] | ||
| [#:request-read-timeout request-read-timeout integer? 60] |
There was a problem hiding this comment.
I'm wondering why these are integer? rather than exact-positive-integer? (or (or/c exact-nonnegative-integer? +inf.0)). It see that #:initial-connection-timeout and #:max-waiting were already there and specified as integer?, though I wonder what they really do if given negative integers. Did you want #:request-read-timeout to be consistent with #:initial-connection-timeout?
I would consider changing all of the documented contracts to exact-positive-integer? (or whatever we name the contract in #81), even if we have to actually accept any integer? in some cases for backward compatability.
There was a problem hiding this comment.
I think both have the integer? contract by mistake. Their actual contracts are number?, but I think they should both be non-negative reals. Same with response-timeout and response-send-timeout (which are currently exact-positive-integers). So we probably need two contracts
(define nonnegative-limit/c (or/c exact-nonnegative-integer? +inf.0))
(define timeout/c (and/c real? (>=/c 0)))a negative #:initial-connection-timeout will immediately timeout all incoming connections, so it's probably safe to change that to timeout/c. That said, I think timeout/c should allow 0 since that can be helpful for testing purposes.
There was a problem hiding this comment.
@Bogdanp I've basically done as you suggest here in #84. It turns out that max-waiting is restricted to exact-nonnegative-integer? by tcp-listen: making that more permissive seems hard (if even possible in a cross-platform way), so I just consistently use exact-nonnegative-integer? for now. For timeout/c, (>=/c 0) already checks real?, so the and/c isn't needed.
|
(I'm writing this now mostly so I remember the idea.) This PR and ad714196 add the same bunch of optional keyword arguments and default values to several functions. An alternative I think I'd prefer would be to pack these values in an opaque struct—say, (λ (...
[#:max-waiting max-waiting 511]
[#:initial-connection-timeout timeout 60]
[#:safety-limits limits
(make-safety-limits #:max-waiting max-waiting
#:initial-connection-timeout timeout)])
...)Is it too late to propose this kind of change, given that this PR has been merged but won't be in the 7.5 release? Potentially relevant to the "too late" determination: this PR talks about version |
|
|
| [max-waiting exact-nonnegative-integer?] | ||
| [initial-connection-timeout integer?] | ||
| [response-timeout exact-positive-integer?] | ||
| [response-send-timeout exact-positive-integer?] |
There was a problem hiding this comment.
@Bogdanp IIUC, adding response-timeout and response-send-timeout elements to dispatch-server-config^ (and likewise for web-config^) would be a breaking change for any programs that define their own units that export dispatch-server-config^. I think instead we need to declare a new signature using the safety-limits struct. I'm still working out the least-ugly way to do that.
There was a problem hiding this comment.
I think a fairly elegant solution is to make dispatch-server-config^ extend a dispatch-server-config*^ and use define-values-for-export to generate the safety-limits element definition.
There was a problem hiding this comment.
Sounds good to me. I think it would be good to add a test specifically for this to prevent these types of breakages in the future. If you don't think you'll get around to it, then let me know and I'll give it a try.
I had never dealt with units before and it never occurred to me that this is a breaking change even though I obviously had to change web-server-unit.rkt in response to this change so a test would've helped for sure.
There was a problem hiding this comment.
@Bogdanp What kind of test do you have in mind for this? It seems hard to protect against someone making a breaking change to a signature or unit (probably unintentionally: units are somewhat obscure in modern Racket) and also changing the test suite at the same time—but maybe you're thinking of something I'm not. In any case, probably some comments would be helpful …
There was a problem hiding this comment.
I was thinking of constructing a dummy web-server-unit in a test-case. The test itself doesn't have to assert anything, it just has to fail to compile when the sigs change and have a nice message like "should not break backwards-compatibility of signatures". I realize this is kind of redundant, given that web-server-unit.rkt itself would fail given a change to either sig, like it did when I made the change, but this would make it harder to unintentionally make a breaking change.
Thought process after modifying a sig: "ah, of course, I need to also change the unit!"
Thought process after modifying a sig with this "test" in place: "oh crap, this is a breaking change, I'd better ask for advice/rethink my approach!"
|
|
||
| (cond | ||
| [(zero? offset) eof] | ||
| [else (read-bytes n in)])) |
There was a problem hiding this comment.
@Bogdanp If I am following correctly (a big "if"), I think this implementation of read-bytes/lazy will busy-wait until enough bytes become available, whereas the old peek-bytes-evt-based version yielded to the Racket thread scheduler until it could make some progress. If I'm right about that, is it something you considered?
I wouldn't hold #84 for it in any case, since it isn't an API change, but on general principles I would think yielding to Racket would be better. If so, we should probably use racket/racket@c19b944 and add an appropriate #:version requirement to info.rkt.
There was a problem hiding this comment.
@LiberalArtist peek-bytes-avail blocks when there isn't enough data available on the port so the code does cooperate with the rest of Racket fine. Just to be sure I ran this test on my machine:
#lang racket/base
(define-values (in out) (make-pipe))
(define (read-bytes/lazy n in [bufsize 4096])
(define buf (make-bytes bufsize))
(define offset
(let loop ([offset 0])
(displayln "reading")
(define len
(peek-bytes-avail! buf offset #f in))
(printf "read ~a bytes\n" len)
(cond
[(eof-object? len) offset]
[else
(define offset* (+ offset len))
(cond
[(> offset* n) offset*]
[else (loop offset*)])])))
(cond
[(zero? offset) eof]
[else (read-bytes n in)]))
(thread
(lambda _
(read-bytes/lazy 1024 in)))
(for ([_ (in-range 1024)])
(displayln "writing")
(display "a" out)
(sleep 1))which yields:
writing
reading
read 1 bytes
reading
writing
read 1 bytes
reading
writing
...
I don't think the commit you linked to would help here. The reason I made this function is that all of the standard reading functions pre-allocate the result buffers based on the input size they're given. This means that calling (read-bytes 1024 some-port) immediately allocates a 1k buffer whether there is 1k of data on the port or not. This is problematic when dealing with user input because someone could send a Content-Length: 10000000000000 and crash our server. Or, presuming we limit the Content-Length to some max, they could send many requests with Content-Length: max-1 without ever sending any body data.
There was a problem hiding this comment.
I see; I was confused about peek-bytes-avail!. Thanks!


















This PR replaces #76 to solve the following problems:
Graceful handling of abrupt client connection termination
This prevents errors such as
from appearing in application output after clients terminate their connections abruptly (without sending a FIN packet).
Given @mflatt's fix for
peek-bytes-evt, this change won't be necessary in Racket 7.5, but I'd like to keep it because it fixes the problem in the current and older versions of Racket and because I believe it simplifies the connection loop.Improved handling of request timeouts
The previous implementation was susceptible to three issues:
kill-connection-w/o-timer!can take way too long #71),The new implementation resets the connection timeout on every new request to a pre-set (but configurable via
#:request-read-timeout) value that the programmer controls (no more slowloris) and subsequently resets it again for every response chunk returned by the application.This fixes #71. Here are the results of the load test in #71 before this change (run for 1 minute, with
#:initial-connection-timeoutset to30seconds):and after this change: