You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Regression: Cannot use cyrptography in embedded wsgi #2299
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.
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.
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?
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.)
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?
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.
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.
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 ;-)
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...
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
@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.
@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.
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.
--- 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()
@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.
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 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()
Activity
reaperhulk commentedon Aug 27, 2015
Wow, would not have expected it to come from that...
/cc @glyph
Naddiseo commentedon Aug 27, 2015
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.
reaperhulk commentedon Aug 27, 2015
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 backendwill do it). Does this resolve your issue?Naddiseo commentedon Aug 27, 2015
Yes, those two lines also resolve the issue.
glyph commentedon Aug 28, 2015
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.)
reaperhulk commentedon Aug 28, 2015
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?
glyph commentedon Aug 29, 2015
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.glyph commentedon Aug 29, 2015
I am pretty sure that you can call between different sub-interpreters just fine, since they share a GIL.
glyph commentedon Aug 30, 2015
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
glyph commentedon Aug 30, 2015
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.
public commentedon Aug 30, 2015
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.
reaperhulk commentedon Aug 30, 2015
@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?
glyph commentedon Aug 30, 2015
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;-)reaperhulk commentedon Sep 8, 2015
Okay, reviving this conversation. Proposal for the sake of discussion: To avoid issues with sub-interpreters we should do the following...
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...
alex commentedon Sep 8, 2015
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:
"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
18 remaining items
toabctl commentedon Sep 29, 2015
@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.reaperhulk commentedon Sep 29, 2015
@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.
toabctl commentedon Sep 29, 2015
No. Sorry for that. I can paste the wsgi file and the apache config if that helps.
Naddiseo commentedon Sep 30, 2015
@reaperhulk, no joy with #2293
jobec commentedon Feb 11, 2016
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 therequestsmodule. 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 processand after a while (the moment the daemon process gets cleaned up) withfunction Cryptography_rand_bytes() called, but no code was attached to it yet with @ffi.def_extern()Fix for an issue where a call to the Requests.post never returned bec…
reaperhulk commentedon Mar 16, 2016
I'm going to close this as our current solution for
mod_wsgiis theWSGIApplicationGroup %{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.
glyph commentedon Mar 16, 2016
Should the FAQ also mention #2537 since that is the (eventual) path forward on this issue? Or am I confused?
jobec commentedon Mar 16, 2016
Are there any downsides in using
backend.activate_builtin_random()? Or is it also a safe workaround?reaperhulk commentedon Mar 16, 2016
@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.chmarr commentedon Sep 9, 2016
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!
jobec commentedon Nov 29, 2016
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 therequestsmodule. 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 processand after a while (the moment the daemon process gets cleaned up) withfunction Cryptography_rand_bytes() called, but no code was attached to it yet with @ffi.def_extern()reaperhulk commentedon Nov 29, 2016
This issue will be resolved with the next cryptography release. See #3229