Archive for May, 2009

Flash ActionScript 3 API for Mikrotik RouterOS 3.x

Lately I have been familiar with the RouterOS series, when we got us a RouterBoard 493. At first I was a bit sceptical since I had never heard of RouterOS or Mikrotik. But as soon as I started testing this nice little hardware/software out, I found out that this was one exceptional nice software. And the nice hardware solutions is also nice. You can buy barebone RouterBoards without casing, and put them inside what you want, or buy a RouterOS license and build your own x86 router with standard x86 hardware.

The great thing about these routers is that they are so configurable, and easy to administer. You should all try them out yourself. They are extremely cheap, and extremely full of features. I know a lot of ISP’s around the world use only mikrotik equiptment in their wireless networks. Since they are very easy to set up with several wireless cards, and they have exceptionally good drivers, where you can fine tune all the parameters.

Anywyas, in addition to supporting configuration over Telnet/SSH/MAC-telnet. They also have a so called RouterOS API. This is a nice little API that gives you computer-friendly access to all the features in the configuration of the box.

Via the API you can read info, set configuration (live), and even listen for events. For example, list out the dBm to all connected WLAN users. Or get notified when someoen pulls a network cable. etc.

The API is “open documentation” and you are welcome to create libraries to different languages and post on their site. They already have PHP, Ruby, Perl, Java, etc implementations, but I wanted to be able to create a Flash AIR application to display and configure routers. So I created a Flash ActionScript 3 class for it.

Now I can create nice interfaces displaying live info from the router, and simple(or andvanced) configuration of the device.

The ActionScript classes looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// ApiSocket.as
//
// RouterOS API class
// Author: Håkon Nessjøen
// Date: 2. May 2009
//
package {
 
	import flash.errors.*;
	import flash.events.*;
	import flash.utils.ByteArray;
	import com.adobe.crypto.MD5;
	import flash.net.Socket;
 
	public class ApiSocket extends Socket {
		static public var RECEIVED:String = "received";
		static public var LOGIN:String = "loggedin";
		private var cmd:String;
		private var doLogin:int;
		private var user:String;
		private var password:String;
		private var returnData:Array;
		private var returnPos:int;
		private var toread:int;
		private var firstRe:int;
		private var tag:String;
		private var gotDone:Boolean;
		private var gotTrap:Boolean;
		private var gotFatal:Boolean;
 
		public function ApiSocket(host:String, port:uint) {
			super(host, port);
			toread = 0;
			doLogin = 0;
			addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
		}
 
		public function login(u:String, p:String) {
			doLogin = 1;
			user = u;
			password = p;
			sendRequest("/login");
		}
 
		public function sendRequest(... outData):void {
			returnData = new Array();
			returnPos = 0;
			firstRe = 0;
			gotDone = false;
			gotTrap = false;
			gotFatal = false;
			tag = "";
			cmd = outData[0];
			returnData[returnPos] = new Object();
 
			for (var i:int = 0; i < outData.length; ++i) {
				var data:ByteArray = new ByteArray();
 
				var len:uint = outData[i].length;
 
				if (len < 0x80)
					data.writeByte(len);
				else
				if (len < 0x4000) {
					len |= 0x8000;
					data.writeByte((len >> 8) & 0xff);
					data.writeByte(len & 0xff);
				} else
				if (len < 0x200000) {
					len |= 0xC00000;
					data.writeByte((len >> 16) & 0xff);
					data.writeByte((len >> 8) & 0xff);
					data.writeByte(len & 0xff);
				} else
				if (len < 0x10000000) {
					len |= 0xE0000000;
					data.writeByte((len >> 24) & 0xff);
					data.writeByte((len >> 16) & 0xff);
					data.writeByte((len >> 8) & 0xff);
					data.writeByte(len & 0xff);
				} else {
					data.writeByte(0xF0);
					data.writeByte((len >> 24) & 0xff);
					data.writeByte((len >> 16) & 0xff);
					data.writeByte((len >> 8) & 0xff);
					data.writeByte(len & 0xff);
				}
 
				writeBytes(data);
				writeUTFBytes(outData[i]);
			}
			writeByte(0);
			flush();
		}
 
		private function readResponse():void {
			var len:int;
 
			if (toread == 0) {
				var len1:uint = readUnsignedByte();
 
				if (len1 == 0) {
					if (gotDone || gotTrap || gotFatal) {
						if (doLogin == 1) {
							if (returnData[0].ret) {
								var chal:ByteArray = new ByteArray();
								var md5:ByteArray = new ByteArray();
 
								for (var i:int = 0; i < returnData[0].ret.length; i += 2) {
									chal.writeByte(int("0x" + returnData[0].ret.substr(i,2)));
								}
 
								md5.writeByte(0);
								md5.writeUTFBytes(password);
								md5.writeBytes(chal);
 
								doLogin++;
								// Send challenge response
								sendRequest("/login", "=name=" + user, "=response=00" + MD5.hashBytes(md5));
							}
						} else if (doLogin == 2) {
							doLogin = 0;
	 						dispatchEvent(new ApiEvent(ApiSocket.LOGIN, "", returnData, gotDone ? 'done' : (gotFatal ? 'fatal' : 'trap')));
						} else {
							dispatchEvent(new ApiEvent(ApiSocket.RECEIVED, tag, returnData, gotDone ? 'done' : (gotFatal ? 'fatal' : 'trap')));
						}
					}
 
					if (bytesAvailable)
						readResponse();
					else
						return;
				}
 
				if (len1 >= 0xF0) {
					len = readUnsignedByte();
					len = (len << 8) + readUnsignedByte();
					len = (len << 8) + readUnsignedByte();
					len = (len << 8) + readUnsignedByte();
				} else
				if (len1 >= 0xE0) {
					len = ((len1 & 15) << 8) + readUnsignedByte();
					len = (len << 8) + readUnsignedByte();
					len = (len << 8) + readUnsignedByte();
				} else
				if (len1 >= 0xC0) {
					len = ((len1 & 31) << 8) + readUnsignedByte();
					len = (len << 8) + readUnsignedByte();
				} else
				if (len1 >= 0x80) {
					len = ((len1 & 63) << 8) + readUnsignedByte();
				} else
					len = len1;
 
				toread = len;
			}
 
			// Calculate how much data of the full length that is available right now
			var slen:int = bytesAvailable > toread ? toread : bytesAvailable;
			// Calculate how much data that has to be read later
			toread = toread > bytesAvailable ? toread - bytesAvailable : 0;
 
			// Read relevant data
			var str:String = readUTFBytes(slen);
 
			if (toread == 0) {
				if (str == '!re') {
					firstRe++;
					if (firstRe > 1) {
						returnPos++
						returnData[returnPos] = new Object();
					}
				}
				if (str == '!trap')
					gotTrap = true;
 
				if (str == '!fatal')
					gotFatal = true;
 
				if (str == '!done')
					gotDone = true;
 
				// Parse key-value pair
				if (str.substr(0,1) == '=') {
					var tmpPos:int = str.indexOf('=',1);
					var tmpKey:String = str.substr(1,tmpPos-1);
					var tmpVal:String = str.substr(tmpPos+1);
					returnData[returnPos][tmpKey] = tmpVal;
				}
 
				// Reset tag
				if (str.substr(0,1) == '!')
					tag = "";
 
				// Set tag
				if (str.substr(0,5) == '.tag=')
					tag = str.substr(5);
 
				// Are there more packets available
				if (bytesAvailable)
					readResponse();
			}
 
		}
 
		private function socketDataHandler(event:ProgressEvent):void {
			readResponse();
		}
	}
}
 
// ApiEvent.as
//
// RouterOS API Event class
// Author: Håkon Nessjøen
// Date: 2. May 2009
//
package {
 
	import flash.events.Event;
 
	public class ApiEvent extends Event {
		static public var RECEIVED:String = "received";
		static public var LOGIN:String = "loggedin";
 
		public var data:Array;
		public var result:String;
		public var tag:String;
 
		public function ApiEvent(type:String, tg:String, dta:Array, res:String){
			super(type);
			data = dta;
			result = res;
			tag = tg;
		}
	}
 
}

And here’s an
Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Short example that outputs wireless registration-table every second
import ApiSocket;
import ApiEvent;
 
var sock:ApiSocket;
var myTimer:Timer = new Timer(1000);
 
myButton.addEventListener(MouseEvent.CLICK, testAPI);
myTimer.addEventListener(TimerEvent.TIMER, timedFunction);
 
function testAPI(evt:MouseEvent):void {
	sock = new ApiSocket("172.17.1.1", 8728);
	sock.addEventListener(ApiEvent.RECEIVED, receive);
	sock.addEventListener(Event.CONNECT, connected);
	sock.addEventListener(ApiEvent.LOGIN, loggedin);
}
 
 
function connected(evt:Event) {
	trace("Connected. Logging in.");
	sock.login("admin","password");
}
 
 
function loggedin(evt:ApiEvent) {
	// result can be done, trap or fatal
	if (evt.result == 'done') {
		myTimer.start();
	}
}
 
function timedFunction(e:TimerEvent) {
	sock.sendRequest("/interface/wireless/registration-table/print", ".tag=mytag");
}
 
function receive(evt:ApiEvent) {
	trace("Got Event with tag " + evt.tag + " result: " + evt.result);
 
	if (evt.tag == 'mytag' && evt.result == 'done') {
		trace("Got rows: " + evt.data.length);
 
		for (var i:int = 0; i < evt.data.length; ++i) {
			trace(evt.data[i]['mac-address'])
			trace("  " + evt.data[i]['signal-strength'])
		}
	}
}

Anyways, the code is nice to use in Flash AIR applications, since Flash AIR doesn’t have any security limitations to connecting with sockets. But if you were to use this class in a SWF file, you would need to do the right measures to let Flash accept your “cross domain scripting”.