Autoplaying Files in Kodi Isengard

Almost all the affects of the change in naming from XBMC to Kodi have been realized at this point except for a few small areas. One of those areas is using the on-box API to send commands into Kodi or automate certain actions.

In my case I was trying to automatically play a file as soon as my Kodi player boots. To do that you simply place a file with the right content in the right place.

My System Details:

  • Hardware: Raspberry Pi 2 /w Edimax EW-7811UTC AC600 Wifi Adapter
  • Software: OpenELEC v6.0.3 (Kodi 15.2 Isengard)

Specifically, create a file called autoexec.py in the /storage/.kodi/userdata/ directory.

import xbmc
xbmc.executebuiltin( "PlayMedia(smb://192.168.1.20/usenet/Baby_Stream.strm)" )
xbmc.executebuiltin( "PlayerControl(repeat)" )

If you’re trying to test the script on the CLI via ssh by using the python interpreter you might notice that calls to import the xbmc module fail.

OpenELEC:~ # python
Python 2.7.3 (default, Feb 29 2016, 21:17:05) 
[GCC 4.9.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import xbmc
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ImportError: No module named xbmc
>>>

This is expected because the xbmc module is not exposed to the default python path.

Testing your Script:

In order to test your script try having Kodi send it through it’s python namespace using the kodi-send command:

OpenELEC:~ #kodi-send -a "RunScript(/storage/.kodi/userdata/autoexec.py)"

Quick and easy automation in Kodi. To see other functions that can be called either via kodi-send or  automated in xbmc.executebuiltin statements, check Kodi’s official docs on the subject.

Advertisements

Udev Network Interface Renaming with no Reboot

While working on the Topology_Converter for work I came upon several lessons with Udev. The topology_converter project essentially takes input (from a graphiviz file) and builds a network topology with proper interface names. In order to make the interface names work there is a script which spits out udev rules.

Writing Udev Rules

With Udev you can rename interfaces using a number of parameters which are defined in rules. Rules should be stuck in the “/etc/udev/rules.d/70-persistent-net.rules” file to follow convention but you could technically stick them anywher in the rules.d directory.

To see all of the possible criteria that can be matched upon for a given network interface, use the command below replacing “eth0” with your interface of choice.

udevadm info -a -p /sys/class/net/eth0

Udevadm info starts with the device specified by the devpath and then
walks up the chain of parent devices. It prints for every device
found, all possible attributes in the udev rules key format.
A rule to match, can be composed by the attributes of the device
and the attributes from one single parent device.

looking at device '/devices/pci0000:00/0000:00:19.0/net/eth0':
 KERNEL=="eth0"
 SUBSYSTEM=="net"
 DRIVER==""
 ATTR{addr_assign_type}=="0"
 ATTR{addr_len}=="6"
 ATTR{address}=="54:ee:75:22:3d:70"
 ATTR{broadcast}=="ff:ff:ff:ff:ff:ff"
 ATTR{carrier}=="0"
 ATTR{carrier_changes}=="1"
 ATTR{dev_id}=="0x0"
 ATTR{dev_port}=="0"
 ATTR{dormant}=="0"
 ATTR{duplex}=="unknown"
 ATTR{flags}=="0x1003"
 ATTR{gro_flush_timeout}=="0"
 ATTR{ifalias}==""
 ATTR{ifindex}=="2"
 ATTR{iflink}=="2"
 ATTR{link_mode}=="0"
 ATTR{mtu}=="1500"
 ATTR{netdev_group}=="0"
 ATTR{operstate}=="down"
 ATTR{proto_down}=="0"
 ATTR{speed}=="-1"
 ATTR{tx_queue_len}=="1000"
 ATTR{type}=="1"

looking at parent device '/devices/pci0000:00/0000:00:19.0':
 KERNELS=="0000:00:19.0"
 SUBSYSTEMS=="pci"
 DRIVERS=="e1000e"
 ATTRS{broken_parity_status}=="0"
 ATTRS{class}=="0x020000"
 ATTRS{consistent_dma_mask_bits}=="64"
 ATTRS{d3cold_allowed}=="1"
 ATTRS{device}=="0x15a2"
 ATTRS{dma_mask_bits}=="64"
 ATTRS{driver_override}=="(null)"
 ATTRS{enable}=="1"
 ATTRS{irq}=="56"
 ATTRS{local_cpulist}=="0-3"
 ATTRS{local_cpus}=="0f"
 ATTRS{msi_bus}=="1"
 ATTRS{numa_node}=="-1"
 ATTRS{subsystem_device}=="0x2227"
 ATTRS{subsystem_vendor}=="0x17aa"
 ATTRS{vendor}=="0x8086"

looking at parent device '/devices/pci0000:00':
 KERNELS=="pci0000:00"
 SUBSYSTEMS==""
 DRIVERS==""

</code>

You can see there are quite a few options to match on. When remapping physical interfaces on Linux, I strongly recommend adding the match for PCI to make sure this interface is mapped to the PCI bus in some way. The concern when not using the PCI match (as shown below) is that if these physical interfaces are to take part in bridges or bonds with vlans or sub interfaces…. in that case your bridge or bond may inherit mac addresses from a physical interface and there will be a collision in the renaming process which means your interfaces may be left named “renameXX” or something like that.

Here are some sample Udev rules for a given series of interface renaming operations.

#### UDEV Rules (/etc/udev/rules.d/70-persistent-net.rules) ####
ACTION=="add", SUBSYSTEM=="net", ATTR{address}=="44:38:39:00:00:1a", NAME="swp2", SUBSYSTEMS=="pci" 
ACTION=="add", SUBSYSTEM=="net", ATTR{address}=="44:38:39:00:00:12", NAME="swp1", SUBSYSTEMS=="pci" 
ACTION=="add", SUBSYSTEM=="net", ATTR{address}=="44:38:39:00:00:49", NAME="swp48", SUBSYSTEMS=="pci" 
ACTION=="add", SUBSYSTEM=="net", ATTR{address}=="44:38:39:00:00:42", NAME="eth0", SUBSYSTEMS=="pci" 
ACTION=="add", SUBSYSTEM=="net", ATTR{address}=="08:00:27:8a:39:05", NAME="vagrant", SUBSYSTEMS=="pci"

Applying the New Rules

Now that you’ve written the new rules it’d be nice to apply them without having to reboot.

EDIT: In Ubuntu 16.04 you have another option.

systemctl restart systemd-udev-trigger.service

 

That can be a little complicated and is totally disruptive to networking traffic likely on all interfaces but the procedure looks like this:

  1. Detect the driver used by each interface that requres a remap. The easiest way is to use
    $ ethtool -i eth0
    driver: e1000e
    version: 3.2.6-k
    firmware-version: 0.2-4
    expansion-rom-version: 
    bus-info: 0000:00:19.0
    supports-statistics: yes
    supports-test: yes
    supports-eeprom-access: yes
    supports-register-dump: yes
    supports-priv-flags: no

    You could potentially use this technique:

    $ basename $(readlink /sys/class/net/eth0
    /device/driver/module)

    or this one:

    $ basename $(readlink /sys/class/net/+interface+/device/driver)

    YMMV  depending on the driver in use.

  2. Remove the driver that is shared/used by each interface that is to be remapped (other interfaces that are using that driver may get caught in the crossfire here).
    $ modprobe -r e1000e
  3. Run the following command to detect the newly installed rules
    $ udevadm control --reload-rules
  4. Apply the new rules with the last command
    $ udevadm trigger

Applying the new rules with the trigger operation will also reinitialize the driver that you’ve previously removed.

Presto you’re done.

Using Nautilus in Ubuntu 14.04 and 16.04 as a Box Client

It is not well known that the Nautilus file manager in Gnome can be used as a client to access box shares. This article seeks to document how to set up that connectivity mostly as a reminder for when I need to do it later.

proceedure1). Open Nautilus and select “Connect to Server”

Select Connect To Server in Nautilus File Browser
Select Connect To Server in Nautilus File Browser

2). Fill in the “Server Address” as follows:

davs://username%40yourdomain.com@dav.box.com/dav

note: The ‘%40’ is the character encoding for ‘@’ and you must leave that there exactly as shown.

Selection_004

 

 

 

 

 

 

3). Click Connect and, when prompted, enter your external password for Enterprise Box. This should bring up a File Browser window showing you the files you have in your Box space.

 

If your password doesn’t work… you may need to create an “External Password” for use with apps (like Nautlius) that do not have access to your single sign-on (SSO) system.

1). Log into your Box account from the website.

2). At the upper right, click your name. From the drop-down menu, click Account Settings.

3). Near the bottom, under “Create External Password”, click Edit password. and save it when finished.

4). Try this password in the above procedure.

 

Heavy Duty (and Cheap) Workbench

After months of searching on Craigslist I was not able to find a 7+ foot workbench that was made of solid wood. I was getting increasingly frustrated so I began looking online for different plans to make my own.

Workbench Criteria:

  • 7 to 8 ft long ~2ft deep
  • THICK wooden top (I wanted more for aesthetics than anything else)
  • Heavy Duty Construction ( I didn’t want to think twice about putting 500 pounds on it )

After a while of searching I found an excellent starting point in an old Family Handyman article. I referenced this article for all the steps on the construction of the base and tabletop with several modifications:

  • I wanted a 2×6 base mainly for looks but also because I intend to keep this workbench for my lifetime and want it to last at least that long.
  • I also added some shelving to the crossbars underneath because it should have been there from the start and I had some leftover lumber from my earlier garage shelving project.
  • I added a 45 degree chamfer on the table top since this is just pine and could otherwise be pretty easily marred on the corners.
  • Lastly I inset a T-square in the corner of the table because I had an extra one lying around and I thought it could be useful.

Cost Breakdown

Materials:

  • $61 — Lumber
  • $50 — Used Vise off of Craigslist (looked new to me)
  • $20 — Lag Bolts and Hardware
  • $5 — Consumables (Wood Glue)
  • FREE — 3″ Deck Screws — I had these leftover
  • FREE — L Square — I had an extra

Tools:

  • $50 — New Table Saw Blade
  • $56 — (3) 36″ Clamps

~$250 total mostly in new tools that I would have bought for something else. All in all I could not be happier with the result, it was just what I wanted and meets every one of my needs.

Bringing the lumber home

This little car has never carried so much lumber in its entire life. So many 2x4s but I made it all in one trip!

Constructing the workbench

Adding the Finishing Touches

Finished.

IMG_20140731_225532
Just what I always wanted for this space.

Building A Solid Oak Picture Frame

 

Had some solid red oak lumber left over from the Babyroom Built-in Project and decided to make a picture frame for my wife for Christmas. This was my first attempt at this sort of thing but it came out excellent!
Solid Oak Picture Frame

Materials:

  • Wood
  • Wood Glue
  • Pre-cut Glass (link below)
  • Pre-cut Matting (link below)
  • Glazier Points
  • Stain
  • Polyurethane or Lacquer
  • Sandpaper (60,120,220 grits)

Tools:

  • Table Saw
  • Bench Router
  • Power Sander
  • Clamps (at least 3 big ones)

Step 1). Determine your Frame Size

What I learned here is that a 16×20 frame has the internal dimensions (aka “id”) of 16×20. Or in other words if you’re building a 16×20 frame, your piece of glass is going to need to be 16×20.

Also if you want to include a border of matting you can matte down a size. The idea being that you could frame an 11×14 photo in a 16×20 frame and the difference between the two sizes can be found as a pre-cut piece of matting.

Step 2). Purchase Matting and Glass

I have been using a store called Jerry’s Artarama for years and they are excellent. They’re more of an art supply store but they have everything one could ever need in the area of framing. They also have some really knowledgeable staff that can give you guidance on how to complete any framing project. If you don’t have a local store near you, you can buy online directly from Jerry’s. These were the items I used for this project:

Lastly there’s always Amazon. Amazon sells all kinds of pre-cut matting that you can have delivered to your door. The only downside for ordering online with something like this is you can’t get a great look at the precise color until it arrives. I like to pick my stain and my matting at the same time for the best results.

Step 3). Cut Lumber To Frame Width

In my case I started with some larger width boards. So I set up the table saw and made them a bit more narrow, in my cases the frame width was about 2.25 inches.

Step 4). Route the Inside Edge of the frame with a Rabbit Bit

rabbetAfter cutting my lumber to the proper width, I got out my router table and went to the store to get a rabbet bit.

In my case I purchased a rabbet bit that would carve out a 1/2″ x  1/2″ channel. I ran this along one of the sides of all my lumber that was previously cut to width.

Step 5). Cut the 45 Degree Corners

At this point it is a matter of cutting your frame pieces so that you can fit your glass and matte. As I was cutting I took my matte board out several times just to make sure everything would fit without much play.

Step 6). Wood Glue and Clamp

Most folks secure frame corners together with several joining techniques however I was using red oak for this project which is a very porous species of wood and I didn’t think it would be necessary to add the extra strength.

To confirm the theory, I cut a few extra corners and glued them together with Elmer’s Wood Glue to test the strength of the glue alone. After the glue hardened over night, I examined the test corner by hand at first but when I was unable to break it by hand I put it in the vice and only then was I able to break it.

Glue alone is more than enough for a picture frame made of oak.

As the corners are drying I strongly recommend adding a ton of long clamps to all sides to further firm everything up. I even added some C-clamps to the individual corner pieces to make sure they would stay flush with one another. I had 7 clamps set up as mine was drying, 4 c-clamps, one for each corner, and 3 big long clamps to span the sides.

Step 7). Sand Sand Sand

After the glue was set over night I started the sanding process. Before I started, I made sure to empty the sander of anything that might have been in the collection bag beforehand for reasons I will explain in the next step.

At this point I began sanding all sides with 60, and 120 grit to hone out any large imperfections with the glue-up.

Step 8). Fill in Any Gaps

Since I was using glue alone and I am not perfect there were some very small gaps in my corners. Since appearance is everything with a picture frame I wanted to make sure to take care of these.

Using the sanding dust in the orbital sander dust collection bag I mixed-up a paste of wood glue and oak sawdust. I then used my finger and a toothpick to apply this slurry wherever there were any imperfections in the corner glue up.

This technique also allows the corners to take some of the stain in, where as glue by itself would not absorb any stain.

Step 9). Sand Again

After letting the second glue-up set it was time to sand again. This time I went right to the 220 grit sand paper and smoothed the entire piece out.

Step 10). Stain And Poly

I chose to use a nice red oak stain and some aerosol polyurethane but you can finish your frame however you like. I was tempted to just use some dutch oil and see how that looked but despite having purchased a bit of dutch oil I never seem to want to use it when I have the choice of stain.

Two coats of stain were applied several hours apart.

Then an additional 24 hours of drying time for the stain at which point the first coat of poly was applied. I hung the piece from the ceiling of my workshop while applying the poly so I could get a nice even coating and do all sides at once. I waited another 5 hours or so before applying the second coat of poly, then let the piece air dry for a couple days and voila, the frame was complete.

Step 11). Mount Picture

I still haven’t done this for my new frame but I’ve performed these last two steps for other frames. Basically it boils down to these little items called glazier points, you insert the glass, followed by the matte board, then your picture, I tend to use a bit of masking tape on the edges of the picture to keep it from sliding around in the matting.

Step 12). Apply the Backing

After taping the picture you insert the backer board (usually cardboard for larger frames) and start to move around the edge of the frame adding glazier points on each side.

I use a flat-head screwdriver and a hammer to tack the glazier points in place behind the backer board to hold everything in place.

Installing A New Car Stereo in 2007-2009 Hyundai Elantra

This guide should apply to all Hyundai Elantras from 2007-2009.

From stock to Awesome!

This slideshow requires JavaScript.

Parts required:

Materials Required:

  • Soldering Iron and Solder
  • Electrical Tape

 

IMG_20160101_115216
Here is the starting point.

Step 1). Loosen the Surrounding Fascia

IMG_20160101_115639
Showing the fascia that is going to be removed.

Note the location of the gray clips below on the backside of the fascia, prying up around these points easiest. I had the most luck working on the lower left and right corners as a starting point.

IMG_20160101_115841
This picture shows the bac side of the fascia. You can see the 8 gray clips along the top and bottom. At this point I had lost two of them in the dash in the lower right corner of the picture.

Step 2). Remove Wire Harnesses from Fascia

Once the fascia itself is loose the 3 cables that connect to it need to be removed. Start by depressing the clip which connects to the back of the hazard lights. Shown in the photo below.

 

IMG_20160101_115626
You can see the wire harness connecting to the back of the hazard lights here.

Next remove the two wiring harnesses that connect to the clock (black wires) and passenger airbag sign (yellow wires) above the radio.

 

IMG_20160101_115753
This picture looks up from the bottom of the radio with the fascia loosened. Notice the two wire harnesses above the radio.

Step 3). Remove the Stock Radio

Unscrew the four screws which surround the unit.

IMG_20160101_115907
Here is the radio with the fascia removed.

Disconnect the wire harness and the antenna cable from the back of the radio.

IMG_20160101_120125
Looking at the cables from the right side of the radio.

Step 4). Prepare the Adapter Cable

At this point I took the Metra Wire Harness adapter cable and started soldering the wires to the new wiring harness provided by the new headunit. Which wires will need to actually be connected will vary based on the capabilities of your headunit.

When looking at the photo below you can see the adapter cable beneath the stock wiring harness that stretches over the black adapter which plugs into the back of the new headunit. I took the liberty of wrapping all my wires in the harness together with a little electrical tape but you don’t HAVE to do that, it’s just a nice touch.

IMG_20160101_120345
Showing the stock wiring harness and the adapter from metra along with the wiring harness provided by the headunit.

Step 5). Install the New Headunit

Connect the wiring harness adapter from metra into the stock wire harness. Then screw in your mounting bracket from metra using the four screw which previously held the old radio in place.

I choose to mount my new head unit using the ISO mount technique which is a bit simpler than the classic DIN method (which employs the metallic cage surrounding the headunit which needs to have some pins bent down to hold it in place). Using the ISO technique requires the removal of the DIN cage from the new headunit and attaching the side rails included in the metra mounting bracket kit. At this point, connect the cables to the back of the new headunit and slide it into place.

I choose to run an additional microphone cable that was included with my headunit for handsfree calling but don’t have any pictures of that step.

At this point you can replace the fascia and then add the trim bracket which surrounds the headunit.

IMG_20160101_125950

DONE
IMG_20160101_125942

 

Basic Raspberry Pi Home Wifi Router

The Goal of This Post:

This post is an extension to Jacob Salema’s Guide that was picked up by Lifehacker. My main issue with his post is that he refers to the end result as a wireless router, which is not entirely accurate. This device is not meant to be internet-facing and is really more of a wireless/ethernet bridge with the configurations provided.

My goal here was to extend what was provided in his initial post and make it suitable for placing a Raspberry Pi directly behind a cable modem and fully exposed to the internet.

raspberry_pi_pi_ap
image kindly borrowed from adafruit

Materials:

  • Raspberry Pi B (gen 2 model) any Raspberry Pi could potentially work here though
  • Edimax EW-7811Un
  • Short piece of Ethernet (to connect to cable modem)
  • Power Adapter and cord for Pi
  • SD card with Raspbian installed
  • (Optional) USB Keyboard and HDMI Monitor to access the PI. All of these steps can be performed over SSH with a little creativity however.

Performance:

The Raspberry Pi’s performance is limited by the USB throughput of the WLAN adapter; which on the Raspberry Pi is a USB2.0 hub limited to a theoretical maximum of 480mbps, so you’ll never be able to pull gigabit ethernet here but this will get the job done for small sites. However if you have really crappy broadband like I do in this location the chokepoint will be the crappy broadband and not the Raspberry Pi.

I have maxed out my crappy broadband connection with the following speedtest.net performance results:

A BLAZING — 2.78mbps download
A SIMILARLY BLAZING — 1.28mbps upload

I repeated the same speedtest.net tests using a top-notch Lenovo X1 Gen3 laptop and got the exact same results so there is no lag using the raspberry pi here (for this crappy broadband connection). Since my broadband is so crappy here I’m using 802.11G wifi which won’t choke anything.

Note: I probably wouldn’t trust this for anything over 10mbps. I think the Raspberry Pi 2 with 802.11n wifi could handle a standard 40mbps connection based on some of the numbers I’m seeing here.

1). Required Installs:

Perform these first before any of the other steps.

sudo apt-get update -y
sudo apt-get install rfkill zd1211-firmware hostapd hostap-utils iw dnsmasq bridge-utils -y

 

2). Interfaces Configuration (/etc/network/interfaces):

Modify the interfaces file (/etc/network/interfaces) as shown below.

allow-hotplug wlan0
allow-hotplug eth0

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp
 
auto wlan0
iface wlan0 inet static
   address 192.168.2.1
   netmask 255.255.255.0

3). DNSmasq Configuration (/etc/dnsmasq.conf):

Modify the DNSmasq configuration file to look exactly like what you see below.

Feel free to modify your domain.

domain=example.com
bogus-priv
no-resolv
server=8.8.8.8
server=8.8.4.4
cache-size=10000
interface=wlan0
dhcp-range=192.168.2.2,192.168.2.254,12h

4). HostAPD Configuration (/etc/hostapd/hostapd.conf):

Modify the configuration file for hostapd to have the following content.

Notice we’re using the “hw_mode=g” option here this is because my limited internet connection couldn’t support max throughput of a wifi-N connection so there would be minimal benefit. If you’re interested in N and have a Raspberry Pi2 and a faster internet connection it may make sense to enable that in your scenario.

Also feel free to modify the SSID to whatever you like and modify the password too, you’ll need at least 8 characters for the password. The channel can also be set to any value between 1-14 (1,6,11,14 are common in the USA)

interface=wlan0
driver=rtl871xdrv
country_code=US
ctrl_interface=wlan0
ctrl_interface_group=0
ssid=NETWORKNAME
hw_mode=g
channel=1
wpa=3
wpa_passphrase=password
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
beacon_int=100
auth_algs=3
macaddr_acl=0
wmm_enabled=1
eap_reauth_period=360000000


5). HostAPD Default Configuration (/etc/default/hostapd):

Modify the defaults file for hostapd (/etc/default/hostapd) to have the same DAEMON_CONF line. The type of quotes used to surround the /etc/hostapd/hostapd.conf file are mission critical; if you use the wrong kind of quotes, hostapd will not start. You can debug the start of hostapd with the command “hostapd -d /etc/hostapd/hostapd.conf” which puts it into debugging mode.

# Defaults for hostapd initscript
#
# See /usr/share/doc/hostapd/README.Debian for information about alternative
# methods of managing hostapd.
#
# Uncomment and set DAEMON_CONF to the absolute path of a hostapd configuration
# file and hostapd will be started during system boot. An example configuration
# file can be found at /usr/share/doc/hostapd/examples/hostapd.conf.gz
#
DAEMON_CONF="/etc/hostapd/hostapd.conf"

# Additional daemon options to be appended to hostapd command:-
# -d show more debug messages (-dd for even more)
# -K include key data in debug messages
# -t include timestamps in some debug messages
#
# Note that -B (daemon mode) and -P (pidfile) options are automatically
# configured by the init.d script and must not be added to DAEMON_OPTS.
#
#DAEMON_OPTS=""

6). Reboot the Pi

Reboot the Pi to apply the interfaces config, start the hostapd daemon, start dnsmasq daemon. After the reboot you should see your new wireless SSID being broadcast and you should be able to login to it too with your provided password. At this point we need to proceed with the IP tables configuration to setup routing and PAT (port address translation).

7). Enable NAT and Routing Non-Persistently

Execute the following commands to enable NAT and routing for this particular session (we will make these settings persistent across reboots in steps 9 and 10).

#Enable Routing
sudo sysctl -w net.ipv4.ip_forward=1

#Apply the NAT/PAT config 
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Routing allows the Pi to move (or “route”) packets between the two interfaces (Wlan0 and Eth0). Making the Pi a Router allows packets which come in on the Wlan interfaces to be forwarded through the Pi and out the Eth0 port.

NAT stands for Network Address Translation. In this case we’re technically performing PAT or Port Address Translation because we are aggregating the connections and streams of multiple downstream/client IP addresses across a single public IP address using different source ports. As a result packets will be re-written as they pass through a NAT router to be sourced from the public IP address of the NAT router. This re-write hides the original source IP address of the client which generated the traffic. In order to keep track of which stream should be returned to which client, the NAT router keeps a table that maps the Egress destination port to an client IP and source port. This table is called a NAT translation table. You can view the content of the Translation table at any time with the following command:

cat /proc/net/ip_conntrack

8). IP Tables Configuration:

IPtables is a program which interacts with the networking stack in the Linux kernel and tells the kernel how to handle incoming network traffic. There are all kinds of customizations that can be made to an internet facing router. What I show below are pretty basic and generally recognized as safe defaults.

Apply the default config by pasting the following commands into the command line on your device:

#allow incoming traffic from the localhost
sudo iptables -A INPUT -i lo -j ACCEPT
#explicitly allow all icmp/ping traffic
sudo iptables -A INPUT -p icmp -m icmp --icmp-type any -j ACCEPT
#explicitly allow all traffic that is already established
sudo iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
#Allow new traffic only from the local/WLAN network
sudo iptables -A INPUT -i wlan0 -m state --state NEW -j ACCEPT
#Drop all other new traffic
sudo iptables -A INPUT -p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -m state --state NEW -j DROP<
#Drop all fragments
sudo iptables -A INPUT -f -j DROP 
# Drop XMAS packets
sudo iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
# Drop NULL packets
sudo iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
#allow our dns traffic 
sudo iptables -A INPUT -i wlan0 -p udp -m udp --sport 53 -j ACCEPT
#log everything else that is about to get dropped. 
sudo iptables -A INPUT -j LOG --log-prefix "IPTABLES Dropped: " --log-level 7 
#drop everything else that has made it this far down and not matched. 
sudo iptables -A INPUT -j DROP

You can see the presently applied iptables rules using the “iptables-save” command with sudo.

pi@raspberrypi:~ $ sudo iptables-save
# Generated by iptables-save v1.4.21 on Thu Dec 24 17:37:34 2015
*nat
:PREROUTING ACCEPT [7039:855804]
:INPUT ACCEPT [1138:80267]
:OUTPUT ACCEPT [1167:81793]
:POSTROUTING ACCEPT [21:3945]
-A POSTROUTING -o eth0 -j MASQUERADE
COMMIT
# Completed on Thu Dec 24 17:37:34 2015
# Generated by iptables-save v1.4.21 on Thu Dec 24 17:37:34 2015
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [444346:360889024]
:OUTPUT ACCEPT [4390:510099]
-A INPUT -i lo -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type any -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i wlan0 -m state --state NEW -j ACCEPT
-A INPUT -p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -m state --state NEW -j DROP
-A INPUT -f -j DROP
-A INPUT -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,PSH,ACK,URG -j DROP
-A INPUT -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP
-A INPUT -i wlan0 -p udp -m udp --sport 53 -j ACCEPT
-A INPUT -j LOG --log-prefix "IPTABLES Dropped: " --log-level 7
-A INPUT -j DROP
COMMIT
# Completed on Thu Dec 24 17:37:34 2015

Once you’ve setup the rules you’d like, and you’ve tested that they behave as expected, proceed to step 8 to save the IP tables rules.

9). Make the IPtables Settings Persistent

During the installation of the iptables-persistent program it will ask you if you want to save the presently applied rules, select YES.

sudo apt-get install iptables-persistent -y

Once the rules are saved, they can be edited at the /etc/iptables/rules.v4 (for normal IPv4 traffic). If you’re testing your iptables changes by applying the rules directly using the iptables syntax in step 7 then as you make changes, they can be made persistent by writing the output of the “iptables-save” command directly to the rules.v4 file like so.

sudo iptables-save > /etc/iptables/rules.v4

10). Enable Routing Persistently

The following change allows the Raspi Router to move packets from one interface (wlan0) to another (eth0) by making the device a router.

sudo sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/g' /etc/sysctl.conf