• The fact that you can execute code simply on import of any python package is a big spookathon to me. It’s not like you can’t do the same thing in, say, a java class, but that only happens when a specific class is loaded, so if you’re a villain doing villainous things you need to pick a very common class in the target library that everyone uses.

    But with python, just typing “import foo” runs through the __init__.py as a script. So you can get it to do all sorts of things on import, meaning now the target isn’t “have they used torch.ones_like somewhere?”, but instead just using it in a project can pwn you. Get access to someone’s publication credentials and you can slipstream your own nefarious code into any python project that would absolutely impact every consuming user. I don’t know that it’s that different ultimately, but it at least feels different to me

      •  dax   ( @dax@beehaw.org ) 
        54 months ago

        Correct, but only in the case of you import package.path.ClassName. That’s a fair bit different than import foo, which is just the top level “namespace” in Python.

        If you were to (for instance) do import package.path.*; it still is only going to actually import symbols you reference later in your code. So the point is you still have to reference TheSketchyClass to get it to take effect, whereas in Python it will happily do it at import, regardless of whether you use any symbols available via the import.

        The easy way to test this is to add your own static initialization block in a class named ImportExample in package import.test; with a System.out.println("hallo"); or something, then do import import.test.*;. As you can see, provided you don’t actually reference ImportExample anywhere in your own code, the static initialization block doesn’t actually get executed (though, if you did reference ImportExample, it would)

        Then again, while I was super deep into java until about 2015, I have no idea what the last 7 years of classloading have wrought upon my once-domain :)