Перейти к содержимому

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

  • автор:

How to Make a Simple Trojan with Python

For the ones who didn’t know yet, a Trojan Horse Attack consists of embedding en exploit in an innocent-looking Application, or even in a document. As you might have guessed today we will embed a backdoor into a Kivy-made GUI. This attack is quite simple, the only thing you need to know is just some python and networking basics. Let us get started!

Enumeration

Requirements

To get started, let’s install the required libraries:

The Trojan

The Backdoor

Among the many things we can embed in a Trojan Horse, I choose to embed a Backdoor.

  • Basically, you can embed everything, but today we’ll embed a backdoor.

The App

This is a key point, we will use the Kivy framework in order to develop an Innocent-looking app, but as the Trojan attack says, it will contain the malicious backdoor, which we’ll use to gain access to the computer. From then, you’ll own the target’s computer.

  • Disclaimer : I am not a graphical apps experienced developer, just use them when I need. So the Trojan we’ll build has not a good graphics, however, you’ll be able to imporove it on your own with the Kivy’s documentation.

As said in the disclaimer, today we won’t focus on the graphic of the App, that can be easily improved just by going to Kivy’s Documentation, rather, we’ll focus on how to embed everything you want(here a Backdoor) in a graphical app.

The Hacker’s Machine

we’ll just need to use Netcat and waitting for the response.open a Terminal Window and:

Start Coding

Now it Is the moment to code our Trojan. Basically, we’ll organize using a function(a malicious one), and a class(the GUI). Such a simple code.

Lines 1/2 : Imported some Kivy basic modules.

Lines 4/6: Imported the Socket and Subprocess module for the backdoor. Then the threading module in order to be able to execute both the malicious code and neutral(the GUI code).

Lines 9/22 : Used the code of the Backdoor Attack in Python article to create a main function that contains the backdoor.

Lines 26/27 : Build a “Hello World” simple GUI.

Lines 31/32 : Created a thread for the main() function and then started it (mal_thread.start()) .

Lines 35/36 : Ran the simple GUI.

On the Attacker Machine

As shown previously, we will be using Netcat to bind a port and listen for incoming connections. In this case, we will use the well known 4444 port. This command will give you no output until the Victim connects.

On the Target Machine

After having started the attack on the Attacker’s Machine, we can complete it on the victim machine.

Just export the code to the target machine and execute it, in order for the backdoor to work make sure you entered the right IP address at line 10.

Once you execute the code on the Victim computer, you’ll see a Kivy app saying “hello world” on the victim’s, and you’ll see this on the Attacker’s side:

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!

Как создать простого трояна на Python

ВНИМАНИЕ! Все представленные ссылки в статьях могут вести на вредоносные сайты либо содержать вирусы. Переходите по ним на свой страхъ и риск. Тот кто целенаправлено зашел на статью знает что делает. Не нажимайте на все подряд бездумно.

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

ВСЯ РАЗМЕЩЕННАЯ ИНФОРМАЦИЯ НА СТРАНИЦАХ ПОРТАЛА ВЗЯТА ИЗ ОТКРЫТЫХ ИСТОЧНИКОВ

БОЛЬШАЯ ЧАСТЬ ИНФОРМАЦИИ ПРЕДОСТАВЛЯЕТСЯ АБСОЛЮТНО БЕСПЛАТНО

Если Вам понравилась статья — поделитесь с друзьями

Любая информация, размещенная на сайте https://rucore.net, предназначена только для свободного изучения пользователями сайта. Наша команда прилагает все усилия для того, чтобы предоставить на этом сайте достоверную и полезную информацию, которая отвечает на вопросы пользователей сайта. Ни при каких обстоятельствах Администрация Сайта не несёт ответственности за какой-либо прямой, непрямой, особый или иной косвенный ущерб в результате использования информации на этом Сайте или на любом другом сайте, на который имеется гиперссылка с данного cайта, возникновение зависимости, снижения продуктивности, увольнения или прерывания трудовой активности, а равно отчисления из учебных учреждений, за любую упущенную выгоду, приостановку хозяйственной деятельности, потерю программ или данных в Ваших информационных системах или иным образом, возникшие в связи с доступом, использованием или невозможностью использования Сайта, Содержимого или какого-либо связанного интернет-сайта, или неработоспособностью, ошибкой, упущением, перебоем, дефектом, простоем в работе или задержкой в передаче, компьютерным вирусом или системным сбоем, даже если администрация будет явно поставлена в известность о возможности такого ущерба.

Используя данный Сайт, Вы выражаете свое согласие с «Отказом от ответственности» и установленными Правилами и принимаете всю ответственность, которая может быть на Вас возложена. А так же Вы можете ознакомиться с полной версией данного «отказа от ответственности» и нашей «политики конфиденциальности» по следующей ссылке.

Цель данного раздела сайта

Основной задачей закрытого раздела сайта, является сбор (парсинг) и сохраниение в базе данных наиболее интересных и качественных материалов из разнообразных источников. Более подробней можно ознакомиться по ссылке.

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

Python Trojan (undetectable)

Spencer Roffey

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.

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

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