# Predictable Random Numbers

Well that title is odd, right?

What I’m wanting to do here is demonstrate one way to generate random numbers using a seed. The requirement here is we need to test a number at any given time, this will be useful if we intend to use the process as a token of sort, think RSA SecureID.

Anyways I wanted to make a implementation that used Python and didn’t cost me hundreds
of dollars.

The first thing I needed was a changing number, but one that only changed every 60 seconds.
I decided to use a timestamp here of Year, Month, Day, Hour, Minute in UTC format.
To do this I used the Python time function’s strftime method:

```In [1]: import time

In [2]: timestamp = time.strftime('%Y%m%d%H%M', time.gmtime())

In [3]: timestamp
Out[3]: '201312101409'```

Creating a random number using this format is useless since anyone who knows the time
can recreate the output token. To resolve this I’m going to use a salt mixed in with this time string.

A 4 digit key can be used as our salt just fine:

`In [1]: key = '1234'`

Now we can combine the two in order to make our seed:

```In [1]: myseed = key + timestamp

In [2]: myseed
Out[2]: '1234201312101409'```

Excellent we have a salted number we can use as a seed, lets go ahead and use the Python
random library to generate some random ranges using this seed:

```In [1]: r = random.Random(myseed)

In [2]: r.randrange(000000, 999999)
Out[2]: 807766```

The beauty about Python’s Random class is it takes a seed for generating random number,
this way we can always guess randomness of the numbers. I also used a output number of
000000 through 999999 (that is a 6 digit random number starting with all 0s and ending
with all 9s).

Below is a few functions thrown together:

```import time
import random

def get_timestamp():
return time.strftime('%Y%m%d%H%M', time.gmtime())

def get_token(key):
r = random.Random('%s%s' % (key, get_timestamp()))
return r.randrange(000000, 999999)

def check_token(key, token):
cur = get_token(key)
if token == cur:
return True
return False```

Using these functions lets create a token and track at what time it was created.

```In [1]: !date
Tue Dec 10 08:37:19 CST 2013

In [2]: token = get_token(1234)

In [3]: token
Out[3]: 771259```

Lets check if this token is valid right after creating it:

```In [1]: !date
Tue Dec 10 08:37:23 CST 2013

In [2]: check_token(1234, token)
Out[2]: True```

And finally lets wait about a minute and check again:

```In [1]: !date
Tue Dec 10 08:38:11 CST 2013

In [2]: check_token(1234, token)
Out[2]: False```

And there you have it, a working proof of concept.

I would like to mention this is purely concept code, it is not very secure. I am also not sure
if the python random library is portable from Python version to version, or even instance to instance.

# Lucky Buddha Beer

A new unique beer we found at the local convenience store.

# Winter is Coming!

It has been getting unnaturally cold in Austin Texas this December,
just have a look at our weekend forecast.

If that forecast doesn’t get my point across, this image should:

Anyways, back on topic. With the freezing weather the wife decided it was time
for home made Pho! Throw in come spices and we have one of my favorite
cold day meals :)

# Python chroot and exit chroot

I know this has been written a few time online, but the last time I needed to read up on it, it took a little long to find the answer.

What I wanted to do was to chroot in to a new root, then exit that chroot via python.

Below we have my current working directory that is /root, take a look at what we have in the directory:

```In [1]: import os

In [2]: os.system('pwd')
/root
Out[2]: 0

In [3]: os.system('ls -l /root')
total 12
drwxr-xr-x 3 root root 4096 Dec  5 15:47 filesystems
drwxr-xr-x 3 root root 4096 Dec  5 15:01 iso
drwxr-xr-x 3 root root 4096 Dec  5 15:14 squashfs
Out[3]: 0```

I’m then going to keep track of my current root, this part is very important:

`In [4]: real_root = os.open('/', os.O_RDONLY)`

And change to a new root, I’m going to use a archlinux squashfs I had laying around:

```In [5]: os.chroot('/root/squashfs/archlinux/')

In [6]: os.chdir('/root')```

We are now in the new room, lets have a look around:

```In [7]: os.system('pwd')
/root
Out[7]: 0

In [8]: os.system('ls -l /root/')
total 16
-rw-r--r-- 1 root root 7725 Dec  5 21:12 install.txt```

And lets go ahead and back out of this chroot back up to the real root filesystem:

```In [9]: os.fchdir(real_root)

In [10]: os.chroot('.')

In [11]: os.chdir('/root')```

And lets verify our old data is in place:

```In [12]: os.system('pwd')
/root
Out[12]: 0

In [13]: os.system('ls -l /root/')
total 12
drwxr-xr-x 3 root root 4096 Dec  5 15:47 filesystems
drwxr-xr-x 3 root root 4096 Dec  5 15:01 iso
drwxr-xr-x 3 root root 4096 Dec  5 15:14 squashfs```

# You are Welcome Deckard Cain!

This weekend I brushed off a few computers and setup Diablo II Lord of Destruction
for the family!

I used to play this game for days on end back in my high school years
(Loved hardcore online play). The wife even played a bit of single player,
so I figured it was time to introduce it to the kids!

Below we have the kids about to be introduced to an truly awesome RPG
video game:

# A Game of Catan

The Saturday two days after Thanksgiving seems like a perfect time to play Settlers of
Catan
. This is one of the best strategic games I own, and we love to play it as a family.

Below we got my two sons ready to start placement of roads, settlements, and cities!

And another action shoot of the wife giving a hand on resource collection.

This was when we decided to take a short snack break, YUM!! As you can see the game
is getting intense!

# Get Interface Golang Part 2

Wanted to share a few updates and tweaks to the original Get Interface name by hardware address code. The below is broken up in to functions to help with code re-useability .

If also prints all interface names and hardware address when no command line argument are present.

```package main

import (
"net"
"fmt"
"os"
"strings"
)

// Use the net library to return all Interfaces
// and capture any errors.
func getInterfaces() ([]net.Interface) {
interfaces, err := net.Interfaces()
if err != nil {
panic("Unable to get interfaces.")
}
return interfaces
}

// Use the net library to get Interface by Index number
// and capture any errors.
func getInterfaceByIndex(index int) (*net.Interface) {
inter, err := net.InterfaceByIndex(index)
if err != nil {
panic("Unable to get interface by index")
}
return inter
}

// Use the net library to get Interface by Name
// and capture any errors
func getInterfaceByName(name string) (*net.Interface) {
inter, err := net.InterfaceByName(name)
if err != nil {
panic("Unable to get interface by name")
}
return inter
}

// Using the net library we will loop over all interfaces
// looking for the interface with matching mac_address.
func getInterfaceByHardwareAddress(mac string) (net.Interface) {
interfaces := getInterfaces()
for _, inter := range interfaces {
if strings.ToUpper(mac) == strings.ToUpper(inter.HardwareAddr.String()) {
return inter
}
}
panic("Unable to find interface with Hardware Address.")
}

func main() {

args := os.Args
// If we have only 2 arguments we will assume the
// second is mac_address.
if len(args) == 2 {
fmt.Println(inter.Name)

// If no arguments were passed in lets just return
// a list of all interface names and hardware addresses.
} else if len(args) == 1 {
for _, inter := range getInterfaces() {
}

// If the number of command line arguments are not expected
// lets panic and explain why.
} else {
panic("We require one (mac_address) or no command line arguments.")
}

}```

Usage looks something like this:

```\$ go build get_interface.go

\$ ./get_interface
lo
en0 12:34:56:68:90:00

\$ ./get_interface 12:34:56:68:90:00
en0```

# Get Interface name by hardware address

At work we have had a need for getting a interface name by mac address and are in a
environment that doesn’t have many common Linux tools (nor would I want to regex it as the
environment will constantly be changing).

My first solution was to to write a C program (about 125 lines) which used the linux/rtnetlink
library. However, now that I’m looking at Golang I figured why not rewrite this (which is only about 40 lines).

Below is the code, hopefully the comments explain the solution.

```package main

import (
"net"
"fmt"
"os"
)

func main() {

// First lets check our command line arguments and be sure we
// have a single input value which we will assume is mac_address.
args := os.Args
if len(args) != 2 {
panic("This binary takes a single argument of interface name.")
}

// Get a list of all interfaces on the machine.
interfaces, err := net.Interfaces()
if err != nil {
panic("Unable to get interfaces.")
}

// Loop over all interfaces
for i := range interfaces {

// Get the interfaces Index and then load
// the interface by Index.
id := interfaces[i].Index
inter, err := net.InterfaceByIndex(id)

if err != nil {
panic("Unable to get interface by id")
}

// If our command line input matches our HardwareAddr
// this is the MAC_ADDRESS you seek.
if args[1] == inter.HardwareAddr.String() {
fmt.Println(inter.Name)
}
}
}```

And the code works something like this:

```\$ ./get_interface 12:34:56:78:90:00
en4```