Author: xathrya

Home / Author: xathrya

IPTables Configuration Tutorial

November 24, 2015 | Article | No Comments

This article will discuss about linux firewall configuration traditionally (using iptables). If you are searching for newer interface such as UFW and FirewallD, this is not the case.

What is iptables?

IPTables is a user space application program that allows a system administrator to configure tables provided by the Linux Kernel Firewall (implemented as different Netfilter modules) and the chains and rules it stores or simply it used to manage firewall rules. To put it general, iptables is used for configuring the packets flow in the network, rules out what packets can be received, transmitted, or forwarded to or from IPs listed in the tables.

This article will give basic instruction of how iptables work and structured. We will also understanding rules for network management. Later, we might expected reading and writing iptables firewall rules will be easy.

Iptables is installed by default on every linux machine. However if you found no iptables, you can install it.

# Debian-based (Debian, Ubuntu, etc)
apt-get install iptables

# RPM-based (RHEL, Centos, etc)
yum install iptables

# Arch-based (Arch Linux, etc)
pacman -S iptables

# Zypper-based (Opensuse, etc)
zypper install iptables

It’s important to note that iptables operated on Linux Kernel Firewall, so we need root privilege.

Let’s start by executing this command on your linux terminal:

iptables --help

Those command will give summary of what iptables program can do.

On a high-level, iptables might contain multiple tables. Tables might contain multiple chains. It can be built-in or user-defined. Chains might contain multiple rules. Rules are defined for packets and will determine what fate will the packets got.

Summary, the structure will be: iptables -> tables -> chains -> rules.

By default, iptables has 4 built-in tables: filter table, nat table, mangle table, raw table.

1. Filter Table

Default for iptables. If another table is not defined, we will use filter table. The built in chains for filter table are:

  • INPUT chain – incoming packet to firewall. It is the chain for packet coming to local server
  • OUTPUT chain – outgoing from firewall. It is chain generated locally and going out of the local server
  • FORWARD chain – packet for another NIC (Network Interface Card) on the local server. It is chain for packet routed through the local server.

2. NAT table

This is iptable for NAT (Network Address Translation). It has following built-in chains:

  • PREROUTING chain – alter packets before routing. Packet translation happens immediately after the packet comes to the system (and before routing). This helps to translate the destination ip address of the packets to something that matches the routing on the local server. This is used for DNAT (Destination NAT)
  • POSTROUTING chain – alter packets after routing. Packet translation happens when the packets are leaving the system. This helps to translate the source ip address of the packets to something that might match the routing on the destination server. This is used for SNAT (Source NAT).
  • OUTPUT chain – NAT for locally generated packets on the firewall.

3. Mangle table

Table for specialized packet alteration. This table alters QoS bits in the TCP header. Mangle table has the following built-in chains:

  • PREROUTING chain
  • OUTPUT chain
  • FORWARD chain
  • INPUT chain
  • POSTROUTING chain

4. Raw table

This table is for configuration excemptions. This table has following built-in chains:

  • PREROUTING chain
  • OUTPUT chain

The Rules

Rules are the core of firewall. They are the law for your firewall to inspect packets and determine what it will do to them. Giving wrong instruction to firewall (giving wrong rules) will make you end in some uncomfortable situation. For example: it will drive your friends away or even can’t distinguish who are friends and who are enemy. Same with your firewall.

Now let’s see the basic of iptables rules.

  • Rules contain a criteria and a target
  • If the criteria matched, it goes to the rules specified in the target (or) executes the special values mention in the target
  • If the criteria is not matched, it will moves on to the next rule and sequentially see rules until it found matched criteria or nothing at all

The value of possible action executed under the matched condition can be summarized to following values:

  • ACCEPT – The packet will be accepted by firewall
  • DROP – The packet will be discarded
  • REJECT – Similar to DROP but firewall will give inform the sender for packet rejection
  • QUEUE – The packet will be passed to userspace
  • RETURN – The firewall will stop executing the next set of rules in the current chain for this packet and the control will be returned to the calling chain.

For every chains there would be columns like target, prot, opt, source, destination.

  • Target is value or action took when the condition met. We have discuss above.
  • Prot or protocol inform us what protocol used. It can be TCP, UDP, ICMP, etc
  • Opt or special options for the specific rule.
  • Source is source ip-addres of packet.
  • Destination is destination ip-address of packet.

Basic IPTables Command

Now, let’s discuss about command used to manipulating rules. The command will be in bold form, while explanation will be next to it.

-A : append
This command append / add rule at the end of list / table.
example :
iptables -A INPUT : append to INPUT chains on FILTER table.

-D : delete
This command delete one rule pointed by a single number which indicated row. The row number is called index. We have to specify the rule that want to be deleted by specifying row number / index where the rule resided.
example :
iptables –D INPUT 1 : delete first entry on INPUT chain

-R : replace
It replace rule with new rule. The old rule will be overwritten and occupied by new one. The order of overall tables is still same.
example :
iptables –R INPUT 2 –s 192.168.1.3 –j DROP : replace rules on entry number 2

-I : insert
Inserting new rule in the table. When we use insert, our new rule will be place on that index while the rest of index will be moved to next sequence. Simply we can say when we insert a rule to row 1, the old rule will be on row 2 later. And so on.
example :
iptables –I INPUT 3 –s 192.168.1.3 –j ACCEPT : insert rule at entry number 3

-L : list
This command will list every rule we have created.
example :
iptables –t nat –L : list all rules on chain in table nat
iptables –L : list all rules on chain in all tables

-F : flush
This command will flush / delete every rule on a table.
example :
iptables –F OUTPUT : flush the content of OUTPUT

-N : new-chain
This command will create a new chain (table) with a name specified in the argument.
example :
iptables –N cha-IN : create new chain in table filter with name cha-IN

-X : delete-chain
This command will delete chain. The deletable chain is the chain which created by -N command. In order the command executed successfully, the chain must be empty or no rules exists.
example :
iptables –x cha-IN : remove chain cha-IN

-P : policy
This command create a default policy to a chain. When a packet which is not suitable with other rules occured, the default policy will determined what machine will do.
example :
iptables –P INPUT DROP : set default policy that drop packet for every unhandled packet on chain INPUT

E : rename-chain
This command will rename a chain. The renamable chain is the chain which created using -N command.
example :
iptables –E eth0_IN cha-IN : rename eth0_IN to cha-IN

-h : help
print out help for iptables.

IPTables Parameters

Iptables receive parameters. In this section we will discuss what is the function of parameter you find when you type `iptables –help` last time.

-p : protocol

Used for checking protocol type. Common protocols are TCP, UDP, ICMP, and ALL. You can read list of protocol available at /etc/protocols. Whenever we used ! we say as “not”. For example we want every protocol can over our network except ICMP. It means not ICMP.
Contoh :
iptables -A INPUT -p ! icmp : allow packet which is not icmp
iptables -A INPUT -p tcp : allow packet which is tcp

-s : source ip-address

Used for matching packet by source ip-address. The address specified here can be single node address such as 192.168.1.1 or a network by netmaskin such as 192.168.1.0/255.255.255.0 or also can be written as 192.168.1.0/24.
example :
iptables -A INPUT -s 192.168.1.3

-d : destination
Used for matching packet by destination address. The usage is similiar to –s
example :
iptables -A OUTPUT -d 192.168.1.3

-j : jump
Used to take values or action for matched packet.
example :
iptables -A INPUT -j DROP

-i : in-interface
Used for matching by incoming interface. This matching is only applied to chain INPUT, FORWARD
example :
iptables -A INPUT -i eth0

-o : out-interface
Used for matching by ougoing interface. The usage is similiar to. Only applied to chain OUTPUT, FORWARD
example :
iptables -A OUTPUT -o eth1

MORE ON IPTABLES TARGET

Target or jump is what action we give to certain packet.

ACCEPT every packet will be received by firewall and forwarded to destination of packet.
example :
iptables -A INPUT -p tcp -–dport 80 -j ACCEPT

DROP
Drop or throw every packet without warning to sender IP address.
example :
iptables -A INPUT -p tcp -–dport 80 -j DROP

REJECT
Reject received packet but will fives signal to sender IP address.
example :
iptables -A INPUT -p tcp -–dport 80 -j REJECT

RETURN
Reject every packet but firewall will gives ICMP error to packet sender. The default would be port-unreachable message. Message can be changed such as icmp-net-unreachable, icmp-host-unreachable, icmp-proto-unreachable, icmp-net-prohibited, etc
example :
iptables -A INPUT -p tcp -–dport 80 -j REJECT –reject-with icmp-net-unreachable

LOG
There are some option used accompanying this target. First is to determining log level. Common log level used are debug, info, notice, warning, err, crit, alert and emerg. Second is -j LOG –log-prefix which used to give string on prefix log so the log reading can be easy.
example :
iptables -A FORWARD -p tcp -j LOG -g-level debug
iptables -A INPUT -p tcp -j LOG -log-prefix “INPUT Packets”

SNAT
Used for Source Network Address Translation. The target is applied for NAT table at chain POSTROUTING. If first packet of connection is applied to SNAT, the the next packet on that connection would have same condition.
example :
iptables –t nat –A POSTROUTING –o eth0 –j SNAT –to-source 194.236.50.155-194.236.50.160:1024-32000

DNAT
Opposite of SNAT, DNAT used for Destination Network Address Translation at packets header. DNAT Only applied to table NAT chain PREROUTING AND OUTPUT or user define chain called by those two.
example :
iptables –t nat –A PREROUTING –p tcp –d 15.45.23.67 –dport 80 –j DNAT –to-destination 192.168.0.2

MASQUERADE
Work similiar with SNAT but this target doesn’t need option -to-source. MASQUERADE is designed to work on non-permanent connection like dial-up or DHCP that has dynamic IP allocation.
Like SNAT, the target work on table NAT on chain POSTROUTING.
example :
iptables –t nat –A POSTROUTING –o eth0 -dport 80 –j MASQUERADE

REDIRECT
REDIRECT used for redirecting route to machine. This target is used to redirect a packet that over some port through proxy application. Moreover it is used for establishing transparent proxy mechanism. For example we want to redirect all connection for http port so it will entering http proxy application such as Squid. This target is only applied for PREROUTING and OUTPUT chain on table NAT or user defined chain used by those chains.
example :
iptables -t nat -A PREROUTING -i eth1 -p tcp –dport 80 -j REDIRECT –to-port 3128
iptables -t nat -A PREROUTING -p tcp -d 0/0 –dport 80 -j REDIRECT –to-port 8080

Understanding ASCII

October 19, 2015 | Article | 4 Comments

What is ASCII?

ASCII is American Standard Code for Information Exchange. What does it mean? And why we use it?

Well, computer only knows number that we call binary number. Therefore, to instruct machine we have to use proper machine language which is binary coded form. Can you instruct machine, write sequence of 0 and 1 bits that make computer do something? It can but would be hard. Since computer only know 0 and 1, they also can’t understand our character. To make computer understand, our character will be mapped / encode to binary. That’s ASCII work for. It represent our character, from ‘A’ to ‘Z’, ‘0’ to ‘9’ and many more characters. This is standard that used in computer. As we say standard, the symbols on ASCII are well-known symbol or mutually agreed by many vendor.This guarantee that computer of different vendor / platform can still communicate and we also can use machine in more human-way.

Character in ASCII code are around 256 symbols numbered from 0 to 255 (in early era there are only 128 characters. The other 128 characters are extended to old standard). Why 0? Because our number system use 0 as lowest value for each digit. If you want to know further about number system, you can read my other article Number System or Decimal Number.

Now, I present to you list of ASCII code in simple table. Click the image to view full version of image.

ASCII Table 0~127

ASCII Table 127-255 (EXTENDED)

Now, what can we do with ASCII? Is it used? There are lot of things ASCII did. If ASCII was not present, we can’t read human character like we did now. So, must we read this article or blog with sequence of 0’s or 1’s? Must we remember and use machine language? If that’s the situation, you can imagine how many 0 and 1 you will see if there is a sentence “Satria is handsome and so cool”. (FYI: one character consist of eight number that can be 0 or 1).

Wow @@

ASCII inside program

Like I said before, computer only knows binary number. In the program, we use characters of ASCII to print or read something. ASCII characters are symbolized by character data type in programming language (character in Pascal or char in C).

This snippet is written in C++ language and will print character of ASCII from 0 to 127 (means: 128 character would appear). Don’t be surprised if some characters are not printable.

#include <iostream>
using namespace std;

int main() {
   int i;

   for(i=0; i< 128; i++) {
      cout<<(char) i<<endl;
   }

   return 0;
}

ASCII is not only a character

ASCII is the way of life! No, that’s only joking. But when I say ASCII is not only a character I mean, yes that’s true.

ASCII are not only characters we often meet everyday like a,b,c,d,.., z or 0,1,…,9 or symbols like [email protected]#$%^&*(). If you compile and execute snippet above and look carefully, you will see weird symbol in some lines. Yes, that’s also part of ASCII.

ASCII characters are also known by computer. Let’s take example of 8’th character in ASCII which is a backspace. This is a symbol used to represents backspace key on keyboard. Not only that, there is also character used for transmission like 2nd symbol which is STX or Start of Text. This character is used by program as beginning of text.

Now, we can conclude that ASCII is a universal code used for general purpose.

A Little Advice in Making C Header File

October 19, 2015 | Article | No Comments

As we know, C and C++ programming language are supporting modular programming. It means that we can break our long code into several separate modules. For this we need a file named header file that mostly are set of function prototypes. Later the functions will be implemented on another source file. Now, what are things we should (or should not) put in header file? When we should create a header file?

This article will give little advice about what we should include in our header file. This list is based on personal experience, so you can agree or reject it.

[DO] Always Create “guard” Macro for Each Header

What is “guard” that I mean? They are 3 line of code that protect your header files from multiple inclusion. This is essentially important as we can include our header as many as we like but compiler only read it once. Therefore, we can guarantee that our declarations are only once. The “guard” are composed by macro #ifndef, #define, #endif. You must check a unique macro name that acts as you unique header identifier. If not exist, we declare our code. Otherwise, the compiler will ignore the declaration. Our code will be between #define and #endif code respectively.

[DO] Create One Header File for Each “Module” of the System

Yes, for each. A module may comprise one or more compilation units. But it should implement just one aspect of the system. Examples of well-chosen modules are:

  • device driver for A/D converter
  • communication protocol
  • alarm manager that is responsible for logging error conditions and alerting the user.

Every module must be create on one header file.

[DO] Include All of the Function Prototypes for Public Interface of Module

For example, a header file lcd.h might contain function prototype for lcd_init(), lcd_write(), and lcd_clear(). But private implementation or helper functions that only known or used by those functions must be remain hidden.

[DON’T] Include Any executable Lines of Code in a Header file, Including Variable Declarations.

It’s not so effective. Another reason is there would be a chance of fatal error by multiple declaration. Especially if you are not providing “guard” for header files. But it is necessary to make an exception for the bodies of some inline functions.

[DON’T] Expose Any Variable in Header File

Again! If you want to make a variable public or known by another module, it’s not wise to put them on header file. Use extern in header file while the actual declaration would be in source code file (.c file).

[DON’T] Expose Internal Format of Any Module-Specific Data Structure Passed to or Returned from One or More of the Module’s Interface Functions

No declaration of structure in header file. Implicitly, no “struct { … } foo;” like code in any header file. If you do have a type that you need to pass in and out of your module so client can create instance of it, simply use “typedef struct moduleb_type” in header type. Outside that module should never know the internal format of the struct.

Maybe this is strict, but I hope this advice will give a better and readable C programming practice. More advice would be added later.

C volatile keywords

October 19, 2015 | Article | No Comments

In C/C++ programming language, volatile keyword is a type qualifier used to declare an object that can be modified in the program by something such as operating system, the hardware, or a concurrently executing thread.

In reality, the C’s volatile keyword is poorly understood by many programmers and used not properly. It’s not surprising as most book covering C language only explain it in one or two sentence. This article will covering about a proper way to use volatile. This article is categorized as little advanced so I hope you have understand C\C++.

Mostly, people experience these while programming C\C++ for embedded code (check for yourself):

  • Code works fine until compiler optimizations enabled
  • Code works fine until interrupts enabled
  • Flaky hardware drivers
  • RTOS tasks that work fine in isolation until other task is spawned.

If you ever experience any of above, most likely you didn’t use the C keyword volatile.

C’s volatile keyword is a qualifier that is applied to a variable when declared and tells the compiler that the value of the variable may change at any time without any action being taken by the code that compiler finds nearby. This is quite serious.

There are some declaration that may have different meaning. Let’s inspect further.

To declare a variable volatile, include the keyword volatile before or after the data type in variable declaration. Both have same meaning:

volatile int xathrya;
int volatile xathrya;

Those are very common declaration. Now, there is another way of declaring pointer. Both of these declaration will declare a pointer to a volatile unsigned integer:

volatile unsigned int * xathrya;
unsigned int * xathrya;

Next, we can have volatile pointers to non-volatile data. But this is very uncommon:

int* volatile xathrya;

You may think that we can have a volatile pointer to volatile variable, and yes this is possible:

int volatile * volatile xathrya;

If you apply volatile to a struct, union, or a class, the entire contents of struct/union/class would be volatile too. If you don’t want this, apply volatile to individual members of struct/union/class.

Now speaking about proper use of volatile. When we declare volatile? Whenever a variable’s value could change unexpectedly. In practice there are only three types of variable could changes:

  1. Memory-mapped peripheral registers
  2. Global variables modified by an interrupt service routine
  3. Global variables accessed by multiple tasks within a multi-threaded application

Let’s discuss each case!

Peripheral registers

Embedded systems contain real hardware, usually with sophisticated peripherals. These peripherals contain registers whose values may change asynchronously to the program flow. As a very simple example, consider an 8-bit status register that is memory mapped at address 0x1234. It is required that you poll the status register until it becomes non-zero. The naive and incorrect implementation is as follows:

uint8_t* pReg = (uint8t *) 0x1234;
// wait for register to become non-zero

while(*pReg == 0) {  } // do something else

This will almost certainly fail as soon as you turn compiler optimization on, since the compiler will generate assembly language that looks something like this:

mov ptr, 0x1234
mov a, ptr
loop:
bz loop

The rationale of the optimizer is quite simple: having already read the variable’s value into the accumulator (on the second line of assembly), there is no need to reread it, since the value will always be the same. Thus, in the third line, we end up with an infinite loop. To force the compiler to do what we want, we modify the declaration to:

uint8_t volatile* pReg = (uint8_t volatile *) 0x1234;

Thus the assembly language would looks like:

mov ptr, 0x1234
loop:
mov a, ptr
bz loop

The desired behavior is achieved.

Subtler problems tend to arise with registers that have special properties. For instance, a lot of peripherals contain registers that are cleared simply by reading them. Extra (or fewer) reads than you are intending can cause quite unexpected results in these cases.

Interrupt Service Routines

Interrupt service routines often set variables that are tested in mainline code. For example, a serial port interrupt may test each received character to see if it is an ETX character (presumably signifying the end of a message). If the character is an ETX, the ISR might set a global flag. An incorrect implementation of this might be:

int etx_rcvd = FALSE;

void main() {
...

   while(!ext_rcvd) {

      // wait
   }

...

}

interrupt void rx_isr(void) {

...

   if(ETX == rx_char) {
      etx_rcvd = TRUE;
   }

...

}

With compiler optimization turned off, this code might work. However, any half decent optimizer will “break” the code. The problem is that the compiler has no idea that etx_rcvd can be changed within an ISR. As far as the compiler is concerned, the expression !ext_rcvd is always true, and, therefore, you can never exit the while loop. Consequently, all the code after the while loop may simply be removed by the optimizer. If you are lucky, your compiler will warn you about this. If you are unlucky (or you haven’t yet learned to take compiler warnings seriously), your code will fail miserably. Naturally, the blame will be placed on a “lousy optimizer.”.

The solution is to declare the variable etx_rcvd to be volatile. Then all of your problems (well, some of them anyway) will disappear.

Multi-threaded applications

Despite the presence of queues, pipes, and other scheduler-aware communications mechanisms in real-time operating systems, it is still fairly common for two tasks to exchange information via a shared memory location (that is, a global). Even as you add a preemptive scheduler to your code, your compiler has no idea what a context switch is or when one might occur. Thus, another task modifying a shared global is conceptually identical to the problem of interrupt service routines discussed previously. So all shared global variables should be declared volatile. For example, this is asking for trouble:

int cntr;

void task1(void) {
   cntr = 0;
   while(cntr == 0) {
      sleep(1);
   }

...

}

void task2(void) {

...

   cntr++;
   sleep(10);

...

}

With a simple observation, we will know that this code will likely fail once the compiler’s optimizer is enabled. Declaring cntr to be volatile is the proper way to solve it.

Some compilers allow you to implicitly declare all variable as volatile. But, resist this temptation since it is essentially a substitute for thought. It also leads to potentially less efficient code. Use volatile if you must.

AVR Microcontroller Programming in Linux

October 19, 2015 | Article | 2 Comments

AVR or Alf & Vegard RISC, is a single chip microcontroller developed by Atmel. AVR is a modified Harvard architecture 8-bit RISC (Reduced Instruction Set Computer) which is a famous microcontroller.

AVR microcontrollers has many categories or we will say family. Family basically a group or category based on similiar characteristic and properties. There are six family and fortunately, AVR microcontrollers have same architecture. Thus programming in one family can be guaranteed work on other family. It is only limited to physical limitation such as different amount of flash storage, etc. AVR’s merit is about ease of porting.

As one of widely used microcontroller, there are lot of communities in internet. We can easily find various options can while developing microcontroller project.

This article will be covering preparation and setting up environment in Linux to develop AVR program.

What you will need:

  1. GNU/Linux
  2. avrdude
  3. avr-gcc
  4. avr-binutils
  5. A programmer (will be described later)
  6. AVR Microcontroller, with it’s development board if any, in this case I use AVR ATMega32

Program in Microcontroller

Before I start, let’s talk about program. What is program? A program is simply set of instructions written using machine language so it can be executed by machine. It is also called “binary” which mean to be not human-readable file (but can be understood by machine). For microcontrollers, binary files have type .hex (Intel Hex Format). You can imagine it as .exe in windows application. There are other forms, but in this article we will focus on .hex.

AVR has a small amount of memory in it. It is a storage where program is actually saved. And yes it is small compared by computer. Just some Kilobytes. When the chip starts up, microcontroller will start running whatever program written in flash.

Compiler and Cross Compiling

Compilation for microcontroller is basically similar to compiling program for PC. However, the difference between those two is in term of product of compilation. Compiler for AVR is run in our PC (developer machine), compile source code, and then produce machine language which is specific for the microcontroller (not our PC). This process is called cross compiling.

There are many cross compiler for AVR. I use AVR-GCC for this purpose (in this article and other similar articles, unless told otherwise).

Other tools we need are collectively known as avr-binutils. The binutils packages provide all the low-level utilities needed in building and manipulating object files. In this package, we have AVR assembler (avr-as), linker (avr-ld), and librarian (avr-ar and avr-ranlib). In addition, we get tools which extract data from object files (avr-objcopy), dissassemble object file information (avr-objdump), and strip information from object files (avr-strip).

The last thing to mention is the libc or standard c library. This is library designed for AVR microcontroller, or in other word it is different with our library used for PC programing.

Check your package management for avr-gcc and avr-binutils and install them.

For Debian and Ubuntu based:

sudo apt-get install gcc-avr
sudo apt-get install binutils-avr
sudo apt-get install gdb-avr
sudo apt-get install avr-libc

For Red Hat and Fedora based:

yum install avr-gcc
yum install avr-binutils
yum install avr-libc
yum install avr-gdb

Now invoke these to test the tools:

avr-gcc
avr-objcopy

Download / Burn the Program to the Chip

To program microcontroller we need a downloader.  It is a special chip that can connect your microcontroller with our computer and write our program into our chip. Every AVR has a set of pins that are programming pins. You have to verify you chip pins and connect the programmer to those pins in the right order.

So what programmer can be used? In this article I used USBasp. Of course you can have other programmers, but I will only talk about this programmer. For information about USBasp, you can visit this link http://www.fischl.de/usbasp/

Now we have know our programmer (I mean USBasp) but then, how to write our program to microcontroller? Relax! We will cover now.

We will use avrdude, a small application to do that. Install it if you have not install.

For Debian and Ubuntu based:

sudo apt-get install avrdude

For Red Hat and Fedora based:

yum install avrdude

Let’s take a peek of avrdude by give this command on our terminal:

avrdude

Let’s see what we have got. You will get something like this:

Usage: avrdude [options]
Options:
-p <partno>                Required. Specify AVR device.
-b <baudrate>              Override RS-232 baud rate.
-B <bitclock>              Specify JTAG/STK500v2 bit clock period (us).
-C <config-file>           Specify location of configuration file.
<strong>-c <programmer>            Specify programmer type.</strong>
-D                         Disable auto erase for flash memory
-i <delay>                 ISP Clock Delay [in microseconds]
-P <port>                  Specify connection port.
-F                         Override invalid signature check.
-e                         Perform a chip erase.
-O                         Perform RC oscillator calibration (see AVR053).
-U <memtype>:r|w|v:<filename>[:format]
 Memory operation specification.
 Multiple -U options are allowed, each request
 is performed in the order specified.
-n                         Do not write anything to the device.
-V                         Do not verify.
-u                         Disable safemode, default when running from a script.
-s                         Silent safemode operation, will not ask you if
fuses should be changed back.
-t                         Enter terminal mode.
-E <exitspec>[,<exitspec>] List programmer exit specifications.
-x <extended_param>        Pass <extended_param> to programmer.
-y                         Count # erase cycles in EEPROM.
-Y <number>                Initialize erase cycle # in EEPROM.
-v                         Verbose output. -v -v for more.
-q                         Quell progress output. -q -q for less.
-?                         Display this usage.

avrdude version 5.10, URL: <http://savannah.nongnu.org/projects/avrdude/>

Woah, that’s too much. But our interest is only in few options. I’ve bold the text which will get our attention. We only interests in -p, -U, and -c options as this is a minimum command we need to invoke along with avrdude.

  • -c : We specify the programmer we type. We are using usbasp so can be replaced with usbasp. Of course if you are using other programmer you must specify. For a complete list about supported programmer, invoke command: avrdude -c asdf. Because asdf is not a valid programmer, avrdude would complaint and print out list of supported programmer to you. Read it and verify your programmer is supported.
  • -U :r|w|v:[:format]: This is the most important command. is either flash or eeprom which is destination where our program will be stored. Next is r (read), w (write), or v (verify) option that you must choose one (only one). Next is which you have to replace with your program path and name. Next is optional format flag [:format] that specify our program format.
  • -p : Specify microcontroller series. Or simply what microcontroller we willl program. For example I will use ATMega32 so i will replace with atmega32.

With these three, we can program in minimal. In this case when I want to program ATMega32 using USBasp with filename avr_leds.hex, the command I use will be:

avrdude -c usbasp -U flash:w:avr_leds.hex -p atmega32

Wait until process is finish and then you can see you microcontroller is programmed now.

Next time I will write some actual writing program for AVR.

Android Operating System is one of popular operating system for mobile device beside Windows Phone, Apple iOS, etc. The popularity comes from the fact that Android is open source, used by various vendor. You have a freedom to modify and do anything to your Android, though you will void your warranty.

This article main focus would be concentrated on installation of development tools, which is Eclipse IDE, Android SDK, and Android Developer Tool.

Why Eclipse? Eclipse is an open source Integrated Development Environment and has full support for Android. It’s also quite simple.

In the time i write this article, I use GNU/Linux Ubuntu 10.10. Of course you can use other linux distribution if you like, especially Debian or Ubuntu derivative distribution. I might encourage you to use later version if possible. You must also have active internet connection to do installation and fetching required packages.

Table of Content

  1. Installation
    1. Eclipse IDE
    2. Oracle Java JDK
    3. Android Developer Tool Plugin
    4. SDK and SDK Platform
  2. Create Android Virtual Device

Installation

[x] Installing Eclipse IDE

First, installing Eclipse. In this article I will use latest Eclipse (per September 6th, 2012) version. It’s Eclipse 4.2 Juno for Linux 32 bit. You can download it at this link.

I pick eclipse-SDK-4.2-linux-gtk.tar.gz, it is a ready to use version means no installation required. Download it and then extract the file.

tar xvzf eclipse-SDK-4.2-linux-gtk.tar.gz

We will have a new extracted directory named eclipse. Move this directory to /opt. This is a good practice for FHS (Filesystem Hierarchy Standard) as an optional software installed to this. In my case I extracted eclipse in /home/xathrya/Downloads. I will invoke following command and remember the command need privileges as /opt is usually owned by root:

mv /home/xathrya/Downloads/eclipse  /opt

Create symbolic link to eclipse in /usr/bin (use root privilege):

ln -s /opt/eclipse/eclipse /usr/bin/eclipse

[x] Installing Oracle Java (Replace OpenJDK)

You can use OpenJDK and skip this. However if you want

Next you must have a running JAVA Runtime Environment. We need to install Oracle Java. Ubuntu has come with a default OpenJDK Environment so we will replace it.

In Ubuntu, the JAVA is located on repository partner which indicated it is a proprietary repository. To install JAVA first we have to add the repository. In this case I use maverick meerkat (Ubuntu 10.10 distribution), if you have other distribution, you can replace maverick with your Ubuntu codename (ex: lucid for lucid lynx, natty for natty narwhal)

sudo add-apt-repository "deb http://archive.canonical.com/ maverick partner"
sudo apt-get update

After that you can install JAVA JRE

sudo apt-get install sun-java6-jre galternatives

last we need to change the default java environment for OpenJDK to Sun JRE 6

sudo galternatives

Select java in left panel and select java-6-sun as shown by image below:

Now, verify your java installation. Invoke this command:

java -version

This should gives you message like this:

java version "1.6.0.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Java HotSpot(TM) Client VM (build 17.1-b03, moxed mode,sharing)

[x] Android Developer Tool Plugin

Now let’s moving to installation of Androit Developer Tool (ADT). It is a special Eclipse plugin contains integrated android environment for building Android application using eclipse. Reminder: my eclipse version is 4.2 (Juno)

Start eclipse. Now navigate to:

Help - Install New Software - Add

enter the following information:

Name: ADT Plugin
Location: https://dl-ssl.google.com/android/eclipse/

Click on OK. Now select “Developer Tools” and/or “NDK Plugins”. Click Next to begin installation. Wait for installation to finish its work. With my connection around 50KB/s the installation done in 30 minutes.

[x] Install the SDK and SDK Platform

Next we will install Android SDK. Downlad Android SDK starter pack from this link

Download the latest SDK. By the time I write this article, the latest version is 20.0.3. You can download linux version directly in this link:

Extract the content of Android SDK pack:

tar xvzf android-sdk_r20.0.3-linux.tgz

In my case I will leave the SDK on /home/xathrya/android-sdk.

Now we need to install platforms and optional additional plugins or sample codes. Start SDK manager:

/home/xathrya/android-sdk/tools/android

Seleck SDK Platforms you want. I choose Android 2.3.3 API 10 as my smartphone Sony Xperia U use this one. When you have selected all packages you want, click Install Selected. You will be prompted to Accept License. Click Accept All and then Install.

Create Android Virtual Device

Now we have to join Eclipse IDE with Android SDK and create and Android Virtual Device (AVD). Android Virtual Device is an emulator to run your application on top of your computer.

In Eclipse, navigate to: Window -> Preferences -> Android

Enter location of your Android SDK installation. In my case it is in /home/xathrya/android-sdk/. Press OK.

Now navigate to Window -> AVD Manager -> New

Insert following information into:

Name: AndroidVirtualDevice
Target: [chose any desired Android version and API level available]

Click Create AVD. The new Android Virtual Device will be created in the directory:

~/.android/avd

We are done!

New World, New NEST!

October 13, 2015 | News | No Comments

Hello, Internet!

I’m Xathrya and this is my new NEST.

If you ever know my old NEST (https://blog.xathrya.id) and got here because of that, thank you! This new NEST will serve as continuation of old NEST. I will fix some things and make the content back here. Recreating is not easy but I will do my best.

I would be pleased if you can help me by suggesting contents or help me spread the fame.

Outside of writing articles, I also studying reverse engineering and playing some CTFs. If you ever know Dago Cybernesha or Sabertooth Ganesha, please say hi. You can also recruit me for CTF if you want 😀

 

Last, thanks for all of my friends who keep me doing my best (and push me to back in action).

Social Share Buttons and Icons powered by Ultimatelysocial