Как создать антивирус на python
Перейти к содержимому

Как создать антивирус на python

  • автор:

Python Trojan (undetectable)

I am going to be showing you how to create a trojan horse virus using python, I have chosen to show a very basic trojan as it will be easier to understand.

I will be using python version 3.8 in this tutorial. This program we are creating also only uses standard libraries that come with python.

A trojan horse virus is a type of malware which disguises itself as a legitimate piece of software, this is to mislead the user so that it can perform tasks undetected. Trojans can enable cyber criminals to create backdoors on your device and steal sensitive data.

The example I will be using today is a trojan disguised as a number guessing game.

Tutorial:

First we will use python and the random library to create a simple number guessing game. We will be storing this under a function called “game”. We will save this file as client.py.

This game generates a random number from 0 to 100. The user is then given as many attempts as they need to guess the number. This is a very simple program. However, this is not going to be the only function running in our program.

We also need to make the trojan function. This will be done using the socket library. This is the client.py.

This is the trojan function, first we declare a few vital variables. These are the host IP address and the port that the client will be connecting to. Choose the IP of whatever device you will be hosting the server on and chose a port that is not in use. Then I created a tuple object of the IP and port stored under “ADDR”, this variable will be used to make the connection.

We must then create the socket object “client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)”. Then create the connection.

Once this is done we will check for any commands received from the server which the attacker will be sending. This is all happening in the background as the game is running and therefore, there are no outputs. I have created a command called “cmdon” and this will be used to give the attacker access to the terminal on the victims machine. The victim will not see any of this happening. When the attacker wishes to stop using terminal commands they can then send the command “cmdoff”.

To finish off the client file, we use the threading library to run both functions simultaneously.

We must now create a server script. We must create a new file and call it “server.py”. This is the script that the attacker will use to initiate the attack.

The image above is a screenshot of the code we will be using for the server.py file. This is a very simple socket server which listens for connections and offers the user input to send to the victim. This is where the command will be sent to execute on the victims machine.

Make sure the server.py file is running on your machine and then run the client.py file on the victims machine.

Using Virus Total I have scanned the client file and it is undetectable.

Можно ли написать антивирус на python?

ri_gilfanov

1. Теоретически, антивирус написать можно. Но для более-менее вменяемого антивируса нужны производительность и доступ к более низкоуровневым вещам, чем Python позволяет из коробки.

Многие библиотеки Python — это обёртки над библиотеками на C/C++. А в коде на C/C++ вообще могут использоваться ассемблерные вставки. В этом смысле, в Python можно прокинуть вызов любого низкоуровневого кода.

Всё, что необходимо для написания антивируса давно должно иметь свободную реализацию на C/C++ и лежать в открытом доступе. Многое уже может иметь обёртки или биндинги для Python, а что не имеет — так со знанием C/C++ их можно сделать.

Конечная программа на Python может полностью полагаться на скомпилированный Си-шный код, так что производительность будет не намного ниже, а возможности те же.

  • трудно скрыть исходники от любопытных;
  • не очень удобно собирать и распространять под разные ОС;
  • для низкоуровневых вещей и/или высокой производительности может потребоваться знание C/C++.

2. Для специалиста по информационной безопасности, Python — несущественный язык программирования.

Специалист по информационной безопасности должен знать низкоуровневые языки — ассемблер и Си.

Name already in use

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Python-Antivirus-v2

A simple antivirus coded in python capable of scanning selected files and deleting files that it detects as infected. This antivirus uses a large list of MD5, SHA1 and SHA256 malware hashes (many of which coming from this repo — https://github.com/Len-Stevens/MD5-Malware-Hashes) to determine infections. However as this project progresses I would like to implement machine learning detection with the long term goal of becoming a fully functioning antivirus.

when you install qt-material pls go to; you_Python_dir\Lib\site-packages\qt_material and replace material.css.template with this File! (else Gui will be broken!)

Dark_homeTab Dark_SettingsTab Dark_VirusResultsTab

Light_homeTab Light_SettingsTab light_VirusResultsTab

[BTC]; ��bc1qz5q86hrj4n983vxey3mxrrd7227ueacdfz56c9
[ETH]; 0x1556536283e5d3A8EA790A2d79266ffec9d7d684
[DOGE]; DHBgSnHnHRVWSnbigfAYvPuwWQG1yLxmvH
[LTC]; LbnYUMif4PPD1rBGLTWJZ23BQ3jyt884Gn
[SHIB]; 0x1556536283e5d3A8EA790A2d79266ffec9d7d684
[SOL]; LBrSZa5hcXgTPjrPKrx4Cp6QafpZ98TkwZWfAi6p3o3
[CAKE]; 0x1556536283e5d3A8EA790A2d79266ffec9d7d684

How to create a computer virus in Python

teaser

I was relaxing on a beach during my summer leave when I received a mail from a reader that asked me if it is technically possible to write a virus using Python.

The short answer: YES.

The longer answer: yes, BUT…

Let’s start by saying that viruses are a little bit anachronistic in 2021… 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.

I met my first computer virus in 1988. I was playing an old CGA platform game with my friend Alex, that owned a wonderful Olivetti M24 computer (yes, I’m THAT old…) when the program froze and a little ball started to go around the screen. We had never seen anything like that before and so we didn’t know it back then, but we were facing the Ping-Pong virus one of the most famous and common viruses ever… at least here in Italy.

Now, before start, you know I have to write a little disclaimer.

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!

Now, we can proceed.

According to Wikipedia…

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

Let’s start coding.

Let’s analyze this code.

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.

Now, let’s implement the 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! 🙂

This routine could also be a good candidate to be written with a generator. What? You don’t know generators? Let’s have a look at this interesting article then! 😉

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:

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.

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

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:

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:

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.

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:

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

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:

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:

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) :

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…

To sum up

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. 🙂

Did you find this article helpful?

Categories: Dev

Updated: August 30, 2021

You May Also Enjoy

The Sunday tip #2: Measuring Python code performance with the timeit module

Good code is also code that performs well, here’s how you can measure your code’s performance in Python

The Sunday tip #1: Python cached integers

Did you know that Python compiler optimize your program caching small integers?

Managing Python versions with pyenv

Are you sure that you are installing Python right?

How to create a telegram bot with Python in minutes

Creating a Telegram bot in Python couldn’t be easier. Don’t you believe me? Have a look at this article and let’s write our first bot in minutes!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *