Archive for the ‘mikrotik’ Category

MAC-address based Telnet server in Linux

My previous post was about RouterOS Mac-Telnet application for Linux users where I talked about the MAC-Telnet client I created for Linux users.

Since then, I have both started porting it to OS X and to create a daemon version of MAC-Telnet, called “mactelnetd”. You can look at the different branches at github.com.

To use mactelnetd, install MAC-Telnet from the github link, using either the latest .deb file from the download section (if you are on Ubuntu or Debian), or download the sources and compile it yourself. You can find instructions for this on my previous post. you first need to edit the /etc/mactelnetd.users file. This file consists of the users and their respective passwords for logging into the server. I wish we wouldn’t have to write the passwords in plain text, but the authentication method used in the mac-telnet protocol demands that we know the actual password, unlike ssh/regular telnet, where the password can be stored as a hash sum.

The format of /etc/mactelnetd.users is like this:

# Users file for MAC-Telnetd
# Use existing usernames from your system
#
# Format:
#username:password
haakon:mypass

Here I have activated the user account haakon, with apssword “mypass”. It is important that the user names that you enter into this file is existing user names from your Linux machine. The mactelnetd daemon will check /etc/passwd for home directory, and what shell to spawn for the user, as any regular terminal server.

When you have created/modified this file to your wishes, you can start the server daemon:

$ sudo mactelnetd

If there were no error messages, it spawned successfully and you can watch it’s log entries via syslog.

$ tail -f /var/log/syslog
Dec 26 01:06:08 haakon-kontorpc mactelnetd[10183]: Bound to 0.0.0.0:20561
Dec 26 01:31:17 haakon-kontorpc mactelnetd[10183]: (28780) New connection from 0:c:42:3e:20:c2.
Dec 26 01:31:17 haakon-kontorpc mactelnetd[10391]: (28780) User haakon logged in.

Here you see the results of me logging into my Linux Desktop machine from a MikroTik Router using the RouterOS command “tool mac-telnet 1c:6f:65:2c:98:b7”

[admin@Holmenveien] > tool mac-telnet 1c:6f:65:2c:98:b7
Login: haakon
Password:
Trying 1C:6F:65:2C:98:B7...
Connected to 1C:6F:65:2C:98:B7
Linux haakon-kontorpc 2.6.35-23-generic-pae #41-Ubuntu SMP Wed Nov 24 10:35:46 UTC 2010 i686 GNU/Linux
Ubuntu 10.10
 
Welcome to Ubuntu!
* Documentation:  https://help.ubuntu.com/
 
haakon@haakon-kontorpc:~$ w
01:32:52 up 24 days, 22:48,  2 users,  load average: 0.53, 0.61, 0.57
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
haakon   tty7     :0               01Dec10 24days 26:29m  3.17s gnome-session
haakon   pts/0    0:c:42:3e:20:c2  01:32    0.00s  0.15s  0.00s w

If you want to shut down the mactelnetd server, simply write “sudo killall mactelnetd” in your shell.

FUN TIP: If you want “fancy” terminal promt like RouterOS has, with syntax coloring on your Linux machine (logging in via console, xterm, ssh or mactelnet), you can install the shell “fish“, and then change your user settings to use it as the default shell by issuing:

$ sudo usermod --shell /usr/bin/fish myusername

NB: Be sure that the file /usr/bin/fish exists, and change “myusername” with your username, and remember to test logging into a second console, just to be sure you did this correctly, before logging out of your current terminal. To revert, set /bin/bash as your shell again, or what ever shell you previously used.

Here’s a direct link to the latest Ubuntu/Debian package at the time of writing:

mactelnet_0.2-1ubuntu1_i386.deb

RouterOS Mac-Telnet application for Linux users

Earlier, I wrote about a Wireshark plugin for dissecting Mac-Telnet packets. Now I have created an open source application for connecting to a RouterOS router via its MAC address from Linux without having to install Wine. At the time of writing the project is still in “alpha” stage. But it is fully functional. Though it will probably be rewritten soon. I feel that the second time you write the same application, it tends to be more robust and thought through.. The first time is more of a proof of concept, and I let myself do a lot of short-cuts, just to be able to see it working.

The source code can be found at github. Just find the “download source” link at the top of the page.

To compile it, simply untar it, and compile it with “make” .
Because it needs to alter the frame headers, it uses RAW sockets, which means that you will need root access to use this tool.

To find the MAC address of connected routers, try the included tool mndp. It might take up to 2 minutes to find all routers, since it is a passive tool that waits for the routers to broadcast their info on the network:

# ./mndp
Searching for MikroTik routers... Abort with CTRL+C.
  0:c:42:43:58:a5 HMG

HMG is my name of the found router, set in the Identity section of the router.

Here are some mac-telnet usage information:

# ./mactelnet --help
Usage: ./mactelnet <ifname> <MAC> <username> [password]
 
Parameters:
  ifname    Network interface that the RouterOS resides on. (ex: eth0)
  MAC       MAC-Address of the RouterOS device. Use mndp to discover them.
  username  Your username.
  password  Your password.

Tip: Log out using CTRL+D on your keyboard.

Usage example:

# sudo ./mactelnet eth0 0:c:42:43:58:a5 admin mysecretpass
Connecting to 0:c:42:43:58:a5...done
 
 
  MMM      MMM       KKK                          TTTTTTTTTTT      KKK
  MMMM    MMMM       KKK                          TTTTTTTTTTT      KKK
  MMM MMMM MMM  III  KKK  KKK  RRRRRR     OOOOOO      TTT     III  KKK  KKK
  MMM  MM  MMM  III  KKKKK     RRR  RRR  OOO  OOO     TTT     III  KKKKK
  MMM      MMM  III  KKK KKK   RRRRRR    OOO  OOO     TTT     III  KKK KKK
  MMM      MMM  III  KKK  KKK  RRR  RRR   OOOOOO      TTT     III  KKK  KKK
 
  MikroTik RouterOS 4.0 (c) 1999-2009       http://www.mikrotik.com/
 
 
[admin@HMG] >

[UPDATE]
Omni Flux sent me a patch that speeds up the MNDP discovery time by sending out a MNDP request before waiting for replies. Thanks!

He also informed me that his tests showed that you could send all the mac-telnet traffic to- and from- the broadcast address. This means that you would not need socket_raw (read: root privileges) capabillities to be able to send data to the router.

So the latest version of mactelnet, now also as a binary .deb package below, can be used without root privileges, unless you don’t want all data from your session to be broadcasted on your local network. You can optionally use the “old” method, where it uses the destination routers mac address as destination instead of broadcast.

Heres the latest “stable”: v0.1 version
Source tarball
Ubuntu/Debian binary package

Last commits on MAC-Telnet at GitHub

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”.