Как написать вирус на питоне

от admin

Writing a virus in python

Why would anyone want to write malware in Python? We’ll do this to learn the general principles of malware development, and at the same time you will practice using this language and be able to apply the knowledge gained for other purposes. In addition, Python malware does come across in the wild, and not all antiviruses pay attention to it.

Most often, Python is used to create backdoors in software in order to download and execute any code on an infected machine. So, in 2017, employees of the Dr.Web company discovered Python.BackDoor.33, and on May 8, 2019, Mac.BackDoor.Siggen.20 was spotted. Another Trojan, RAT Python, stole user data from infected devices and used Telegram as a data transfer channel.

We will create three demo programs: a locker that will block access to the computer until the user enters the correct password, an encryptor that will bypass directories and encrypt all files in them, and a virus that will distribute its code, infecting other programs. in Python.

The topic of remote administration of infected machines is beyond the scope of this article, but you can get a basic code base with all the explanations in the article “ Reverse shell in Python “.

Despite the fact that our creations do not claim to be of any high technical level, they can be dangerous under certain conditions. Therefore, I warn you that severe punishment may follow for disrupting other people’s computers and destroying information. Let’s agree right away: you will only run everything that we describe here on your own machine, and even then be careful not to accidentally encrypt the entire disk for yourself.

All information is provided for informational purposes only. Neither the author nor the editors are responsible for any possible harm caused by the materials of this article

Setting up the environment

So, first of all, of course, we need Python itself, and the third version. I will not describe in detail how to install it, but I will immediately send you to download the free book “Python Bite” ( PDF ). In it you will find the answer to this and many other Python-related questions.

Additionally, we will install several modules that we will use:

This completes the preparatory stage, you can start writing the code.

Locker

The idea is to create a full screen window and prevent the user from closing it.

Now let’s get down to the main part of the program.

Here pyautogui.FAILSAFE = False is the protection that is activated when you move the cursor to the upper left corner of the screen. When it is triggered, the program is closed. We do not need this, so we disable this function.

To make our locker work on any monitor with any resolution, we read the width and height of the screen and, using a simple formula, calculate where the cursor will go, click, and so on. In our case, the cursor hits the center of the screen, that is, we divide the width and height by two. We will sleep add a pause () so that the user can enter the code to cancel.

Now we have not blocked the input of text, but you can do it, and then the user will not get rid of us in any way. To do this, we will write some more code. I do not advise you to do it right away. First, let’s configure the program so that it turns off when you enter a password. But the code for blocking the keyboard and mouse looks like this:

Let’s create a function for entering the key:

Everything is simple here. If the key is not the one we specified, the program continues to run. If the passwords match, we slow down.

The last function that is needed for the pest window to work:

At this point, our impromptu locker is ready.

Cryptographer

We will write this virus using only one third-party library — pyAesCrypt. The idea is to encrypt all files in the specified directory and all directories below. This is an important limitation to avoid breaking the operating system. For work, we will create two files — an encryptor and a decryptor. After work, the executable files will self-delete.

First, we request the path to the attacked directory and the password for encryption and decryption:

Next, we will generate scripts for encryption and decryption. It looks like this:

Moving on to the files that we will use as templates. Let’s start with the encoder. We need two standard libraries:

We write the encryption function (all according to the pyAesCrypt manual):

Instead of str (password), the script generator will insert the password.

Important nuances. We will encrypt and decrypt using a buffer, thus we get rid of the limitation on the file size (at least, we will significantly reduce this limitation). The call is os.remove(file) needed to delete the original file, since we copy the file and encrypt the copy. You can choose to copy the file instead of deleting it.

Now a function that bypasses folders. Nothing complicated here either.

Let’s add two more lines at the end. One for starting a bypass, the second for self-destructing the program.

The desired path will be substituted here again.

Here is the entire source.

Now the “mirrored” file. If in the ransomware we wrote encrypt, then in the decryptor we write decrypt. There is no point in repeating the parsing of the same lines, so the final version is right away.

A total of 29 lines, of which it took three to decipher. In case one of the files suddenly turns out to be damaged and an error occurs, we use the exception catch ( try. except ). That is, if we fail to decrypt the file, we just skip it.

Virus

The idea here is to create a program that will infect other programs with the specified extension. Unlike real viruses that infect any executable file, ours will only infect other Python programs.

This time we don’t need any third-party libraries, only the sys and os modules are needed. We connect them.

Let’s create three functions: message, parser, infection.

The function that reports the attack:

Let’s call it right away to understand that the program has worked:

Directory traversal is similar to what we did in the ransomware.

In theory, we could poison the sources in other languages ​​in the same way, adding the code in these languages ​​to the files with the appropriate extensions. And on Unix-like systems, scripts in Bash, Ruby, Perl and the like can simply be replaced with Python scripts by correcting the path to the interpreter in the first line.

The virus will infect files “down” from the directory where it is located (we get the path by calling os.getcwd() ).

At the beginning and at the end of the file, we write the following comments:

I’ll explain why a little later.

Next is the function that is responsible for self-replication.

Now, I think, it became clearer why we need “start” and “stop” labels. They mark the beginning and end of the virus code. First, we read the file and go through it line by line. When we come across the starting mark, we raise the flag. Add an empty line so that the virus in the source code starts on a new line. We read the file a second time and write the source code line by line. The last step is to write a virus, two indents and the original code. You can mock and write it in some special way — for example, modify all output lines.

Making an executable file

How to run a virus written in a scripting language on a victim’s machine? There are two ways: either to somehow make sure that the interpreter is installed there, or to pack our creation along with everything you need into a single executable file. The PyInstaller utility serves this purpose. Here’s how to use it.

And enter the command

We wait a bit, and a bunch of files appear in the program folder. You can safely get rid of everything except executables, they will be in the dist folder.

It is said that ever since malware in Python began to appear, antiviruses have become extremely nervous about PyInstaller, even if it comes with a perfectly safe program.

Conclusion

So, we wrote three malicious programs using a scripting language and packaged them using PyInstaller.

Of course, our virus is not the scariest one in the world, and the locker and ransomware still need to somehow be delivered to the victim’s car. At the same time, none of our programs communicate with the C & C server and I have not obfuscated the code at all, so there is still a huge scope for creativity.

Nevertheless, the level of detection by antiviruses turned out to be surprisingly low. It turns out that even the simplest self-written malware can become a threat. So antiviruses are antiviruses, but it will always be unsafe to download random programs from the Internet and run them without thinking.

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:

Читать:
Как взять значение из combobox c

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!

Write a Simple Virus in Python

Sometimes we find our files being infected with a computer virus . In this tutorial, we will get introduced to the concept of a virus by writing a simple one in Python.

First thing first, let’s get introduced to the definition of a computer virus. A virus is a typical malware program that infects a particular type of file or most files by injecting data or code. It tries to list files in all directories and then inject typical data/code in those files.

Point to be noted; a virus does not replicate itself. It just continuously infects all files in the directories/folders. The malware that replicates itself and consumes hard disk space is typically called a Worm .

If you are interested to write other types of malwares, you can go through my previous posts:

Okay, now, let’s get started writing one.

Requirements

To write a simple virus, we will use the following modules.

os module

Here, module os is the most important one as it will help us to list all the files along with the absolute path. An absolute path starts with the root directory / . For example, if my current working directory is Downloads and there is file named hi.txt inside a subfolder named test_sub . Then

Absolute path is necessary here as while working with numerous files you must know the exact location. Using filenames only, your script do not know where to look for that files.

pathlib module

Here, we use pathlib to retrive the extension of a file. It can be done in multiple ways though, so you may not find this module necessary at all.

datetime and time

datetime and time is used only for the start time of execution. If you want the script to start working right now, you may not need these modules as well.

Virus Class

The initializer method

Now, lets create a virus class that accepts four arguments when it is called.

Here, the infect_string will be used to insert in a file. If the user does not provide an input, the default value is “I am a Virus”.

By default the path is set to be the root directory / . From here, it will browse all subdirectories and files. However, the user can provide a target path as well.

User can define target file extension . If not, the default is set to be python files .py .

User can also provide the target_file_list that conatains all the listed target files. If None , the constructor method set it as an empty list.

Btw, if you are wondering that why the code looks a bit ugly, you can use the following as well.

I just prefer the earlier way to set all default values inside the constructor method. However, the latter is a lot easier to understand and use.

Method to list all target files

here we use another mthod named list_files that lists all files within directories and subdirectories given an initial path.

here, in the method we did the followings:

  1. list all files in the current working directory
  2. iterate over all files and do the followings
    • only consider visible files (avoid hidden files, e.g., starts with dot . in Unix-based systems)
    • get the absolute path using os.path.join
    • retrieve the file extension using pathlib.Path
    • check if it is a directory using os.path.isdir (if yes, call the same function and pass the path to continue digging deeper, in coding world it is called a **recursive function** )
    • Check if the extension matches with target extension (if yes, check whether it is already infected by looking for the string in the file; if string not found, append to the list).

Method to infect the files

Here, we will add another method that can infect (insert/prepend) the string in the given filename.

To prepend the self.infect_string , we first read the whole file and keep the contents in a variable data ; then add our string before the data and write to the file.

point to be noted, in this example as we are using python files, we need to exclude our own file, right? :zany_face:

that’s why I exclude the filename there in the very first condition.

Final method that integrates everything

Now, we can first define when to start our virus.

  • Do you want to set a timer (e.g., 60 seconds), then provide input to the timer while calling this method.
  • Do you want to set a date (e.g., someone’s birthday), then provide input to the target_date while calling this method.

And, then our primary mission begins.

  1. List all target files by calling the list_files method
  2. For each file, insert the string using the infect method

okay, so, here is our code

Main Function

Now, let’s create our main function and run the code

Here, we first create an object of the class. And then call the start_virus_infections method with providing a timer or a date. To avoid hassle, use os.path.abspath(«») , which refers to the current directory only so that you do not get hurt with inserting the string in other necessary python codes you wrote before.

Testing

To have a easier testing environment, create a few python files in the same directory and check if your virus is able to insert the string to those files. To make things easier, run the following code to create three python files (create a seperate script).

Both codes are available in GitHub.

that’s all folks, you can look at other security concept tutorials in python. I have created a repository for that. I am planning to provide security concepts by writing python codes. Please feel free to put a star if you like the repository.

Also, the associated blog post links are available in the ReadMe file over there.

Как написать шифровальщик на Python

Как написать шифровальщик на Python

Почему кому-то может прийти в голову писать малварь на Python? Мы сделаем это, чтобы изучить общие принципы вредоносостроения, а заодно вы попрактикуетесь в использовании этого языка и сможете применять полученные знания в других целях. К тому же вредонос на Python таки попадается в дикой природе, и далеко не все антивирусы обращают на него внимание.

Чаще всего Python применяют для создания бэкдоров в софте, чтобы загружать и исполнять любой код на зараженной машине. Так, в 2017 году сотрудники компании Dr.Web обнаружили Python.BackDoor.33, а 8 мая 2019 года был замечен Mac.BackDoor.Siggen.20. Другой троян — RAT Python крал пользовательские данные с зараженных устройств и использовал Telegram в качестве канала передачи данных.

Мы же создадим три демонстрационные программы: локер, который будет блокировать доступ к компьютеру, пока пользователь не введет правильный пароль, шифровальщик, который будет обходить директории и шифровать все лежащие в них файлы, а также вирус, который будет распространять свой код, заражая другие программы на Python.

Как написать локер, шифровальщик и вирус на Python

Несмотря на то что наши творения не претендуют на сколько-нибудь высокий технический уровень, они в определенных условиях могут быть опасными. Поэтому предупреждаю, что за нарушение работы чужих компьютеров и уничтожение информации может последовать строгое наказание. Давайте сразу договоримся: запускать все, что мы здесь описываем, вы будете только на своей машине, да и то осторожно — чтобы случайно не зашифровать себе весь диск.

Вся информация предоставлена исключительно в ознакомительных целях. Ни автор, ни редакция не несут ответственности за любой возможный вред, причиненный материалами данной статьи.

Настройка среды

Итак, первым делом нам, конечно, понадобится сам Python, причем третьей версии. Не буду детально расписывать, как его устанавливать, и сразу отправлю вас скачивать бесплатную книгу «Укус питона» (PDF). В ней вы найдете ответ на этот и многие другие вопросы, связанные с Python.

Дополнительно установим несколько модулей, которые будем использовать:

На этом с подготовительным этапом покончено, можно приступать к написанию кода.

Создание локера

Идея — создаем окно на полный экран и не даем пользователю закрыть его.

Теперь возьмемся за основную часть программы.

Здесь pyautogui.FAILSAFE = False — защита, которая активируется при перемещении курсора в верхний левый угол экрана. При ее срабатывании программа закрывается. Нам это не надо, поэтому вырубаем эту функцию.

Чтобы наш локер работал на любом мониторе с любым разрешением, считываем ширину и высоту экрана и по простой формуле вычисляем, куда будет попадать курсор, делаться клик и так далее. В нашем случае курсор попадает в центр экрана, то есть ширину и высоту мы делим на два. Паузу (sleep) добавим для того, чтобы пользователь мог ввести код для отмены.

Сейчас мы не блокировали ввод текста, но можно это сделать, и тогда пользователь никак от нас не избавится. Для этого напишем еще немного кода. Не советую делать это сразу. Сначала давайте настроим программу, чтобы она выключалась при вводе пароля. Но код для блокирования клавиатуры и мыши выглядит вот так:

Создадим функцию для ввода ключа:

Тут всё просто. Если ключ не тот, который мы задали, программа продолжает работать. Если пароли совпали — тормозим.

Последняя функция, которая нужна для работы окна-вредителя:

На этом наш импровизированный локер готов.

Создание шифровальщика

Этот вирус мы напишем при помощи только одной сторонней библиотеки — pyAesCrypt. Идея — шифруем все файлы в указанной директории и всех директориях ниже. Это важное ограничение, которое позволяет не сломать операционку. Для работы создадим два файла — шифратор и дешифратор. После работы исполняемые файлы будут самоудаляться.

Сначала запрашиваем путь к атакуемому каталогу и пароль для шифрования и дешифровки:

Дальше мы будем генерировать скрипты для шифрования и дешифровки. Выглядит это примерно так:

Переходим к файлам, которые мы будем использовать в качестве шаблонов. Начнем с шифратора. Нам потребуются две стандартные библиотеки:

Пишем функцию шифрования (все по мануалу pyAesCrypt):

Вместо str(password) скрипт-генератор вставит пароль.

Важные нюансы. Шифровать и дешифровать мы будем при помощи буфера, таким образом мы избавимся от ограничения на размер файла (по крайней мере, значительно уменьшим это ограничение). Вызов os.remove(file) нужен для удаления исходного файла, так как мы копируем файл и шифруем копию. Можно настроить копирование файла вместо удаления.

Теперь функция, которая обходит папки. Тут тоже ничего сложного.

В конце добавим еще две строки. Одна для запуска обхода, вторая — для самоуничтожения программы.

Здесь снова будет подставляться нужный путь.

Вот весь исходник целиком.

Теперь «зеркальный» файл. Если в шифровальщике мы писали encrypt, то в дешифраторе пишем decrypt. Повторять разбор тех же строк нет смысла, поэтому сразу финальный вариант.

Итого 29 строк, из которых на дешифровку ушло три. На случай, если какой-то из файлов вдруг окажется поврежденным и возникнет ошибка, пользуемся отловом исключений (try…except). То есть, если не получиться расшифровать файл, мы его просто пропускаем.

Создание вируса

Здесь идея в том, чтобы создать программу, которая будет заражать другие программы с указанным расширением. В отличие от настоящих вирусов, которые заражают любой исполняемый файл, наш будет поражать только другие программы на Python.

На этот раз нам не потребуются никакие сторонние библиотеки, нужны только модули sys и os. Подключаем их.

Создадим три функции: сообщение, парсер, заражение.

Функция, которая сообщает об атаке:

Сразу вызовем ее, чтобы понять, что программа отработала:

Обход директорий похож на тот, что мы делали в шифровальщике.

В теории мы могли бы таким же образом отравлять исходники и на других языках, добавив код на этих языках в файлы с соответствующими расширениями. А в Unix-образных системах скрипты на Bash, Ruby, Perl и подобном можно просто подменить скриптами на Python, исправив путь к интерпретатору в первой строке.

Вирус будет заражать файлы «вниз» от того каталога, где он находится (путь мы получаем, вызвав os.getcwd()).

В начале и в конце файла пишем вот такие комментарии:

Чуть позже объясню зачем.

Дальше функция, которая отвечает за саморепликацию.

Теперь, думаю, стало понятнее, зачем нужны метки «старт» и «стоп». Они обозначают начало и конец кода вируса. Сперва мы читаем файл и построчно просматриваем его. Когда мы наткнулись на стартовую метку, поднимаем флаг. Пустую строку добавляем, чтобы вирус в исходном коде начинался с новой строки. Читаем файл второй раз и записываем построчно исходный код. Последний шаг — пишем вирус, два отступа и оригинальный код. Можно поиздеваться и записать его как-нибудь по-особому — например, видоизменить все выводимые строки.

Создание исполняемого файла

Как запустить вирус, написанный на скриптовом языке, на машине жертвы? Есть два пути: либо как-то убедиться, что там установлен интерпретатор, либо запаковать созданный нами шифровальщик вместе со всем необходимым в единый исполняемый файл. Этой цели служит утилита PyInstaller. Вот как ей пользоваться.

И вводим команду

Немного ждем, и у нас в папке с программой появляется куча файлов. Можете смело избавляться от всего, кроме экзешников, они будет лежать в папке dist.

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

Я решил проверить, что VirusTotal скажет о моих творениях. Вот отчеты:

  • файл Crypt.exe не понравился 12 антивирусам из 72;
  • файл Locker.exe — 10 антивирусам из 72;
  • файл Virus.exe — 23 антивирусам из 72.

Худший результат показал Virus.exe — то ли некоторые антивирусы обратили внимание на саморепликацию, то ли просто название файла не понравилось. Но как видите, содержимое любого из этих файлов насторожило далеко не все антивирусы.

Итого

Итак, мы написали три вредоносные программы: локер, шифровальщик и вирус, использовав скриптовый язык, и упаковали их при помощи PyInstaller.

Безусловно, наш вирус — не самый страшный на свете, а локер и шифровальщик еще нужно как-то доставлять до машины жертвы. При этом ни одна из наших программ не общается с C&C-сервером и я совсем не обфусцировал код.

Тем не менее уровень детекта антивирусами оказался на удивление низким. Получается, что даже самый простой вирус шифровальщик может стать угрозой. Так что антивирусы антивирусами, но скачивать из интернета случайные программы и запускать их не думая всегда будет небезопасно.

Related Posts