Streaming from an underwater camera with a Raspberry Pi

kjaerra

Among this summer’s projects was getting an underwater camera online and streaming. The camera is placed within a fishing device designed like a cage, called Kjærra, dating back to the 14th century. The trap has a one-way entry; the fish enters the cage and can’t escape, and is subsequently extracted from the cage. When the trap is opened, the salmon (or trout) inside will be auctioned off to the spectators.

Underwater camera

Underwater camera

Starting with the camera itself, an underwater camera was acquired. The camera unit was secured between two pieces of wood, to make mounting easier and to prevent the camera from being destroyed or dismounted when the fish are extracted from the cage. The camera comes with a 20 meter cable which we led to a nearby dry location, where it’s powered from a battery and charger, providing a stable power source. The camera even has LEDs for night vision, but we’re not using it since it could confuse and scare the fish.

Finding underwater cameras that provide IP network video streams seemed quite impossible. This camera was no exception, providing only regular video signal (the good old yellow RCA plug). To convert the video signal into a computer readable format, we connected the very portable Vivotek VS8100 video server. Apart from the 12V power plug, the unit offers a video signal socket (BNC) and an RJ45 network socket. The unit could even be directly connected to the 12V power cable already provided with the camera.

Video server

Video server

The final piece was of course a Raspberry Pi mini computer, completing the chain by connecting it to the video server. Running the brilliant piece of software avconv, the Raspberry Pi pulls an RTSP video stream from the video server and converts it into an RMTP video stream which in turn is accepted by the streaming distribution server, an Adobe Flash Media Server 3.5. When we’re not streaming live, a short film with some useful information is shown instead.

When streaming live, what the camera sees may be viewed at Østlands-posten’s site. Østlands-posten is hosting the stream distribution; thanks a lot!

Also thanks to Magnus and Lasse at Arkena for hints and clues in this project.

This is the avconv command line, with any sensitive information redacted:

/usr/bin/avconv \
 -i rtsp://underwatercam:554/live.sdp \
 -f flv \
 -vcodec copy \
 -an \
 rtmp://fms-server/path?doPublish=MyPassword/streamName >/dev/null 2>&1

MikroTik configuration revision control with rancid

The config revision control tool rancid (Really Awesome New Cisco confIg Differ, but not at all limited to Cisco devices) has proven extremely useful. Rancid notifies you if there’s been some changes to a device, and since it’s Subversion backed it’s easy to extract full configurations in case you need it. Rancid has been supporting MikroTik devices for some time now.

Rancid exists in a lot of Linux repositories, or it could be installed from source – how to do that is documented elsewhere. After installing rancid, here’s what was needed for rancid to keep an eye on my MikroTik devices.

First I created a readonly user across all MikroTik units, intuitively named rancid. To mass create this account, I used dsh – described in an earlier article. Make sure your Linux system’s rancid user is able to log in to your devices using SSH keys and not passwords.

Next step is configuring rancid’s authentication file, ~/.cloginrc. Even though a password is required in the file, setting the identity will make rancid use key based SSH logins. Here’s my .cloginrc for reference:

add user * rancid
add password * SomeGarbledPasswordThatWon'tBeUsedAnyway
add method * ssh
add identity id_dsa

To verify that rancid may log in to the MikroTik devices, try a manual login as the rancid user:

~$ ~rancid/bin/mtlogin 10.10.0.1

You should be logged in to the device, and in the device’s log you should see

publickey accepted for user: rancid+ct

Now that the rancid user is able to log in to your units, it’s time to move on with configuring rancid. Most rancid.conf settings work out of the box, I only had to change these to convince rancid to use Debian’s standard svn repo directory. Make sure the “rancid” user or group has the necessary permissions to create a new repo. I also created a group called “devices”.

CVSROOT=/var/lib/svn/rancid; export CVSROOT
RCSSYS=svn; export RCSSYS
LIST_OF_GROUPS="devices"

After running rancid for the first time, a new repo has been created. Under ~rancid/var/ a “devices” directory has been created. In here you will find a file named “router.db”. Here you need to add your devices, like this:

10.10.0.1:mikrotik:up
10.10.0.2:mikrotik:up

When all this is in place, it’s time to allow rancid to run from cron.

Securely managing multiple Mikrotik units with dsh

dsh is a nice Unix/Linux tool for managing multiple systems efficiently, and I’m using it both at home and at work. In some distributions dsh has been replaced by pdsh, but no worries, pdsh is dsh compatible. Since all MikroTik devices running RouterOS might be managed over SSH, why not use dsh to manage these as well? Here’s a quick howto.

  1. Install ssh and dsh.
  2. If you don’t have one already, create an SSH DSA key pair:
    ssh-keygen -t dsa
    Do this with the Unix/Linux user account you’re managing the devices from. I strongly recommend securing the key pair with a password.
  3. Distribute the public part of the key pair (id_dsa.pub) to each MikroTik unit, using an existing account (e.g. admin). I used ncftpput for efficient distribution. The public key should now be visible in the “Files” folder on each MikroTik device.
  4. Now attach the public SSH key to a user account. I’ll use the admin account in this example. In cli, this is done with
    /user ssh-keys import public-key-file=id_dsa.pub user=admin
  5. Create a dsh group file, let’s call the group mikrotik (either /etc/dsh/group/mikrotik or ~/.dsh/group/mikrotik). Add the IP address or hostname of each MikroTik devices to this file, one unit per line. Specify the user name if required.

Sample group file:

admin@10.10.0.1
admin@10.10.0.2

You should confirm that SSH works fine with each device before expecting dsh to work. Example command:

~$ ssh admin@10.10.0.1

When this works fine, you’re now ready to mass manage your MikroTik devices. A few useful commands are shown below.

Check for and download the newest RouterOS version to all devices:

~$ dsh -g mikrotik '/system package update check-for-updates'
~$ dsh -g mikrotik '/system package update download'
~$ dsh -g mikrotik '/system package update print'

Change admin’s password (note that this will leave the new password in your user’s shell history):

~$ dsh -g mikrotik '/user set password=ThisIsTheNewPassword admin'

Check if any device needs a firmware upgrade:

~$ dsh -g mikrotik '/system routerboard print'

Add a new user:

~$ dsh -g mikrotik '/user add name=NewUser disabled=no group=full'

Språktest av 4 åringer

Når får vi obligatorisk språktest av journalister?

Using BOPM with InspIRCd

Using Blitzed Open Proxy Monitor (BOPM) with a fairly new version of InspIRCd needed a slightly different configuration than suggested here and there. The following is working for me, using InspIRCd 2.0.9 and the BOPM package provided by Ubuntu (Lucid, but shouldn’t make much of a difference).

First of all, the BOPM service wasn’t granted the proper user mode and consequently never registered the connect notifications. The InspIRCd documentation suggests that the proper modes might be set either in bopm.conf or InspIRCd’s configuration. BOPM’s documentation seems to suggest that the following is the correct config setting:

# bopm.conf
mode = "+c";

However, running BOPM in debug mode, it complained about mode c being unknown:

501 bopm c :is unknown mode char to me

This worked so much better:

# bopm.conf
mode = "+s +cC";

Now, BOPM will be notified upon every client connect, both local and remote. Next task is finding the proper regexp for detecting client connections. This is how a connect notification might look like:

*** CONNECT: Client connecting on port 6667 (class unnamed-26): ircnick!ircnick@server.example.com (192.168.200.103) [ircnick]

To catch the above notification, the following regular expression added to bopm.conf seems to work:

# bopm.conf
connregex = "\\*\\*\\* CONNECT: Client connecting on port [0-9]+.*?: ([^!]+)!([^@]+)@([^ ]+) \\(([0-9\\.]+)\\) \\[.*\\]";

Note: For some previous versions of InspIRCd, it seems the client IP is shown in brackets instead of parentheses. Also, it seems to not show the connection class. Obviously that will require a modified connregex.

For reference, this extract from inspircd.conf shows the necessary configuration on the InspIRCd side:

# inspircd.conf (or opers.conf)
<class name="BanOnly" commands="ZLINE" usermodes="s">
<type name="BOPM" classes="BanOnly" modes="+s +cC">
<oper name="bopm" password="bopmpass" host="*@localhost *@127.0.0.1" type="BOPM">

Reaching multiple instances of the same IP address

A friend recently presented me with the following challenge: Configure a system through which several appliances, all of them having an identical, non-routable, default IP configuration, can be reached simultaneously. All appliances are preconfigured with an IP address of 192.168.1.1 and they had no routing configuration enabled. Yet they should all be reachable over the Internet. The diagram below shows the basic infrastructure.

For the server (the nice grey cabinet to the left) to reach all those systems at the same time, a VLAN setup was required, so we set up a VLAN trunk to a nearby switch. Then the different appliances were connected to different un-tagged switch ports in dedicated VLANs – the first appliance was connected to a switch port in VLAN 10, the next to a switch port in VLAN 11, etc. Corresponding VLAN interfaces were configured on the server, and a local IP address was configured on each. To keep a minimum level of sanity, I configured the VLAN interface on vlan10 as 192.168.1.10, while vlan11 got 192.168.1.11, etc. To avoid too much confusion on the switch, I also set the MAC address on each VLAN interface to distinct values.

Next step was to configure correct IP routing using iproute2:
# VLAN 10
/sbin/ip link add link eth1 name eth1.10 type vlan id 10
/sbin/ip link set dev eth1.10 down
/sbin/ip link set dev eth1.10 address 00:04:de:ad:be:10
/sbin/ip link set dev eth1.10 up
/sbin/ip addr add local 192.168.1.10/24 brd 192.168.1.255 dev eth1.10
/sbin/ip route add 192.168.1.0/24 dev eth1.10 proto kernel scope link src 192.168.1.10 table 10
/sbin/ip rule add from 192.168.1.10 lookup 10 prio 1010
# VLAN 11
/sbin/ip link add link eth1 name eth1.11 type vlan id 11
/sbin/ip link set dev eth1.11 down
/sbin/ip link set dev eth1.11 address 00:04:de:ad:be:11
/sbin/ip link set dev eth1.11 up
/sbin/ip addr add local 192.168.1.11/24 brd 192.168.1.255 dev eth1.11
/sbin/ip route add 192.168.1.0/24 dev eth1.11 proto kernel scope link src 192.168.1.11 table 11
/sbin/ip rule add from 192.168.1.11 lookup 11 prio 1011

At this point I could reach the different appliances from the different source IPs:
# ping -I 192.168.1.10 192.168.1.1 -c1
PING 192.168.1.1 (192.168.1.1) from 192.168.1.10 : 56(84) bytes of data.
64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=0.119 ms

Snooping with tcpdump on the different VLAN interfaces, also showing the MAC addresses, confirmed that the pings were reaching the correct appliance.

Then I set up corresponding IP addresses on the outside interface (eth0). The 10.0.0.195 address matches the device in VLAN 10, 10.0.0.196 matches VLAN 11 and so on. The outside IP addresses are official IP addresses, but I’ve changed them to protect the innocent.

/sbin/ip addr add local 10.0.0.195/24 dev eth0
/sbin/ip rule add to 10.0.0.195 fwmark 10 table 10
/sbin/ip rule add fwmark 10 lookup 10
/sbin/ip addr add local 10.0.0.196/24 dev eth0
/sbin/ip rule add to 10.0.0.196 fwmark 11 table 11
/sbin/ip rule add fwmark 11 lookup 11

To make sure the packets were being identified correctly all the way through, they were tagged upon reaching the outside interface, based on the IP on which they arrived.

So far so good, now it was time for iptables to show its powers:
# VLAN 10
/sbin/iptables -t mangle -A PREROUTING -i eth0 -d 10.0.0.195 -j MARK --set-mark 10
/sbin/iptables -t nat -A PREROUTING -i eth0 -d 10.0.0.195 -j DNAT --to-destination 192.168.1.1
/sbin/iptables -A FORWARD -m mark --mark 10 -j ACCEPT
/sbin/iptables -t nat -A POSTROUTING -m mark --mark 10 -j SNAT --to-source 192.168.1.10
# VLAN 11
/sbin/iptables -t mangle -A PREROUTING -i eth0 -d 10.0.0.196 -j MARK --set-mark 11
/sbin/iptables -t nat -A PREROUTING -i eth0 -d 10.0.0.196 -j DNAT --to-destination 192.168.1.1
/sbin/iptables -A FORWARD -m mark --mark 11 -j ACCEPT
/sbin/iptables -t nat -A POSTROUTING -m mark --mark 11 -j SNAT --to-source 192.168.1.11

The above commands maps the outside addresses on eth0 to the corresponding VLANs on the inside. Note that every incoming packet is destination NATed (DNAT) to 192.168.1.1 while they are being source NATed (SNAT) based on the VLAN to which they are mapped. As the appliances were not able to route traffic, all communication had to look like it happened on the local network only.

Now I expected to be able to access each appliance from the outside, but it turned out that only one appliance could be reached. tcpdumping on each VLAN interface confirmed that traffic from the outside reached each appliance, and the appliance responded, but the response never came all the way back. This was rather puzzling as nothing appeared in any log. However, my colleagues reminded me about rp_filter, which dropped weird traffic without logging anything. Thus, the key that unlocked everything was this:
echo 0 > /proc/sys/net/ipv4/conf/all/rp_filter
echo 0 > /proc/sys/net/ipv4/conf/eth1.10/rp_filter
echo 0 > /proc/sys/net/ipv4/conf/eth1.11/rp_filter

And voila – from the outside world, we were able to reach every single appliance on the inside, all with the same unroutable RFC1918 address.

Path MTU discovery ICMP messages

This is more for my own reference… After configuring my ADSL modem to run i bridge mode, it seems I’m running into a few path MTU issues. To identify any path MTU messages, I’ve been analyzing the traffic on the outside interface looking for path MTU issues using the following tcpdump syntax:

tcpdump -n -s0 -i ppp0 'icmp[icmptype] != icmp-echo and icmp[icmptype] != icmp-echoreply'

Update: Of course, this exact syntax is documented on tcpdump’s own site

Avoid hotlinking with Varnish

There’s a quite a few articles on how to configure Apache to avoid hotlinking, so that material on your web server isn’t used on remote sites (at least not without your knowing).

This is how to do the same with Varnish. The example suggests that you forbid hotlinking to anything under http://www.example.com/fun/. The code will of course need to be added to whatever else exists in vcl_recv.

sub vcl_recv {
  if (req.http.host == "www.example.com" &&
  req.url ~ "^/fun/" &&
  (req.http.referer && req.http.referer !~ "^http://www.example.com/")) {
    error 403 "No hotlinking please";
  }
}

Spanning-tree on Linksys srw2008

After finally admitting defeat I had to boot into Windows for managing my Linksys SRW2008 switch through its WebView, the reason being I could not find out how to enable regular spanning-tree on the switch.

Having enabled it through its IE-specific web UI, I logged in to the (rather poorly documented) CLI afterwards to check what had changed in the config. And the single, magic configuration line that enabled spanning-tree on the switch was this one:

spanning-tree

*sigh*

GeoIP and MySQL

For my own and possibly others’ reference, these are quick notes on how to use GeoIP data from MaxMind in their new split file formats. Older tutorials describe using the GeoIP data from a time when they were one file, it seems now MaxMind have split into two files.

The files are split into Location and Blocks, so we create two tables to accommodate this:

CREATE TABLE location (
 LocId INT(8) NOT NULL,
 PRIMARY KEY (LocId),
 country CHAR(2),
 region VARCHAR(255),
 city VARCHAR(255),
 postalCode VARCHAR(255),
 latitude DECIMAL(20,17),
 longitude DECIMAL(20,17),
 metroCode VARCHAR(50),
 areaCode VARCHAR(50)
) ENGINE=INNODB;
CREATE TABLE blocks (
 startIpNum INT(10) NOT NULL,
 EndIpNum INT(10) NOT NULL,
 LocId INT(8) NOT NULL,
 FOREIGN KEY (LocID) REFERENCES location(LocId) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB;

Now it’s time to import the data from the files. Since LocId is a foreign key to the blocks table, location must be inserted first.

mysql> LOAD DATA LOCAL INFILE '/root/GeoLiteCity_20090601/GeoLiteCity-Location.csv' INTO TABLE location FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' (LocId, country, region, city, postalCode, latitude, longitude, metroCode, areaCode);
Query OK, 248276 rows affected, 13 warnings (9.65 sec)
Records: 248277 Deleted: 0 Skipped: 1 Warnings: 9
mysql> LOAD DATA LOCAL INFILE '/root/GeoLiteCity_20090601/GeoLiteCity-Blocks.csv' INTO TABLE blocks FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' (startIpNum, EndIpNum, LocId);
Query OK, 4132041 rows affected, 65535 warnings (15 min 20.44 sec)
Records: 4132041 Deleted: 0 Skipped: 0 Warnings: 2739156

That done, we try a select.

mysql> select A.country from location A
  JOIN blocks B on A.LocId = B.LocId
  AND 404232216 >= startIpNum AND 404232216 <= EndIpNum;
+---------+
| country |
+---------+
| US      |
+---------+
1 row in set (2 min 3.58 sec)

As I had no indexes yet, the query took some time. So let’s add them:

mysql> CREATE INDEX startIp_ind ON blocks (startIpNum);
Query OK, 4132041 rows affected (9 min 22.23 sec)
Records: 4132041 Duplicates: 0 Warnings: 0
mysql> CREATE INDEX endIp_ind ON blocks (endIpNum);
Query OK, 4132041 rows affected (9 min 22.33 sec)
Records: 4132041 Duplicates: 0 Warnings: 0
mysql> CREATE INDEX LocId_ind ON location (LocId);
Query OK, 248276 rows affected (4.08 sec)
Records: 248276 Duplicates: 0 Warnings: 0

And voila:

mysql> select A.country from location A
  JOIN blocks B on A.LocId = B.LocId
  AND 404232216 >= startIpNum AND 404232216 <= EndIpNum;
+---------+
| country |
+---------+
| US      |
+---------+
1 row in set (0.55 sec)

Also, a better SQL query could’ve been more efficient, but hey – this is for illustrative purposes.