Exploring Encryption for Messaging in Python

This is a post for an encryption program written in Python3 as a project to showcase and grow my knowledge in python, encryption, encoding, and Linux/Windows command line interface (CLI) implementations to code.

This project will be ongoing and each section will have a date marking the date of the posting. The actual post date will represent the creation of the post, not the most recent entry.

The files can be accessed from Github and the title of each update will link directly to that version of the program.

Humble Beginnings: XOR (June 18th 2023)

As someone with a intermediate understanding of python writing a simple program to encode messages using an XOR cipher was not to difficult, only running into common problems (spelling, capitalization, etc.).

This program started with the idea of a simple and fun way to send messages back in forth with a friend in a multi-person Discord server without others being able to understand what was being said.

def xor(msg, key = 'default', encode = False, decode = False):
	if encode:
		encrypted = ""
		key_index = 0
		for char in msg:
			#convert character to ascii code
			char_code = ord(char)
			#get the corresponding key char
			key_char = key[key_index % len(key)]
			#convert key char to ascii code
			key_code = ord(key_char)
			#XOR with key
			encrypted_char = char_code ^ key_code
			#convert enc ascii back to char
			encrypted += chr(encrypted_char)
			key_index += 1
		return encrypted
	if decode:
		decrypted = ""
		key_index = 0
		for char in msg:
			#convert char to ascii
			char_code = ord(char)
			#get the corresponding key char
			key_char = key[key_index % len(key)]
			#convert key char to ascii code
			key_code = ord(key_char)
			#XOR with key
			decrypted_char = char_code ^ key_code
			#convert dec ascii back to char
			decrypted += chr(decrypted_char)
			key_index += 1
		return decrypted

super_secret = "This is a secret message"
encrypted_data = xor(super_secret, "password", encode = True)
decrypted_data = xor(encrypted_data, "password", decode = True)

print("the cipher text is: ")
print(encrypted_data)
print("The plain text is: ")
print(decrypted_data)

Problems

There were few problems that were run into during this section of the program, a few being:

  • The first issue was a TypeError where the original code didn’t have the section of key iteration and casting it to its ASCII value. This error was thrown because it was expecting a integer but was being supplied a string
    • The second part of this error was when I changed the key to its ASCII value it was giving the error when using the ord function as I was supplying the entire key instead of iterating letter by letter.

Lessons Learned

I am a firm believer in the John C. Maxwell quote “You never really know something until you [could] teach it to someone else.” So I try to make sure that I understand why and how things work before considering a problem or project finished.

  • I learned in more depth how the XOR and other logic gate functions work
  • I continued to grow my python knowledge

Next Steps

The next steps I hope to add the ability to add the message, key, and encode/decode values from the CLI and adding another type of encryption or encoding.

This code also only reliably works in a sandbox where it feeds it straight from encode to decode through the variables, so the next version will encode the data to base64 so that it can be transmitted.

Better Experience (June 19, 2023)

This version of the program added Base64 encoding to the program so that the encrypted text was able to be copied and pasted and sent in common text.

A simple input based menu was also created for the program so the values didn’t need to be hard coded.

The files were also added to Github so that the updates can be seen and older versions of the program can be viewed.

Problems

I only ran in to minor problems in this version of the program, all of which can be chalked up to me stretching my programming legs.

Lessons Learned

  • I brushed up on my input based menu skills
  • I learned about the getpass library and implemented it for the key
  • I read up on and added the base64 library

Next Steps

I plan to add another, more complicated to implement form of encryption.

WannaCry, How does it work?

Overview

Wanancry (2017) is a piece of malware described as ransomeware1 and a worm2 that, when introduced to an unpatched Windows machine, would encrypt the files and require a ransom payment of Bitcoin. Paying this fee would allegedly decrypt the files and free the infected machine.

How were devices infected?

Devices were infected using an exploit called EternalBlue. This exploit used a vulnerability in Windows SMB (Server Message Block)3 that allowed a remote code execution from any unpatched devices with SMBv1 enabled. Microsoft patched this vulnerability two months prior, which would have protected all vulnerable devices. Many users and organizations do not update operating systems regularly; this allowed WannaCry to spread even with the patch out.

What did WannaCry Do?

The TLDR of WannaCry (less technical)

When a device was infected with WannaCry, most files would be encrypted. This includes .docx, .gif, .png, .jpeg, .jpg, .vmdk, .mp3, .class, .zip, .backup, .sqlitedb, and many more important file extensions4. A message would then pop up demanding the payment of $300 in bitcoin to a given wallet address ($600 after 3 days). After 7 days the files would become unrecoverable.

Wanna Decrypt0r

  • 1 – Two timers indicating the time that the price will be raised (3 days) and the time until all files will be unrecoverable (7 days)
  • 2 – The bitcoin wallet for users to (allegedly) decrypt files
  • 3 – Paragraph stating the timeframes for payment

The Kill-switch

WannaCry would reach out to the domain “http://www[.]iuqerfsodp9ifjaposdfjhgosurijfaewrwergwea[.]com,” and if the connection was not successful, the malware would continue infecting the machine. Once this piece of code was found, MalwareTech registered the domain. Using this newly registered site, which only cost $10.69, this strain of WannaCry was stopped in its tracks. Though new infections were prevented, those that had already taken place were still left to be dealt with.

There is no apparent reason why this was contained within the malware. The leading theory is that it is an intentional kill-switch that the creator(s) of WannaCry could use to stop the worm at any time.

Ransomware Mitigation

One of the best ways to protect oneself from ransomware is not to download any files from untrusted sources, click on emails from unknown senders (always check the domain), and keep software up to date. Updating software would have protected many from the rampage of WannaCry as the EternalBlue vulnerability was patched in March of 2017 and WannaCry began in May of 2017.

Keeping up-to-date backups is also a great way to fix a device if it happens to be infected. Paying the ransom has no guarantee of freeing a machine, but the malware will be removed if a device can be restored to a previous state before it was infected.

Extra

Ransomware –

Ransomware is a strain of malware that blocks a users access from files or an entire device with the promise that if a price is payed, access would be restored.

Worm –

A worm is a malware type that replicates itself from device to device without the help of a user.

SMB –

Server Message Block is a protocol created by Microsoft that is used for shared access to files and devices (printers) across a network.

File Extension List –

.123.3dm.3ds.3g2.3gp.602.7z.ARC.PAQ.accdb
.aes.ai.asc.asf.asm.asp.avi.backup.bak.bat
.bmp.brd.bz2.c.cgm.class.cmd.cpp.crt.cs
.csr.csv.db.dbf.dch.der.dif.dip.djvu.doc
.docb.docmdocx.dot.dotm.dotx.dwg.edb.eml.fla
.flv.frm.gif.gpg.gz.h.hwp.ibd.iso.jar
.java.jpeg.jpg.js.jsp.key.lay.lay6.ldf.m3u
.m4u.max.mdb.mdf.mid.mkv.mml.mov.mp3.mp4
.mpeg.mpg.msg.myd.myi.nef.odb.odg.odp.ods
.odt.otp.ots.ott.p12.pas.pdf.pem.pfx.php
.pl.png.pot.potm.potx.ppam.pps.ppsm.ppsx.ppt
.pptm.pptx.ps1.psd.pst.rar.raw.rb.rtf.sch
.sh.sldm.sldx.slk.sln.snt.sql.sqlite3.sqlitedb.stc
.std.sti.stw.suo.svg.swf.sxc.sxd.sxi.sxm
.sxw.tar.tbk.tgz.tif.tiff.txt.uop.uot.vb
.vbs.vcd.vdi.vmdk.vmx.vob.vsd.vsdx.wav.wb2
.wk1.wks.wma.wmv.xlc.xlm.xls.xlsb.xlsm.xlsx
.xlt.xltm.xltx.xlw.zip
Github list

Types of Hackers

White Hat: Ethical Hackers

White hat hackers are hackers that are hired or contracted by companies to find vulnerabilities in internal systems, this is also called a penetration test. These hackers are given a scope, this defines what systems the hacker can attack.

Example of a Scope:

  • Company A hires Penetration Tester X to run a test on its web server. Company A, in writing, tells X that they may use any public facing resources (such as Company A‘s Website), but may not enter the company’s internal network or compromise employee credentials. Thus, giving a clear picture of what systems X can attack.

A large part of penetration testing is the six phases used as a step-by-step guide to accessing a system.

Penetration Testing Phases:

  1. Planning – This is the stage where the hacker(s) are given the scope of the assignment, meet with the client and discuss expectations and goals of the test.
  2. Reconnaissance – During the recon phase, the hacker(s) are tasked with gaining as much information as possible. This is done using manual recon sources such as Google searches, Google dorking, social media, etc or automated recon tools such as Recon-ng, Maltego, The Harvester, and many more.
  3. Scanning – In the scanning phase, the goal is to find vulnerabilities. Depending on the scope of the test, this can mean running port scans on hosts using NMAP, finding directories on a web application using Dirbuster, etc.
  4. Gain Access – Using the vulnerabilities found in the scanning phase, the hacker(s) will exploit the systems to make their way towards the goal that was defined during the planning phase. This could be gaining access to a database, obtaining administrator credentials, etc.
  5. Maintain Access – This step may be prohibited in the scope of the test as maintaining access often requires installing a backdoor or stealing credentials. Many companies (rightfully so) do not want the ability to remotely access their systems, only to know that it is possible.
  6. Reporting – The final step is when the company and the hacker(s) meet up and discuss the findings and what can be done to mitigate the threats introduced by those vulnerabilities.

There are also multiple types of penetration tests. This includes Black Box, Gray Box, and White Box. This color designation is separate from the one used for the “hat” categories of hackers.

Black Box:

  • Penetration Testers are given little to no information.
  • Network Recon may be required. (depending on the scope)
  • All penetration testing phases may be required. (planning, reconnaissance, scanning, gain access, maintain access [this step may go against the scope], reporting)

White Box:

  • Penetration Testers are given ample information.
    • For software tests – source code may be given
    • For network security tests – network map and netblocks may be given
    • For internal test – credentials and physical maps may be given
  • Due to amount of given information, tasks may need to be delegated among a team of testers.

Grey Box:

  • Given minimal information.
  • Due to the amount of information, the tester is able to focus on a specific task.
    • Ex: Tester X is given the SSID and Security key and is asked to map devices on that network.

Black Hat: Malicious Hackers

Black hat hackers are on the opposite side of the coin as the white hat. While the white hat hackers are building the defenses to protect businesses, black hat hackers are trying to bypass the systems put in place by ethical hackers. The goals of these hackers are based on personal gain, money, power, etc.

These hackers have almost the exact same process as white hat hackers. Those steps are planning, reconnaissance, scanning, gaining access, maintaining access, but the one difference is instead of reporting, they pillage. Once they find the intended goal of the attack (user database, credit cards, passwords, etc.) they steal (pillage) that information and cover their tracks on the way out.

Here are some examples of Black Hat hacks/hackers:

Grey Hat: The Middle Ground Hackers

Grey hat hackers have the skills of a White Hat hacker but violate the law by breaking into systems like a Black Hat hacker. The difference between Black and Grey Hat hackers is the motivation. Black Hats hack for personal gain, Grey Hats hack to find vulnerabilities and help those affected (without being hired as a White Hat).

It has become harder for Grey Hat hackers to disclose vulnerabilities to companies due to how common it has been to prosecute those hackers. This is because breaking into a system is illegal regardless of intentions.

Script Kiddie: Newbie Hackers

Script Kiddies are generally hackers that are still developing the skills to write their own programs and thus, use programs that are downloadable and easy to use to run their exploits. They are generally motivated by the thrill of the hack or the reaction of their peers.

Common tools used by Script Kiddies:

  • Wireshark
  • Metasploit
  • Social Engineering Toolkit
  • Online DDoS tools
  • Nmap
  • and other tools that are easy to learn the basic functions

These may also be used by Security Professionals but, Script Kiddies use them without understanding how they work or the possible backlash that can come from using it on someone else’s network.

Nation State Actors: Government Threat Protection

CISsecurity defines Nation-State Actors as those who “aggressively target and gain persistent access to public and private sector networks to compromise, steal, change, or destroy information. They may be part of a state apparatus or receive direction, funding, or technical assistance from a nation-state”

In other terms, Nation State-Sponsored Hackers are those funded or directed by a government body to target other nations’ private or public sectors to gain, change, or destroy information.

Nation-State threats on the US usually come from one or more of the countries Iran, North Korea, China, and/or Russia.

Hacktivist: Activism Hackers

Hacktivism is the use of hacking to promote social/political change, usually promoting freedom of speech, information, or human rights.

The biggest Hacktivism group that most people inside (and even outside) the field of technology know of is Anonymous. Anonymous uses hacking to promote the freedom of the general population. Some examples of this include:

  • War on ISIS – After the Paris terror attacks (2015) Anonymous declared war on ISIS
  • War on Russia (2022) – After Russia invaded Ukraine, Anonymous took down Russian news sites and leaked databases of Russian government employees
  • Project Changology (2008) – Anonymous combats Scientology’s use of internet censorship to promote their ideologies