← Back to DAGDA | Support | Source: https://github.com/pyca/cryptography/issues/2299
Skip to content

Regression: Cannot use cyrptography in embedded wsgi #2299

Closed

Description

@Naddiseo

We have discovered at $work that the 1.0 cryptography release does not work with apache2+mod_wsgi. The error log spits out "Truncated or oversized response headers received from daemon process", which seems to happen if the wsgi process dies. We've tracked the issue down to an upgrade with cryptography, and something to do with threading and/or the Python GIL (a work around is in the wsgi config to set WSGIApplicationGroup to %{GLOBAL}).

I did a git bisect from 0.9.3 and 1.0, and found that the issue was introduced in commit b3d37a5.

Activity

  1. reaperhulk commented on Aug 27, 2015

    @reaperhulk
    Member

    Wow, would not have expected it to come from that...

    /cc @glyph

  2. Naddiseo commented on Aug 27, 2015

    @Naddiseo
    Author

    Me either, the commit itself doesn't look like it could cause something like this, I think that it may have been an earlier commit that introduced code paths that weren't called until the triggering commit.

  3. reaperhulk commented on Aug 27, 2015

    @reaperhulk
    Member

    Out of curiosity... Calling backend.activate_builtin_random() should disable this code path (you'll need to have a backend available in that scope of course. from cryptography.hazmat.backends.openssl.backend import backend will do it). Does this resolve your issue?

  4. Naddiseo commented on Aug 27, 2015

    @Naddiseo
    Author

    Yes, those two lines also resolve the issue.

  5. glyph commented on Aug 28, 2015

    @glyph
    Contributor

    OK, so here's a hypothesis:

    This is a problem because sub-interpreters have an entirely different Python namespace (different modules, etc) but the same C namespace (same GIL, same C-level global variables, shared libraries, etc). I'm not sure exactly why initializing the engine a second time causes a problem, but it's C-level runtime initialization stuff, so ¯_(ツ)_/¯. I'm sure that cryptography being surprised to discover an already-initialized OpenSSL causes all kinds of exciting issues.

    @reaperhulk - you should like this one since it would also explain some of the other concurrency issues you're seeing at import time.

    (The main hypothesis I guess I'm describing here is that subinterpreters are just a completely broken concept nobody should use, but maybe cryptography could be made to work around these issues.)

  6. reaperhulk commented on Aug 28, 2015

    @reaperhulk
    Member

    If we work on that assumption we can make engine addition idempotent at the C layer (see #2293) but since the random engine has callbacks in Python (that potentially point to functions not in the "current" sub-interpreter) it would still fail in the sub-interpreter...correct?

  7. glyph commented on Aug 29, 2015

    @glyph
    Contributor

    There's a pretty good explanation here - http://emptysqua.re/blog/python-c-extensions-and-mod-wsgi/#but-c-extensions-are-not-isolated - of how C extensions are treated by mod_wsgi.

  8. glyph commented on Aug 29, 2015

    @glyph
    Contributor

    I am pretty sure that you can call between different sub-interpreters just fine, since they share a GIL.

  9. glyph commented on Aug 30, 2015

    @glyph
    Contributor

    I flied a cffi bug to ask for a way to keep the GIL while calling C: https://bitbucket.org/cffi/cffi/issues/220/some-way-to-annotate-a-call-to-ask-it-not

  10. glyph commented on Aug 30, 2015

    @glyph
    Contributor

    One perhaps-obvious solution here would be to move all this library initialization to the module scope so that it's protected by the import lock, rather than trying to protect it with an ad-hoc lock. It seems counter to the way that cryptography is constructed, to avoid shared mutable state, but in this case there is just the illusion of such avoidance: the mutable state does in fact exist and attempting to abstract it away is hard in a multi-interpreter environment.

  11. public commented on Aug 30, 2015

    @public
    Member

    Sub interpreters could definitely trigger a race in the engine setup code. #2293 proposes making this process idempotent which seems like a fairly reasonable solution to me.

  12. reaperhulk commented on Aug 30, 2015

    @reaperhulk
    Member

    @glyph I'm not opposed to that solution if it resolves our problem, but does it given the change in behavior in python 3.4?

  13. glyph commented on Aug 30, 2015

    @glyph
    Contributor

    Possibly not; I can't figure out at a glance how the per-module locks are initialized. @cyli suggests that cryptography could just take out a filesystem lock in /tmp ;-)

  14. reaperhulk commented on Sep 8, 2015

    @reaperhulk
    Member

    Okay, reviving this conversation. Proposal for the sake of discussion: To avoid issues with sub-interpreters we should do the following...

    • Move os random engine back to C
    • Make os random engine registration idempotent (we can hold a lock at the C layer which will prevent races with the sub-interpreters)
    • Move the locking callbacks to C (since they are presumably subject to the same issues)
    • Make locking callback registration idempotent (this part might be tricky if we want to detect locking callbacks already being registered by things like import _ssl)

    Do people agree that this would resolve the issue? If not, why not? And if so, is there a way to do this without doing it all in C because obviously we'd prefer to not do that...

  15. alex commented on Sep 8, 2015

    @alex
    Member

    FWIW, I'm strictly opposed to moving this code back itno C.

    On Tue, Sep 8, 2015 at 11:05 AM, Paul Kehrer notifications@github.com
    wrote:

    Okay, reviving this conversation. Proposal for the sake of discussion: To
    avoid issues with sub-interpreters we should do the following:

    • Move os random engine back to C
    • Make os random engine registration idempotent (we can hold a lock at
      the C layer which will prevent races with the sub-interpreters)
    • Move the locking callbacks to C (since they are presumably subject
      to the same issues)
    • Make locking callback registration idempotent (this part might be
      tricky if we want to detect locking callbacks already being registered by
      things like import _ssl)

    Do people agree that this would resolve the issue? If not, why not? And if
    so, is there a way to do this without doing it all in C because obviously
    we'd prefer to not do that...

    —
    Reply to this email directly or view it on GitHub
    #2299 (comment).

    "I disapprove of what you say, but I will defend to the death your right to
    say it." -- Evelyn Beatrice Hall (summarizing Voltaire)
    "The people's good is the highest law." -- Cicero
    GPG Key fingerprint: 125F 5C67 DFE9 4084

  16. 18 remaining items

  17. toabctl commented on Sep 29, 2015

    @toabctl

    @Naddiseo if you get a chance could you test #2293? I made some changes to that approach.

    @reaperhulk I have a similiar problem (running on py27, cryptography 1.0 in a apache2 wsgi env and getting RuntimeError: osrandom engine already registered) and the patch you proposed in #2293 fixes this problem.

  18. reaperhulk commented on Sep 29, 2015

    @reaperhulk
    Member

    @toabctl that's great -- any chance you can provide a docker container that replicates the bug? We haven't been willing to land #2293 thus far because it relies on locking callbacks that are registered in Python. I think #2293 is really just narrowing the window for the race condition and not fixing the underlying issue, but I'd like to experiment with an environment that triggers the initial bug.

  19. toabctl commented on Sep 29, 2015

    @toabctl

    any chance you can provide a docker container that replicates the bug?

    No. Sorry for that. I can paste the wsgi file and the apache config if that helps.

  20. Naddiseo commented on Sep 30, 2015

    @Naddiseo
    Author

    @reaperhulk, no joy with #2293

  21. jobec commented on Feb 11, 2016

    @jobec

    I noticed a similar issue with to combination of apache, mod_wsgi and the Requests module.

    When doing a request to a HTTPS site with Requests, the function call never returns.
    The backend.activate_builtin_random() line of code mentioned in reply 4 also did the trick.

    I eventually figured it out because I saw the following error in my apache error log:
    extern "Python": function Cryptography_rand_bytes() called, but no code was attached to it yet with @ffi.def_extern(). Returning 0.

    For the code that was causing the issue, see: snok/django-auth-adfs@28936fb

    --- UPDATE 2016/11/29 ---
    I ran into this bug again (v1.4 of cryptography).
    It appears this backend.activate_builtin_random() MUST be called before doing any HTTPS request with the requests module. If it's not called before it, it will hang the wsgi process.
    First with an error like: Timeout when reading response headers from daemon process and after a while (the moment the daemon process gets cleaned up) with function Cryptography_rand_bytes() called, but no code was attached to it yet with @ffi.def_extern()

  22. reaperhulk commented on Mar 16, 2016

    @reaperhulk
    Member

    I'm going to close this as our current solution for mod_wsgi is the WSGIApplicationGroup %{GLOBAL} fix and we've recently documented it in our FAQ.

    Hopefully at some point in the future this won't be required, but for now it's the best we can do.

  23. glyph commented on Mar 16, 2016

    @glyph
    Contributor

    Should the FAQ also mention #2537 since that is the (eventual) path forward on this issue? Or am I confused?

  24. jobec commented on Mar 16, 2016

    @jobec

    Are there any downsides in using backend.activate_builtin_random() ? Or is it also a safe workaround?

  25. reaperhulk commented on Mar 16, 2016

    @reaperhulk
    Member

    @glyph until we merge it I'm going to be somewhat quiet about it (other than to perhaps point people that direction).

    @jobec The random initialization issue appears to be mostly handled by some code we put in the 1.2 release, so it shouldn't be necessary to separately call activate_builtin_random (although doing so shouldn't cause problems). We've been receiving sporadic reports of other issues though, so that's why we've stated that the official way to handle this is the ApplicationGroup directive.

  26. chmarr commented on Sep 9, 2016

    @chmarr

    Adding a note here as I ran into this problem and the documented workaround - setting WSGIProgressGroup %{global} - didn't work for me. I hope someone else will find this useful.

    From what I can glean, setting %{GLOBAL} doesn't assign the reference (e.g. WSGISCriptAlias) to the first sub-interpreter, but simply to the first process group. Sub-interpreters are created purely by the number of different wsgi applications that are in that process group, with "different application" is roughly equivalent to a different wsgi.py file. So, assuming that diagnosis true, the documented solution doesn't work at all and is in fact completely wrong.

    I added some code to the wsgi.py file to syslog out id(os) and os.getpid(), as a way of detecting additional sub-interpreters being generated. Using id(builtins) didn't seem to be useful.

    The fix was to ensure each application runs in a different process group, I.e., a different WSGIDaemonProcess for every different wsgi.py file you have. When I did this, this problem, along with the 'isinstance' problem the WSGI documentation referred to, completely went away.

    (As an aside, I only have a single wsgi.py file, but I'm referring to them from two different VirtualServers. I think that whatever code detects references to the same wsgi.py file breaks across the virtualserver boundary. I have multiple references to the wsgi.py file inside one of the VirtualServers, and that doesn't appear to cause additional sub-interpreters.)

    I hope this helps!

  27. jobec commented on Nov 29, 2016

    @jobec

    I ran into this bug again (v1.4 of cryptography).
    It appears backend.activate_builtin_random() MUST be called before doing any HTTPS request with the requests module. If it's not called before it, it will hang the wsgi process.

    First with an error like: Timeout when reading response headers from daemon process and after a while (the moment the daemon process gets cleaned up) with function Cryptography_rand_bytes() called, but no code was attached to it yet with @ffi.def_extern()

  28. reaperhulk commented on Nov 29, 2016

    @reaperhulk
    Member

    This issue will be resolved with the next cryptography release. See #3229

  29. locked as resolved and limited conversation to collaborators on Aug 13, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions