Search code examples
pythonsecuritymoduleanalysis

Can I use IF statements for importing modules? Is importing later in a python script possible?


From Perspective Of Pentester/Red Team in Attack

Okay so lets say we are trying our best to avoid detection or to avoid Blue Team from realizing that the script imports the module 'x'.

We implement a fail-safe in our code that checks whether condition a is true. If this is not our target, we want the script to act in a way that won't draw attention.

From my understanding, Blue Team can use process analysis (is that the right word?) to find out what the python script actually does when ran.

Assuming Blue Team is not looking at the actual python script but instead, looking at the calls the python script makes, would it be possible to only import a module when condition a is true. This would then lower the detection threshold.

However, I came across python documentation that recommends to keep all imports at the beginning of a script. With this, we wouldn't be able to implement IF statements to choose whether we should import something or not.

Pseudocode (Python)

import sys
# ...other functions
def check_user():
    # check user against target fingerprint
    if a is True:
        import x

TLDR: Can I use IF/THEN statements for importing modules? Can I import a module later on in a python script?

Security-Related Question: What is a good program to use to analyze python scripts and their calls / actions without analyzing the actual code?


Solution

  • You can import modules conditionally in Python.

    Example :

    def check():
       if sys.version_info[0] == 2:
          from itertools import izip
       else:
          izip = zip
    
       a=[1,2,3]
       b=[4,5,6]
    
       print(izip)
       for c in izip(a,b):
           print(c)
    

    Here based on Python version izip is imported conditionally