Skip to content

Improve connection loop and handling of request timeouts - #77

Merged
jeapostrophe merged 31 commits into
racket:masterfrom
Bogdanp:improve-connection-loop-and-timeouts
Oct 28, 2019
Merged

jeapostrophe merged 31 commits into
racket:masterfrom
Bogdanp:improve-connection-loop-and-timeouts

Conversation

@Bogdanp

@Bogdanp Bogdanp commented Oct 16, 2019

Copy link
Copy Markdown
Contributor

This PR replaces #76 to solve the following problems:

Graceful handling of abrupt client connection termination

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).

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:

  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 (as far as I can tell, this is the reason for the spikes seen in kill-connection-w/o-timer! can take way too long #71),
  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 (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-timeout set to 30 seconds):

vegeta-plot

Requests      [total, rate, throughput]  6000, 100.02, 98.67
Duration      [total, attack, wait]      1m0.808040997s, 59.988771286s, 819.269711ms
Latencies     [mean, 50, 95, 99, max]    455.306658ms, 442.734716ms, 544.037257ms, 616.684004ms, 1.426095694s
Bytes In      [total, mean]              84000, 14.00
Bytes Out     [total, mean]              0, 0.00
Success       [ratio]                    100.00%
Status Codes  [code:count]               200:6000
Error Set:

and after this change:

vegeta-plot (1)

Requests      [total, rate, throughput]  6000, 100.02, 99.24
Duration      [total, attack, wait]      1m0.460767363s, 59.987907058s, 472.860305ms
Latencies     [mean, 50, 95, 99, max]    451.890332ms, 432.016258ms, 564.902571ms, 620.574971ms, 690.550534ms
Bytes In      [total, mean]              84000, 14.00
Bytes Out     [total, mean]              0, 0.00
Success       [ratio]                    100.00%
Status Codes  [code:count]               200:6000
Error Set:

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.
@jeapostrophe

Copy link
Copy Markdown
Contributor

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.

@Bogdanp

Bogdanp commented Oct 16, 2019

Copy link
Copy Markdown
Contributor Author

This seems like a good change to me. Do you anticipate needing to do any other things?

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.

@samth

samth commented Oct 16, 2019

Copy link
Copy Markdown
Member

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.

@Bogdanp

Bogdanp commented Oct 17, 2019 •

Copy link
Copy Markdown
Contributor Author

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:

  1. it swallows all errors and
  2. the example command in the README points the Racket application to a URL that doesn't exist, which makes it so that all the requests to the Racket app behave pathologically (i.e. only respond after they hit their 400ms deadline).

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:

  • one that has the original flaw, where all requests to the application are expected to take at least 400ms and
  • one that doesn't have the original flaw, where the Racket application calls two external URLs that either respond within about 20ms or fail (10% of the time).

With all that in mind here are the results of running 1-minute load tests with #:inital-connection-timeout set to 30 seconds:

Flawed load test (note the different Y-axis scales)

web-server's master branch:

plot-flawed-old

Requests      [total, rate, throughput]  6000, 100.02, 98.49
Duration      [total, attack, wait]      1m0.917604758s, 59.990200854s, 927.403904ms
Latencies     [mean, 50, 95, 99, max]    418.044443ms, 401.879058ms, 552.046522ms, 645.548494ms, 1.028426647s
Bytes In      [total, mean]              154161, 25.69
Bytes Out     [total, mean]              0, 0.00
Success       [ratio]                    100.00%
Status Codes  [code:count]               200:6000  
Error Set:

This branch:

plot-flawed-new

Requests      [total, rate, throughput]  6000, 100.01, 99.34
Duration      [total, attack, wait]      1m0.397687911s, 59.991816982s, 405.870929ms
Latencies     [mean, 50, 95, 99, max]    414.109118ms, 402.048475ms, 517.542767ms, 625.602045ms, 660.877933ms
Bytes In      [total, mean]              154252, 25.71
Bytes Out     [total, mean]              0, 0.00
Success       [ratio]                    100.00%
Status Codes  [code:count]               200:6000  
Error Set:

Verdict:

The large spikes that occur every 30 seconds in the master branch are gone. The smaller spikes that remain seem like they're due to GC. Running with or without incremental GC doesn't seem to make a difference, nor does manually calling (collect-garbage 'incremental).

Load test at 100 req/s

web-server's master branch:

plot-old

Requests      [total, rate, throughput]  6000, 100.02, 99.37
Duration      [total, attack, wait]      1m0.377516589s, 59.990445757s, 387.070832ms
Latencies     [mean, 50, 95, 99, max]    101.078387ms, 20.848776ms, 402.474647ms, 494.547807ms, 675.470996ms
Bytes In      [total, mean]              161168, 26.86
Bytes Out     [total, mean]              0, 0.00
Success       [ratio]                    100.00%
Status Codes  [code:count]               200:6000  
Error Set:

This branch:

plot-new

Requests      [total, rate, throughput]  6000, 100.01, 99.45
Duration      [total, attack, wait]      1m0.332176157s, 59.991004461s, 341.171696ms
Latencies     [mean, 50, 95, 99, max]    96.417541ms, 20.875604ms, 402.524095ms, 499.563755ms, 634.641157ms
Bytes In      [total, mean]              161272, 26.88
Bytes Out     [total, mean]              0, 0.00
Success       [ratio]                    100.00%
Status Codes  [code:count]               200:6000  
Error Set:

Verdict:

Pretty much no difference here, although there is a spike at exactly 30s on the master branch, it doesn't have that much of an impact. This makes sense because we're not applying that much pressure to the Racket application here. The reason so many of the requests here take 400ms is because the external (go) server has a 10% chance to fail each request it receives.

Load test at 200 req/s

web-server's master branch:

plot-old-200rps

Requests      [total, rate, throughput]  12000, 200.02, 198.73
Duration      [total, attack, wait]      1m0.384772106s, 59.995053071s, 389.719035ms
Latencies     [mean, 50, 95, 99, max]    109.584086ms, 21.037219ms, 408.384216ms, 544.915674ms, 915.979837ms
Bytes In      [total, mean]              322596, 26.88
Bytes Out     [total, mean]              0, 0.00
Success       [ratio]                    100.00%
Status Codes  [code:count]               200:12000  
Error Set:

This branch:

plot-new-200rps

Requests      [total, rate, throughput]  12000, 200.02, 198.76
Duration      [total, attack, wait]      1m0.373345484s, 59.994451006s, 378.894478ms
Latencies     [mean, 50, 95, 99, max]    102.626128ms, 20.05742ms, 403.464991ms, 531.450832ms, 666.035216ms
Bytes In      [total, mean]              322570, 26.88
Bytes Out     [total, mean]              0, 0.00
Success       [ratio]                    100.00%
Status Codes  [code:count]               200:12000  
Error Set:

Verdict:

The spikes at 30s intervals start to show up again on the master branch, but not on this branch.

Load test at 250 req/s

web-server's master branch:

plot-old-250rps

Requests      [total, rate, throughput]  15000, 250.02, 235.39
Duration      [total, attack, wait]      1m0.376152415s, 59.996395233s, 379.757182ms
Latencies     [mean, 50, 95, 99, max]    297.958123ms, 30.741528ms, 1.285437273s, 1.839496892s, 2.990780468s
Bytes In      [total, mean]              340889, 22.73
Bytes Out     [total, mean]              0, 0.00
Success       [ratio]                    94.75%
Status Codes  [code:count]               0:788  200:14212  
Error Set:
unexpected EOF
Get http://127.0.0.1:3000/numbers?u=http://127.0.0.1:8090/primes&u=http://127.0.0.1:8090/rand: dial tcp 0.0.0.0:0->127.0.0.1:3000: bind: can't assign requested address
Get http://127.0.0.1:3000/numbers?u=http://127.0.0.1:8090/primes&u=http://127.0.0.1:8090/rand: dial tcp 0.0.0.0:0->127.0.0.1:3000: connect: connection reset by peer

This branch:

plot-new-250rps

Requests      [total, rate, throughput]  15000, 250.02, 239.21
Duration      [total, attack, wait]      1m0.53713129s, 59.99558211s, 541.54918ms
Latencies     [mean, 50, 95, 99, max]    161.095029ms, 22.077429ms, 471.41102ms, 688.9755ms, 1.281980366s
Bytes In      [total, mean]              363401, 24.23
Bytes Out     [total, mean]              0, 0.00
Success       [ratio]                    96.54%
Status Codes  [code:count]               0:519  200:14481  
Error Set:
Get http://127.0.0.1:3000/numbers?u=http://127.0.0.1:8090/primes&u=http://127.0.0.1:8090/rand: dial tcp 0.0.0.0:0->127.0.0.1:3000: bind: can't assign requested address
Get http://127.0.0.1:3000/numbers?u=http://127.0.0.1:8090/primes&u=http://127.0.0.1:8090/rand: dial tcp 0.0.0.0:0->127.0.0.1:3000: connect: connection reset by peer
Get http://127.0.0.1:3000/numbers?u=http://127.0.0.1:8090/primes&u=http://127.0.0.1:8090/rand: read tcp 127.0.0.1:65051->127.0.0.1:3000: read: connection reset by peer
Get http://127.0.0.1:3000/numbers?u=http://127.0.0.1:8090/primes&u=http://127.0.0.1:8090/rand: read tcp 127.0.0.1:65081->127.0.0.1:3000: read: connection reset by peer
Get http://127.0.0.1:3000/numbers?u=http://127.0.0.1:8090/primes&u=http://127.0.0.1:8090/rand: read tcp 127.0.0.1:65086->127.0.0.1:3000: read: connection reset by peer
Get http://127.0.0.1:3000/numbers?u=http://127.0.0.1:8090/primes&u=http://127.0.0.1:8090/rand: read tcp 127.0.0.1:65087->127.0.0.1:3000: read: connection reset by peer
Get http://127.0.0.1:3000/numbers?u=http://127.0.0.1:8090/primes&u=http://127.0.0.1:8090/rand: read tcp 127.0.0.1:65097->127.0.0.1:3000: read: connection reset by peer
Get http://127.0.0.1:3000/numbers?u=http://127.0.0.1:8090/primes&u=http://127.0.0.1:8090/rand: read tcp 127.0.0.1:65096->127.0.0.1:3000: read: connection reset by peer

Verdict:

This shows another flaw with the load test Racket application, but I thought it was interesting. Both tests run out of file descriptors (although my limit is 512000!) around the 33 second mark, but this branch recovers much better. I wouldn't read too much into this one.


I've attached all of the plots and result data to this comment so you can play around with them. I still want to graph memory use during the load test and during a slowloris attack in case there are more improvements that could be made before this gets merged.


Interactive plots and report data: results.zip . You can view the report data by running vegeta report FILENAME.bin.

@Bogdanp

Bogdanp commented Oct 17, 2019 •

Copy link
Copy Markdown
Contributor Author

I realized I could convert the result data to JSON and then make plots (using the plot lib!) that compare the result groups against one another so here are the resulting plots from that:

  • red lines: master branch
  • green lines: this branch

Flawed load test

compare-flawed

Load test at 100 req/s

compare-100rps

Load test at 200 req/s

compare-200rps


I'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.

@jeapostrophe

Copy link
Copy Markdown
Contributor

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?

@Bogdanp

Bogdanp commented Oct 18, 2019 •

Copy link
Copy Markdown
Contributor Author

@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:

untitled

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:

untitled

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 racket plot.rkt).

EDIT 2: And here is the same test again, with memory use as reported by the GC plotted:

untitled2

EDIT 3: Here's a plot of memory usage during a slowloris attack:

slowloris

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.

@jeapostrophe

Copy link
Copy Markdown
Contributor

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.
@Bogdanp

Bogdanp commented Oct 19, 2019

Copy link
Copy Markdown
Contributor Author

@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.
@jeapostrophe

Copy link
Copy Markdown
Contributor

I'm reading along and you're doing a great job!

(or f00 f01)
headers
;; FIXME
(port->bytes contents))])])))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this strategy for dealing with the memory limits and the impersonator trick is a nice one I would not have thought of.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@Bogdanp

Bogdanp commented Oct 25, 2019

Copy link
Copy Markdown
Contributor Author

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:

  • blue is this branch
  • pink is the master branch
  • xs are gc pauses

100 requests/s to a slow request handler

plot-qps

6000 concurrent connection slowloris with 15s read timeout

plot-slowloris

100 concurrent connections each uploading a 10MB file

plot-large-uploads

@samth

samth commented Oct 25, 2019

Copy link
Copy Markdown
Member

Those graphs are very impressive! One question: why do the pink lines end earlier than the blue ones in the second two graphs?

@Bogdanp

Bogdanp commented Oct 25, 2019 •

Copy link
Copy Markdown
Contributor Author

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

  • the ability to guard against extremely large files because we can (and do) continually check the file size of each uploaded file as we read it,
  • the ability for users to upload files that exceed available system memory (configurable by application authors via the new #:max-request-files and #:max-request-file-length arguments to serve))
  • and a little bit of extra protection against DoS attacks because of the slowdown (piping /dev/zero into a client socket is slightly less effective at DoSing a server now).

Here's the source code for the file upload attack.

@jeapostrophe

Copy link
Copy Markdown
Contributor

This is awesome!

@Bogdanp

Bogdanp commented Oct 28, 2019

Copy link
Copy Markdown
Contributor Author

@jeapostrophe these changes are good to go!

@jeapostrophe
jeapostrophe merged commit a58eccb into racket:master Oct 28, 2019
@jeapostrophe

Copy link
Copy Markdown
Contributor

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!

@LiberalArtist

Copy link
Copy Markdown
Contributor

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 +inf.0).

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.

@Bogdanp

Bogdanp commented Nov 12, 2019

Copy link
Copy Markdown
Contributor Author

@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.

@LiberalArtist

Copy link
Copy Markdown
Contributor

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 POST request. In particular, I think safer/lazier request parsing will be a big improvement across the board, since application-level logic that could reject unauthorized requests comes after the construction of a request object (other than e.g. checking TLS client certificates).

At first glance, your nonnegative-length/c seems like a good approach. Before I make too many suggestions, though, I do want to take a little while to properly digest this code.

[#: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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

@LiberalArtist

Copy link
Copy Markdown
Contributor

(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, safety-limits?. I think I'd provide two keyword constructor functions: make-safety-limits, which would use these sensible defaults for unsupplied arguments, and make-unlimited-safety-limits, which would use +inf.0 by default. This would provide a single point of control for adding other limits in the future and passing on limits values, and keeping the internal representation private would give maximum flexibility (e.g. maybe one day someone wants to support a callback function to decide what's allowed or not). I'd probably add #:max-waiting and #:initial-connection-timeout to the struct as well, so, for compatibility, existing functions would be something like:

(λ (...
    [#: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 1.6 in history notes, but doesn't actually increment the package version—I do that in 1def684/#75. It also doesn't update typed/web-server/http, e.g. for the binding:file changes. (I have some questions about those, but I haven't fully explored them yet.)

@jeapostrophe

Copy link
Copy Markdown
Contributor

safety-limits is very pretty.

[max-waiting exact-nonnegative-integer?]
[initial-connection-timeout integer?]
[response-timeout exact-positive-integer?]
[response-send-timeout exact-positive-integer?]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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 …

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Bogdanp Yes, that sounds like a great idea!


(cond
[(zero? offset) eof]
[else (read-bytes n in)]))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see; I was confused about peek-bytes-avail!. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

kill-connection-w/o-timer! can take way too long

4 participants