Category Archives: Linux

Android VPN

strongswanandroid

This setup below is what suited my requirements.  I'm sure there'll be another way of implementing this, but this works for me :)

For this I'm using the following:

# emerge --info
Portage 2.3.0 (python 3.4.3-final-0, default/linux/amd64/13.0/no-multilib, gcc-4.9.3, glibc-2.22-r4, 4.8.7-gentoo x86_64)
=================================================================
System uname: Linux-4.8.7-gentoo-x86_64-Intel-R-_Core-TM-_i7-6700K_CPU_@_4.00GHz-with-gentoo-2.2
KiB Mem: 32896588 total, 15127076 free
KiB Swap: 3640916 total, 3640916 free
Timestamp of repository gentoo: Sun, 13 Nov 2016 04:15:01 +0000

And this version of strongswan:

# emerge -p strongswan

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild R ~] net-misc/strongswan-5.5.0

Strongswan Config

Once installed, we need to setup the configs.  The main config is located at /etc/ipsec.conf:

This is my file with the obvious changes ;)

# ipsec.conf - strongSwan IPsec configuration file

config setup
 uniqueids=never
 #charondebug="cfg 2, dmn 2, ike 2, net 2"

conn %default
 dpdaction=restart
 dpddelay=300s
 reauth=yes
 aggressive=no
 fragmentation=yes
 type=tunnel
 forceencaps=yes
 modeconfig=pull
 auto=add
 closeaction=clear
 compress=no
 left=my.vpn.com
 leftid="C=GB, O=strongSwan, CN=my.vpn.com"
 leftsubnet=0.0.0.0/0
 leftcert=vpnHostCert.pem
 leftsendcert=always
 leftfirewall=yes

conn IPSec-Android-Strongswan
 keyexchange=ikev2
 rightauth=pubkey
 rightauth2=eap-md5
 right=%any
 rightid="C=GB, O=strongSwan, CN=my@email.com"
 rightsourceip=10.10.10.199/31
 rightsendcert=ifasked

# Unable to get the native VPN working with this setup
#conn IPSec-Android-Native
# keyexchange=ikev1
# rightauth=pubkey
# rightauth2=xauth
# right=%any
# rightsourceip=10.10.10.199/26
# rightsendcert=ifasked

I'll explain each segment in order.  The official doc can be found here.

conn %default This is the default stanza.  This instructs strongswan to use anything here in addition to other connections if defined.
dpdaction=restart Controls the use of the Dead Peer Detection.
dpddelay=300s How often to check if the client is still connected.
reauth=yes When re-exchanging keys whether to re-athenticate.
aggressive=no Whether to use IKEv1 Aggressive or Main Mode (the default).
fragmentation=yes If set to yes (the default since 5.5.1) and the peer supports it, larger IKE messages will be sent in fragments.
type=tunnel The type of the connection.
forceencaps=yes Force UDP encapsulation for ESP packets even if no NAT situation is detected.
modeconfig=pull Defines which mode is used to assign a virtual IP.
auto=add What operation, if any, should be done automatically at IPsec startup.
closeaction=clear Defines the action to take if the remote peer unexpectedly closes.
compress=no Whether IPComp compression of content is proposed on the connection.
left=my.vpn.com The IP address of the participant's public-network interface.
leftid="C=GB, O=strongSwan, CN=my.vpn.com" How the left|right participant should be identified for authentication.
leftsubnet=0.0.0.0/0 Private subnet behind the left participant.
leftcert=vpnHostCert.pem The path to the left|right participant's X.509 certificate.
leftsendcert=always Ifasked, meaning that
the peer must send a certificate request (CR) payload in order to get a certificate in return
leftfirewall=yes Whether the left participant is doing forwarding-firewalling (including masquerading)
using iptables for traffic from leftsubnet.
conn IPSec-Android-Strongswan A connection stanza
keyexchange=ikev2 Method of key exchange.
rightauth=pubkey Authentication method to use locally (left) or require from the remote (right) side.
rightauth2=eap-md5 Same as rightauth, but defines an additional authentication exchange.
right=%any If %any is used for the remote endpoint it literally means any IP address.
rightid="C=GB, O=strongSwan, CN=my@email.com" How the right participant should be identified for authentication.
rightsourceip=10.10.10.199/26 The internal source IP to use in a tunnel for the remote peer.
rightsendcert=ifasked ifasked, meaning that
the peer must send a certificate request (CR) payload in order to get a certificate in return.
conn IPSec-Android-Native A connection stanza
keyexchange=ikev1 Method of key exchange.
rightauth=pubkey Authentication method to use locally (left) or require from the remote (right) side.
rightauth2=xauth Same as rightauth, but defines an additional authentication exchange.
right=%any If %any is used for the remote endpoint it literally means any IP address.
rightsourceip=10.10.10.200 The internal source IP to use in a tunnel for the remote peer.
rightsendcert=ifasked ifasked, meaning that
the peer must send a certificate request (CR) payload in order to get a certificate in return.

Next we setup a secret.

# cat /etc/ipsec.secrets 
: RSA vpnHostKey.pem
<user> : XAUTH "top_secret_password"
<user> : EAP "top_secret_password"

I'll explain each line.  Full documentation can be found here.

: RSA vpnHostKey.pem Sets the cert to be used for authentication.
<user> : XAUTH "top_secret_password" Sets the password for XAUTH method of authentication.
<user> : EAP "top_secret_password" Sets the password for EAP method of authentication.

That's it for the strongswan config itself. Now we need to create the certificates.

As of version 5.8.0, ipsec.conf and ipsec.secrets are no longer required or work.  These now need to be converted into a json format in swanctl.conf.

connections {
        IPSec-Android-Strongswan {
          unique=no
          version=2
          dpd_delay=300s
          rekey_time=0
          reauth_time=0
          aggressive=no
          fragmentation=yes
          encap=yes
          pull=yes
          version=2
          pools=vpn_example
          mobike=yes
          send_cert=always
                local {
                  certs=vpnHostCert.pem
                  id = @vpn.example.com
                }
                remote {
                  auth=pubkey
                }
                remote2 {
                  auth=eap-md5
                }
                children {
                        IPSec-Android-Strongswan {
                          mode=tunnel
                          dpd_action=clear
                          start_action=none
                          close_action=none
                          ipcomp=yes
                          local_ts=0.0.0.0/0
                        }
                }
        }
}
pools {
  vpn_example {
    addrs=10.10.10.10/30
  }
}
secrets {
  private-vpn_example {
    file=vpnHostKey.pem
  }
  eap-user1 {
    id=username1
    secret="password1"
  }
  eap-user2 {
    id=username2
    secret="password2"
  }
}
authorities {
  IPSec-Android-Strongswan {
    cacert=strongswanCert.pem
  }
}

Certificates

NOTE:  From 5.8.0, the certificate paths have changed from /etc/ipsec.d/... to /etc/swanctl/...

x509/ = User Certs

private/ = Private key(s)

x509ca/ = Root cert(s)

Let's start by creating the root certificate:

$ cd /etc/ipsec.d/
$ ipsec pki --gen --type rsa --size 4096 --outform pem > private/strongswanKey.pem
$ chmod 600 private/strongswanKey.pem
$ ipsec pki --self --ca --lifetime 3650 --in private/strongswanKey.pem --type rsa --dn "C=GB, O=strongSwan, CN=strongSwan Root CA" --outform pem > cacerts/strongswanCert.pem

You can change the Distinguished Name (DN) to more relevant values for country (C), organization (O), and common name (CN), but you don’t have to.

To list the properties of your newly generated certificate, type in the following command:

$ ipsec pki --print --in cacerts/strongswanCert.pem

Create your VPN host certificate:

$ cd /etc/ipsec.d/
$ ipsec pki --gen --type rsa --size 2048 --outform pem > private/vpnHostKey.pem
$ chmod 600 private/vpnHostKey.pem
$ ipsec pki --pub --in private/vpnHostKey.pem --type rsa | ipsec pki --issue --lifetime 730 --cacert cacerts/strongswanCert.pem --cakey private/strongswanKey.pem --dn "C=GB, O=strongSwan, CN=my.vpn.com" --san my.vpn.com --flag serverAuth --flag ikeIntermediate --outform pem > certs/vpnHostCert.pem

To look at the properties of your new certificate, execute the command:

ipsec pki --print --in certs/vpnHostCert.pem

Create a client certificate:

$ cd /etc/ipsec.d/
$ ipsec pki --gen --type rsa --size 2048 --outform pem > private/UserKey.pem
$ chmod 600 private/UserKey.pem
$ ipsec pki --pub --in private/UserKey.pem --type rsa | ipsec pki --issue --lifetime 730 --cacert cacerts/strongswanCert.pem --cakey private/strongswanKey.pem --dn "C=GB, O=strongSwan, CN=user@vpn.com" --san user@vpn.com --outform pem > certs/UserCert.pem

Export client certificate as a PKCS#12 file:

cd /etc/ipsec.d/
$ openssl pkcs12 -export -inkey private/UserKey.pem \
 -in certs/UserCert.pem -name "User's VPN Certificate" \
 -certfile cacerts/strongswanCert.pem \
 -caname "strongSwan Root CA" \
 -out User.p12

Revoke a certificate (if needed):

$ cd /etc/ipsec.d/
$ ipsec pki --signcrl --reason key-compromise \
 --cacert cacerts/strongswanCert.pem \
 --cakey private/strongswanKey.pem \
 --cert certs/UserCert.pem \
 --outform pem > crls/crl.pem

To add another revoked certificate to the same list, we need to copy the existing list into a temporary file:

$ cd /etc/ipsec.d/
$ cp crls/crl.pem crl.pem.tmp
$ ipsec pki --signcrl --reason key-compromise \
	--cacert cacerts/strongswanCert.pem \
	--cakey private/strongswanKey.pem \
	--cert certs/AnotherStolenCert.pem \
	--lastcrl crl.pem.tmp \
	--outform pem > crls/crl.pem
$ rm crl.pem.tmp

CERTIFICATES – RECAP:

So far you’ve created the following files:

/etc/ipsec.d/private/strongswanKey.pem  # CA private key
/etc/ipsec.d/cacerts/strongswanCert.pem # CA certificate
/etc/ipsec.d/private/vpnHostKey.pem     # VPN host private key
/etc/ipsec.d/certs/vpnHostCert.pem      # VPN host certificate
/etc/ipsec.d/private/UserKey.pem   # Client "User" private key
/etc/ipsec.d/certs/UserCert.pem    # Client "User" certificate
/etc/ipsec.d/User.p12              # Client "User" PKCS#12 file

Firewall Rules

I'm sure you'll have some sort of router ;)  So you'll need to open up and forward the ports to your VPN server.

You'll only need UDP ports 500 & 4500.

Port 500 is the IPSEC port and 4500 is the port used for NATing.

That's the entry point sorted.  Now for iptables.

I have these defined to manage the VPN traffic:

iptables -t nat -A POSTROUTING -s <VIP> -o <INTERFACE> -m policy --dir out --pol ipsec -j ACCEPT
iptables -t nat -A POSTROUTING -s <VIP> -o <INTERFACE> -j MASQUERADE
iptables -t nat -A POSTROUTING -o <INTERFACE> ! -p esp -j SNAT --to-source <VPN_IP>
iptables -A INPUT -p esp -j ACCEPT
iptables -A INPUT -p ah -j ACCEPT

<VIP> is the IP/CIDR which is assigned to the client.
<INTERFACE> is the network interface name eg eth0.
<VPN_IP> is the IP the VPN server listens on.
The bottom two just accept the required protocols.

You may also need to open up access to ranges used by your mobile service provider.  eg

iptables -A INPUT -s <mobile_cidr>/22 -p udp -m multiport --dports 500,4500 -j ACCEPT

You may also need to allow the VIP address assigned to the client to connect to internal services.  This could be something as global as:

iptables -A INPUT -s 10.10.10.200 -j ACCEPT

or could be tied down to specific ports.

DNS

If the virtual IP that is assigned is on the same network as the server, you can just add the following to your ipsec.conf:

rightdns = <dns_server_ip>

If you assign a virtual IP that is on a different network, then you will need to make some additional changes.  You won't see any errors regarding DNS in any logs, it just won't work!
For example, in the client log, you'd see:

Aug 28 06:59:18 08[IKE] installing DNS server 111.111.111.119
Aug 28 06:59:18 08[IKE] installing new virtual IP 112.112.112.120

but if you try and resolve any internal hostnames, it just won't work.

You need to make the following change to either strongswan.conf or charon.conf (recommended) within the strongswan.d directory.

charon {
    plugins {
        attr {
        dns = 111.111.111.119
       split-include = 112.112.112.120, 111.111.111.0/24
             }
            }
       }

As we are splitting the DNS, we need to use the attr plugin.  You can check if this is loaded when the strongswan daemon is started.

Aug 28 07:28:23 <hostname> charon[22120]: 00[LIB] loaded plugins: charon pkcs11 aes des blowfish rc2 sha2 sha1 md4 md5 rdrand random nonce x509 revocation constraints pubkey pkcs1 pkcs7 pkcs8 pkcs12 pgp dnskey sshkey pem openssl gcrypt fips-prf gmp xcbc cmac hmac ctr ccm gcm attr kernel-netlink resolve socket-default socket-dynamic farp stroke vici updown eap-identity eap-sim eap-aka eap-aka-3gpp2 eap-simaka-pseudonym eap-simaka-reauth eap-md5 eap-gtc eap-mschapv2 eap-radius eap-tls xauth-generic xauth-eap xauth-pam dhcp unity

The other thing you will need to do (only if you run your own DNS) is to allow the VPN network to query DNS.  This is done by adding the VPN subnet or assigned virtual IP of the client to named.conf.

This is found within the options block.

allow-query { 127.0.0.1; 111.111.111.0/24; 112.112.112.120; };

Client setup (strongswan)

First of all, you'll need to get the pk12 certificate you've created onto your phone (email, cloud storage etc etc).  Once saved to a location, we need to load it into Android.

Go to settings and tap "Security".

Then tap "Install from storage".

Browse to where you saved the cert.  You will be asked for the passphrase set in the cert.

Once installed, go back to "Security" and tap "User credentials"

You should see your certificate entry.  There are no details to be had here.  The only option if you tap the cert is to remove it.

That's it for the certificate installation; now onto the client setup.

If you haven't installed Strongswan, what are you waiting for? ;)

Open the app and tap "ADD VPN PROFILE"

Complete the details and ensure you have selected the installed certificate (User certificate).

Click SAVE and you're done.

Now to test it!  Disconnect from your wifi and tap the entry you should now have in the strongswan app.  If all went well, you should be connected.

Timecapsule on Linux

TimeMachine01_Logo1

TIME CAPSULE INSTALL & SETUP

Install Netatalk

# emerge -av netatalk
net-fs/netatalk-3.1.6::gentoo USE="(acl) avahi cracklib dbus pam samba shadow ssl tcpd utils -debug -kerberos -ldap -pgp -quota -static-libs -tracker" PYTHON_TARGETS="python2_7"

Configure Netatalk

Edit the file /etc/afp.conf:

vi /etc/afp.conf

Place the following contents. Edit the paths, usernames and IP range:

[Global]
 mimic model = TimeCapsule6,106
 log level = default:warn
 log file = /var/log/afpd.log
# either individual or CIDR
 hosts allow = 196.168.100.0/24

# I didn't require this option
#[Homes]
#basedir regex = /home

[TimeMachine]
 path = /mnt/data/timecapsule/
 valid users = me you someone
 time machine = yes
 appledouble = ea


# Nor did I require this.
#[Shared Media]
# path = /mnt/data/torrents/
# valid users = me you someone

Obviously, don't forget to create the mount point.

mkdir /mnt/data/timecapsule

Set the correct perms

chmod 775 /mnt/data/timecapsule

You will also need to change the group as this will currently be root:root

chown -R root.user /mnt/data/timecapsule

or

chgrp -R user /mnt/data/timecapsule

Create & Format the destination filesystem

Create the partition.
(I just used the whole 1Tb disk)

# fdisk /dev/sdb

Once the partition is defined, set the filesystem type of af.

Disk /dev/sdb: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xb59eb59e

Device Boot Start End Sectors Size Id Type
/dev/sdb1 2048 1953525167 1953523120 931.5G af HFS / HFS+

Install the tool for formatting the filesystem.

Version 332.14_p1 at the time of writing.

emerge -av diskdev_cmds

Then format it

mkfs.hfsplus -v timemachine /dev/sdb1

Automount at boot time.  Add it to /etc/fstab

/dev/sdb1 /mnt/data/timecapsule hfsplus rw,noatime,user 0 1

Now mount it.

mount -a

Start the netatalk daemon. (I use systemd)

systemctl start netatalk

If all went to plan, the filesystem is mounted and the netatalk daemon running.  On the Mac, when you open Timemachine, you should automagically see your server.
Select it and enter the account details.  For security reasons, I created a new user on the server and set /sbin/nologin as the shell.  This way, the user has no access to the server and is not privileged to do anything.

Portage TMPFS

Portage TMPDIR on tmpfs

When emerging packages it is possible to build them in tmpfs (RAM) space instead of having build files pushed and pulled to Hard Disk Drive (HDD) or Solid State Drive (SSD) space. Building in tmpfs both speeds up emerge times and reduces HDD/SSD wearing. For system's containing SSDs, it is generally a good idea to have Portage compile using tmpfs (RAM) instead burning up precious SSD write cycles (especially on something like compiling software).

fstab Configuration

Mount Portage's TMPDIR to tmpfs by adding the following to the system's /etc/fstab config file:

FILE /etc/fstab tmpfs fstab example
tmpfs		/var/tmp/portage		tmpfs	uid=portage,gid=portage,mode=775,size=2048M,noatime	0 0

Adjust the size parameter /etc/fstab to the desired amount of RAM. Systems with large amounts of RAM can increase the number quite significantly.

After /etc/fstab has been modified, mount Portage's TMPDIR to RAM by running the mount command followed by the directory location outline in fstab:

root #mount /var/tmp/portage

Considering tmpfs' Size

The system's tmpfs space should be large enough to handle the largest packages to be compiled on the system. If the tmpfs space were to ever become completely full then the emerge will fail. Most packages do not need more than 1 GB of tmpfs space their compiles, but there are few very large packages. If you have a lot of RAM, setting Be careful to include enough tmpfs space when installing the following packages:

app-office/openoffice: 10GBs or so.

www-client/chromium: More than 2GBs.

sys-devel/gcc: More than 4 GiB.

Per-Package Choices at Compile Time

Portage can be configured to build large packages outside of the tmpfs space on a per-package basis.

Create a file to tell Portage where to place the temporary files directory:

FILE /etc/portage/env/notmpfs.conf
PORTAGE_TMPDIR="/var/tmp/notmpfs"

Create a separate temporary file directory outside of the tmpfs mount location:

mkdir /var/tmp/notmpfs && chown portage:portage /var/tmp/notmpfs && chmod 775 /var/tmp/notmpfs

Create a special Portage file called package.env in /etc/portage and list all the packages that are too large to be compiled using tmpfs:

FILE /etc/portage/package.env
app-office/libreoffice notmpfs.conf
mail-client/mozilla-thunderbird notmpfs.conf
www-client/chromium notmpfs.conf

Kodi with Systemd

kodi-logo-weis3
Kodi As An Appliance

After installing a base gentoo OS (no gui)
install evilvm and kodi (or use upstream kodi)

If using upstream kodi, create the file: /etc/portage/sets/kodi and populate with: (adjust accordingly)

app-eselect/eselect-java
dev-java/java-config
dev-java/openjdk-bin
dev-lang/swig
dev-libs/crossguid
dev-libs/flatbuffers
dev-libs/libcdio
dev-libs/libfmt
dev-libs/libfstrcmp
dev-libs/libinput
dev-libs/libtomcrypt
dev-libs/libtommath
dev-libs/rapidjson
dev-libs/spdlog
dev-libs/tinyxml
dev-python/cffi
dev-python/olefile
dev-python/pillow
dev-python/pycparser
dev-python/pycryptodome
dev-python/xkbcommon
dev-vcs/git
media-fonts/roboto
media-libs/intel-hybrid-codec-driver
media-libs/libass
media-libs/libdisplay-info
media-libs/libdisplay-info
media-libs/libdvdcss
media-libs/libdvdnav
media-libs/libdvdread
media-libs/libva-intel-driver
media-libs/libva-intel-media-driver
media-libs/taglib
media-sound/pulseaudio
net-fs/nfs-utils
net-fs/samba
net-libs/libmicrohttpd
sci-libs/kissfft
sys-apps/baselayout-java
sys-devel/clang
=llvm-core/clang-17.0.6
=llvm-core/llvm-17.0.6
x11-wm/evilwm

install the deps with: emerge -quUND @kodi

Ensure you have all the correct use flags defined in /etc/portage/package.use/package.use

Create the file: /usr/lib/systemd/system/kodi.service and populate with:

[Unit]
Description = Starts instance of Kodi
After = systemd-user-sessions.service network.target sound.target startx.service

[Service]
User = kodi
Group = kodi
PAMName=login
Type = simple
ExecStart = sh /usr/bin/kodi-standalone2 -- :0 -nolisten tcp
Restart = on-abort

[Install]
WantedBy = multi-user.target

Then create the file: /usr/lib/systemd/system/startx.service and populate with:


[Unit]
Description=StartX service

[Service]
User = kodi
Group = kodi
PAMName=login
Type = simple
ExecStart=/usr/bin/startx :0 /usr/bin/evilwm

[Install]
WantedBy=multi-user.target

Only enable the kodi server: systemctld enable kodi

If you have Intel GFX, create the file: /etc/X11/xorg.conf.d/20-intel.conf and populate with: (adjust accordingly)

Section "Module"
Load "glx"
EndSection

Section "Device"
Identifier "Card0"
Driver "modesetting"
#BusID "PCI:0:2:0"
Option "TripleBuffer" "false"
Option "TearFree" "true"
Option "SwapbuffersWait" "true"
Option "AccelMethod" "glamor"
Option "DRI" "iris"
EndSection

Section "dri"
Mode 0666
EndSection

#Breaks Gnome when set to false, but breaks kodi if enabled
Section "Extensions"
Option "Composite" "False"
EndSection

Create the kodi user and assign to the following groups:

useradd -G tty,audio,video,render,pipewire kodi

If everything went to plan, executing: systemctl start kodi should fire up X and land you at kodi.

NetworkManager with no GUI

I'm writing this as systemd seems to be getting stronger and is replacing initd little by little.  Now if like me you have one or more  Linux systems that do not run a desktop environment.  You may find yourself using a few apps that normally require a GUI to be configured.  NetworkManager is one of those, but does allow you to use the CLI (nmcli).

Here's how:

Assuming you already have everything installed :)

systemctl enable NetworkManager

Will start networkmanager at boot.

nmcli d

will list all interfaces controlled by networkmanager.

To add a connection eg wifi

nmcli c add ifname wlp5s0 type wifi ssid <your ssid>

This will create the file

/etc/NetworkManager/system-connections/wifi-wlp5s0

Which will contain the skeleton config (non working)

[connection]
id=<your ssid>
uuid=b083dd98-f1e0-4bc5-bff6-56c4a1b56e2f
interface-name=wlp5s0
type=wifi
[wifi]
ssid=1027251N
mode=infrastructure

We now need to configure the connection.  (additions highlighted)

[connection]
id=<your ssid>
uuid=b083dd98-f1e0-4bc5-bff6-56c4a1b56e2f
type=wifi
[wifi]
ssid=1027251N
mode=infrastructure
mac-address=00:23:14:B7:57:A0
security=wifi-security
[wifi-security]
key-mgmt=wpa-psk
auth-alg=open
psk=<your ultra secure key>

executing

nmcli c reload

will/should now connect you :)

Block countries with IPTables

I get an absolute battering from China on a daily basis with the occasional attack from France, Germany or the US.  Time to block countries :)

First and foremost, make sure you have iptables installed, configured and working.
Next we'll install some additions:

emerge -av xtables-addons geoipupdate

You may need to remove some of the modules to allow xtables to install (depends on your setup).  This can be achieved by adding the following line to /etc/portage/make.conf:

XTABLES_ADDONS="=account =chaos =condition =delude =dhcpmac =fuzzy geoip =iface =ipmark =ipp2p =ipv4options =length2 =logmark =lscan =pknock =psd =quota2 =rawnat =steal =sysrq =tarpit =dnetmap =echo =gradm"

I'm only interested in geoip, so I removed everything else.

Make the directory where iptables will look for the database:

mkdir -p /usr/share/xt_geoip/

Execute the following to download the geoiplite databases:

If you have a paid account, you could potentially replace the URLs in the download script (untested)

cd /usr/share/xt_geoip/ && /lib64/xtables-addons/xt_geoip_dl && /lib64/xtables-addons/xt_geoip_build *.csv

You could cron this as a weekly update.

xt_geoip_dl: Downloads the CSV database files
xt_geoip_build: Processes the files into a format iptables can read.

/usr/share/xt_geoip/LE/<country abbreviation>.iv4 & .iv6

Now you can block countries using iptables

iptables -A INPUT -m geoip --src-cc CN -j DROP

An iptables -L -n will show

DROP all -- 0.0.0.0/0 0.0.0.0/0 -m geoip --source-country CN

 

Joining video files

If you've ever downloaded several video files that made up a complete <insert description>.  There is a very simple way to join them up.

Say you had 3 files video1.avi, video2.avi & video3.avi.  Now provided they've been encoded with identical settings, just follow this process:

1) echo "file 'video1.avi'" >> list.txt
echo "file 'video2.avi'" >> list.txt
echo "file 'video3.avi;" >> list.txt

2) ffmpeg -f concat -i list.txt -c copy video.avi

That's it!

Nexus Unlock and Root/Unroot.

Original post is here.

Before beginning, you’ll want to install the Android SDK tools onto your computer so you can use tools such as fastboot and adb. Otherwise, you won’t be able to communicate with your Nexus device.  On Gentoo this is done by adding dev-util/android-tools to /etc/portage/package.keywords and then emerge -av dev-util/android-tools.

nexus4_lte_fastboot
Unlocking the Nexus device is really simply. Boot it up into fastboot mode — on the Nexus 4, this is done by holding the Power + Volume Down buttons at the same time. Once you see a screen like above, open up a command line terminal and (assuming you’re using Linux; adjust slightly as appropriate for other operating systems) type fastboot devices. If anything appears from this command, the computer recognizes the Nexus device. Then, type fastboot oem unlock, and accept the warning shown on the Nexus device by navigating with the Volume Buttons and accepting with the Power button. Congratulations, your Nexus device is now unlocked!

Rooting manually is a little tricky, because rooting the stock version of Android (the one that Google provided that originally came with the device) used to be pretty tricky. At least with a Nexus device, you just need to download a flashable CF-Auto-Root file and flash that onto the device, giving you root access. However, you’re still most likely going to need to use a custom recovery, and while you’re at it you may as well install a custom ROM onto your device (which won’t require an additional flash of CF-Auto-Root).

Unrooting your device is nearly impossible to do without flashing stock back onto your device. You’ll need to download the latest factory image from Google’s Android Developer Images site, and move the two included .img files from the .zip into a separate folder, and then open the secondary .zip and move those .img files into the same separate folder as well.

Then type the following commands into your computer while it is connected to the Nexus device:

  1. fastboot devices (to make sure that the computer sees your Nexus 4)
  2. fastboot flash bootloader bootloader_xxxx.img (Replace bootloader_xxxx.img with the actual file name)
  3. fastboot reboot-bootloader
  4. fastboot flash radio radio_xxxx.img (Replace radio_xxxx.img with the actual file name. For Android 4.3, the version should end in a .84)
  5. fastboot reboot-bootloader
  6. fastboot flash system system.img
  7. fastboot flash userdata userdata.img
  8. fastboot flash boot boot.img
  9. fastboot flash recovery recovery.img
  10. fastboot format cache (to remove any old traces of the old system)
  11. OPTIONAL: fastboot oem lock (this re-locks the bootloader to prevent future tinkering with the device, i.e. forces you to “unlock” the bootloader again and wipe the device before tinkering)
  12. fasboot reboot

Conclusion

You should now be back to a completely stock configuration for your Nexus device! Playing around with a Nexus device is a lot of fun, and it provides a great learning experience about how to tinker with Android. Above all, it can provide a lot of extra functionality (such as LTE functionality on the Nexus 4) that isn’t built into Android itself — you just have to go find it yourself.

25 Most Frequently Used Linux IPTables Rules Examples

I thought this was a very good article.  Credit to the original author.

by Ramesh Natarajan on June 14, 2011

At a first glance, IPTables rules might look cryptic.

In this article, I’ve given 25 practical IPTables rules that you can copy/paste and use it for your needs.

These examples will act as a basic templates for you to tweak these rules to suite your specific requirement.

1. Delete Existing Rules

Before you start building new set of rules, you might want to clean-up all the default rules, and existing rules. Use the iptables flush command as shown below to do this.

iptables -F
(or)
iptables --flush

2. Set Default Chain Policies

The default chain policy is ACCEPT. Change this to DROP for all INPUT, FORWARD, and OUTPUT chains as shown below.

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

When you make both INPUT, and OUTPUT chain’s default policy as DROP, for every firewall rule requirement you have, you should define two rules. i.e one for incoming and one for outgoing.

In all our examples below, we have two rules for each scenario, as we’ve set DROP as default policy for both INPUT and OUTPUT chain.

If you trust your internal users, you can omit the last line above. i.e Do not DROP all outgoing packets by default. In that case, for every firewall rule requirement you have, you just have to define only one rule. i.e define rule only for incoming, as the outgoing is ACCEPT for all packets.

Note: If you don’t know what a chain means, you should first familiarize yourself with the IPTables fundamentals.

3. Block a Specific ip-address

Before we proceed further will other examples, if you want to block a specific ip-address, you should do that first as shown below. Change the “x.x.x.x” in the following example to the specific ip-address that you like to block.

BLOCK_THIS_IP="x.x.x.x"
iptables -A INPUT -s "$BLOCK_THIS_IP" -j DROP

This is helpful when you find some strange activities from a specific ip-address in your log files, and you want to temporarily block that ip-address while you do further research.

You can also use one of the following variations, which blocks only TCP traffic on eth0 connection for this ip-address.

iptables -A INPUT -i eth0 -s "$BLOCK_THIS_IP" -j DROP
iptables -A INPUT -i eth0 -p tcp -s "$BLOCK_THIS_IP" -j DROP

4. Allow ALL Incoming SSH

The following rules allow ALL incoming ssh connections on eth0 interface.

iptables -A INPUT -i eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

Note: If you like to understand exactly what each and every one of the arguments means, you should read How to Add IPTables Firewall Rules

5. Allow Incoming SSH only from a Sepcific Network

The following rules allow incoming ssh connections only from 192.168.100.X network.

iptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

In the above example, instead of /24, you can also use the full subnet mask. i.e “192.168.100.0/255.255.255.0″.

6. Allow Incoming HTTP and HTTPS

The following rules allow all incoming web traffic. i.e HTTP traffic to port 80.

iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT

The following rules allow all incoming secure web traffic. i.e HTTPS traffic to port 443.

iptables -A INPUT -i eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT

7. Combine Multiple Rules Together using MultiPorts

When you are allowing incoming connections from outside world to multiple ports, instead of writing individual rules for each and every port, you can combine them together using the multiport extension as shown below.

The following example allows all incoming SSH, HTTP and HTTPS traffic.

iptables -A INPUT -i eth0 -p tcp -m multiport --dports 22,80,443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp -m multiport --sports 22,80,443 -m state --state ESTABLISHED -j ACCEPT

8. Allow Outgoing SSH

The following rules allow outgoing ssh connection. i.e When you ssh from inside to an outside server.

iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

Please note that this is slightly different than the incoming rule. i.e We allow both the NEW and ESTABLISHED state on the OUTPUT chain, and only ESTABLISHED state on the INPUT chain. For the incoming rule, it is vice versa.

9. Allow Outgoing SSH only to a Specific Network

The following rules allow outgoing ssh connection only to a specific network. i.e You an ssh only to 192.168.100.0/24 network from the inside.

iptables -A OUTPUT -o eth0 -p tcp -d 192.168.100.0/24 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT

10. Allow Outgoing HTTPS

The following rules allow outgoing secure web traffic. This is helpful when you want to allow internet traffic for your users. On servers, these rules are also helpful when you want to use wget to download some files from outside.

iptables -A OUTPUT -o eth0 -p tcp --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp --sport 443 -m state --state ESTABLISHED -j ACCEPT

Note: For outgoing HTTP web traffic, add two additional rules like the above, and change 443 to 80.

11. Load Balance Incoming Web Traffic

You can also load balance your incoming web traffic using iptables firewall rules.

This uses the iptables nth extension. The following example load balances the HTTPS traffic to three different ip-address. For every 3th packet, it is load balanced to the appropriate server (using the counter 0).

iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 0 -j DNAT --to-destination 192.168.1.101:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 1 -j DNAT --to-destination 192.168.1.102:443
iptables -A PREROUTING -i eth0 -p tcp --dport 443 -m state --state NEW -m nth --counter 0 --every 3 --packet 2 -j DNAT --to-destination 192.168.1.103:443

12. Allow Ping from Outside to Inside

The following rules allow outside users to be able to ping your servers.

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A OUTPUT -p icmp --icmp-type echo-reply -j ACCEPT

13. Allow Ping from Inside to Outside

The following rules allow you to ping from inside to any of the outside servers.

iptables -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT

14. Allow Loopback Access

You should allow full loopback access on your servers. i.e access using 127.0.0.1

iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

15. Allow Internal Network to External network.

On the firewall server where one ethernet card is connected to the external, and another ethernet card connected to the internal servers, use the following rules to allow internal network talk to external network.

In this example, eth1 is connected to external network (internet), and eth0 is connected to internal network (For example: 192.168.1.x).

iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT

16. Allow outbound DNS

The following rules allow outgoing DNS connections.

iptables -A OUTPUT -p udp -o eth0 --dport 53 -j ACCEPT
iptables -A INPUT -p udp -i eth0 --sport 53 -j ACCEPT

17. Allow NIS Connections

If you are running NIS to manage your user accounts, you should allow the NIS connections. Even when the SSH connection is allowed, if you don’t allow the NIS related ypbind connections, users will not be able to login.

The NIS ports are dynamic. i.e When the ypbind starts it allocates the ports.

First do a rpcinfo -p as shown below and get the port numbers. In this example, it was using port 853 and 850.

rpcinfo -p | grep ypbind

Now allow incoming connection to the port 111, and the ports that were used by ypbind.

iptables -A INPUT -p tcp --dport 111 -j ACCEPT
iptables -A INPUT -p udp --dport 111 -j ACCEPT
iptables -A INPUT -p tcp --dport 853 -j ACCEPT
iptables -A INPUT -p udp --dport 853 -j ACCEPT
iptables -A INPUT -p tcp --dport 850 -j ACCEPT
iptables -A INPUT -p udp --dport 850 -j ACCEPT

The above will not work when you restart the ypbind, as it will have different port numbers that time.

There are two solutions to this: 1) Use static ip-address for your NIS, or 2) Use some clever shell scripting techniques to automatically grab the dynamic port number from the “rpcinfo -p” command output, and use those in the above iptables rules.

18. Allow Rsync From a Specific Network

The following rules allows rsync only from a specific network.

iptables -A INPUT -i eth0 -p tcp -s 192.168.101.0/24 --dport 873 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 873 -m state --state ESTABLISHED -j ACCEPT

19. Allow MySQL connection only from a specific network

If you are running MySQL, typically you don’t want to allow direct connection from outside. In most cases, you might have web server running on the same server where the MySQL database runs.

However DBA and developers might need to login directly to the MySQL from their laptop and desktop using MySQL client. In those case, you might want to allow your internal network to talk to the MySQL directly as shown below.

iptables -A INPUT -i eth0 -p tcp -s 192.168.100.0/24 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 3306 -m state --state ESTABLISHED -j ACCEPT

20. Allow Sendmail or Postfix Traffic

The following rules allow mail traffic. It may be sendmail or postfix.

iptables -A INPUT -i eth0 -p tcp --dport 25 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 25 -m state --state ESTABLISHED -j ACCEPT

21. Allow IMAP and IMAPS

The following rules allow IMAP/IMAP2 traffic.

iptables -A INPUT -i eth0 -p tcp --dport 143 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 143 -m state --state ESTABLISHED -j ACCEPT

The following rules allow IMAPS traffic.

iptables -A INPUT -i eth0 -p tcp --dport 993 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 993 -m state --state ESTABLISHED -j ACCEPT

22. Allow POP3 and POP3S

The following rules allow POP3 access.

iptables -A INPUT -i eth0 -p tcp --dport 110 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 110 -m state --state ESTABLISHED -j ACCEPT

The following rules allow POP3S access.

iptables -A INPUT -i eth0 -p tcp --dport 995 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 995 -m state --state ESTABLISHED -j ACCEPT

23. Prevent DoS Attack

The following iptables rule will help you prevent the Denial of Service (DoS) attack on your webserver.

iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT

In the above example:

  • -m limit: This uses the limit iptables extension
  • –limit 25/minute: This limits only maximum of 25 connection per minute. Change this value based on your specific requirement
  • –limit-burst 100: This value indicates that the limit/minute will be enforced only after the total number of connection have reached the limit-burst level.

24. Port Forwarding

The following example routes all traffic that comes to the port 442 to 22. This means that the incoming ssh connection can come from both port 22 and 422.

iptables -t nat -A PREROUTING -p tcp -d 192.168.102.37 --dport 422 -j DNAT --to 192.168.102.37:22

If you do the above, you also need to explicitly allow incoming connection on the port 422.

iptables -A INPUT -i eth0 -p tcp --dport 422 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o eth0 -p tcp --sport 422 -m state --state ESTABLISHED -j ACCEPT

25. Log Dropped Packets

You might also want to log all the dropped packets. These rules should be at the bottom.

First, create a new chain called LOGGING.

iptables -N LOGGING

Next, make sure all the remaining incoming connections jump to the LOGGING chain as shown below.

iptables -A INPUT -j LOGGING

Next, log these packets by specifying a custom “log-prefix”.

iptables -A LOGGING -m limit --limit 2/min -j LOG --log-prefix "IPTables Packet Dropped: " --log-level 7

Finally, drop these packets.

iptables -A LOGGING -j DROP