Tag Archives: linux

Convert HDD to VDI

Virtualbox_logo

I've only had to do this a couple of times in my life, but it's useful to know ;)  There are 2 ways this can be achieved.  I'll state the PROS/CONS at the end of each guide.

Details:
Host system - Gentoo X86_64 with 24Tb storage :), VirtualBox
Guest HDD - Gentoo X86_64 500Gb

I'm going to assume that you have good Linux knowledge using the cli with mounting, tarballing, fdisk and formatting filesystems.

#1 (pure disk dump)

Obviously connect the drive you wish to convert.

Create a drive image using dd:

dd if=/dev/sdX of=/path/to/output/file.dd

Then convert it to a VDI (Virtual Disk Image):

VBoxManage convertfromraw ImageFile.dd OutputFile.vdi

Create a new virtual machine and attach the vdi as the main drive.

Once booted into the VM, you will need to install virtualbox guest addititions and may need to reconfigure/recompile the kernel.

Done!

PROS:

  • Not complicated.
  • Relatively quick to do.

CONS:

  • Uses a lot of space as dd reads every sector of the source drive.
  • If you delete any data from the VM, it will not reduce the VDI size.  Dynamic disks only grow, not shrink.

#2 (only copy files)

Connect the HDD.

Open a terminal.

su to root

Mount each filesystem.  (I did the following)

mkdir -p /mnt/{oldhdd,newhdd}/{bootfs,rootfs,homefs}

mount /dev/sdb1 /mnt/oldhdd/bootfs

mount /dev/sdb2 /mnt/oldhdd/rootfs

mount /dev/sdb3 /mnt/oldhdd/homefs

cd into the place you wish to save the data.

cd /mnt/newhdd/bootfs

tar czvf bootfs.tgz /mnt/oldhdd/bootfs/.

cd ../rootfs

tar czvf rootfs.tgz /mnt/oldhdd/rootfs/.

cd ../homefs

tar czvf homefs.tgz /mnt/oldhdd/homefs/.

If you don't have an existing Linux VM, create one including an empty HDD and boot it with your favourite Linux CD/DVD.  Ensure the tarballs you have just created are available to the VM.  hint:  setup a shared folder in the VBoxManager GUI and mount it in the VM.

You'll need to partition the empty HDD appropriately to accommodate the data you'll be restoring and format each filesystem.  Mount each filesystem you've just created and and the shared directory then unpack the tarballs to the new HDD.

So we'll mount the prepared HDD.

mount /dev/sda2 /mnt/newhdd/rootfs

mount /dev/sda1 /mnt/newhdd/rootfs/boot

eg

tar zxvf /path/to/share/rootfs.tgz -C /mnt/newhdd/rootfs

tar zxvf /path/to/share/bootfs.tgz -C /mnt/newhdd/rootfs/boot

The fun doesn't end yet :)  Now we have restored our data, we now need to reinstall the boot loader.  In this case, grub2.  But first we need to chroot into our restored data.

cd /mnt/newhdd/rootfs

mount -t proc none /mnt/newhdd/rootfs/etc/proc

chroot /mnt/newhdd/rootfs /bin/bash

env-update

source /etc/profile

grub-install /dev/sda

edit /etc/fstab if required

grub-mkconfig -o /boot/grub/grub.cfg

exit

Unmount the filesystems and reboot the VM.  If everything went to plan, you should now be booted into your VM.  You will need to install guest additions and may need to reconfigure and recompile your kernel.

PROS:
The VDI only uses the space required.

CONS:
More involved and takes longer.

#3 (existing VM)

This is a combination of #1 & #2 methods.

Create a drive image using dd:

dd if=/dev/sdX of=/path/to/output/file.dd

Then convert it to a VDI (Virtual Disk Image):

VBoxManage convertfromraw ImageFile.dd OutputFile.vdi

Add the new VDI as an additional HDD to your VM.  Also create a new HDD and partition appropriately.

Within the VM,

tar clf - -C /mnt/oldhdd/bootfs .| tar xf - -C /mnt/newhdd/bootfs

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.

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.

Splunk & Systemd

No longer required from Splunk version 7.2.2 onwards

Universal Forwarder

Copy this text into a file named "/usr/lib/systemd/system/splunkforwarder.service".

[Unit]
Description=Splunk Universal Forwarder
Wants=network.target
After=network.target

[Service]
Type=forking
RemainAfterExit=yes
ExecStart=/opt/splunkforwarder/bin/splunk start
ExecStop=/opt/splunkforwarder/bin/splunk stop
ExecReload=/opt/splunkforwarder/bin/splunk restart
StandardOutput=syslog
Restart=always

[Install]
WantedBy=multi-user.target

Next, create a symlink that systemd will use to fetch this control file.

systemctl enable splunkforwarder

That's it.  You can either reboot or run

systemctl start splunkforwarder

SearchHead, Indexer, Heavy Forwarder

Copy this text into a file named "/usr/lib/systemd/system/splunkforwarder.service".

[Unit]
Description=Splunk
Wants=network.target
After=network.target

[Service]
User=splunk
Group=splunk
Type=forking
RemainAfterExit=yes
ExecStart=/opt/splunk/bin/splunk start --answer-yes --no-prompt --accept-license
ExecStop=/opt/splunk/bin/splunk stop
ExecReload=/opt/splunk/bin/splunk restart
StandardOutput=syslog
#ExecStart=/bin/sh -c "echo never >/sys/kernel/mm/transparent_hugepage/enabled"
#ExecStart=/bin/sh -c "echo never >/sys/kernel/mm/transparent_hugepage/defrag"
#ulimit -Sn 65535
#ulimit -Hn 65535
LimitNOFILE=65535
#ulimit -Su 20480
#ulimit -Hu 20480
LimitNPROC=20480
#ulimit -Hf unlimited
#ulimit -Sf unlimited
LimitFSIZE=infinity
LimitCORE=infinity
#Restart=always

[Install]
WantedBy=multi-user.target
If you have THP compiled into your kernel (hint: it's enabled by default), then you'll need to uncomment the two ExecStart lines

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

Flacpack automation.

On my travels around t'interweb, I occasionally download the odd album in a lossless format. These are usually direct from a bands site or from sites like allflac.com or bandcamp.com . I like to archive these off and keep them somewhere safe. The usual procedure for this has been, create a rar archive then parity redundancy followed by unpacking the flac files, converting to mp3 and then tagging and renaming each file.
Quite frankly I was getting bored of this so created a script. It's not perfect by a long shot, but if you have the prerequisites in place, it usual does the job :)

Pop this in /usr/local/bin

Bash script here.

PREREQUISITES:
Script *MUST* be called from within the source directory.
auCDtect for checking the authenticity of the lossless. (now available in portage)

USAGE:
flacpack -V <toggle various> -N <don't encode to mp3> -h <help>

Bash Colours

Example:
echo -e "\e[1;34mThis is a blue text.\e[0m"

Explanation:
Bash uses numeric codes to set attributes of the text to be displayed.

Attribute codes:
00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed

Text colour codes:
30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white

Background colour codes:
40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white

In the example above, I used the ANSI escape sequence \e[attribute code;text colour codem to display a blue text. Therefore, we have to use -e option in calling echo to escape the input. Note that the colour effect had to be ended by \e[0m to prevent the display of the prompt with different colours. However, the effects are sometimes interesting. I encourage you to play around with it.

To have a background, we must use the background colour codes. The sequence then becomes \e[attribute code;text colour code;background colour codem. As you can guess, any missing code is simply taken as zero value by bash. Provided you shell supports 8-bit colours (the new Cygwin version 1.43 and a00.seng.engr do), you can display a coloured welcome message when you log into bash should you wish to.

Exim Cheat Sheet

Here are some useful things to know for managing an Exim 4 server. This assumes a prior working knowledge of SMTP, MTAs, and a UNIX shell prompt.

Message-IDs and spool files

The message-IDs that Exim uses to refer to messages in its queue are mixed-case alpha-numeric, and take the form of: XXXXXX-YYYYYY-ZZ. Most commands related to managing the queue and logging use these message-ids.

There are three -- count 'em, THREE -- files for each message in the spool directory. If you're dealing with these files by hand, instead of using the appropriate exim commands as detailed below, make sure you get them all, and don't leave Exim with remnants of messages in the queue. I used to mess directly with these files when I first started running Exim machines, but thanks to the utilities described below, I haven't needed to do that in many months.

Files in /var/spool/exim/msglog contain logging information for each message and are named the same as the message-id.

Files in /var/spool/exim/input are named after the message-id, plus a suffix denoting whether it is the envelope header (-H) or message data (-D).

These directories may contain further hashed subdirectories to deal with larger mail queues, so don't expect everything to always appear directly in the top /var/spool/exim/input or /var/spool/exim/msglog directories; any searches or greps will need to be recursive. See if there is a proper way to do what you're doing before working directly on the spool files.

Basic information

Print a count of the messages in the queue:

root@localhost# exim -bpc

Print a listing of the messages in the queue (time queued, size, message-id, sender, recipient):

root@localhost# exim -bp

Print a summary of messages in the queue (count, volume, oldest, newest, domain, and totals):

root@localhost# exim -bp | exiqsumm

Print what Exim is doing right now:

root@localhost# exiwhat

Test how exim will route a given address:

root@localhost# exim -bt alias@localdomain.com
user@thishost.com
    <-- alias@localdomain.com
  router = localuser, transport = local_delivery
root@localhost# exim -bt user@thishost.com
user@thishost.com
  router = localuser, transport = local_delivery
root@localhost# exim -bt user@remotehost.com
  router = lookuphost, transport = remote_smtp
  host mail.remotehost.com [1.2.3.4] MX=0

Run a pretend SMTP transaction from the command line, as if it were coming from the given IP address. This will display Exim's checks, ACLs, and filters as they are applied. The message will NOT actually be delivered.

root@localhost# exim -bh 192.168.11.22

Display all of Exim's configuration settings:

root@localhost# exim -bP

Searching the queue with exiqgrep

Exim includes a utility that is quite nice for grepping through the queue, called exiqgrep. Learn it. Know it. Live it. If you're not using this, and if you're not familiar with the various flags it uses, you're probably doing things the hard way, like piping `exim -bp` into awk, grep, cut, or `wc -l`. Don't make life harder than it already is.

First, various flags that control what messages are matched. These can be combined to come up with a very particular search.

Use -f to search the queue for messages from a specific sender:

root@localhost# exiqgrep -f [luser]@domain

Use -r to search the queue for messages for a specific recipient/domain:

root@localhost# exiqgrep -r [luser]@domain

Use -o to print messages older than the specified number of seconds. For example, messages older than 1 day:

root@localhost# exiqgrep -o 86400 [...]

Use -y to print messages that are younger than the specified number of seconds. For example, messages less than an hour old:

root@localhost# exiqgrep -y 3600 [...]

Use -s to match the size of a message with a regex. For example, 700-799 bytes:

root@localhost# exiqgrep -s '^7..$' [...]

Use -z to match only frozen messages, or -x to match only unfrozen messages.

There are also a few flags that control the display of the output.

Use -i to print just the message-id as a result of one of the above two searches:

root@localhost# exiqgrep -i [ -r | -f ] ...

Use -c to print a count of messages matching one of the above searches:

root@localhost# exiqgrep -c ...

Print just the message-id of the entire queue:

root@localhost# exiqgrep -i

Managing the queue

The main exim binary (/usr/sbin/exim) is used with various flags to make things happen to messages in the queue. Most of these require one or more message-IDs to be specified in the command line, which is where `exiqgrep -i` as described above really comes in handy.

Start a queue run:

root@localhost# exim -q -v

Start a queue run for just local deliveries:

root@localhost# exim -ql -v

Remove a message from the queue:

root@localhost# exim -Mrm <message-id> [ <message-id> ... ]

Freeze a message:

root@localhost# exim -Mf <message-id> [ <message-id> ... ]

Thaw a message:

root@localhost# exim -Mt <message-id> [ <message-id> ... ]

Deliver a message, whether it's frozen or not, whether the retry time has been reached or not:

root@localhost# exim -M <message-id> [ <message-id> ... ]

Deliver a message, but only if the retry time has been reached:

root@localhost# exim -Mc <message-id> [ <message-id> ... ]

Force a message to fail and bounce as "cancelled by administrator":

root@localhost# exim -Mg <message-id> [ <message-id> ... ]

Remove all frozen messages:

root@localhost# exiqgrep -z -i | xargs exim -Mrm

Remove all messages older than five days (86400 * 5 = 432000 seconds):

root@localhost# exiqgrep -o 432000 -i | xargs exim -Mrm

Freeze all queued mail from a given sender:

root@localhost# exiqgrep -i -f luser@example.tld | xargs exim -Mf

View a message's headers:

root@localhost# exim -Mvh <message-id>

View a message's body:

root@localhost# exim -Mvb <message-id>

View a message's logs:

root@localhost# exim -Mvl <message-id>

Add a recipient to a message:

root@localhost# exim -Mar <message-id> <address> [ <address> ... ]

Edit the sender of a message:

root@localhost# exim -Mes <message-id> <address>

Access control

Exim allows you to apply access control lists at various points of the SMTP transaction by specifying an ACL to use and defining its conditions in exim.conf. You could start with the HELO string.

# Specify the ACL to use after HELO
acl_smtp_helo = check_helo

# Conditions for the check_helo ACL:
check_helo:

    deny message = Gave HELO/EHLO as "friend"
    log_message = HELO/EHLO friend
    condition = ${if eq {$sender_helo_name}{friend} {yes}{no}}

    deny message = Gave HELO/EHLO as our IP address
    log_message = HELO/EHLO our IP address
    condition = ${if eq {$sender_helo_name}{$interface_address} {yes}{no}}

    accept

NOTE: Pursue HELO checking at your own peril. The HELO is fairly unimportant in the grand scheme of SMTP these days, so don't put too much faith in whatever it contains. Some spam might seem to use a telltale HELO string, but you might be surprised at how many legitimate messages start off with a questionable HELO as well. Anyway, it's just as easy for a spammer to send a proper HELO than it is to send HELO im.a.spammer, so consider yourself lucky if you're able to stop much spam this way.

Next, you can perform a check on the sender address or remote host. This shows how to do that after the RCPT TO command; if you reject here, as opposed to rejecting after the MAIL FROM, you'll have better data to log, such as who the message was intended for.

# Specify the ACL to use after RCPT TO
acl_smtp_rcpt = check_recipient

# Conditions for the check_recipient ACL
check_recipient:

    # [...]

    drop hosts = /etc/exim_reject_hosts
    drop senders = /etc/exim_reject_senders

    # [ Probably a whole lot more... ]

This example uses two plain text files as blacklists. Add appropriate entries to these files - hostnames/IP addresses to /etc/exim_reject_hosts, addresses to /etc/exim_reject_senders, one entry per line.

It is also possible to perform content scanning using a regex against the body of a message, though obviously this can cause Exim to use more CPU than it otherwise would need to, especially on large messages.

# Specify the ACL to use after DATA
acl_smtp_data = check_message

# Conditions for the check_messages ACL
check_message:

    deny message = "Sorry, Charlie: $regex_match_string"
    regex = ^Subject:: .*Lower your self-esteem by becoming a sysadmin

    accept

Fix SMTP-Auth for Pine

If pine can't use SMTP authentication on an Exim host and just returns an "unable to authenticate" message without even asking for a password, add the following line to exim.conf:

  begin authenticators

  fixed_plain:
  driver = plaintext
  public_name = PLAIN
  server_condition = "${perl{checkuserpass}{$1}{$2}{$3}}"
  server_set_id = $2
> server_prompts = :

This was a problem on CPanel Exim builds awhile ago, but they seem to have added this line to their current stock configuration.

Log the subject line

This is one of the most useful configuration tweaks I've ever found for Exim. Add this to exim.conf, and you can log the subject lines of messages that pass through your server. This is great for troubleshooting, and for getting a very rough idea of what messages may be spam.

log_selector = +subject

Reducing or increasing what is logged.

Disable identd lookups

Frankly, I don't think identd has been useful for a long time, if ever. Identd relies on the connecting host to confirm the identity (system UID) of the remote user who owns the process that is making the network connection. This may be of some use in the world of shell accounts and IRC users, but it really has no place on a high-volume SMTP server, where the UID is often simply "mail" or whatever the remote MTA runs as, which is useless to know. It's overhead, and results in nothing but delays while the identd query is refused or times out. You can stop your Exim server from making these queries by setting the timeout to zero seconds in exim.conf:

rfc1413_query_timeout = 0s

Disable Attachment Blocking

To disable the executable-attachment blocking that many Cpanel servers do by default but don't provide any controls for on a per-domain basis, add the following block to the beginning of the /etc/antivirus.exim file:

if $header_to: matches "example\.com|example2\.com"
then
  finish
endif

It is probably possible to use a separate file to list these domains, but I haven't had to do this enough times to warrant setting such a thing up.

Searching the logs with exigrep

The exigrep utility (not to be confused with exiqgrep) is used to search an exim log for a string or pattern. It will print all log entries with the same internal message-id as those that matched the pattern, which is very handy since any message will take up at least three lines in the log. exigrep will search the entire content of a log entry, not just particular fields.

One can search for messages sent from a particular IP address:

root@localhost# exigrep '<= .* \[12.34.56.78\] ' /path/to/exim_log

Search for messages sent to a particular IP address:

root@localhost# exigrep '=> .* \[12.34.56.78\]' /path/to/exim_log

This example searches for outgoing messages, which have the "=>" symbol, sent to "user@domain.tld". The pipe to grep for the "<=" symbol will match only the lines with information on the sender - the From address, the sender's IP address, the message size, the message ID, and the subject line if you have enabled logging the subject. The purpose of doing such a search is that the desired information is not on the same log line as the string being searched for.

root@localhost# exigrep '=> .*user@domain.tld' /path/to/exim_log | fgrep '<='

Generate and display Exim stats from a logfile:

root@localhost# eximstats /path/to/exim_mainlog

Same as above, with less verbose output:

root@localhost# eximstats -ne -nr -nt /path/to/exim_mainlog

Same as above, for one particular day:

root@localhost# fgrep YYYY-MM-DD /path/to/exim_mainlog | eximstats

Bonus!

To delete all queued messages containing a certain string in the body:

root@localhost# grep -lr 'a certain string' /var/spool/exim/input/ | \
                sed -e 's/^.*\/\([a-zA-Z0-9-]*\)-[DH]$/\1/g' | xargs exim -Mrm

Note that the above only delves into /var/spool/exim in order to grep for queue files with the given string, and that's just because exiqgrep doesn't have a feature to grep the actual bodies of messages. If you are deleting these files directly, YOU ARE DOING IT WRONG! Use the appropriate exim command to properly deal with the queue.

If you have to feed many, many message-ids (such as the output of an `exiqgrep -i` command that returns a lot of matches) to an exim command, you may exhaust the limit of your shell's command line arguments. In that case, pipe the listing of message-ids into xargs to run only a limited number of them at once. For example, to remove thousands of messages sent from joe@example.com:

root@localhost# exiqgrep -i -f '<joe@example.com>' | xargs exim -Mrm

Speaking of "DOING IT WRONG" -- Attention, CPanel forum readers

I get a number of hits to this page from a link in this post at the CPanel forums. The question is:

Due to spamming, spoofing from fields, etc., etc., etc., I am finding it necessary to spend more time to clear the exim queue from time to time. [...] what command would I use to delete the queue

The answer is: Just turn exim off, because your customers are better off knowing that email simply isn't running on your server, than having their queued messages deleted without notice.

Or, figure out what is happening. The examples given in that post pay no regard to the legitimacy of any message, they simply delete everything, making the presumption that if a message is in the queue, it's junk. That is total fallacy. There are a number of reasons legitimate mail can end up in the queue. Maybe your backups or CPanel's "upcp" process are running, and your load average is high -- exim goes into a queue-only mode at a certain threshold, where it stops trying to deliver messages as they come in and just queues them until the load goes back down. Or, maybe it's an outgoing message, and the DNS lookup failed, or the connection to the domain's MX failed, or maybe the remote MX is busy or greylisting you with a 4xx deferral. These are all temporary failures, not permanent ones, and the whole point of having temporary failures in SMTP and a mail queue in your MTA is to be able to try again after awhile.

Exim already purges messages from the queue after the period of time specified in exim.conf. If you have this value set appropriately, there is absolutely no point in removing everything from your queue every day with a cron job. You will lose legitimate mail, and the sender and recipient will never know if or why it happened. Do not do this!

If you regularly have a large number of messages in your queue, find out why they are there. If they are outbound messages, see who is sending them, where they're addressed to, and why they aren't getting there. If they are inbound messages, find out why they aren't getting delivered to your user's account. If you need to delete some, use exiqgrep to pick out just the ones that should be deleted.

Reload the configuration

After making changes to exim.conf, you need to give the main exim pid a SIGHUP to re-exec it and have the configuration re-read. Sure, you could stop and start the service, but that's overkill and causes a few seconds of unnecessary downtime. Just do this:

root@localhost# kill -HUP `cat /var/spool/exim/exim-daemon.pid`

You should then see something resembling the following in exim_mainlog:

pid 1079: SIGHUP received: re-exec daemon
exim 4.52 daemon started: pid=1079, -q1h, listening for SMTP on port 25 (IPv4)

Read The Fucking Manual

The Exim Home Page

Documentation For Exim

The Exim Specification - Version 4.5x

Exim command line arguments

Thanks to bradthemad.