News for hackers. Stuff that matters.
Re:Making Python Less Random by mianos on Friday July 12, 2024 @01:04AM (#40942834)
This is utterly insane:

   import os
   os.urandom = lambda n: b'\x00' * n
   import random
   random.randint = lambda a, b: a
I love it!
Re:Making Python Less Random by FreakLegion on Friday July 12, 2024 @01:24AM (#40942894)
That's monkey patching, and it actually would've worked fine. There isn't enough context in the write-up to say for sure, but presumably he was just doing it too late, after the third-party library was already imported. At that point the third-party library has its own reference to the original function(s), so patching the reference(s) in the source module doesn't do anything. If the source module had been patched first, though, it all would've worked out.
Re:Making Python Less Random by jnwatson on Friday July 12, 2024 @02:43AM (#40943196)
This assumes there are no calls to random functions from C extensions. Still, I would have started with the above.
Re:Making Python Less Random by FreakLegion on Friday July 12, 2024 @03:20AM (#40943351)
Less so that, since he says he knows the sources of randomness, but it does assume esoteric import methods aren't used. If for some reason the third-party library is e.g. loading modules with importlib, all bets are off.
Re:Making Python Less Random by mianos on Friday July 12, 2024 @04:37AM (#40943728)
I think he was saying something else was calling it and that was busting other things. Gevent did some crazy antics to get the whole tcp interface patched up. https://www.gevent.org/api/gevent.monkey.html#gevent.monkey....
Re:Making Python Less Random by FreakLegion on Friday July 12, 2024 @06:46PM (#40950147)
Right, but the reason something else was able to call it was that he patched it too late. The same thing can happen with gevent. From the docs:

> Patching should be done as early as possible in the lifecycle of the program. For example, the main module (the one that tests against __main__ or is otherwise the first imported) should begin with this code, ideally before any other imports:

    from gevent import monkey
    monkey.patch_all()
A corollary of the above is that patching should be done on the main thread and should be done while the program is single-threaded.

It's possible to patch later on, but much more involved. If you patch module A after you've already loaded module B, which itself loads module A, then you have to both patch module A and track down and patch every reference to module A in module B. Usually those will just be global references, but not always.