Forem Creators and Builders 🌱

Cover image for CryptoJacking: Detection & Prevention in Python
Mariah Dominique Rucker
Mariah Dominique Rucker

Posted on • Updated on

CryptoJacking: Detection & Prevention in Python

Cryptocurrency is a new digital currency that gains popularity year by year and has turned into new ways for fraud like cryptojacking. Malware in form of cryptojacking results in mining of cryptocurrency with no approval thereby incurring huge financial losses and slows down efficiency of the hosting site. Nevertheless, one can locate and avert cryptojacking by writing them in python. This tutorial discusses how one can use python to identify and prevent crypto jacking.

How CryptoJacking Works

Here are the steps to create a script in Python that detects and prevents cryptojacking:

  1. Research what is cryptojacking and how it can be detected.
  2. Discovery of the required tools and scripts for making the script.
  3. Program code to spot and obstruct cryptojacking.
  4. Ensure you test the script to confirm that it works well.
  5. Place the script in the desired environment.

Import the necessary libraries:

import psutil
import requests
import time
Enter fullscreen mode Exit fullscreen mode

Create a function or routine which determines whether the CPU use is over and beyond the specified point. It can also be an indication of a cryptojacking attack whereby the CPU usage is high.

Function check_cpu_usage() {
  // Get the current CPU usage
  let cpu_usage = get_cpu_usage();

  // Check if the usage is above a certain threshold
  if (cpu_usage > threshold) {
    // Alert the user that their CPU usage is high
    alert("Your CPU usage is high. This may be a sign of cryptojacking.");
  }
}
Enter fullscreen mode Exit fullscreen mode

Develop a script that tests the IP address of the node against a list of mining pools to establish whether the IP address belongs to any of the pools.

def check_mining_pool():
    mining_pools = ["stratum+tcp://eu1.ethermine.org:4444",
                    "stratum+tcp://us1.ethermine.org:4444",
                    "stratum+tcp://us2.ethermine.org:4444",
                    "stratum+tcp://eu1.nanopool.org:9999",
                    "stratum+tcp://us-east1.nanopool.org:9999",
                    "stratum+tcp://us-west1.nanopool.org:9999"]
    r = requests.get('https://api.ipify.org')
    ip_address = r.text
    for pool in mining_pools:
        if ip_address in pool:
            return True
    return False
Enter fullscreen mode Exit fullscreen mode

Make a while loop running and having it calling the check_cpu_usage() and check_mining_pool() functions. Print a warning message then break the loop if either of these functions is true.

def main():
    while True:
        if check_cpu_usage():
            print("Warning: High CPU usage detected. Possible cryptojacking.")
            break
        if check_mining_pool():
            print("Warning: Connected to a known mining pool. Possible cryptojacking.")
            break
        time.sleep(60)
Enter fullscreen mode Exit fullscreen mode

Therefore, begin the script by calling on the main() function.

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

It runs a script that looks at every 60th second for CPU usage and network connectivity of mining pools. This can be done by carrying out at least of two kinds of checks that may alert a potential cryptojacking with an issuing alert and end this operation. The threshold and mining pool are adjustable by your own desire.

CryptoJacking Process

There are more than one things you can do aside to be on the lookout for cryptojacking.

  1. Create a Python script: Educate people on this kind of cybercrime and its risks. This is beneficial as it enables you and people at large to know the risk involved in cryptojacking and how one can avoid it.

  2. Keep your software up to date: Cryptojacking malware can exploit weaknesses found in older versions of operating systems, browsers, or other applications installed on a computer.

  3. Use an ad blocker: It is possible to counteract cryptojacking malware through use of an ad blocker, since some sites incorporate this type of ads.

  4. Use antivirus software: Cryptojacking is a malware that can be discovered by antivirus programs, hence stopping it to invade into a computer.

  5. Be cautious of suspicious links: Remember that the malicious cryptojacking software can come via dodgy e-mails and pages. Ensure your safety by abstaining from opening any link sent form unfamiliar contacts.

  6. Use a virtual private network (VPN): Using a VPN like encrypting your sent data can also mask your IP, hence shielding your computer from crypto jacked attacks.

To this end, adopting the cited python script along with other best practices outlined above will greatly reduce the possibility of being infected by cryptojackers and thus maintain confidentiality not just of your personal data but also for your computer.

Here are some more measures you can take in Python to prevent cryptojacking:

Use browser extensions: You can also download other browser extensions such as NoCoin that will work by identifying and stopping any cryptojacking scripts detected in your browser.

import requests

def check_browser_cryptojacking():
    url = "https://raw.githubusercontent.com/hoshsadiq/adblock-nocoin-list/master/nocoin.txt"
    r = requests.get(url)
    nocoin_list = r.text.split("\n")
    active_extensions = [
        "NoCoin"
    ] # list of active browser extensions
    for extension in active_extensions:
        if extension == "NoCoin":
            for site in nocoin_list:
                if site in driver.current_url:
                    return True
    return False
Enter fullscreen mode Exit fullscreen mode

In case, the NoCoin extension is activated and the current site belongs to the NoCoin blocklist, this function outputs true, meaning that cryptojacking is present.

Monitor network traffic: One may use a monitoring tool such as Wireshark to track down network activities and identify unlawful links with the mining pools.

import pyshark

def check_network_traffic():
    cap = pyshark.LiveCapture(interface='eth0', bpf_filter='port 3333')
    cap.sniff(timeout=60)
    for packet in cap:
        if packet.eth.type == 2048:
            ip_layer = packet[1]
            tcp_layer = packet[2]
            if ip_layer.dst == '185.244.25.214' and tcp_layer.dstport == '3333':
                return True
    return False
Enter fullscreen mode Exit fullscreen mode

If a connection is detected on the eth0 interface to the mining pool at 185.244.25.214: After 60 seconds, the function can give true, which may be indicative of a suspected cryptomining activity.

Minimize Cryptojacking exposure by implementing the above discussed practices.

GitHub: github.com/mariahrucker
LinkedIn: linkedin.com/in/mariahrucker
Instagram: instagram.com/techmariah
Other: linktr.ee/mariahrucker

Top comments (0)