The Hacker's Manual 2015
The Hacker's Manual 2015
146
PAGES OF TH
BEST LINUX E
TUTORIALS
FULLY
REVISED &
UPDATED
FOR 2014
Linux magazine
OUT
NOW!
Welcome
Welcome!
EDITORIAL
Editor Neil Mohr
Bookazine editor Chris Thornett
Managing art editor Paul Blachford
LICENSING
Head of international licensing Regina Erak
[email protected] Tel +44 (0)1225 732359
Copyright No part of this publication may be reproduced without
written permission from our publisher. We assume all letters sent
by email, fax or post are for publication unless otherwise stated,
and reserve the right to edit contributions. All contributions to Linux
Format are submitted and accepted on the basis of non-exclusive
worldwide licence to publish or license others to do so unless
otherwise agreed in advance in writing. Linux Format recognises all
copyrights in this issue. Where possible, we have acknowledged the
copyright holder. Contact us if we havent credited your copyright
and we will always correct any oversight. We cannot be held
responsible for mistakes or misprints.
All DVD demos and reader submissions are supplied to us on the
assumption they can be incorporated into a future covermounted
DVD, unless stated to the contrary.
Disclaimer All tips in this magazine are used at your own risk. We
accept no liability for any loss of data or damage to your computer,
peripherals or software through the use of any tips or advice.
Printed in the UK by William Gibbons
Future Publishing Ltd 2014
Future Publishing Ltd, 30 Monmouth Street,
Bath BA1 2BW Tel 01225 442244
Email [email protected]
Contents
Privacy
Protect your privacy .............................................................................................. 8
Set up a secure VPS........................................................................................... 16
Open source alternatives to Google services .....................20
Secure Android .......................................................................................................30
Encrypt your hard disk...................................................................................34
Hardware
Hack the Raspberry Pi.................................................................................... 38
Make an Arduino-powered controller for Kerbal.............46
Install Linux on your new Chromebook ..................................... 52
Build a multi-Pi cluster .................................................................................... 56
Free your Android phone.............................................................................60
4
Contents
Web
Hack the web.............................................................................................................66
PHP: Custom website scraping............................................................74
OwnCloud 7: Own your data ....................................................................78
Django: Build a custom CMS .................................................................. 82
Python: Make a Twitter client .................................................................86
Networking
Samba: Dancing with Windows........................................................... 92
Networking: The basics.................................................................................98
Wireshark: Analyse traffic ....................................................................... 102
Networking: Build a router......................................................................106
Deluge: Set up a torrent server .......................................................... 110
Docker: Build containers............................................................................114
Zabbix: Monitor your network............................................................. 118
Hacks
Speed up Linux ....................................................................................................124
Linux kernel: Build your own................................................................. 132
Python: Code a Gimp plugin ................................................................ 136
Terminal: Time-savers ................................................................................ 144
5
Privacy
Privacy
Privacy
G
YOUR
G
N
I
PR
T
C
S SL
Tails
Y,
AC
IV
, PRO
TE
Privacy
pt
oC
at
r
To
TR
Tru
eCrypt
GP G
y
r
C
Privacy
Make sure
you check
Firefoxs
Privacy
Preferences
to block thirdparty cookies.
Tough cookie
Almost every website uses cookies to store information about
the visitors and how they use the website. These are stored
on a users computer but the user has little control over what
information is stored within the cookie.
Cookies have plenty of legitimate uses, such as for storing
settings and preferences on a website, eg online email
services use cookies to remember your login details.
However, these cookies also allow the website to track you
as you move around on their website. This might sound pretty
harmless, but major websites such as Google arent just
confined to a single domain. Google, as you may be aware,
controls the largest advertising network on the internet.
As you move from website to website, in addition to
displaying advertisements, the advertising system will also
track the websites you visit. The advertising system then uses
this data to display advertisements that are similar to the
sites that youve visited.
Google is not alone in doing this, according to a survey by
www.digitaltrends.com, there at least 125 different
companies or company products being used to track your
online activity through the top 100 sites. Many of these are
simple advertising networks, but others are particularly
nefarious. Take for example the Disqus comment widget.
Did you
know?
The NSA has been
collecting a lot of
metadata about
internet traffic.
Things like whos
talking to who, when
and for how long.
Metadata is a lot
easier to store and
analyse, and can be
extremely personal
to the individual.
Switch to SSL
One of the first steps you should take
when navigating the Internet badlands is
to encrypt your network traffic by
switching to the Secure Sockets Layer
(SSL) protocol. SSL uses certificates to
create a secure, encrypted link between
the visitors web browser and the web
server that hosts the page.
The encrypted connection ensures
that any data thats transferred from the
browser to the web server, such as your
credit card details, remains private during
transmission. The certificate is provided
Privacy
Privacy plugins
BetterPrivacy plugin prompts you to
delete all local shared objects (LSOs)
every time you close the browser.
HTTPS Everywhere plugin Forces
the web browser to use HTTPS with all
sites that support it.
The Web of Trust plugin Identifies
dangerous websites from search results.
DoNotTrackMe plugin Stops third
parties, ad agencies, and search engines
from tracking the webpages you visit.
10
Privacy
Browse anonymously
I know JonDo
To use the service, download the Java-based JonDo client,
extract its contents and run its installation script as root. The
script will install the client under /usr/local. When its done
you can launch it by typing jondo on the command line.
When it starts for the first time, an installation assistant
will take you through a brief connection process. When its
done, the app will connect to a proxy server. You can choose
which proxy network you want to use from a pull-down list.
The geographic location of each network is marked with its
countrys flag.
In addition to the JonDo tool, the project also produces a
secure profile for Firefox called JonDoFox. Or, you can
download JonDos own Firefox-based browser called
JonDoBrowser. You can download and install the Deb
package for the browser from the projects website or add
their repository to your Debian-based distro. The
Security add-ons
In addition to using a proxy
service its also a good idea to
equip your web browser with
a bunch of security and
privacy-enhancing plugins.
With AdBlock Plus you can
blacklist and whitelist specific
advertisers. Another useful
addition is the NoScript
Avoid being tracked by spoofing the MAC address of your network card,
such as ifconfig eth0 hw ether 0A:A0:04:D4:AA:11.
11
Privacy
To prevent man-in-the-middle
attacks, ZRTP uses Short
Authentication String (SAS).
key to decrypt the message. Additionally the sender can also
sign the message with their private keys. This helps verify the
identity of the person who sent the message. The recipient
can verify the signature with the senders public key.
The freely available GNU Privacy Guard, popularly known
as GPG, is the GPL licensed alternative to the PGP suite of
cryptographic software. Youll find it pre-installed in almost
every Linux distribution.
Many desktop Linux distros ship with the Thunderbird
email client. The Enigmail extension for Thunderbird brings
the advantages of GPG to the email client, and you can
download the plugin from within the application itself.
This plugin will automatically fire up a setup wizard to
configure the extension, which will tweak your email settings,
eg so you cant compose HTML messages. Note: You can skip
the wizard and configure Enigmail manually as well.
Once installed the extension will add a new OpenPGP
entry to the Thunderbirds menu. Not all of your contacts will
Perzo.com
is a privacycentric online
comms service.
In addition to
encryption it
lets you send
messages
that will selfdestruct after
a specified
duration.
12
Privacy
Install Mailvelope
Exchange keys
Snoop-proof chats
To use the service youll have to first install it as an add-on to
either Firefox or Chrome. When initiating a conversation, youll
first have to pick a name for the chat room you wish to create
as well as a screen name. Once it has the information,
CryptoCat will generate the encryption keys, create your chat
room and log you in. Those who wish to join you must install
the browser add-on as well, and then just enter the name of
your chat room to join you.
Since theres no password protection and youll all be
using pseudonyms and not your real name, CryptoCat offers
the Q&A mechanism to verify the identity of the users.
Furthermore, from within the interface you can change your
status and toggle desktop and audio notifications.
CryptoCat is designed for facilitating encrypted multiuser group conversations. But you can also chat privately
with a member. Also remember that while your
communications are encrypted, the connection is not
anonymised and your identity can still be traced. To prevent
Encrypt messages
this, CryptoCat recommends you use the service via the Tor
proxy network.
As with text, you can also make secure voice and video
calls to another user via Voice over IP (VoIP). To ensure the
privacy of the connected parties, the creator of PGP, Phil
Zimmerman has created the ZRTP protocol.
This protocol is responsible for negotiating keys between
the connected peers and establishes a SRTP connection
between them which does the actual encryption. The GNU
ZRTP library implements most of the features.
To prevent man-in-the-middle attacks, ZRTP uses a
mechanism called Short Authentication String or SAS. ZRTP
defines the length of the SAS as four characters. When a call
is made using ZRTP, one party reads the first two characters
of the SAS and the other reads the last two. Both values
should match. Its good practice to compare the values at the
beginning of the call and then again after reasonable intervals.
A Java implementation of the GNU ZRTP library is
implemented in the open source Jitsi VoIP client [see
Roundup, p22 LXF181]. This supports protocols, such as SIP
and XMPP and can stream desktops and establish audio
conference calls.
13
Privacy
Encrypted drives
There are several options for encrypting removable drives,
such as Gnomes Disk Utility. However, the most popular
option despite the recent controversies is the TrueCrypt tool.
TrueCrypt is an open source cross-platform tool that
creates an on-the-fly encrypted volume. This means that data
is automatically encrypted right before its saved and
decrypted right after its loaded. TrueCrypt is controversial
both because its 70,000 lines of code have never been fully
vetted, and for the odd and abrupt manner with which the
development team decided to end support forTrueCrypt .
The crowdfunded Open Crypto Audit Project (https://
opencryptoaudit.org) is correcting the vetting issue and
plans to continue development. The audit project also hosts a
verified copy of v7.1, which wed recommend using as its the
last stable edition.
Instead of creating an encrypted folder, TrueCrypt creates
a virtual disk within a file and encrypts this. Whenever you use
TrueCrypt to decrypt the disk, itll be presented in your file
manager as a hard disk. While its encrypted, it appears on
your filesystem as an ordinary file. You can even copy it to a
14
Privacy
Create volume
Volume options
Mount volume
Switch distro
If youre concerned about your privacy, you should ditch your
regular distro and use one of the specialised ones designed to
protect your privacy. Not only do they lack features that tread
on your privacy (such as Ubuntus Amazon lens) they also
include several of the tools covered here.
The Debian-based Tails (The Amnesic Incognito Live)
distro runs from RAM and makes sure it doesnt use the swap
partition even if theres one available. When Tails is shutdown,
itll also securely wipes the RAM to remove all traces of ever
being used. Tails features the Gnome 2 desktop, but also
offers an option to camouflage the desktop to resemble that
of Windows XP. The distro includes the Tor Browser Bundle
and its Iceweasel-based Tor Browser includes privacyenhancing plugins such as Https Everywhere, NoScript,
Cookie Monster, Adblock Plus and others.
15
Secure VPS
16
Secure VPS
If you require a greater level of guest
isolation, then you should direct your attention
towards a bare metal (or Type 1) hypervisor,
such as VMWare or Xen. This model enables
your guest OSes to run their own kernels,
so you can run whatever you like. The
hypervisor itself is fairly minimal and handles
all the low-level hardware shenanigans.
In order to be of any use to guest OSes,
a control domain (dom0) needs to be running
on top of the hypervisor. This is a privileged
VM running a Xen-enabled kernel which
manages all the lesser guests (unprivileged
domains) and provides an interface for them
to interact with hardware. The Linux kernel
supports Xen, but one can also use NetBSD or
OpenSolaris as the control stack. We should
also mention KVM here, which does an
excellent job of obscuring the boundary
between Type 1 and Type 2. Once the KVM
module is loaded, the host OS becomes a
hypervisor; a virtualiser, such as Qemu can
then utilise it to run any OS compatible with
the host's CPU architecture. In fact, Qemu can
virtualise x86, PowerPC and S/390 guests,
but theres a performance cost when
emulating foreign architectures. Guests fall
into two camps:
Paravirtualisation (PV) This requires a
PV-aware kernel, so the guest knows that its
running on imaginary hardware.
Hardware-assisted Virtualisation (HVM)
Paravirtualisations counterpart, HVM or full
virtualisation requires a CPU with
virtualisation extensions which mitigates the
performance penalty associated with tricking
the Guest OS by emulating BIOS and other
hardware. To further complicate matters, fully
virtualised guests can be partially
paravirtualised through so-called PV-on-HVM
drivers, so that I/O can be accelerated and
grey areas introduced.
Whatever path you go down, after a quick
and easy credit card payment you will be
provided with a hostname/IP address and
password. You will then be able to ssh into
your new appliance with full root access:
$ ssh root@host
There are a few initial things you should
take care of, just as when you install a new OS
on an actual machine. Some of these might be
Elliptic Curve Crypto is so advanced that you can get away with much shorter key lengths
(256, 384 and 521 bits versus 1,024, 2,048, 3,072 or 4,096 for RSA).
Disclaimer
Cheap VPS servers are definitely not a good
idea for conducting any mission-critical
operations or storing any data that is remotely
sensitive. In this guide we do some rudimentary
hardening, but this won't make you bulletproof.
Sound advice is to not run services you don't
need/understand and update everything
regularly. Almost by design, there will always be
some room for mischief. There are attack
vectors outside of the VM itself: a kernel-level
17
Secure VPS
$ ssh-copy-id user@host
Replace user and host with the user you
set up before and the address of your VPS.
This will append your public key to the file
~/.ssh/authorized_keys on the remote host.
If you do have to copy your private key, make
sure that its permissions (600) are preserved,
otherwise you will found yourself castigated
for insecure practices.
Now test your freshly baked key. If you kept
the default filename then you don't need any
special syntax, otherwise you'll have to use the
-i (identity file) option:
$ ssh -i ~/.ssh/private_key user@host
If all has gone according to plan, you
should be prompted for the passphrase for
your private key and allowed to log in. With
that done, we can change the following lines in
Consider tunnelling
services you run explicitly
for you over SSH.
Full lockdown
Filtering outgoing packets is really only for the paranoid, but if the tinfoil hat demands it here is a
quick summary of traffic you will probably want to allow before the big ol' REJECT rule.
Loopback traffic
DNS
NTP
HTTP(S)
FTP
git
TCP 9418
ping
If you really want to fulfil the ultimate control freak sysadmin stereotype, then its possible to log
all the packets that iptables rejects, but this can very quickly lead to oversized log files and full
disks, which will be much more of a problem for you than someone scanning your box for
non-existent SMB shares.
18
Secure VPS
packets. The latter is good for evading
detection, but annoying for diagnosing issues.
You can examine your current iptables rules
by running the following as root:
$ iptables -L
Let's start with a tabula rasa by purging all
currently operational rules (even though there
properly aren't any) and any extra chains:
$ iptables -F
$ iptables -X
While its tempting to lock down everything
here, and indeed an overly permissive firewall
is not a good idea, it will be beneficial to
concede that connection establishment and
packet filtering are more complicated than
you might think. It would, after all, be very
embarrassing if you locked yourself out of
your own machine.
Our first two handy rules deal with traffic
on the local interface. A lot of programs talk to
each other this way, but we don't allow traffic
to access lo from the outside world. The third
rule conveniently allows all connections that
are currently established and any further
connections which they engender. That should
save you some heartache you generally
want to let in packets from the services to
which you connect.
$ iptables -A INPUT -i lo -j ACCEPT
$ iptables -A INPUT ! -i lo -d 127.0.0.0/8 -j
REJECT
$ iptables -A INPUT -m state --state
ESTABLISHED, RELATED -j ACCEPT
Now we ensure incoming SSH connections
will not get summarily squashed:
$ iptables -A INPUT -p tcp --dport 2022 -j
ACCEPT
The -A option indicates that we are
appending this rule to the input chain, so that
it is processed after all the other rules. We
could also use -I INPUT 1 to insert this rule at
the top of the chain.
With logging turned on we can see all the noisy broadcasts around us that we are ignoring.
If you want to stay sane, dont try to understand the pricing structure for EC2 instances.
Privacy
+ You
Search
Images
Maps
Play
YouTube
News
Gmail
Drive
Escape
And Facebook
Calendar
SIGN OUT
Flickr + more!
What guarantees do
you have regarding the
safety of your data?
Advertising
20
Business
About
Settings
Google.com
Privacy
The demo at
http://demo.
owncloud.org
lets you have a
play around with
OwnCloud before
installing it.
within your LAN. They could also be made available from the
outside, but then you run into the question of the upload
speed of your internet connection. Most domestic internet
connections are asymmetric; giving far higher speeds for
downloads than uploads. But accessing data from the outside
world counts as an upload, so it would be slower not
unusably so, but its something to be aware of, particularly if
you want to support multiple users. If you are providing
access from the world at large, life is a lot easier if your
internet provider is able to give you a static IP address,
otherwise you will need a dynamic DNS service.
The website offers two ways of installing OwnCloud, the simplest of these is to
download and extract a tarball unless your distro has a package for it.
21
Privacy
Cloud storage
If you want to go it alone, theres a personal free software alternative to
Dropbox, Flickr and many other online services.
The OwnCloud
basic package:
file storage,
online music or
picture galleries,
calendar and
address books,
all in the same
browser window.
22
Privacy
A container of applications
23
Privacy
Selecting a database
The OwnCloud
bookmark
manager isnt
as sophisticated
as other similar
applications,
but is already
very usable.
24
General configuration
Remember that little gear icon in the bottom-left corner?
If you click on it while logged in as administrator, it will also
show an Admin tab. Thats the place where you can create
other users accounts, and organise them in groups, each one
with its own administrator. Groups are necessary if you want
or need to control, with the greatest possible flexibility, how
much users can share among themselves, or with the rest of
the internet. Apart from grouping, each user can have a
different quota of the available space. Even if you are the only
user of your ownCloud, create a different user identity for
your daily activities. The administrator account should be
reserved for administration, if only to make it harder for you
to mess up something by mistake. Besides managing users,
Privacy
the OwnCloud admin panel lets you download and export the
system core files, the user files or the complete cloud (user
data, files and database), for backups or migration. While
doing this only takes a click, they are manual clicks.
Installing applications found on http://apps.owncloud.
com, or elsewhere is easy upload and unpack their source
files in the apps sub folder of OwnCloud, then configure them
in the apps section of the administration panel.
Where is that file? In your OwnCloud, or on your hard drive? It doesnt matter
actually, because you can access it both ways.
25
Privacy
Webmail
Keep your emails private set up your own webmail service.
Installing webmail
Installing Roundcube is simple. You can either do it through
your package manager or directly on to your server by
downloading the tarball from www.roundcube.net. Unpack
the tarball into the root of your web server. This creates a
directory called roundcubemail-0.9.0 (for the current
version). Either rename or symlink this to something more
usable, like roundcube or even
webmail. Roundcube needs to
write to files in its logs and
temp directories, so make
sure these are owned by the
user running the web server,
usually apache or www-data.
Then run the installer by pointing your browser at http://
address-of-server/roundcube/installer. Make sure that
none of the checks show Not OK. Missing optional modules
are fine, and you only need one database available
(Roundcube supports several database formats).
One important setting it checks is PHPs date.timezone
option, which needs to be set in order for your mails to have
the correct timestamp. If you are using a VPS rather than a
local server, this should be set to the timezone for wherever
the server is physically located. The setting is found in
/etc/php5/apache2/php.ini and the line should be
uncommented by removing the leading ; and then the
timezone added. You will usually find the correct timezone
specification in /etc/timezone. You need to restart Apache
after changing this, or any other PHP settings, with:
sudo apachectrl restart
Setting things up
Privacy
Administration
One of the great things about the public services is that they
just work. You have no setting up to do beyond creating an
account, you dont have to worry about backups, storage
requirements, network security, DDoS attacks or a host of other
concerns. If you really want to go it alone in a serious way, you
need to consider these just as you would for traditional
computing and data storage systems. Of course, the risks can
be turned into benefits.
Using a private cloud to store all your files introduces a
single point of failure, but it also means that you only have
The page that youll see when you load your webmail URL into
your web browser depends on your settings. If youve set up a
single mail server, it will go straight to asking for your
username and password, otherwise you will see either a
menu to select between the different servers you have set up
or a text box if you have added no servers.
The first time that you log in there will be a delay as your
mailbox is scanned. The speed at which your mailbox loads
Roundcube is installed using its own web-based installer. The first step checks
whether all system requirements are met.
27
Privacy
Social networking
Allay your privacy concerns establish your own social media platform.
A familiar procedure
The installation process is similar to many other web
applications. Download the ZIP file, unpack it into your web
servers document directory, preferably making a symlink to a
more useful name than elgg-1.8.15, and set up the database.
Elgg uses MySQL, so the standard instructions given
elsewhere apply for creating a database and user. You also
need to create a data directory for Elgg this should not be in
your web servers DocumentRoot, the area from which it
serves pages, as you do not want the contents to be directly
Adding a MySQL DB
MySQL is a database server; all of the packages we have mentioned here
need some sort of database to hold settings and data. While MySQL is one
of the most popular, there are alternatives. SQLite is, as the name
suggests, a much lighter option. It stores a complete database in a single
file and works well on single user systems that do not have particularly
demanding requirements. However, it does not scale particularly well,
either in terms of users or load. Because MySQL uses the classic server/
client model, one server will take care of the database needs of several
programs, so if you are using more than one of the packages covered here,
MySQL is probably the best choice. The disadvantage is that you need to
set up databases and users on the server for each package. When you
install MySQL, it asks for a password this is for the root user and not to
be used by individual packages. You can create a new database and a user
for it using the command line
mysql -uroot -p
MySQL client will prompt for a password,then you create the database and
user with:
CREATE DATABASE dbname;
GRANT ALL PRIVILEGES ON dbname.* TO username@localhost
IDENTIFIED BY password;
FLUSH PRIVILEGES;
The first line creates the database, the second creates a user with a
password, allowing them full access to that one database. The flush
command tells MySQL to implement the changes immediately. When
youve finished \q will exit the client. You can tell your program to use that
28
Privacy
Openstack
While we have concentrated on ownCloud here, there are
alternatives; one such is OpenStack (see Dockers, p114).
However, OpenStack is aimed more towards large scale use.
OwnCloud can be used in enterprise deployments and there
are commercial variants available, but it is also well suited to
personal and small organisation use. On the other hand,
OpenStack is aimed more at those wishing to offer cloud
services commercially. That certainly doesnt rule out
OpenStack, and if your requirements are for something more
than a personal cloud service, you should take a look at
www.openstack.org to see if it better suits your needs.
There are even themes that can make Elgg look very like a certain well-known
social networking site.
What is LAMP?
Web services run on what is known as a LAMP system, where
the first three letters stand for Linux, Apache and MySQL
while the P could be PHP, Perl or Python, depending on your
preferences. Apache is the de facto standard web server for
Linux, although there are alternatives, such as Lighttpd and
Cherokee, which are often lighter and work with these
services. However, Apache is the most popular and
everything comes set up to work with it, whereas using a
different web server may involve some more work, details of
which can often be found on the projects websites. Installing
SIGN OUT
29
Secure Android
Your smartphone is your PC. We investigate
how you can secure it against prying eyes...
30
Privacy
Control permissions
Once youve identified a privacy-intruding app
you can remove it. Google recently let slip a
privacy functionality in Android 4.3 that users
could unlock with the Aps Ops Launcher tool.
With this feature you could selectively turn off
privacy-related permissions. For example, you
could install the Shazam music recognition
app but turn off its ability to track your location.
However, Google removed the feature in the
following update, much to the chagrin of the
EFF. When asked, Google said the feature was
experimental and was released by accident.
If you have a rooted Android device you can
still get the feature as a module for the Xposed
framework. Users of rooted devices can also
use the XPrivacy module for Xposed.
With XPrivacy you can control specific
permissions for all installed apps. The best bit
31
Privacy
Communicate securely
Use your phone in Incognito mode.
he key to securing your phone against
any sort of surveillance is end-to-end
encryption. There are an increasing
number of apps and services that let you
encrypt the data on your device before it is
sent off and then decrypted at the recipients
device. Encryption doesnt prevent the caching
of data but safeguards it against any kind of
snooping by making it unintelligible to anyone
without the correct decryption keys.
Begin your lockdown efforts by obfuscating
your web browsing activities. Just like any
desktop web browser, you can install a variety
of add-ons to your Android browser.
Some of the popular Privacy-inducing addons are the Phony add-on which you can use to
customise the user-agent on the browser and
hide the fact that you are on a mobile device.
Then theres the self-destructing cookies addon which will automatically delete all cookies
when you close a site. For more comprehensive
control you can use the CleanQuit add-on
which removes all information about the
previous session including the browsing &
download history and site preferences.
If you want anonymity, you should switch to
the Orweb browser (http://bit.ly/1eiYktj)
which is preconfigured to help you browse the
web anonymously. Its also loaded with plugins
to disguise your device, gives you control over
cookies, prevents loading of Flash content and
keeps no browsing history. It requires the Orbot
plugin, and Orbot is Tor for Android. (See p34
for more details about the Tor Project). On
initial launch, Orbot runs through a quick setup
wizard. If you have a rooted phone, you can
turn on transparent proxying, which allows all
network apps to automatically run through the
Tor network.
To sign and encrypt email messages on
your mobile device you need the Android
Privacy Guard (APG) app, which is an open
32
Surprisingly, a lot of us
still use the smartphone
to make actual calls.
internet many people still use texting as their
primary means of communication.
You can encrypt SMS messages with the
open source TextSecure app, which can
encrypt SMS stored locally on the phone.
However, to send encrypted messages over the
air, the recipient must also have TextSecure or
theyll receive unencrypted messages. When
you run the app first time, it gives you the
option to create encrypted versions of all local
messages. Although it doesnt touch the
existing unencrypted SMS, its advisable to
delete them after creating encrypted versions.
Before you can send messages youll have
to create a secure connection with the
recipients device by exchanging keys.
TextSecure will send a message to the
recipient, whose TextSecure app will
automatically respond with a message to
establish a secure connection. From then on
you send and receive encrypted messages.
Surprisingly, a lot of us still use the
smartphone to make actual calls and there are
Privacy
and fix bugs that were only fixed by Google in the next Android release.
The third-party firmware also includes the the Privacy Guard app which
gives you better control over apps and their permissions.
The newer versions of the app also include the AppOps feature,
redacted by Google in Android 4.3. With this feature users can
prevent individual apps for accessing your data. The latest version
of CyanogenMod also integrates the secure SMS app TextSecure in
the firmware itself.
33
Privacy
Encrypt your
hard drive
Do you want to keep your data safe from pilferers? We show you how to
fortify your hard drive using disk encryption.
A stack of blocks
Running cryptsetup --help not only shows the commands you can use, but
also displays a list of the available hashes and ciphers.
34
Privacy
Encrypting something
Cryptsetup can create two types of encrypted devices: plain
dm-crypt and LUKS. If you know you need to use plain
dm-crypt, you already know far more about disk encryption
than well cover here, so well only look at LUKS, which is the
best choice for most uses. Experimenting with filesystems,
encrypted or otherwise, risks the data on the disk while
youre learning. All examples here use /dev/sdb, which we
take to be an external or otherwise spare device do not try
things out on your system disk until youre comfortable doing
so. All these commands need to be run as root, so log into a
terminal as root with su, or prefix each command with sudo.
Lets start by creating an encrypted device:
cryptsetup luksFormat /dev/sdb1
This sets up an encrypted partition on /dev/sdb1 after
prompting you for a passphrase. You can open the encrypted
device with:
cryptsetup luksOpen /dev/sdb1 name
This will ask for the passphrase and then create the device
in /dev/mapper, using the name given on the command line.
You can then use /dev/mapper/name as you would any disk
block device:
mkfs.ext4 /dev/mapper/name
mount /dev/mapper/name/ /mnt/encrypted
The usual rules about passphrases apply: keep them long
and varied, hard to guess but easy to remember. If you lose
the passphrase, you lose the contents of the device.
name
It goes without saying that keyfiles should be stored
securely, readable only by root and not stored on the
encrypted device. Personally, even if a volume is always
unlocked by key file, I prefer to also set a very strong
passphrase, recorded in a secure place, to guard against the
key file ever becoming corrupted or otherwise inaccessible.
Keys can also be changed or removed with the
luksChangeKey and luksRemoveKey commands.
More options
Use cryptsetup
luksDump to
find out about a
LUKS encrypted
partition. There
are also backup
and restore
commands to
keep a copy
of the LUKS
information.
LUKS
Linux Unified Key Setup was created to
provide a standard, platformindependent (despite the name) format
for storing encryption data on disks. It
doesnt specify the encryption methods
used, but how information about those
methods is stored. It also provides a
more robust way of storing keys or
35
Hardware
36
Hardware
Hardware
F
37
Hardware
he Raspberry Pi was
conceptualised as an
educational device. The
Raspberry Pi Foundation
designed the no-frills computer to make
an affordable and functional computing
device for kids who wanted to learn to
program, but found it difficult to come
up with the cash to procure hardware offthe-shelf. However, the device hit it off
with the hackers and modders who
began using it creatively and
made it usable to audiences
far beyond what Eben Upton,
Rob Mullins, Jack Lang and
Alan Mycroft had originally
imagined when discussing the
idea at the University of
Cambridges Computer Laboratory.
But this has created a misconception.
A lot of people believe that the Pi can either
be used inside an elementary educational
institute or in the hands of an experienced
campaigner wholl plug it inside a RC car or
space-faring teddy bears. While this is true,
38
Hardware
It weighs just
9 grams but the
Raspberry Pi
camera module
can shoot still
images with a
resolution of
2,592x1,944 as
well as Full HD
1080p video
30fps and 720p
video 60fps.
Post to Twitter
Well now setup a new Twitter account and ask the Pi to post
images to it. Make sure the account is private. Begin by
installing Pythons pip package manager for installing Python
39
Hardware
Skills: Networking,
interoperability,
data management
Hack #2: File-sharing Samba server
The ability to share and access data on your Raspberry Pi
from other machines is very useful indeed. For example, if you
are using it as an always-on download box, youd want to
move the downloaded data off the Pi as well. Now that data
could either be on the SD card or on an attached USB disk.
With the Samba software which is an implementation of the
SMB/CIFS networking protocol you can use your Raspberry
Pi as Network Attached Storage (NAS) device and easily
access the USB drive attached to the Pi from computers on
your network.
The sudo apt-get install samba samba-common-bin
command will fetch the required software. Now, attach the
USB disk to the Pi which will be automatically mounted under
the /media folder. Lets assume the USB drive is mounted to
/media/usb. You now need to configure Samba so the drive
Remmina has a very usable interface and scrolls automatically when the
mouse moves over the screen edge.
Overclock the Pi
While the Pis 700MHz processor is good
enough to set up these hacks, after a
while youd wish you could squeeze more
juice out of it. The good news is that you
can! The Pis BCM2835 processor can be
run above its default speed...
However, remember that such
performance comes at a price the
processor will draw more power, run
hotter than before, and may not last as
long as a regular Pi running at its default
speed. Also, while its possible to alter the
Pis performance manually, the safest way
40
Hardware
OwnCloud 7 is
a significant step
up from earlier
versions, with
a streamlined
workflow.
41
Hardware
Skills: Streaming,
emulation and GPIO
Hack #5: Stream music from the web
Weve got music everywhere. In addition to DRM-free tracks
on the hard disk, youve probably got hundreds of tracks on
Spotify or Google Play. You can get them all together with the
Pi MusicBox distro which transforms the Raspberry Pi into
the ultimate music player.
The Pi MusicBox can output music through speakers
attached to the headphone jack of the Pi, and also through
the HDMI and USB ports. So all you gotta do is install the
distro, hook up some speakers to the Pi, plug in your account
credentials and let it rip. You can then control your juiced up
Pi from any computer on the network and even from any
Android device.
Begin by downloading the compressed image for the Pi
MusicBox distro from www.pimusicbox.com. Extract the
downloaded ZIP file and then put the .img image file on your
SD card with the dd command, such as sudo dd
if=musicbox0.5.img of=/dev/sdd. Remember to replace
/d/ev/sdd with the location of your SD card.
If you use the Ethernet port to connect the Pi to the
internet, you can boot the Pi from the newly created SD card.
However, if you use a wireless card, youll need to edit the
distros configuration file and manually point it to your
wireless router. Access the newly created SD card from a
regular distro and navigate to the config folder and open the
settings.ini file in a text editor. Near the top of the file youll
notice two variables, WIFI_NETWORK and WIFI_PASSWORD.
Insert the corresponding values of your network next to these
two variables and save the file. The caveat is that PiMusicBox
will only work with WPA2-protected wireless networks.
Once thats done, boot the Pi with the configured SD card.
On first boot, the distro will resize the filesystem to take over
the complete card, and restart automatically. If you have a
monitor attached to the Pi you can follow the booting
process, otherwise wait a minute or two, then fire up a
browser on any computer on your network and head to
http://musicbox.local. If that doesnt take you anywhere,
then point your browser to the IP address of the Pi.
42
Hardware
might seem like a limitation but it really isnt, thanks to the
brilliant SoX sound exchange audio editor. Well use the nifty
little tool to process any MP3 file irrespective of its encoding
and convert it into the correct WAV file on-the-fly.
Begin by installing the audio editor and its dependencies
with sudo apt-get install sox libsox-fmt-all. When its done,
type in the following command, substituting SomeSong.
mp3 with the name of the MP3 file you wish to play:
sox -t mp3 SomeSong.mp3 -t wav -r 22050 -c 1 - | sudo
./pifm - 101.2.
The first part of the command converts the MP3 file into a
WAV file, changes its audio sampling rate to 22050 Hz and
down-mixes the track to mono. The converted track is then
sent to the standard output, denoted by the hyphen, and is
then piped (|) into the standard input of the pifm command.
The only difference in the pifm command in the above
example is that instead of specifying the name of the file to
broadcast, we are asking the script to instead broadcast the
standard input. If youve still got your FM receiver tuned to the
101.2 frequency, you should now hear your MP3.
You can do some wonderful things with SoX. You can, for
example, use it to broadcast your favourite streams live from
the Internet. The command sox -t mp3 http://www.
tuxradar.com/files/podcast/tuxradar_s06e02.mp3 -t
wav -r 22050 -c 1 - | sudo ./pifm - 101.2 will broadcast the
TuxRadar podcast. The only difference between this
command and the previous example is that instead of
pointing to a local MP3, you are now pointing to one that
resides online.
EmulationStation will only display the emulators that have ROMs added.
43
Hardware
You can customise and extend Jasper by adding your own commands.
44
search = twitter.get_followers_list(screen_
name=geekybodhi,cursor=next_cursor)
for result in search[users]:
print result[name]
their_name= result[name]
espeak.synth(their_name)
time.sleep(2)
next_cursor = search[next_cursor]
In the above code, we connect to our Twitter account and
fetch a list of all our followers. We use a technique known as
cursoring to separate a large set of results (the list of
followers) into pages and then move forward through them
(with next_cursor). The For loop lasts till our list of followers
is exhausted. For every follower, the loop prints its name,
stores it in a variable (their_name) and then passes it on to
the eSpeak library which reads it aloud. It then pauses for a
couple of seconds before moving on to the next follower.
Hardware
As an example
of what you can
do in LXF186,
Jonni shows how
to build a cannon
and blow stuff up
in Minecraft.
45
Hardware
Arduino: Kerbal
Space Program
Making a custom controller for Kerbal isnt rocket science, we show you how.
his exclusively for that. But the general principles are the
same and thats what were going to explain here.
Lets start with an Arduino. There are several versions,
but youll want the Leonardo. This is the only one that can
emulate a USB keyboard in hardware. You can buy a
barebones one for about 14, but if this is your first project,
youll want some LEDs and resistors as well as a prototyping
breadboard. There are some good starter bundles at
http://4tronix.co.uk and http://proto-pic.co.uk. The basic
principle is that you connect a button or a switch to the
Arduino and then program it so that when you press the
button it sends the corresponding key-press to the PC. Your
game will behave as if youd pressed the key on the keyboard,
and you can keep the regular keyboard plugged in too, so that
Debouncing
Hardware switches and
buttons are mechanical
devices with mechanical
imperfections. When you
close a switch, the electrical
contacts will bounce slightly,
making and breaking contact
for a few milliseconds until
they settle into place. If your
Arduino sends a key press
each time the contact is
made, youll send several key
presses when you only want
one. The solution is called
debouncing and its
really simple. All you do is
program the Arduino to wait
46
Hardware
you dont need to replicate every single key just the fun
ones you need for the game.
Now you could use a button or a switch for every function
in the game, but why limit yourself when you are starting from
scratch? Analog joysticks arent appropriate for every game,
but there are fairly cheap digital joysticks available
from http://uk.rs-online that use microswitches. Each
direction can be programmed as a separate key press and
suddenly WASD is transformed into a four-way joystick.
You can even remap the joystick on the fly so that it sends
different key-presses at different times. When we switch to
docking mode, for example, our joysticks are remapped to
strafe sideways, rather than rotate our ship.
Rotary controls
Throttle functions dont need to be programmed as plus and
minus buttons, because you can create a rotary control.
The easiest way to do this is with a potentiometer, which is a
variable resistor that changes as you turn the dial this is
how volume controls work. You can feed the output from this
to one of the analog inputs on the Arduino and it will turn the
continuously varying voltage into a discrete number between
zero and 1,023.
The disadvantage with potentiometers is that they have
physical end-stops. On our controller, for instance, we have
buttons acting as throttle presets so that we can immediately
punch in 0 per cent, 20 per cent, 80 per cent or 100 per cent
thrust. If we used a potentiometer dial to turn the throttle up
to full and then pressed the button for 0 per cent thrust, the
dial would still be turned all the way up and we wouldnt be
able to turn it up any further. One solution is to use a rotary
encoder, which can be turned endlessly in either direction.
These are very cheap, but programming the Arduino to detect
which direction they are turning is a little bit fiddly. Plus, most
of them only have 12 steps around the circle, which doesnt
Dont just
replace each key
with a button
switches and
dials can be
more useful.
47
Hardware
The electronics
Connect switches and lights together using the magic of soldering.
1
Proof of concept
How to solder
Soldering is mainly about keeping a steady hand. Clamp or blu-tack the wires so
that the ends overlap, then apply the soldering iron for a few seconds and touch
the solder to the wire so that it melts and flows across the surface. Make sure
you allow the soldered wires to cool before moving them.
Crimping
Plugging bare wires into the Arduino
doesnt work very well because the
ends arent stiff enough to push
into the headers. You need metal
spikes called crimp connectors on
the ends of the wire. You can buy
these and attach them yourself, but
48
Every switch and light on your control panel needs its own connection leads.
Ribbon cable makes for tidier wiring, but its harder to solder and you cant move
switches around if you change your mind about the positioning. Use 2.4mm
heatshrink tubing to insulate the ends.
Hardware
5
Ohms Law
If you connect an LED directly
to the 5V pin of the Arduino it
will be uncomfortably bright,
and might even blow the LED
entirely. This is because LEDs are
semiconductors and have almost no
internal resistance.
Ohms law says that voltage =
current x resistance, which means
Test as you go
Use the breadboard to test each component as you add it. This makes sure that
you havent connected leads the wrong way round and helps you to learn
Arduino programming incrementally.
49
Hardware
The enclosure
Assemble a panel worthy of the Apollo program.
9
A basic box
Power hub
Virtually every control or light you add will
need its own connection to ground or +5V, and
sometimes both. The Arduino Leonardo only has
two ground pins and one +5V, so you cant
connect them all directly. An easy solution is to
use a strip of Veroboard (pre-drilled board with
copper tracks) and solder some headers to it.
You can plug this into an Arduino GND pin and
that whole track on the Veroboard will count as
ground. Do the same for +5V to create a hub.
10
11
Drill holes
12
At this point, polish out any scratches on the front face as this will be much
harder when the switches are all in place. Mount the panel onto your box and
bolt the controls on. Leave the wooden back off, so you still have access.
50
Hardware
13
Using diodes
14
A keypad matrix
15
Squeeze it all in
Mount the Arduino on the back panel and connect everything to its designated
pin. Keep a note of what is plugged where and dont forget to record the wire
colours, so you can find things during testing.
Currents
The Arduino can only supply a maximum of 200mA on the 5V rail, and 50mA
on the 3.3V rail. If your controller has a lot of LEDs, you will quickly exceed
this and your Arduino wont work properly. A 2.60 breadboard power supply
module from Amazon will give you over 500mA on each rail. Use this to power
your components and leave the Arduino running off the USB cable. Or you
can splice open a USB cable and run the 5-volt wire to the power module
instead. The ground wire goes to the power module and also back to the PC,
and the data wires run to the PC as normal.
14
Hardware
Install
Linux
on your new
Chromebook
For those whove bought a Chromebook and miss a full operating system,
well show you how to get an assortment of Linux distros up and running.
C
Jargon
buster!
apt-get
The program used
to install software
packages on
Debian, Ubuntu and
other Linux distros.
Hidden shell
This is LXDE
running on a
Chromebook,
but Chrome OS
is still there.
52
Hardware
sh -e ~/Downloads/crouton -r list
sh -e ~/Downloads/crouton -t list 2>&1 | more
The second command needs to be passed to more
because it is several screenfuls hit Space to page through
them all. Once youve decided the release and target you
want, you can run Crouton. To install Ubuntu 13.10 (Saucy
Salamander) with the Unity desktop, for example, run:
sudo sh -e ~/Downloads/crouton -r saucy -t unity
This uses sudo because you need root to install the
software. You can also specify multiple targets, like this
example that installs Debian Wheezy with the LXDE desktop
and the XBMC media centre:
sudo sh -e ~/Downloads/crouton -r \wheezy -t lxde,xmbc
Unity is perfect
for running
everything in
full screen.
Jargon
buster!
chroot
A directory into
which a program is
locked. It cant see
anything outside.
Starting up
Depending on the target(s) selected and the speed of your
internet connection, this could take a while. When it has
finished, it tells you the command needed to start your
chosen distro in the chroot, such as:
sudo startunity
Run that command and you will be in a standard Ubuntu
desktop. When you have finished, log out in the usual way and
you go back to the familiar Chrome OS. You can switch
between the two by holding Ctrl+Alt+Shift and pressing
Forward or Back, too. In fact, the Chrome OS navigation keys
above the numeric row are treated as the F keys by Linux, so
these are really Ctrl+Alt+Shift+F1 and Ctrl+Alt+Shift+F2.
The installation you end up with is not the complete distro
as you would get installing it natively, but any extra packages
can be installed in the usual way. If using Unity, the Software
Centre is not installed, so open a terminal in Unity
(Ctrl+Alt+T) and run:
sudo apt-get update
sudo apt-get install software-center
Now you can install any other packages you need from the
GUI. You can also install extra target environments with the -u
flag. For example, to add the LXDE environment to the
Ubuntu chroot we created before, we would run:
sudo sh -e ~/Downloads/crouton -r saucy -u -t lxde
Quick
tip
When trying
multiple distros
or targets, clean
out any you have
finished with. At
several GB each,
your storage will
soon disappear.
53
Hardware
Install a release
Open a shell
The default targets include only the command line package manager,
apt-get. For most people, the first step is to open a terminal and use it
to install a more friendly option, such as software-center for Ubuntu
or Synaptic for Ubuntu or Debian. Run sudo apt-get update to make
sure you get the current version, then sudo apt-get synaptic.
54
Running Crouton with -t list will show you all the available targets.
Youll probably want one of the standard desktop environments.
Chromebooks are relatively low-powered, and a lightweight desktop
such as LXDE is a good choice, while Unity is better suited to running
everything full-screen.
Run Synaptic
Once you have Synaptic installed, you have easy access to all the
software in a distros repository. Most of the targets are slimmed
down, to save on downloads and give a faster installation, but you can
install anything you want from here. Either use the Search button or
just browse the categories to see what is available.
Hardware
Recovery disks
Back up to USB
After downloading, the image is written to your USB stick. If you dont
create a recovery disk, its also possible to get this image from
another computer and copy it manually, by following the instructions
at http://google.com/chromeos/recovery, but you have to make
sure you get the right image they are specific to each model.
In case of emergency
55
Hardware
Python: Build a
multi-Pi cluster
Connect a bunch of Raspberry Pis together in a cluster affectionately
known as a Bramble and harnesses their power to crack passwords.
Python. For this demonstration, we used two Pis powered by
a Pimoroni hub (which gives independent power to each
port) and connected via a 100Mb five-port switch, which
cost 5 from eBay). The hub can power a maximum of five
Raspberry Pis, so one day perhaps this Bramble will grow.
For this tutorial, we will have our compute units bruteforcing two well-known hashing algorithms: MD5 and SHA-1.
More specifically, we shall try to find a pre-image for a given
hash value which we shall compute from a (rather spineless)
passphrase. While both of these algorithms are vulnerable to
collision attacks (where the goal is to find any pair of inputs
with the same hash), pre-image attacks are much harder to
come by. Such an attack does exist for MD5, but it still would
require an unreasonable length of time. At the time of
writing, there is no pre-image attack known for SHA-1.
The Flame malware in 2012 exploited collision weaknesses
in MD5 to forge Microsoft security certificates.
A thorny issue
The collective term for the aforementioned networks is a
Beowulf cluster. This name derives from the eponymous
hero of the classic Anglo-Saxon poem, who had 30 mens
heft of grasp in the gripe of his hand. Where the compute
hardware consists solely of Raspberry Pis, a new moniker
has been invented by the RPi community: a Bramble. While
most desktop computers are (depending on your chosen
benchmark) around an order of magnitude faster than the
Pi, it is still an enjoyable and inexpensive exercise to multiply
by Pi and therefore learn about distributed computing in
56
Hardware
the appropriate ranges of ASCII codes:
ascii = range(48,59)+ range(65,91) + range(97,123)
chars = [chr(j) for j in ascii]
We can use the itertools module to generate all possible
combinations of a given length here. This saves on some
potentially irksome code. The itertools.product class returns
a generator object, so rather than squashing us (or rather
our Pis and Brambles) with a huge list, it spits out one
combination per iteration. The repeat parameter is the
length of the outputted strings. So we repeatedly check to
see if its output hashes to our target hash.
for j in itertools.product(chars,repeat=length):
guess = ".join(j)
m = hashlib.md5(guess)
hash = m.hexdigest()
if hash == target_hash_md5:
print "Great victory!"
break
return(guess)
The functions md5cracker() and shacracker() can be
called with the length argument described above and it is
straightforward enough to modify it to brute-force a range of
password lengths. On a single-core powered 2.1GHz Athlon
laptop, attempting all three-character passwords using our
set of characters took about 0.7 seconds; four characters
took 40 seconds; and five figures took about 40 minutes.
As we are dealing with 62 characters, the latter figure
suggests we are churning through about 380 kilohashes per
second, so we could expect to crack a six-character
password in about two days and an eight-character one in
about 18 years. For SHA-1, the same machine managed
about 314kH/s, which is sinisterly close to 100,000 times pi.
Less decrepit hardware will fare much better, but a lone Pi
does much worse, managing a pitiful 6kH/s for MD5 and a
not much better 8kH/s for SHA-1. All this with no X server or
other daemons running. Clearly something does not work so
well on the ARM architecture further investigation is
beyond the scope of this article, since anything we can do
John the Ripper can do better (more on that later).
Incidentally, the Python file also contains the following
codeblock at the end:
if __name__ == '__main__':
import timeit
print(timeit.timeit(stmt = "shacracker(4)", setup="from __
main__ import shacracker", number=1))
This means that if the file is executed from the command
prompt, then it will be automagically benchmarked by the
timeit module. One could attempt to speed up this code
Distributed Dzargon
Computing architecture can be roughly split into
four classes: Single Instruction Single Data
(SISD), Single Instruction Multiple Data (SIMD),
Multiple Instruction Single Data (MISD) and
Multiple Instruction Multiple Data (MIMD). This
categorisation originated in the 1960s and is
known as Flynns Taxonomy, after its inventor
Michael J Flynn. Multiprocessor systems as we
know them did not exist at the time, but
machines were nonetheless capable of
performing parallel operations, in much the
same way as Intels SSE (Streaming SIMD
Extensions) that first appeared in Pentium III
57
Hardware
network config files or with a simple:
$ ifconfig eth0 10.0.1.1/24
This might involve a hefty bout of display and keyboard
cable swapping if you have many Pis. The actual addresses
arent so important here, as long as everyone is on the same
subnet then dispy will be able to discover all of the slaves.
A simple job cluster for our md5cracker() function is
created using dispy like this:
cluster = dispy.JobCluster(md5cracker,callback=callback)
The callback parameter tells our cluster to call a function
called callback() whenever one of the nodes finds the
password or runs out of work. A callback function can also
be used to collate intermediate or approximate results for
more complex scenarios, but we shant worry about this. Our
callback function need only check the result and if its not
False then it can shut down all the other jobs:
def callback(job):
if job.result:
print "Great Victory!", job.result
for j in jobs:
if j.status in [dispy.DispyJob.Created, dispy.DispyJob.
Running]:
cluster.cancel(j)
Since the md5cracker() function needs the itertools and
hashlib modules, these have to be imported from inside the
function. For reasons of synchronisation, dispy wont let you
share any in-scope variables with the workers, so the
md5cracker() function accepts the following additional
parameters: chars (list of characters), length (password
length) and thash (the target hash).
Finally we will use the following bit of boiler-plate to kick
the system into action when multipi.py is executed and
display some stats when tis done:
if __name__ == '__main__':
cluster = dispy.JobCluster(md5cracker,callback=callback)
jobs = []
start = 0
for j in range(nchunks):
end = start + chunk_size
job = cluster.submit(start,end,chars,length,target_hash_
md5)
job.id = j
start = end
jobs.append(job)
cluster.wait()
cluster.stats()
58
This used 9 RPi slaves and 1 Cubie board as a master controller for
MPI processing. It had a neat 16x2 RGB display for status information.
Now it has been repurposed as the 32-node Cubical Monolith Project.
Hardware
additionally require the libssl and libcrypto headers. The
following commands will install these on Raspbian,
assuming that you have a working internet connection:
$ apt-get update
$ apt-get install libssl-dev
Download the source from the website, and then unzip it
and begin the lengthy compilation process like so:
$ tar -xvzf john-$VER-jumbo-$REL.tar.gz
$ cd john/src
$ make generic
This takes about half an hour on a standard-clocked Pi.
Once it has finished building, we can use the following
command to test out our install:
$ cd ../run
$ ./john --test
Our freshly-squeezed binary will benchmark all of its
available algorithms. RawMD5 scored about 330kH/s on our
device, outperforming by a factor of about 50 our Python
implementation. For SHA-1 (--mode=raw-sha1), John
managed a respectable 190kH/s. Now make a text file
target.md5 consisting of a single line with our target MD5
hash from before, beginning 392b2. We can implement our
letters and numbers-only character set by using Incremental
mode with the Alnum character set.
$ ./john --incremental=alnum --length=6 --format=raw-md5
target.md5
This would probably take about two days to complete on
your average Raspberry Pi, and it still would not find the
required pre-image. This remains as a challenge for you, dear
reader. However, your challenge is eased by JtRs extremely
helpful --node option, which enables you to achieve some
primitive parallelism. For example, if we were to saturate our
switch with five Pis, we could add the option --node n/5 to
Words work
It would be remiss not to mention the more intelligent
wordlist mode of JtR. Numerous wordlists are available from
the website, and one can also define mangling rules for
combining them. It is even possible to use a hybrid mode
with some incremental characters, to maximise your
chances of success prior to the universe ending. At the time
of writing, the most impressive MD5 benchmark is close to
2GH/s (this is with the aid of 16 Radeon 7550s). With such
power, an eight-character password (using only the 62
characters weve been working with) could be recovered in
about a week. Faster technology is always just around the
corner, and so the old adage that eight-character passwords
are secure no longer holds up. In sum: get thyself a password
manager and be safe, kids. Q
59
Hardware
Bye then.
Free
Android
Is Android becoming less open source? We think its drifting in that
direction and investigate what the Linux community can do about it.
60
Hardware
Free choices
F-Droid
The name F-Droid is used to refer to two
separate but connected entities. It is a
repository of applications for Android, like
the Play Stores predecessor the Android
Market, with an important difference. Every
piece of software in there is free and open
source. Secondly, there is the F-Droid client,
used to browse the F-Droid catalogue (we
cant call it a market or store when
everything in it is free). This client is not
available in the Play Store, you will need to
install it directly from the site. In order to do
that, you have to allow your device to load
software from other sources go into
Settings>Security and tick the box for
Unknown sources. Note that this can be
considered a security risk, in that you are
able to install anything from anywhere; but
it is your phone, your choice to make and
your right to be able to install what you
want even if some smartphone makers
see things differently.
Now go to https://f-droid.org and
download the apk package. If you do this
using the phones browser, you can simply
open the file to install it. If you downloaded
it to your computer, transfer it to the phone
by USB, a file sharing site or memory card
61
Hardware
and open it. Alternatively, open the site in
your desktop browser and scan the QR
code with your phone. When you start
F-Droid, you will see three tabs: available
apps, installed apps and those with
updates. You may be surprised to find that
the installed tab contains programs already;
that is because many of the open
source apps on F-Droid are also
in the Play Store. What may be
more surprising is that some
of them show updates even
though the Play Store
shows them as up to date,
some apps have newer
versions in F-Droid. If you try
to update these you may find
that you need to uninstall the Play
Store version first, which will erase any
settings you have. Some backup programs,
such as oandbackup (in F-Droid, of course)
allow you to save your user data and restore
after installing the new version.
Naturally, you will not find as many apps
in F-Droids catalogue as in the Play Store,
but the quantity is decent and growing, and
Replicant
62
Using F-Droid to
make sure you
are using open
source software
on your Android
device is a step in the right direction, but
what if you want a completely free system?
This is nowhere near as easy, because of
the extent that proprietary software is used
in our devices. On the one hand, there is the
Google element all the software that
operates through Play Services and uses
Googles services. That can be dealt with,
although you may lose some features you
are used to. More difficult to deal with are
the hardware drivers, most of which use
proprietary blobs. This issue is similar to
that for some desktop and laptop hardware,
but often more complex.
Privacy
ne of the reasons people give for
wanting to move away from Google
(and other cloud services) is privacy.
It is not surprising that people do not want
their movements and communications
watched over by others, especially in light of
last years revelations about Prism and various
state agencies. By not using Googles software
you may think you have regained your privacy,
but no mobile phone user has complete
Hardware
Image link. Here, you need to download four
image files: boot.img, recovery.img,
system.img, userdata.img and an MD5
checksum file. Then click on the Base URL
link and get fastboot from the tools
directory. Save all the files to the same
directory and cd to that directory in a
terminal. If you downloaded fastboot, make
it executable with
chmod +x fastboot
If you already have fastboot installed,
replace ./fastboot with fastboot in each
of the following commands. Put the phone
into fastboot mode by turning it off and
then holding down the power and volume
up buttons until the bootloader screen
appears with FASTBOOT MODE at the
top. Now connect the phone to your
computer by USB. If you have not installed
a custom ROM or rooted your device
before, you will need to unlock the
bootloader. If in doubt, look at the LOCK
STATE line on the bootloader screen. If it
shows locked, run this in your terminal:
sudo ./fastboot oem unlock
The phone will ask for confirmation
use the volume buttons to highlight your
choice and power to apply it. Now flash the
images to the device with these commands:
sudo ./fastboot flash boot boot.img
sudo ./fastboot flash recovery recovery.img
sudo ./fastboot flash system system.img
sudo ./fastboot flash userdata userdata.img
After each
command
completes, you
should see
Write Success!
on the phone.
The third one takes a while system.img is
by far the largest of the files. Finally, clear
the cache and reboot with
sudo ./fastboot erase cache
sudo ./fastboot reboot
You should see the Replicant logo while
booting, and then it loads to the home
screen. You can tell you are no longer locked
to Google by the way it does not ask you to
sign in to a GMail account first.
Replicant contains a decent-sized selection of apps and widgets by default, with many
additional ones available in F-Droid.
http://teamw.in/project/twrp2
Download the correct image file for your
device and flash it using fastboot, like so:
sudo ./fastboot imagefile
Then you can reboot into the bootloader,
select Recovery, go to the Mounts and
Storage section to mount /system and
then send each file from the computer
with adb, available from the same place as
fastboot, they are companion programs.
sudo ./adb push firmware.file /system/
vendor/firmware/firmware.file
using the correct locations for your device.
63
Web
64
Web
Web
H
65
HACK
Wondering how the bad guys do it?
Join us on a legal trip to the dark side*
and hack your own software in safety
Hacking works
in many ways, but
here were going
to look at attacks
that come via the
web, because
these are the most likely to affect ordinary
people. Some of these attacks, such as the
Anonymous revenge attacks, have made front
page news, because theyve taken websites
offline, or added graffiti to front pages. Others are
going on every day, often making criminals vast
sums of money, yet are seldom reported.
If you run a website, youll undoubtedly see
many attacks in your server logs. If youre a web
*Legalities
The laws governing hacking vary from country to
country, so we cant give any concrete legal advice.
However, it is safe to say that performing any of the
techniques described here on a website you dont
have permission to change is illegal in most
66
THE WEB
Web
Web
Crack WordPress
Attacking a vulnerable web app.
According to
the Web Hacking
Information
Database, crosssite scripting
(XSS) is the
second most
common form
of attack on
websites.
Protect yourself
If youre running any type of web app, its imperative that
youre aware of the risks. Vulnerabilities could go further than
just the app itself, since an attacker may be able to get control
of the server. If youre running off-the-shelf software (such as
WordPress), a good rule of thumb is: the simpler and more
standard things are, the easier it is to keep on top of things,
and the easier it is to keep up to date. Always make sure
Levels of protection
Theres no such thing as perfect security.
Thats true in the real world just as much
as its true in the digital world. The
information in this article will make you
safer, but it wont make you safe. Security
is always a balancing act of convenience
and vulnerability, and choosing how
important these competing areas are is a
personal matter. This article can only
Import the VM
Start the VM
Web
Find vulnerabilities
How to identify and exploit a weakness in your site.
Here, we
spotted a
missing nonce
field that enabled
us to exploit
the form.
68
Web
The Quick Start tab is new in ZAP 2. Just enter the URL you want to attack and
it will spider the website and search for vulnerabilities. Its a good starting point,
but it wont find everything.
Web
Sslstrip saves
a copy of all the
unencrypted
traffic. A simple
grep can pull out
any credentials
(no, theyre not
real accounts).
70
Web
Get encrypted
You can view the internet a bit like the postal service. Data is
normally sent unencrypted, which is like sending it on a
postcard. Any number of people could read this between
when you send it and when it arrives, and the same is true of
information sent as HTTP, FTP, Telnet or any of the other
unencrypted postcards. There are times when this doesnt
matter you may not care that your grannys postman
knows that the weather in Spain is lovely and there are
times when it does you probably dont want your postman
Using justniffer, we were able to grab emails that had been sent to a phone
attached to the hotspot.
Certificate attacks
All forms of encryption are based around keys.
These are a bit like passwords in that they let you
decrypt a document. There is always
a challenge in making sure both parties to an
encrypted communication know the keys to
decrypt it. On the web, certificates are used.
These certificates are generated by trusted
authorities, and guarantee that the data youre
getting (and the keys used) really come from the
71
Web
DDOS
72
Protect yourself
Protecting yourself from a DDOS attack is simply a case of
minimising the hit you take from each malicious packet. This
means stopping as many of them as possible as soon as they
enter your network. To do this, you need a firewall, and you
need to know how to configure it to identify and drop the
relevant packages.
Exactly how to do this depends on your firewall, and the
rules you need change in a constant game of cat and mouse
as the attackers change their packets to get around firewall
rules. However, we will say this: make sure you know how to
protect yourself before you get attacked. Try out the various
DDOS tools on offer, and practise blocking them out, because
you dont want to have to learn this after your sites already
gone down. Running DDOS tools is also an excellent way to
check how your site will perform under a heavy load.
Alternatively, you can put your server on a network that
can take care of this for you. Services such as CloudFlare put
your server behind their firewall (virtually, you dont have to
reconnect your server). This means that you dont need to
worry about the intricacies of firewall configuration. Q
SERIOUS ABOUT
HARDWARE?
NOW
ON APPLE
NEWSSTAND
Download the
day they go
on sale in the
UK!
PERFORMANCE ADVICE
FOR SERIOUS GAMERS
ON SALE EVERY MONTH
MAKE YOUR
OWN GAMES
Build a platform
game in Minecraft
SUPER SIZED
+SUPER FAST
THROW OUT YOUR HARD DRIVE
4K ON A
BUDGET
499 AOC 4K screen
Tweaking for hi-res
High-end gaming rigs
NEXT-GEN CPU
DEVIL'S
CANYON
PLUS
Screenshots that
look awesome
Clean up your audio
Build your own
music server
Stream to Twitch
easily with Raptr
SAMSUNG 850
PRO 512GB
BUILD A
BUDGET
GAMING PC
THE BEST
GAME ENGINES
CREATE CHARACTERS
How games developers turn
concepts into powerful heroes
NVIDIA
SHIELD
NO.1 FOR
REVIEWS
GIGABYTE Z97
GAMING 5
INTEL CORE
i5-4690K
APPLE iMAC
21-INCH
PLEXTOR M6e
M.2
PLUS
Speed up Windows
The best gaming
headsets revealed
Master PC audio
Make awesome
pixel art in GIMP
VS
SCREEN WARS
ASUS RoG
SWIFT & LG
ULTRAWIDE
G-Sync smoothness
takes on cinematic
gaming immersion
FUTURE
PC TECH!
NEXT-GEN SSD
NO.1 FOR
REVIEWS
CRUCIAL MX100
CORSAIR RAPTORSSD
K40
GAMDIAS EROS
GIGABYTE P34G
JUST
IN
TROUBLESHOOTING TIPS
Web
PHP: Custom
website scraping
Based on your personal specifications, well help you find the
exact data that you want from a website without any obstacles.
Using PHP
Using the file_get_contents() function is the simplest
method to make a string from a URL. Once you are
comfortable with this method, you may want to move on to
using Curl which has many features that the file_get_
Curl is enabled
and functions
can be used.
74
Web
Monitoring the winds of change
So there you are, you built a custom
scrape for a particular website so that it
crawls all of the desired categories and
finds the gold entries. After a month or
two, you went back to check it out and
you found there was no output.
Simple scrape
When you do a quick search in the source code, you will find
the price $2.84 show up twice somewhere within the jumble
of glyphs. You could be glad of either code block to use for
pattern matching, but we will use the block that has the
<input> HTML tag and the name of displayedGiftPrice.
Since displayedGiftPrice only shows up once in the page,
it is a very simple price scrape.
At this simplest level, the code looks like this:
$data = file_get_contents(http://www.amazon.com/MYSQLFundamentals-Snippets-Kent-Elchuk-ebook/dp/
B00BSUOD72/ref=sr_1_1?ie=UTF8&qid=1386253046&sr=81&keywords=php+mysql+fundamentals+and+snippets);
/** Get the price match */
preg_match(/
displayedGiftPrice[\s]*value=(.*)[\s]*\/>/,$data,$desired_
match);
print_r($desired_match);
echo $desired_match[1];
Now, lets go through the code. The first string $data
grabs the url of the desired page you want to scrape. In this
case, it is the URL for one specific product at Amazon.
After that, the preg_match function should then be used
to match the desired block code from the source code. The
preg_match function identifies a match from a string and
returns it as an array. The first bracket (.*) will accept any
characters between displayedGiftPrice value= and the
ending double quote .
Essentially, this match will return an array with two values.
One value will be the entire match and the other will be the
desired value you want. In this case, the value we want is, of
course, the price.
Quick
tip
File_get_
contents() and
Curl functions can
load web pages
and turn the source
code into a string!
75
Web
to find a reoccurring matching pattern that will occur for all of
the entries in the list.
The whole idea of this exercise is to identify the desired
data and make sure it is trackable to the seller. This way,
when your item meets the desired price point, you can get an
email, text message and link to the product so that you can
buy it without any hassle.
Multiple items
This tutorial will show how to scrape all items from the Kindle
section when the term Kindle Fire HDX 8.9 is searched.
When this exact query is made, www.amazon.com returns
seven results. What to do with these seven results?
One option is to just pull exactly what we want, while
another option is to make criteria for separate items. For
example, for the item Kindle Fire HDX 8.9, HDX Display, Wi-Fi
and 4G LTE, 32 GB, you may only be willing to pay less than
$529, while you are willing to spend $229 for the item named
Kindle Fire HDX 7, HDX Display, Wi-Fi, 16 GB. So, there are the
desired items.
Now we come to the fun part, which is building a custom
scraper that will only find these items and check for the
desired criteria. Although another method to attack this is to
make an array of URLs and run them through a loop, we have
already chosen that scraping the single url is what we are
going to do. Since other sellers and used items could find
their way to this page on a later date, this page can be a good
starting point and it is a good learning exercise.
Search Kindles: Kindle Fire HDX 8.9
http://www.amazon.com/s/ref=sr_
nr_n_13?rh=n%3A2102313011%2Ck%3AKindle+Fire+HDX+
8.9&keywords=Kindle+Fire+HDX+8.9&ie=UTF8&qid=138645
8068&rnid=2941120011
Upon analysis of the desired page, there are seven items.
Now, pattern analysing gets interesting because six have a
price and one does not. Therefore, this Junker entry without
a price will be filtered out because it is currently unavailable.
Looking into the details of the source code, you will see
that items that have prices have a special HTML class
associated with the item, while the one without the price does
not. The code could have been displayed in a manner for
which the class could have existed even without a price, but it
had not. Therefore, the absolute key to building the scraper
Add php in
front of the file
to run it from the
command line.
76
Web
lines, the sim covers the bases required to extract the match
each and every time.
The above match only gives us each entry that will be
scraped. Now, the next procedure is to get the name and
price for each entry and do something with it. In order to do
that, the array called $posts is iterated with a foreach loop so
that the exact data for each entry is accurately kept together
for analysis.
With the previous example, you could easily just add that,
in the same way that you would the name and price. Then,
you could secretly make a second database table that
reflected price changed from the original day the product was
added to your Watch list.
For example, you could make a database table that inserts
the item ID, name and price. Then, every day you could run a
Cron job that checks for deals. A simple MySQL query could
be something like:
SELECT name FROM original_table WHERE id IN
(SELECT id FROM bargains WHERE price <= $my_
scraped_price )
A final idea if youre interested in taking this project further
is to give yourself an email or text message when you hit the
jackpot. Many phone providers these days allow you to use
email to send a text message to someones phone. The text
message is often sent via your phone number followed by an
email address such as [email protected].
The PHP mail() function or SMTP can be used to send this
message. Pear, for instance, has a fantastic class for sending
email with SMTP.
Quick
tip
The preg_match()
function can be
used to find a
single pattern in
a string while the
preg_match_all()
function can find all
repeated patterns!
77
Web
OwnCloud 7:
Own your data
Oft' accused of having their head in the clouds, Linux Format heads for the
stratosphere. Also the latest release of OwnCloud.
Build Service provides packages for popular distributions.
Instructions are available at http://owncloud.org/install.
On Ubuntu 14.04, for example, you would create the file
/etc/apt/sources.list.d/owncloud.list containing the line:
deb http://download.opensuse.org/repositories/isv:/
ownCloud:/community/xUbuntu_14.04/ /
Then (optionally) add the repo key to apt to suppress
warning messages about foreign packages:
wget http://download.opensuse.org/repositories/
isv:ownCloud:community/xUbuntu_14.04/Release.key
sudo apt-key add - < Release.key
And finally update the package database and install a
shiny (or watery?) new version of OwnCloud:
sudo apt-get update
sudo apt-get install owncloud
Cloud provider
78
OwnCloud 7 Tutorial
Web
untrusted. And rightfully so, but you know that you made the
certificate, and you trust yourself, so you should add a
security exception here. Even though visitors won't be able to
verify the server's identity (unless you somehow shared the
certificate's fingerprint with them), they will at least know that
the connection is encrypted.
Your first job as cloud overlord is to set up an
administrator account and choose the format for the
OwnCloud database. If you envisage a small cloud (such as
cirrus uncinus) then SQLite will be fine, but if you have
multiple users all co-operating/fighting over terribly
important documents (and TPS reports) then SQLite will
buckle under the strain and you will need a proper SQL
database. We'll stick with SQLite for now, but note that it is
possible to convert to one of the more grown up databases
further down the line. Choose a suitable moniker for your
admin account, use a good password and click Finish setup.
Bam! Owncloud is ready to go. You'll be invited to
download the sync apps for desktop machines (Yes, theres a
Linux client) and mobile devices, and instructed to connect
your calendar and contacts. All in good time though. First of
all we really ought to disable insecure http connections. So go
to the menu in the top right and open the Admin panel. Scroll
down until you find the Enforce HTTPS check box, which
you should tick. Now logout and try and visit your Owncloud
via http://. All going well you should be redirected to the
https:// site. Safe and sound.
SSLCertificateKeyFile /etc/apache2/ssl/
owncloud.key
You should also change the ServerAdmin
email address and the ServerName address to
your domain name or IP address. Now enable the
Apache SSL module and our new configuration,
either by using the a2en{mod,site} helpers
provided in Debian-based packages, or by using
a good old fashioned:
ln -s /etc/apache2/mods-available/ssl.conf /etc/
apache2/mods-enabled/
ln -s /etc/apache2/sites-available/default-ssl.conf
/etc/apache2/sites-enabled/
Restart the Apache daemon and you should
be wired for SSL.
Quick
tip
If you're important
and are looking
for an Enterprise
grade solution
for on-premises
cloud storage,
then checkout
the commercial
offering at https://
owncloud.com.
The initial setup screen posts warnings about our self-signed certificate.
High-grade encryption doesnt really help if theres a man in the middle.
79
Tutorial OwnCloud 7
Web
shares, OpenStack object storage or third-party storage, such
as Google Drive, Dropbox, Amazon S3. The exciting new
addition here is the ability to share between OwnCloud
installations or so-called server to server sharing. This is
easy to set up, you can enable specific OwnCloud shares for
users, or if you trust them you can grant them the freedom to
connect to the OwnCloud resources. Obviously they will
require their own login details for each resource they access.
80
OwnCloud 7 Tutorial
Web
The official desktop client is a simple-but-functional Qt4
application, which sits nicely in the System Tray and lets you
know when it's syncing in much the same way as its Dropbox
equivalent. By default it will sync your entire OwnCloud
account to the local directory ~/owncloud, but you can pick
and choose folders as befits your own cloudy proclivities.
Syncing on my mind
You can set bandwidth limits too. The desktop client does
look a bit awkward if youre using Gnome, with its
disappearing System Tray, though, in theory, once you've got
it all configured you shouldn't need to interact with it
anymore. Obviously, the desktop client won't be much use if
you want to sync to a remote machine though: In this
situation you'll want to use the aforementioned WebDAV.
The davfs2 program works via the FUSE kernel module
and enables you to view WebDAV shares as if they were local
filesystems. To install the package on Debian-based distros is
just a simple matter of:
$ sudo apt-get install davfs2
and the package is certainly present in other distro's repos.
You can optionally set the SUID bit on the executable so that
non-root users can mount WebDAV shares. Debian and
Ubuntu can do this for you with:
$ sudo dpkg-reconfigure davfs2
If you accept the warnings (it's pretty safe actually since
the program drops its root privileges), then anyone in the
webdav group will be able to mount WebDAV shares, so add
your user to this group like so:
$ sudo gpasswd -a username webdav
Now make a folder ~/owncloud-dav which will be our
mount point. We also need to specify our OwnCloud login
credentials, which are stored in the file ~/.davfs2/secrets.
This file may have been created for you during the
reconfigure earlier, but you can easily create it manually if not.
Since this file will contain sensitive data it is important to lock
down the permissions:
$ chmod 600 ~/.davfs2/secrets
Quick
tip
If your OwnCloud
server changes
its IP address or
domain name
then you'll need
to update the
trusted_domains
array in the file
/var/www/
owncloud/config/
config.php .
The Pictures
app will tile
your photos as
sensibly as it can,
but lacks a sort
by date option.
81
Web
Django: Build
a custom CMS
You hate WordPress, Drupal hates you and everyone hates PHP. What can
you do? We have a suggestion that will help ease your CMS pain.
Quick
tip
Another up and
coming Djangobased CMS is the
much-acclaimed
Mezzanine. Grant
it some of your
time and attention:
http://mezzanine.
jupo.org.
82
Understanding frameworks
In order to separate the design, content and back-end
code, mankind has invented web frameworks. These help
non-hardcore coders use modular applications and easily
extensible templates that dont require hours of fighting with
PHP and CSS in order to achieve seemingly simple ends.
One such framework is the well-regarded Django. Django
follows the model-view-controller (MVC) design, in which
applications must be well-behaved with regard to separating
representations of input (via the controller) and output (via
the view). The model handles all the in-between gubbins: the
data and logic connected to any instructions received from
the controller and their processing into output to the viewer.
In the present article we will employ Django to set up a basic
CMS-based website. There are many CMS packages to
choose from (see www.djangopackages.com/grids/g/cms)
but lets take a closer look at one of the most popular, the
imaginatively-titled Django CMS.
Its recommended to run Django CMS in isolation through
Virtualenv, since this will ensure its Python dependencies
dont clash with anything else on the system. To get this set
up, first install Pip from your distributions repositories. Then
install the virtualenv package (as root):
Create a blog
Django 3.0 was released in April 2013. One of its major new
features is the powerful front-end system, which enables you
to manipulate all the elements and plugins on your page
directly from the admin view, without having to do any kind
of code-tinkering. This makes doing basic site overhaul and
construction work a breeze, but remember that this front-end
is still in its infancy and as such gets confusing on occasion.
For example, you might need to enlarge the left-hand panel
to reveal all of the page actions. For the blog that were about
to bring into existence, you might see a couple of spurious
errors along the lines of: Menu *menu cannot be loaded...
These conveniently disappear with a simple refresh. Perhaps
they will even have been fixed by the time you read this. While
were in the left-hand panel, its worth navigating to the sites
options and changing example.com to localhost:8000 since
some pages will direct you to the absolute URL.
Web
Projects in Django have two important files which you will
deal with in this tutorial: settings.py and urls.py. The former
details various low-level configurations such as project paths,
any extra apps needed and which database engine will be
used. When you add items to this, you will need to rebuild the
project database for them to be picked up. Oftentimes these
extra apps have their own databases which need to be
migrated. Fortunately, the South utility takes care of this for
us. The file urls.py contains a list of regular expressions that
tell Django what to do with certain URL patterns. For example,
we tell Django to invoke the Zinnia blog well make for this
tutorial for URLs with /weblog/ after the servers URL.
Django CMS permits (almost) seamless integration of
Django applications in your website. In demonstration of this
fact, lets get the popular Zinnia blog application up and
running. Interrupt your webserver with Ctrl+C, then install the
Zinnia Python modules as well as the apphook so that the
CMS and blog can converse:
(env) $ pip install django-blog-zinnia cmsplugin_zinnia
This requires a few additional bits of Django gubbins, so you
need to add the following to the INSTALLED_APPS section in
~/django/my_demo/settings.py:
zinnia,
cmsplugin_zinnia,
tagging
django.contrib.comments
While youre in settings.py, also add this line to prevent
Zinnia attempting to send you an email whenever someone
posts a comment on your blog:
ZINNIA_MAIL_COMMENT_AUTHORS=False
Next, we add the following to the beginning of the urlpatterns
definition in ~/django/my_demo/urls.py:
url(r^weblog/, include(zinnia.urls)),
url(r^comments/, include(django.contrib.comments.
urls)),
Once thats done, register all of your new apps into the Django
database with:
(env) $ ./manage.py syncdb
(env) $ ./manage.py migrate
You should then be able to see a vanilla Zinnia weblog at
http://localhost:8000/weblog. The point of the cmspluginzinnia apphook is to enable content from the blog to be
displayed elsewhere on our website. Look at the step-by-step
guide to see how this is achieved.
Now that youve got somewhere to voice your words, why
not add a gallery to display your etchings and photographs?
The Imagestore application is popular for these purposes.
Install it with a simple:
(env) $ pip install imagestore
Also add the following to the INSTALLED_APPS section of
~/django/my_demo/settings.py:
...
imagestore,
sorl.thumbnail,
imagestore.imagestore_cms,
...
Add its urls to ~/django/my_demo/urls.py:
url(r^gallery/, include(imagestore.urls,
namespace=imagestore)),
Then run:
(env) $ ./manage.py syncdb --migrate
This will update the database. You might get an error from
the South database migration tool as it tries to import the
permissions setting, but if you run the command again it
should work correctly. Now add a new page and call it Gallery.
This will automatically hook into the Imagestore, so when you
click on it you will see your galleries. Or you would if there
were any. We can add galleries from the admin panel on the
left, which now has an Imagestore section within the Home
tab. Once youve added some galleries, you can incorporate
them on pages individually, using the newly visible Album and
Album as Carousel elements in the structure view.
Quick
tip
Find a more
thorough guide to
uWSGI and Nginx
on the official
uWSGI website:
http://bit.ly/
uWSGINginx.
Its a piece of cake to embed YouTube videos in your site. Getting the
good people at Nvidia to supply card specs, not so much.
83
Web
location /static {
alias /home/user/django/my_demo/static;
}
location / {
uwsgi_pass django;
include uwsgi_params;
}
}
The Zinnia
app is pretty
impressive in
its own right.
Oh Lord, wont
you buy me
This site is built
with Django CMS.
84
Web
Create a blog with Django and Zinnia
Start Zinnia
When we restart the webserver you should see a Zinnia menu in the
top bar. Clicking New entry in here will awkwardly put a rich text blog
entry form in the panel to the left. Herein you can make your first
Zinnia blog entry, if that is your will. We can do better though, in
particular we can integrate the blogging application into the layout of
our choosing.
Create a layout
Select the structure view at the top and click on the menu on the right
hand side of the content bar. Add a Multi Column environment with
two columns. Initially both columns are set to the same size, which is
unsatisfactory. But click save and then expand the multi-column
environment and configure the columns as you see fit. Ive gone for
50 percent on the left and 25 percent on the right.
Make a page
Lets create a new page for our blog selecting Page > Add Page > New
Page. Call it blog, or perhaps something more imaginative. The Slug
is how the page will be referenced in URLs, and will autocomplete
based on the Title. This means that your blog can be easily and
efficiently indexed by web spiders and robots. Click save to bring the
page into being.
Next head to the right column and add a Latest Entries plugin from
the right-hand menu. Edit the plugins settings so that it displays only
the latest entry, with the entry-detailed template. Below this you will
need to add another latest entries element with an offset of 1 and in
the default entry-list style. This will display just the titles of all your
previous entries.
Get blogging
It does a fine job of displaying the content, in this case a lego model of
the ITER Tokamak fusion reactor. As you develop your site you will be
able to customize and add new widgets and wotsits to your hearts
content. Of course, the real fun starts when you start to write your
own templates, but its still impressive how much can be achieved
without even a single line of code.
85
Web
Make a
Twitter client
Well show you how to do Twitter like a boss. A command-line boss that
accepts arguments and catches errors.
Twitter enables
developers access to its
comprehensive REST API.
Our search
for Windows XP
found a lot of
worried people
survival kit
indeed. Notice
how nicely
the unicode
characters
are printed.
Adding argparse
By importing the argparse module and then creating an
ArgumentParser object and calling parse_args() your
program will get a -h or --help option for free. You can see this
in action by creating a file called argtest.py with the
following contents:
import argparse
parser = argparse.ArgumentParser()
args = parser.parse_args()
Then run python argtest.py -h to see your free usage
message. As it stands this is not particularly useful, but once
we start adding arguments this will change. Arguments can
be positional (mandatory) or optional and we can add a
mandatory argument to argtest.py by inserting the following
just above the last line:
parser.add_argument("grr_arg", help="Repeat what you just
told me")
86
Web
Taking a REST
REST is short for Representational State
Transfer and refers to a set of principles for
gathering and sharing data rather than any
concrete protocol. Twitter implements two
major APIs, a RESTful one, which we will use,
and a streaming one, which we wont.
The streaming API provides low-latency
access to real-time data, which you can do all
sorts of fancy stuff with, but the RESTful API
provides a simple query and response
mechanism which suits our purposes just fine.
Using arguments
More complicated arguments can easily be dealt with, for
example we could sum an arbitrarily long list of integers by
modifying the add_argument call like this:
parser.add_argument('integers', metavar='N', type=int,
nargs='+', help='some integers')
By default, arguments are assumed to be strings, so we
use the type= option to stipulate that integers are provided.
The metavar directive refers to how our argument is referred
to in the usage message, and nargs=+ refers to the fact
that many integers may be provided. We could make a
regular-ordinary program for summing two integers with
nargs=2, but where would be the fun in that? We have to put
the arguments provided into the list args.integers, so we can
process it like so:
print "The answer is {}.".format(sum(args.integers))
Our Twitter project works exclusively with optional
arguments. These creatures are preceded with dashes, often
having a long form, eg --verbosity, and a short form, say -v.
Our Twitter program has 5 options in total (not counting the
complementary --help option): --search, --trending-topics,
--user-tweets, --trending-tweets, and --woeid.
As it stands --woeid only affects the --trending-topics and
--trending-tweets options. While the argparse module could
easily handle grouping these arguments so that an error is
issued if you try and use --woeid with another option, its
much easier to not bother and silently ignore the users
superfluous input: Havent we all seen enough errors?
For example, the search argument which takes an
additional string argument (the thing youre searching for) is
described as follows:
parser.add_argument("-s", "--search",
type=str,
dest="search_term",
nargs=1,
help="Display tweets containing a particular string.")
Our usage
instructions for
all the optional
arguments you
can use.
87
Web
OpenHatch community
OpenHatch.org is a Boston-based
not-for-profit with the admirable and
noble goal of lowering the barriers into
open source development.
Its website provides a system for
matching volunteer contributors to
various community and education
projects and it runs numerous free
workshops imparting the skills
required to become a bona fide open
source contributor. Since 2011 it has
with it, which results in an error. You can test for this in the
Python interpreter as follows, where woeid is the WOEID of
your desired location:
import twitter_functions
test = twitter_functions.api.GetTrendsWoeid(woeid)
If you dont get an error ending with Sorry, this page does
not exist, then all is well. We use Pythons error catching to
fallback to the global trends function GetTrendsCurrent()
when this happens:
try:
trending_topics = api.GetTrendsWoeid(woeid)
except twitter.TwitterError:
trending_topics = api.GetTrendsCurrent()
Its prudent (but not necessarily essential, the catchall
clause except: is entirely valid) to specify the exception that
you want to catch if you arent specific, however, confusion
and hairpulling may arise.
The common base
exceptions include IOError,
for when file operations go
wrong, and ImportError
which is thrown up when you
try and import something
that isnt there:
try:
import sys, absent_module
except ImportError:
print "the module is not there"
sys.exit()
Modules will also provide their own exceptions, for example if
Unicode fixer
The function trendingTweets() is a little more complicated:
we need to first get a list of trending topics, and then for each
of these grab some tweets.
But theres a sting in the tail
sometimes the topics
returned will have funky
unicode characters in them,
and these need to be
sanitised before we can feed
them to our search function. Specifically, we need to use the
quote function of urllib2 to do proper escaping, otherwise it
will try and fail to ASCII-ize them.
trending_topics = api.GetTrendsCurrent()
for topic in trending_topics:
print "**",topic.name
esc_topic_name = twitter.urllib2.quote(topic.name.
encode('utf8'))
tweets = api.GetSearch(esc_topic_name)
for tweet in tweets[:5]:
print '@' + tweet.user.screen_name + ': ',
util.safe_print(tweet.GetText())
print '\n'
Weve been a bit naughty in assuming that there will be at
least five tweets, the syntax for limiting the number of tweets
GetSearch returns seems to be in a state of flux, but since
these are trending its reasonable that there will be plenty.
And that completes our first foray into pythonic twittering.
We have developed the beginnings of a command-line Twitter
client, we have parsed options, caught exceptions and
sanitised strings. If your appetite is sufficiently whetted then
why not go further? You could add a --friends option to just
display tweets from your friends, a --post option to post stuff,
a --follow option, and really anything else you want. Q
88
*V]LYPUN
UN [OL
SH[LZ[ UL^
[LJOUVSVN`
VSVN`
PU KLW[O
KL
PU KL[HPS
KL
M\SS` [LZ[LK
NLHY
Networking
90
Networking
Networking
T
he true sign of a Linux master is expertise on
the desktop, the command line and, most
crucially, the network. The skills to mesh
machines together, even those running different
operating systems, are vital a lone PC is the rarest
of creatures in this day and age.
91
Networking
Samba
Dancing with Windows
The Windows interoperability suite for Linux that boasts
Active Directory support. Lets take it for a spin.
92
Networking
SMBFS and CIFS
Two virtual filesystem implementations
on Linux allow mounting of SMB shares: SMBFS
and CIFS. The latter is the newer implementation
and is built into the kernel. The user-space tools
that you need to use CIFS were originally part of
Samba but are now a separate package thats
called cifs-utils.
The original SMBFS, which is also part of the
Samba suite, has been deprecated you should
use CIFS to mount Samba filesystems. The
Quick tip
You do not need to restart or signal Samba
when modifying smb.conf because it
automatically detects changes.
Add/Remove NetBIOS
There is another networking protocol that has
long been associated with Windows networking
and, therefore, is an integral part of the Samba
suite: NetBIOS. These days, NetBIOS generally
refers to the NetBIOS over TCP/IP protocol,
which is considered a legacy protocol. It offers
name resolution, file and printer sharing with
devices that do not have DNS capabilities.
It used to be essential in a Windows network,
but is no longer necessary unless older versions
of Windows are involved, but you still need it if
you want clients running OSes prior to Windows
2000 to be able to access your shares. If you
dont want to include NetBIOS, the following
additions to the [global] section of smb.conf
make this explicit:
[global]
# disable NetBIOS
disable netbios = yes
smb ports = 445
Should you need it, however, enabling
NetBIOS requires other changes to smb.conf:
[global]
# NetBIOS identification
workgroup = WORKGROUP
netbios name = MYHOST
wins support = Yes
This tells Samba to use NetBIOS to make
itself known on the Windows network in its
default workgroup (Windows machines default
to a workgroup called WORKGROUP) and to act
as a WINS server. The NetBIOS name is the
equivalent of a host name it doesnt need to
be the same as the host name, but that is
customary. WINS is the Windows Internet
93
Networking
Quick tip
Upgrading users should note that the
smbpasswd file has changed internally, and
is therefore not portable between Samba 3.x
and Samba 4.
Password management
This is the first area where the Active Directory
setup differs from the classic setup. Classic
Samba uses its own password database
containing encrypted passwords but, because
94
Windows 7 RSAT :
www.microsoft.com/en-gb/download/details.
aspx?id=7887
If you want the Windows machine to respond
to ICMP Ping requests, you will need to add an
appropriate rule to the Windows firewall (or
completely disable the firewall).
To add a rule, go to Start > Control Panel >
System and Security > Windows Firewall >
Advanced Settings > Inbound Rules > New Rule.
Create a custom rule for the ICMPv4 protocol.
Remember that the Home and Starter versions
of Windows are unable to join a domain.
For Active
Directory Users
and Computers
search for
dsa.msc and
run it as an
administrator.
Networking
# mkdir /var/spool/samba
# chmod 1777 /var/spool/samba
The necessary Samba configuration sets up
CUPS printing and shares its printers on a
[printers] share:
[global]
load printers = yes
printing = cups
printcap name = cups
[printers]
comment = Printers
path = /var/spool/samba
browsable = yes
writable = yes
printable = yes
[print$]
comment = Printer Drivers
path = /usr/share/samba/print
writable = yes
The additional [print$] share is optional,
but it is for Point and Print Drivers. It allows an
administrator to upload printer drivers to the
server so that a user installing the printer does
not have to look for a driver themselves. The
directory for the [print$] share should be
created along with subdirectories for the
architectures to be supported:
# mkdir -p /usr/share/samba/print/{COLOR,IA
64,W32ALPHA,W32MIPS,W32PPC,W32X86,
WIN40,x64}
The easiest way to upload a printer driver
is by an administrator user logged in to a
Domain control
Well now take a look at the Active Directory
implementation provided by Samba 4. It is best
to assume that, while Samba 4 can act as either
a Standalone/NT Domain Member or as an
Active Directory Domain Controller, the two
configurations are very different and, to some
extent, incompatible.
Setting up Samba as an Active Directory
domain controller is, however, straightforward
because there is a provisioning tool that
performs the set-up tasks:
# samba-tool domain provision
Realm [MYDOMAIN.CO.UK]:
Quick tip
There are some tutorial videos at
https://wiki.samba.org/index.php/
Samba4/videos, which provide good
walkthroughs of the provisioning process.
Domain [MYDOMAIN]:
Server Role (dc, member, standalone) [dc]:
DNS backend (SAMBA_INTERNAL, BIND9_
FLATFILE, BIND9_DLZ, NONE) [SAMBA_
INTERNAL]:
DNS forwarder IP address (write none to
disable forwarding) [10.0.0.138]:
Administrator password:
Retype password:
Passwords need to be suitably complex: one
upper-case letter, one digit and at least eight
characters long. Pa$$w0rd is a suitable
example that we used for our tests, though its
not very secure. When the provisioning
completes, it will explain that it has generated
a Kerberos configuration suitable for Samba 4.
You need to copy this file into place:
# cp /var/lib/samba/private/krb5.conf /etc
Next, the DNS resolver needs to be
configured to point at Samba, because it is also
the DNS for the new Windows domain. You can
do this either by editing /etc/resolv.conf or,
if thats written by a service such as dhcpcd,
adjusting the services configuration.
95
Networking
Testing phase
With the configuration steps completed, we can
start the domain controller and perform some
tests. Active Directory mode uses a new samba
binary instead of the usual smbd. Here, we start
it in the foreground while testing:
# samba -i -M single mydomain
Copyright Andrew Tridgell and the Samba
Team 1992-2012
samba: using single process model
# host -t SRV _ldap._tcp.mydomain.co.uk
_ldap._tcp.mydomain.co.uk has SRV record 0
100 389 myhost.mydomain.co.uk.
# host -t SRV _kerberos._udp.mydomain.co.uk
The Samba Web Adminstration Tool (SWAT) is still around, but hasnt been updated.
96
IPC$
IPC
IPC Service (Samba 4.0.3)
$ smbclient //localhost/netlogon
-UAdministrator%Pa$$w0rd -c ls
Domain=[MYDOMAIN] OS=[Unix]
Server=[Samba 4.0.3]
.
D
0 Thu Feb 7
20:06:55 2013
..
D
0 Thu Feb 7
20:08:44 2013
Another service provided by an Active
Directory Domain Controller is time
synchronisation. While optional, providing this
service is highly recommended because
Kerberos is highly sensitive to time variations
between clients and the server.
The so-called Windows Time Service that
a domain controller provides is a Network Time
Protocol (NTP) server with extensions for
authentication. Theres a number of NTP
implementations on Linux, such as ntpd and
open-ntpd, but only ntpd version 4.2.6
onwards supports the necessary authentication
extensions, and then only if that support has
been compiled in (you should check your ntpd
version with ntpd --version). A suitably
configured ntpd asks Samba to perform any
necessary authentication. The ntpd
configuration goes in /etc/ntpd.conf. Here is a
suitable example:
server 127.127.1.0
fudge 127.127.1.0 stratum 12
ntpsigndsocket /var/lib/samba/ntp_signd/
restrict default mssntp
The important lines, which may not be in
an existing ntpd.conf, are the last two. The
ntpsigndsocket entry defines the path to the
directory where Samba places the socket file,
through which it will receive authentication
requests. The restrict entry tells ntpd that
incoming requests need to be authenticated.
The socket path is determined by Sambas
configuration, and you can confirm the correct
path with:
# samba-tool testparm --verbose --suppress-
Networking
Domain admin
To add the client to the domain, go to Start >
Computer > Right-click > Properties > Change
settings. This will display the Computer Name/
Domain Changes dialog, where you should
select Domain in the Member Of section and
enter the Samba domain name (for example,
mydomain) before pressing OK. This should
request the administrator account credentials
(the username is Administrator and the
password is Pa$$w0rd if you have been
following our example settings).
Domain administration can be performed
locally on the server using the samba-tool
command line utility, or
remotely from a Windows
computer connected to the
domain. An administrator, using
a suitably configured computer,
can run the Active Directory
Users and Computers tool.
This offers full control over users and
computers, and also functions exactly the same
as though it were administering Microsofts
Active Directory.
Adding users to AD is done differently from
classic Samba (which uses smbpasswd), but
its more flexible because it can be done from
a server command prompt using samba-tool
or remotely from Windows with Active Directory
Users and Computers.
When Active Directory users are created,
they are unrelated to existing users in
/etc/passwd because they are given different
Quick tip
The release notes for the latest stable
release Samba 4.0.22 are available at
http://bit.ly/1oKq4tc.
Networking
Networking:
Take your first steps towards understanding networking and linking
your Linux boxes, as we introduce some of the key concepts.
tools (such as the network analyser, Wireshark on p102) to
examine and build networks.
First, our goal is to introduce you to the three ideas that
underpin everything else that happens with networks
packets, physical connections and addressing. Then were
going to create some virtual machines (see p106) and build
some simple networks.
WireShark
does a similar
job to tcpdump
capturing
packets, but
provides a nice
colourful GUI
to help you see
whats going on.
98
Networking
The basics
Networking models
In this article, we cover a lot of ground, from
physical media to packets to MAC addresses
and routed IP networks. If it seems difficult to
understand how this all fits together, imagine
how difficult it is to make the systems that
enable all this to work. Its very complicated, and
there are many components that all have to work
together if your network connection is going to
work the way it should.
To make networking software and hardware
that works together easier to create, some clever
people came together and created the Open
Systems Interconnection model. The OSI
specifies seven layers, each of which describes a
set of related functions that are critical if the
network is to work as expected. Each separate
MAC addresses
Now you know how many computers can share a single
physical network, you might be wondering how computers
can identify each other on the network that is, how can
you send information only to Bobs computer, not Alices?
In fact, the answer is that when computers are connected
by the same bit of physical medium for example, a copper
cable they see every packet sent to every other computer.
Nmap is a
command line
tool for scanning
your network.
Here, weve
used Zenmap
to interpret the
results of a scan
to display the
topology of
the network.
99
Networking
Understanding IP addresses
IP addresses are a touch more complicated than
suggested in the articles main body. Although
we usually write an IP address as four numbers,
separated by periods, they are in fact
a single 32-bit binary number. Each of the four
numbers represents a group of eight bits
(an octet) in the binary form of the address,
for example:
192.168.1.111000000.10101000.00000001.0
0000001
This means that each of the four numbers in an
IP address can range from 0 through to 255.
The prefix that we talked about specifies how
many bits in the binary representation belong to
This is an
example of a
network interface
card; the device
that mediates
between your
system and the
physical medium.
Logical networks
The use of switches to extend networks and reduce collisions
isnt the end of the story, however. Another hurdle to jump
over is the fact that MAC addresses have a flat structure,
which means theres no easy way to organise the addresses
or group them together.
This isnt a problem when youre dealing with a small
network, but as your network begins to grow, your switches
will find themselves quickly handling enormous lists of MAC
addresses that have to be searched through in order to figure
out which port a packet must be sent out of. This would slow
down the switches and would make a global network, such as
the internet itself impossible to build.
To get around this, we split large networks into many
smaller, logically grouped networks and use inter-networking
technologies to route traffic between them. How does this
work? Well, we first need to introduce you to a new type of
100
Networking
interface the packets should be sent out of. This default route
is your computers fallback if theres not another route
specified for the IP address youre trying to communicate
with it will send packets to this gateway.
If you compare the destination of the default route to the
output of the ip neighbour command, youll see that your
computer has the MAC address of its default gateway, and so
the two are able to communicate directly.
Arping around
Your computer builds the table of MAC to IP address shown
in the ip neigh command by using the Address Resolution
Protocol (ARP). This protocol defines a special packet, just
like the ones we saw above when we ran the tcpdump
command. When your computer wants to find out the MAC
address of a computer with a particular IP address, it will
construct an ARP request
packet.
This includes your MAC
address as the sender, and
the IP address of the host
whose MAC address you
want to know, but it doesnt
specify the destination MAC address. This packet is then
broadcast to every host connected to the same physical LAN
as you that is, it will be sent out of every port on a switch,
but not from one router to another saying Request who
has 192.168.1.2 tell 192.168.1.1, for example.
If that IP address exists on the network, a REPLY ARP
packet will be sent back to the requesters MAC address,
saying Reply 192.168.1.2 is-at ea:34:43:81:02:7c. Now the
two computers will be able to communicate directly.
You can see this in action by running the tcpdump
command from earlier again. Instead of opening a web page,
however, in another terminal, run as root
arping 192.168.1.1
where the IP address is that of your default gateway. If you
now look at the tcpdump output, you should see an ARP
conversation taking place. Q
Switches are
the unsung
core of many
networks,
reducing collision
domains and
making it
possible for
many hosts to
communicate
reliably in a
single network.
101
Networking
Wireshark:
Analyse traffic
We explain all the necessary essentials that you need to know to start using
the GUI-enhanced Wireshark, and analyse three kinds of network traffic.
102
Networking
see and change the Capture Options by selecting Capture >
Options from the menu. There you can select the network
Interface(s), see your IP address, apply capture filters, put
your network card in promiscuous mode, and save your
capture data in one or multiple files. You can even choose to
stop packet capturing after a given number of network
packets or a given amount of time or indeed a given size of
data (in bytes).
Wireshark doesn't save the captured data by default but
you can always save your data afterwards. It's considered
good practice to first save and then examine the network
packets unless there's a specific reason for not doing so.
Wireshark enables you to read and analyse already
captured network data from a large amount of file formats
including tcpdump, libpcap, Suns snoop, HPs nettl, K12 text
file etc. This means that you can read almost any format of
captured network data with Wireshark. Similarly, Wireshark
enables you to save your captured network data in a variety
of formats. You can even use Wireshark to convert a file from
a given format to another.
You can also export an existing file as a plain text file from
the File menu. This option is mainly for manually processing
network data or using it as input to another program.
There is an option that allows you to print your packets.
I have never used this option in real life but it may be useful to
print packets and their full contents for educational purposes.
Display filters
While capture filters are applied during network data capture
and make Wireshark discard network traffic that doesn't
match the filter, display filters are applied after capture and
'hide' network traffic without deleting it. You can always
disable a Display filter and get your hidden data back.
Generally, display filters are considered more useful and
versatile than capture filters because it's unlikely you'll know
in advance what you'll capture or want to examine.
Nevertheless, applying filters at capture time can save you
time and disk space and that's the main reason you might
want to use them.
Wireshark will highlight when a display filter is syntactically
correct with a light green background. When the syntax is
erroneous, the background becomes pink.
Display filters support comparison and logical operators.
The http.response.code == 404 && ip.addr == 192.168.1.1
display filter shows the traffic that either comes from the
192.168.1.1 IP address or goes to the 192.168.1.1 IP address
that also has the 404 (Not Found) HTTP response code in it.
The !bootp && !ip && !arp filter excludes BOOTP, IP and
The three
packets (SYN,
SYN+ACK and
ACK) of a TCP
3-way handshake.
Quick
tip
The fact that the
FTP protocol
usually uses
port number 21
doesnt mean
its not allowed
to use a different
port number. In
other words, don't
blindly rely on the
port number to
characterise TCP/
IP traffic.
Networking
Quick
tip
When you put
your network card
in promiscuous
mode, you allow
the network device
to catch and read
every network
packet that arrives
to it even if the
receiver is another
device on the
network. Network
packets still go
to their original
destination.
in the SYN packet. The server sends back a TCP (SYN, ACK)
packet which includes the sequence number of the opposite
direction and an acknowledgement of the previous sequence
number. Finally, in order to truly establish the TCP connection,
the client sends a TCP ACK packet to acknowledge the
sequence number of the server. After the TCP three-way
handshake, the connection is established and is ready to
send and receive data.
The traffic for this case was produced by running the
following command:
$ wget http://www.linuxformat.com/
After some necessary DNS, ARP and ICMP network traffic,
the TCP three-way handshake begins (which you can see
pictured top, p103). The client IP address is 10.0.2.15 and the
destination IP address is 80.244.178.150. A pretty simple
display filter (tcp && !http) makes Wireshark display 63 out
of 82 packets. The three packet numbers used in the
handshake are sequential because the host wasnt
performing any other network activity at the time of
capturing, but this is rarely the case.
Ping scans
This part will examine the network traffic that's produced by
Nmap when it performs a ping scan. LAN ping scans are
executed using the ARP protocol. Hosts outside a LAN are
scanned using the ICMP protocol, so if you execute a Nmap
ping scan outside of a LAN, the traffic will be different from
one presented. In the example below, the Nmap command
scans 255 IP addresses, from 10.67.93.1 to 10.67.93.255. The
results show that at execution time only 10 hosts were up or,
to be precise, only ten hosts answered the Nmap scan:
$ sudo nmap -sP 10.67.93.1-255
Starting Nmap 6.47 ( http://nmap.org ) at 2014-09-05 11:51
EEST
Nmap scan report for xxxxx.yyyyy.zzzzz.gr (10.67.93.1)
Host is up (0.0030s latency).
MAC Address: 64:70:02:AD:E9:44 (Tp-link Technologies
CO.)
Nmap scan report for srv-gym-ag-anarg.att.sch.gr
(10.67.93.10)
Host is up (0.0051s latency).
MAC Address: 00:0C:F1:E8:1D:6E (Intel)
Nmap scan report for 10.67.93.20
Host is up (0.0066s latency).
MAC Address: D0:27:88:1D:15:20 (Hon Hai Precision Ind.
Co.Ltd)
Nmap scan report for 10.67.93.21
Host is up (0.0053s latency).
MAC Address: D0:27:88:1D:D6:FB (Hon Hai Precision Ind.
Co.Ltd)
Nmap scan report for 10.67.93.22
Host is up (0.0080s latency).
MAC Address: 00:1A:92:44:D7:67 (Asustek Computer)
Nmap scan report for 10.67.93.29
Host is up (0.057s latency).
MAC Address: 00:78:E2:47:49:E5 (Unknown)
Nmap scan report for 10.67.93.78
Host is up (0.0023s latency).
MAC Address: 00:80:48:24:6A:CC (Compex Incorporated)
Nmap scan report for 10.67.93.147
Host is up (0.028s latency).
MAC Address: 00:14:38:64:5D:35 (Hewlett-Packard)
More networking tutorials Turn a Linux box into a router, see page 106.
104
Networking
Nmap scan report for 10.67.93.172
Host is up (0.016s latency).
MAC Address: 00:50:27:00:E4:F0 (Genicom)
Nmap scan report for wwww.yyyyy.zzzzz.gr (10.67.93.11)
Host is up.
Nmap done: 255 IP addresses (10 hosts up) scanned in 1.25
seconds
The purpose of the ping test is simply to find out if an IP is
up or not see the grab on the opposite page. What's
important for Nmap in a ping scan is not the actual data of
the received packets but, put relatively simply, the existence
of a reply packet. As all traffic is in a LAN, each network device
uses its MAC address in the reply so you only see MAC
addresses in both Source and Destination fields. The
presence of a reply makes Nmap understand that a host is up
and running. As a MAC address includes information about
the manufacturer of the network device, Nmap also reports
that information for you.
Nmap also calculates the round trip time delay (or
latency). This gives a pretty accurate estimate of the time
needed for the initial packet (sent by Nmap) to go to a target
device, plus the time that the response packet took to return
to Nmap. A big latency time is not a good thing and should
certainly be examined.
there will be two answers for the DNS query. In time, you will
be able to take all this in with one glance.
UDP uses the underlying IP protocol to transport a
message from one machine to another, and provides the
same unreliable, connectionless packet delivery as IP. It
doesn't use acknowledgements to make sure messages
arrive, it doesn't order incoming messages, and it doesn't
provide feedback to control the rate at which information
flows between the machines. Thus, UDP messages can be
lost, duplicated, or arrive out of order. Furthermore, packets
can arrive faster than the recipient can process them.
The destination port of the first packet is 53 which is the
usual port number of the DNS service. The UDP part of the
second packet shows the port numbers used for the reply:
User Datagram Protocol, Src Port: 53 (53), Dst Port: 53366
(53366)
Source Port: 53 (53)
Destination Port: 53366 (53366)
Length: 90
Checksum: 0xb94b [validation disabled]
[Stream index: 0]
As it happens with most tools, the more you use
Wireshark, the more efficient you will become with it, so keep
on practicing and learning! Q
Quick
tip
There is also a
console version of
Wireshark called
tshark. The two
main advantages
of tshark are that
it can be used in
scripts and that
it can be used
through an SSH
connection. Its
main disadvantage
is that it does not
have a GUI. Tshark
can also entirely
replace tcpdump.
Here is how Wireshark shows the traffic of a DNS query after applying a
Display filter. Notice the green colour around DNS that shows the validity of it.
The IP protocol
IP stands for Internet Protocol. The main
characteristic of IP is that it's not a reliable
protocol by design. Unreliable means that
packets may not reach its destination for various
reasons, including transmission errors, network
hardware failures and network congestion.
Networks may also deliver packets out of order,
deliver them after a substantial delay or deliver
duplicates. Nevertheless, a programmer can
program reliable applications that use IP by
implementing their own error-checking code but
this is a non-trivial task.
105
Networking
Networking:
After introducing you to the building blocks and tools of networking, were
going to put all that knowledge together to create real, working networks.
The contents
of the /etc/
sysconfig/
network-scripts
directory looks
intimidating, but
if you focus on
the ifcfg-ethX
files, youll find
theres a lot you
can do here.
106
Basic networking
With the installation complete on both machines, its time to
get both connected to the internet via the default NAT
network. This will give us a chance to get familiar with Red
Hats network configuration files and to refresh some of the
information we covered in the previous pages.
The first thing to do after your new VM has booted is to
switch to the /etc/sysconfig/network-scripts directory.
On Red Hat-based distributions, this directory contains the
start-up scripts and configurations for every network device
connected to your machine. If you followed our step-by-step,
you should see two configuration files, ifcfg-eth0 and ifcfgeth1 (if youre using a different version of Red Hat, it might be
ifcfg-em1 and ifcfg-em2 that you see). Eth0 is the first
network device on the system, and should refer to Adapter 1
in the VirtualBox configuration that is the NAT network.
Using Vi, edit ifcfg-eth0, making sure the following lines
are present and set to these values:
NM_CONTROLLED=no
BOOTPROTO=dhcp
ONBOOT=yes
The first line stops NetworkManager from controlling this
interface since were trying to do things manually, its
interference could confuse matters, so we turn it off.
The second line specifies what protocol it should use to
get its IP address. Here, weve specified DHCP, or Dynamic
Networking
Build a router
Create a virtual machine
Name your VM
Select the CD
Install CentOS
Networking
Static networking
In the previous section, most of the hard work was done for
us by the DHCP protocol and VirtualBox. This time around,
were going to create a network connection between our two
VMs, but were going to do all the configuration ourselves.
The first thing to note is that if these were real machines,
wed have to connect them together with a physical wire,
either directly or via a switch or router. Since these are VMs,
weve already done this by connecting their second interfaces
to the same internal network.
So, as before, youll need to start by visiting the /etc/
sysconfig/network-scripts directory. Youll want to edit the
ifcfg-eth1 file, but it will need to look different from before:
NM_CONTROLLED=no
BOOTPROTO=static
IPADDR=192.168.1.2
PREFIX=24
ONBOOT=yes
The boot protocol is now set to static, which means rather
than automatically receiving an IP address, you will have to
manually set an IP address for the VM. This is done in the
Networking
Building a router
So far, we havent had to worry about setting the gateway on
either of our machines because weve relied on the DHCP
from VirtualBoxs default NAT network to provide this, along
with DNS, so that our systems can connect to the wider
internet. To demonstrate some more networking features,
were going to disable the NAT connection on the second VM
and configure the first as a router to provide internet access.
The first thing to do is run ifdown eth0 to shut down the
NAT interface on the second VM. Now that the interface is
configured, this command, along with its counterpart ifup,
can be used to control whether an interface is active or not.
With this change made, you can now try to ping Google
from this machine, and you should find it no longer works.
Before you can make it work again, however, you need to
make some changes to the first VMs configuration.
First, you have to tell it that its allowed to forward packets
from one network interface to another the most important
and really only thing a router is used for. Linux is quite
capable of doing this, but by default the feature is turned off.
To turn it back on, edit the /etc/sysctl.conf file, which
controls various aspects of the kernels operation, setting
net.ipv4.ip_forward = 1. Then, run sysctl -p /etc/sysctl.
conf to load the new configuration.
Once thats done, youll need to configure your own NAT,
or network masquerade in Linux speak, with IPTables the
firewall thats built in to the kernel.
IPTables scares lots of people, but its really quite simple
its just a set of rules that the kernel looks at when processing
a packet. If a packet matches any of these rules, the kernel
applies the action specified in that rule to that packet. Actions
can include things such as dropping or accepting a packet, or
manipulating a packet to change its origin or destination. In
our case, when a packet arrives at the first VM from the
second, on the eth1 interface, we want the firewall to apply
IPTables can
look complicated,
especially when
there are lots of
rules involved,
but in simple
cases, adding
just a few rules
is very easy.
Debian-based distributions
Weve focused on the Red Hat approach to
configuration, with CentOS using the same
model. Of course, Red Hat-based distributions
arent the only popular ones for use on servers
in fact, many people prefer to use Debian, or its
younger, popular variant, Ubuntu.
Debian-based distributions, however, take
a different approach. All the tools that weve
introduced you to, such as the ip suite of
commands, ping and so on still work. Whats
more, files such as /etc/resolv.conf and /etc/
hosts are both still in the same place.
The major difference is in the interface
configuration files. Rather than splitting
109
Networking
Deluge: Set up a
Linux Format shows you how to turn an old computer, or even your beloved
Raspberry Pi, into an always-on torrent box using Deluge.
share the same disk with the operating system as well, its
best to keep the OS files on a separate partition.
There are numerous torrent clients available for Linux.
Well be using the Deluge BitTorrent client for this little
project, which can run as a daemon on our headless server
and accept connections from other Deluge clients. The
Deluge client is cross platform, so you can connect to the
torrent box from Linux, Windows and Mac OS X.
Deluge offers multiple ways of accessing it remotely.
You can access basic functions via a browser-based user
interface. Setting this up doesnt require much work, but
exposes only some of Deluges features. To exploit it to the hilt
youll need to setup the Deluge daemon to accept
connections from other desktop Deluge installations.
Setting up Deluge
Lets begin by first setting up Deluges WebUI which doesnt
take much effort. Pull the required packages with:
sudo apt-get install deluged python-mako deluge-web
The command will automatically start the Deluge daemon,
but youll have to start the web interface by entering delugeweb & in the terminal.
By default the Deluge web-client runs on port 8112. Fire up
a browser and point it to the IP address of the server, such as
192.168.3.101:8112. The Deluge web interface will prompt you
for a password. The default password is deluge. As soon as
110
Networking
torrent server
you enter the web interface, Deluge will prompt you to change
the password.
Before you can start using the web client youll have to
connect to the Deluge daemons. The web interface will
automatically launch the Connection Manager window, which
lists all of the running Deluge daemon. Simply select the
daemon and click on the Connect button. Youll now be able
to use the web client to add and control all your torrents
running on the torrent box.
If you wish to change the port on which the web client
runs, youll need to edit its configuration file. Head to Deluges
configuration directory with cd ~/.config/deluge/ and open
the configuration file called web.conf in your favourite text
editor. Scroll down the file and find the line that reads port:
8112 and replace 8112 with any port number above 1000.
Daemons work
As mentioned earlier, to get the maximum out of Deluge you
will need to configure the Deluge daemon to accept
connections from a remote client. Start by pulling up the
Deluge console client to make configuration changes to the
Deluge daemon, with the command:
sudo apt-get install deluge-console
To make changes to the daemon, first stop the daemon with:
sudo pkill deluged
Install clients
Add host
Networking
Enhance your torrent experience
Deluge includes a host of useful plugins. To enable them head to Edit >
Preferences and switch to the Plugins category. Click on the checkbox
next to a plugin to enable it. Enabled plugins appear as separate
categories in the Preferences window. The client ships with eight plugins
and you can click the Find More Plugins button to fetch and install
additional third-party plugins.
If you use the Firefox web browser you can add the Bit Torrent WebUI+
Firefox extension that will let you add torrents to the Deluge daemon via
the web interface. After youve installed the extension, itll open a dialog
box for you to enter the connection details of the Deluge WebUI, and
when you click on a torrent link in future, the torrent will be automatically
added to the remote torrent box.
You can also install an app on your Android device to add and control
downloads. The Google Play Store lists several apps that can connect to
the Deluge daemon. Two of the most popular apps are Transdrone and
the feature-rich TransDroid app. While the former is available in the Play
Store, to download the latter you will need to visit the official site via your
smartphone (http://transdroid.org/latest).
112
Useful plugins
One useful plugins is the Scheduler, which lets you limit bandwidth
usage based on the time of day. The Notification plugin displays pop-ups
on the desktop or sends you email alerts when a torrent finishes
downloading. Advanced users will also like the Execute plugin, which
runs a specified command when a new torrent is added or a torrent
completes downloading.
If you use the Chrome browser, you can install the DelugeSiphon app
from the Google Play Store. When installed, youll need to click on its
icon in the address bar and head to the Options page. Enter the IP
address of the daemon along with the port number and the password of
the WebUI. This will enable you to right-click on any torrent file and
select the Send to Deluge option to add the torrent.
Networking
Format the external drive as NTFS. Then make sure the distro can read
NTFS drives by installing the packages with sudo apt-get install ntfs3g and create a mount point for the disk with sudo mkdir /media/
usb-disk. Now plug in the USB device and find its device address with
the sudo fdisk -l. Assuming theres one partition called sdb1, mount it
with sudo mount -t auto /dev/sdb1 /media/usb-disk.
Create directories
Next create new folders for Deluge to store downloads in. Use sudo
mkdir /media/usb-disk/torrents/downloading and sudo mkdir
/media/usb-disk/torrents/completed to create directories that will
store incomplete and completed downloads. Create another directory
with sudo mkdir /media/usb-disk/torrents/watch. Well configure
Deluge to scan this directory and auto-add any new .torrent files.
Once the directories have been created, youll have to plug them into the
Deluge desktop clients. Fire up Deluge and head to Edit > Preferences.
In the Preferences window, select the Downloads category, which lets
you specify the different folders for storing downloads. Toggle the radio
boxes next to the first two options and use the file manager to point to
the folders youve created on the external drive attached to the box. Q
113
Networking
Docker: Build
containers
Linux Format looks at Docker, the project that promises to solve all
manner of application development and deployment headaches.
still in use today. FreeBSD introduced the jail command
which added to the concept and compartmentalised the
system to a greater degree. Solaris, AIX and HP-UX all have
their own variants too, but as you'd expect, Linux leads the
way with a number of projects offering slightly differing
implementations of the idea. These projects build upon a
kernel feature known as cgroups, which (put very simply)
provides a way of bundling a collection of processes together
into a group and managing their consumption of system
resources. Related to cgroups is yet another kernel feature:
namespace isolation, which enables groups of processes to
be isolated from others on the same system (so that they are
not aware of the resources of other processes).
A
Quick
tip
The Docker project
likes to compare its
containers to the
shipping equivalent:
a box with standard
properties - agreed
dimensions and
characteristics that
can be lifted and
shifted anywhere in
the world no matter
what it contains.
114
Networking
run inside it. Once Docker completed its tasks, the container
was shut down. We can use this downloaded image in a more
interactive way by using the -i and -t flags, which enable us to
use the containers STDIN and give us a terminal connection.
sudo docker run -i -t ubuntu /bin/bash
This should give a root prompt almost immediately within
the container itself. The speed with which that hopefully
appeared is one of the reasons for Dockers popularity.
Containers are very fast and lightweight. Many of them can
co-exist on a system, many more than could be handled if
they were more like traditional heavy virtual machines. This is
partly due to Docker using union file systems which are file
systems that operate by creating layers. This makes them
extremely fast. As you would expect, Linux comes with more
than one variant. Docker by default uses devicemapper, but
also supports AUFS, btrs and vfs.
From that prompt, run a few commands such as df -h, ls
and finally top. While the first two should look pretty vanilla as
far as output goes, top will show a rather odd situation of only
two running processes: bash and the top command itself.
Exit this strange matrix like situation by pressing q (to come
Quick
tip
LXC (LinuX
Containers) can
refer to both
the underlying
capabilities of the
kernel (cgroups
et al) and also to
the project that
maintains the
userland tools
which is well worth
a look and has
reached version 1.0.
The Docker website no fail whale here and includes a live online tutorial
which runs through the basics in roughly 10 minutes.
Networking
The Docker
Hub contains
many predefined
Linux containers
from the usual
suspects.
Networking
Nginx running
in a Docker
container.
It may look
like a humble
beginning, but
after a few
tweaks well
be besieged by
Silicon Valley
acquisition
offers, were sure.
with the end copy. This can also be done manually if required
we could start the Ubuntu image, make changes to it at the
command line, exit it and then save the changes using the
docker commit command. This git-like command gives us a
kind of version control over our containers. When were done
with a particular container, using the docker stop and docker
rm commands cleans everything up for us.
Dock together
Of course, having a standalone web server isnt that much
use these days. What if we want to set up a dynamic site that
reads data from a database? Docker has the concept of
linking containers together. Assuming that we had a database
container named data running say, MySQL, we could create a
new Nginx container as follows:
sudo docker run -d -p 8080:80 --name whatever nginx-test
--link data:mysql
The Nginx system will now be able to reference the
database using the alias mysql, and environment variables
and a /etc/hosts entry will be created on the system for the
database. Docker uses a secure tunnel for container to
container traffic here, meaning that the database doesnt
need to export ports to the outside world. Docker takes care
of all of this automatically.
Docker also includes a Vagrant-like ability to share
directories between the Docker host and containers running
on it. The -v flag to the docker run command enables
parameters such as -v /home/web/data:/web/data which
will result in the container seeing a mount point /web/data.
The -v flag can also create standalone volumes in the
container (eg -v /data). For persistent data, the advice
appears to be to create a dedicated container to er contain
it and to then make that data available to other containers.
They can see it by use of the --volumes-from option to
docker run command.
Now that weve had a whirlwind tour of some of the basic
Docker functionality, in next months tutorial well look at
some of Dockers more advanced features and use-cases for
this software. Until then, enjoy experimenting with your new
found container skills and take a look at the options available
for the docker command. Theres also plenty of extra,
in-depth information to be plundered from the official Docker
website (www.docker.com). Happy docking! Q
Quick
tip
The Docker
project maintains
an online public
image repository,
similar to the likes
of Vagrant, where
anyone can store
Docker container
images if they
register. You dont
need to register
an account to
download anything.
117
Networking
Zabbix: Monitor
Zabbix is a network monitoring app that watches everything and we mean
everything. We wonder if its the eye of Sauron come to life.
checksum of a file, and much more. All the collected
information is stored in databases, and you can use MySQL,
Oracle or PostgreSQL, as Zabbix supports all of them.
Outclassing competition
118
But why should you use Zabbix when most people throw
around names such as Cacti and Nagios all the time?
Zabbix, just like its more popular brethren, supports
Simple Network Management Protocol (SNMP). This means
that these apps can monitor almost any device on a network,
such as routers, printers, switches, modems, etc.
While Nagios is the industry standard for monitoring local
and remote machines and IT infrastructure, its almost always
used together with other monitoring tools. This is because
Nagios doesnt have a visualisation feature and cant reduce
recorded data to easily understandable graphs. That said,
Nagios has an excellent alerting feature to keep sysadmins
informed of all the devices it is tracking.
In contrast, Cacti doesnt have an alerting mechanism, but
it can create beautiful and detailed graphs that represent all
the data it collects across devices on the network.
Our tool of choice, however, is very handy at sending out
alerts and creating graphs. In addition to sending alerts via
email, SMS and Jabber, it lets you set up automatic actions.
That is, you can configure Zabbix to itself take action on
remote machines when certain defined events occur.
In terms of visualisation, Zabbix supports real-time
graphing of monitored items and offers graphs, network
maps, screens, and even slideshows, making it suitable for
complex networks, whose sysadmins prefer to see graphical
representations of data.
Understanding Zabbix
A monitoring app primarily performs two functions. It collects
data on all the devices on the network and reports it to a
central controlling authority. Zabbix relies on two key
components for these functions zabbix-server and
zabbix-agent.
As the name suggests, you install zabbix-agent onto all
the machines you wish to monitor on the network. The agent
can monitor hardware resources, as well as applications, and
pushes all the collected information to zabbix-server.
For now, zabbix-agent is available for Linux, FreeBSD,
OpenBSD, NetBSD, HP-UX, MacOS X, Solaris and various
Windows versions.
The other part, zabbix-server, is responsible for polling
and trapping of data. In case of problems or downtime, the
server sends notifications to the configured accounts.
You only need to install one instance of zabbix-server on
your network. With Zabbix, you get a centralised web
interface that you can use to control what events are
monitored across the network. Due to its vast number of
Networking
your network
When things go wrong
Installing Zabbix
The project offers binaries for a few distributions, such as
Debian and CentOS, and most distros carry Zabbix in their
repositories. But, as is the case with many administration
tools, the repos dont always carry the latest version.
Weve used CentOS as the base on which we install
zabbix-server. The network has other machines with other
flavours of Linux, such as Linux Mint.
You should already have all the required PHP and MySQL
packages installed on the machine, but if youre installing
Zabbix on a fresh system, the following command will install
the dependencies:
su -c yum -y install mysql-server php5-mysql php5-gd
The best way to install Zabbix on CentOS is through the
EPEL repository, as the stock repos dont offer the latest
version. If its not already configured on your machine, you will
have to first set up the EPEL repo:
su -c yum -y localinstall http://dl.fedoraproject.org/pub/
epel/6/i386/epel-release-6-8.noarch.rpm
su -c yum -y install zabbix20-server-mysql zabbix20-webmysql
The first command above will configure and enable the
repository. In the second command, we specify the packages
we wish to install, in this case Zabbix 2.0.x.
Zabbix supports MySQL, PostgreSQL and Oracle
databases, and can store the collected data in any of these.
The default configuration expects a database named zabbix.
The default username for this database is zabbix, and no
password is configured. You can edit the /etc/zabbix/
zabbix_server.conf file in case you wish to change any of
these pre-defined settings.
If you do decide to change the database settings, make
sure to keep these handy, as we will need them in just a bit
when we create the database for Zabbix. You need to run the
following commands from the terminal:
mysql -uroot -e create database zabbix
mysql -uroot -e create user zabbix@localhost identified by
ChangeMe
mysql -uroot -e grant all on zabbix.* to zabbix@localhost
mysql -uroot -e flush privileges
The commands above are all self-explanatory. We create
the database in the first command and a user in the second.
Make sure to specify the exact username and password that
youve defined in the /etc/zabbix/zabbix_server.conf file.
Refer to the box for more details on MySQL administration.
Now that the database is in place, we are ready to
populate it:
mysql -uzabbix -pChangeMe zabbix < /usr/share/zabbixmysql/schema.sql
mysql -uzabbix -pChangeMe zabbix < /usr/share/zabbixmysql/images.sql
mysql -uzabbix -pChangeMe zabbix < /usr/share/zabbix-
Quick
tip
As all the data
is recorded in a
database, the
more memory you
have, the faster the
database access.
Networking
mysql/data.sql
The server component of Zabbix comprises three distinct
parts: zabbix-server, the database and the graphical
frontend. Weve installed the first two, but still need to install
the browser-based frontend.
Quick
tip
Databases are the
main bottleneck
for Zabbix. Make
sure to properly
tune your database
to squeeze
performance out of
your system.
Zabbix has no
love for orphaned
users, a user
must belong
to at least one
user group.
Monitor everything
While trial and error is a time-tested technique for mastering
just about anything, Zabbix is not one of those things. Sure,
you can attempt to find your way through all the tabs, menus,
sub-menus, drop-down lists and everything else, but youd be
far better served if you spent some quality time with the
comprehensive Zabbix manual (https://www.zabbix.com/
documentation/2.0/manual).
Every entity on the network that you wish to monitor, be it
a printer, a network switch, a file, router, physical server, or
virtual machine, etc, is identified as a host. To begin
monitoring anything, you first need to create a host. To add
a host, navigate to Configuration > Hosts and click the Create
host button on the right. When adding a host, you must select
at least one host group. This is because permissions are
linked to groups and not individual hosts. Fill in all the other
details, such as the IP address of the host, and click Save
when youre done. For more details, refer to https://www.
zabbix.com/documentation/2.0/manual/config/hosts.
Your newly-created host will now show in the list of
configured hosts. Click the Items link for your host.
For each host that you define, you must also define items.
Items are used to specify what specific data is to be gathered
for each of the configured hosts. Whether you wish to monitor
the CPU load of a machine, check an applications memory
usage, check disk statistics, etc, you must describe the items
for each of these. The most important element when defining
items is the item key. This is what is used to determine
exactly what you want Zabbix to monitor. Click the Select
button next to the Key field and select a key from the list.
For example, if you want to monitor CPU usage, select the
system.cpu.load key.
Return to Configuration > Hosts. If all goes well,
you should see a green signal symbol under the Availability
heading. This means that the host and item have been
properly configured. If, however, you see a red symbol, hover
the mouse over the symbol to find out what the error is.
Depending on the error, you will have to change the item or
host configuration.
Networking
For more details, refer to https://www.zabbix.com/
documentation/2.0/manual/config/items/item.
The Zabbix installation provides a Zabbix server host, with 58
items configured out of the box. But this host isnt enabled by
default. You can enable it, and study the items in it to get
a better understanding of how Zabbix works and what it
means to configure hosts and items.
Once youve created hosts and items, you can head
straight over to Monitoring > Latest data to see what
information Zabbix has managed to collect about your
configured hosts. If you use the default Zabbix server hosts,
you can also see the collected data represented in graphs.
From under the Local data heading, select the item that you
want more details on and then click the graph link at the
extreme right.
Trigger happy
You still need to create a Trigger for your configured hosts.
A trigger is used to analyse the collected data and compare it
with acceptable values. In case there is a discrepancy in the
two values, Zabbix will report a problem. You can use
operators, such as more than, less than, not equal to, etc, to
define triggers. As with items, you create triggers from the
Configuration > Hosts screen itself.
Once this is done, the final step is to configure the system
to send Notifications, in case Zabbix discovers any problems
with the collected data. This is done in two steps.
You have to first define a media type, which is the delivery
mechanism used to send out notifications, such as SMS,
Jabber, email, etc. You can configure the media type from the
Administration > Media types page.
Next, you must define an action under Configuration >
Actions. For each action, you must specify an event source,
such as trigger, and the operation. The operation can be
either to send a message via the configured media type or to
execute a remote command. The latter option you can use to
automatically run the pre-defined command on the remote
machine in case certain conditions are met. You can use this
feature to execute critical commands, such as deleting older
files and emptying /tmp on the remote machine in case it
runs out of disk space, etc.
If you plan to watch the same set of parameters for all the
machines on your network, it makes little sense to go through
all of these steps repeatedly. Zabbix offers a far more
practical solution in the way of templates. You can think of
templates as a set of predefined entities, such as items,
triggers, actions, etc. You can apply such templates to each
new host you create to save time.
Your choice
of Item type,
whether Zabbix
agent, SNMP, etc,
will decide what
items you can
track.
Hacks
122
Hacks
Hacks
T
123
Hacks
SPEED UP LINUX
Roll your sleeves and follow Linux Format into the
garage to give your Linux box a high-octane tune up.
124
Hacks
/etc/xdg/
autostart
to reveal
apps hidden
by default
in Startup
Applications.
125
Speed up Linux
Remove language
126
Use apt-fast
Hacks
Instead of turning off KDEs file indexing completely, you can fine
tune it by using several parameters.
127
Hacks
Advanced hacks
Tighten up swap space and indexing and streamline your kernel.
128
Hacks
accept any value between 0 and 100. Set a lower value if you
want to avoid swapping out processes. If you set a value of 0
the kernel will avoid swapping process out of physical
memory and onto the swap partition for as long as possible.
Using the command sudo sysctl vm.swappiness=10
you can temporarily change the swappiness value to 10.
This change will be lost when you restart the computer. If you
notice a spring in the step of your distro, you can preserve the
value by editing the /etc/sysctl.conf file in a text editor.
Look for the vm.swappiness parameter in the file and change
its value. If it doesnt exist, you can add it at the end of the file,
like so: vm.swappiness=10.
If you use
the distro for
conducting
heavy-duty
read/write
operations,
then use the
e4defrag
tool to make
sure the
filesystem isnt
fragmented.
129
Hacks
130
Hacks
Build a custom
Dont just stick with your distro defaults you can compile your
own Linux kernel for extra performance and features.
Setting up
The first thing youll need to do is get hold of the kernel
source code. Different distros use different versions of the
kernel, and most of them add extra patches, but in this case
well be taking the pure and clean approach using the
source code that Linus Torvalds himself has signed off.
The home of kernel development on the internet is at
www.kernel.org, and there you can download the latest
official release. In this tutorial well be using version 3.17.1 as
provided in the file linux-3.17.1.tar.xz; there will probably be a
newer version by the time you read this, so as you follow the
steps, change the version numbers where appropriate.
Now, instead of extracting the source code in your home
directory (or a temporary location), its much better to extract
it in /usr/src instead. This isnt critically important now, but it
will come into play later certain programs need to find
header (.h) files for the currently running kernel, and they will
often look for source code in /usr/src. VirtualBox is one
132
Hacks
Linux kernel
Now lets move on to the best part of building a kernel:
customising it for your particular system. Inside the main
/usr/src/linux-3.17.1 directory, enter:
make xconfig
If you have the Qt 4 development files installed (for
example, libqt4-dev in Debian/Ubuntu), this command will
build and run a graphical configuration tool. For a GTK-based
alternative try:
make gconfig
and if you cant get either of the graphical versions to work,
theres a perfectly decent text-based fallback available with
this command (Ncurses required):
make menuconfig
Even though the interfaces are different, all of these
configuration tools show the same options. And there are a
lot of options thousands of them, in fact. If youre reading
this tutorial on a dark winter evening and youve got some
spare time, make yourself a cuppa and go through some of
the categories.
Admittedly, much of the information is ultra technical
and only actually applies to very specific hardware or system
setups, but just by browsing around, you can see how
incredibly feature-rich and versatile the Linux kernel is. And
you can see why its used on everything from mobile phones
to supercomputers.
133
Hacks
least your kernel will be built with specific optimisations for
recent Intel chips.
Moving on to the kernels experimental features, as you
navigate around inside the categories, you will see some
options marked with Experimental or Dangerous next to
them. Suffice to say, these are not features you can depend
on, because they have bugs and they need time to mature.
But if youre desperate to try a bleeding-edge feature that
youve read about somewhere, heres where to look.
Patch me up
A great way to spruce up your kernel with extra features is to
use one of the many patchsets available on the net. (See
Patchsets to look out for, opposite, to learn more about this.)
Well be using an old kernel (3.10.9) for ease and apply a realtime patch provided in the patch-3.10.9-rt5.patch.gz file.
Weve downloaded this into our /usr/src/linux-3.10.9
directory, and as the name suggests, its a single .patch file
thats compressed with gzip.
If you have a look inside the file (for example, zless patch3.10.9-rt5.patch.gz), youll see a bunch of lines starting with
plus (+) and minus (-) characters. In a nutshell, plus-lines are
those which are added to the kernel source code by the
patch; minus-lines are taken away. Between each section
marked by the word diff, youll see +++ and --- lines these
show which files are to be modified.
You can patch your source code straight away, but its a
very good idea to do a dry run first, to make sure that nothing
gets messed up. Fortunately, the patch command has an
option to do exactly this:
zcat patch-3.10.9-rt5.patch.gz | patch -p1 --dry-run
Here were extracting the compressed patch to stdout
(the terminal), and then piping its contents into the patch
utility. Using -p1 here specifies that we want to patch inside
the current directory, and --dry-run prevents any file changes
from taking place it just shows what would happen. You
134
Hacks
but if you secure shell (SSH) into an X Window Systemless server, use the Ncurses-based menuconfig instead.
Note that many patchsets take a while to sync with the latest
kernel tree, so you might not be able to find a patch to match
the exact kernel version that youre building.
135
Hacks
Python: Code
a Gimp plugin
Use Python to add some extra features to the favourite open source imagemanipulation app, without even a word about Gimp masks.
Get started
On Linux, most packages will ensure that all the required
Python gubbins get installed alongside Gimp; your Windows
and Mac friends will have these included as standard since
version 2.8. You can check everything is ready by starting up
Gimp and checking for the Python-Fu entry in the Filters
menu. If its not there, youll need to check your installation. If
it is there, then go ahead and click on it. If all goes to plan this
should open up an expectant-looking console window, with a
prompt (>>>) hungry for your input. Everything that Gimp
can do is registered in something called the Procedure
You can customise lines and splodges to your hearts content, though frankly
doing this is unlikely to produce anything particularly useful.
136
Hacks
pdb.gimp_context_set_brush_size(128)
pdb.gimp_paintbrush_default(layer,2,[160,100])
If you have the brush called Cell 01 available, then the
above code will draw a green splodge in the middle of your
canvas. If you dont, then youll get an error message. You can
get a list of all the brushes available to you by calling pdb.
gimp_brushes_get_list(). The paintbrush tool is more
suited to these fancy brushes than the hard-edged pencil,
and if you look in the procedure browser at the function
gimp_paintbrush, you will see that you can configure
gradients and fades too. For simplicity, we have just used the
defaults/current settings here. On the disc you will find a file
linesplodge.py which will register this a fully-fledged Gimp
plugin, replete with a few tweaks.
For the rest of the tutorial we will describe a slightly more
advanced plugin for creating bokeh effects in your own
pictures. Bokeh derives from a Japanese word meaning blur
or haze, and in photography refers to the out-of-focus effects
caused by light sources outside of the depth of field. It often
results in uniformly coloured, blurred, disc-shaped artefacts
in the highlights of the image, reminiscent of lens flare.
The effect you get in each case is a characteristic of the lens
Applying our
bokeh plugin
has created
a pleasing
bokeh effect in
the highlights.
137
Hacks
Quick
tip
For many, many
more home-brewed
plugins, check out
the Gimp Plugin
Registry at http://
registry.gimp.org
plugin will not burden them with further layers. This means
that one can apply the function many times with different
parameters and still have all the flare-effect discs on the same
layer. It is recommended to turn the blur parameter to zero
after the first iteration, since otherwise the user would just be
blurring the already blurred layer.
After initialising a few de rigueur variables, we set about
making our two new layers. For our blur layer, we copy our
original image and add a transparency channel. The bokeh
layer is created much as in the previous example.
blur_layer = pdb.gimp_layer_copy(timg.layers[0],1)
pdb.gimp_image_insert_layer(timg, blur_layer, None, 0)
bokeh_layer = pdb.gimp_layer_new(timg, width, height,
RGBA_IMAGE, "bokeh", 100, NORMAL_MODE)
pdb.gimp_image_insert_layer(timg, bokeh_layer, None, 0)
Our scripts next task of note is to extract a list of points
from the users chosen path. This is slightly non-trivial since a
general path could be quite a complicated object, with curves
and changes of direction and allsorts. Details are in the box
below, but dont worry all you need to understand is that
the main for loop will proceed along the path in the order
Bring a bucket
To draw our appropriately-coloured disc on the bokeh layer,
we start somewhat counter-intuitively by drawing a black
disc. Rather than use the paintbrush tool, which would rely on
all possible users having consistent brush sets, we will make
our circle by bucket filling a circular selection. The selection is
achieved like so:
pdb.gimp_image_select_ellipse(timg, CHANNEL_OP_
REPLACE, x - radius, y - radius, diameter, diameter)
There are a few constants that refer to various Gimp-specific
138
Hacks
modes and other arcana. They are easily identified by their
shouty case. Here the second argument stands for the
number 2, but also to the fact that the current selection
should be replaced by the specified elliptical one.
The dimensions are specified by giving the top left corner
of the box that encloses the ellipse and the said boxs width.
We feather this selection by two pixels, just to take the edge
off, and then set the foreground colour to black. Then we
bucket fill this new selection in Behind mode so as not to
interfere with any other discs on the layer:
pdb.gimp_selection_feather(timg, 2)
pdb.gimp_context_set_foreground('#000000')
pdb.gimp_edit_bucket_fill_full(bokeh_layer, 0,BEHIND_
MODE,100,0,False,True,0,0,0)
And now the reason for using black: we are going to draw
the discs in additive colour mode. This means that regions of
overlapping discs will get brighter, in a manner which vaguely
resembles what goes on in photography. The trouble is,
additive colour doesnt really do anything on transparency,
so we black it up first, and then all the black is undone by our
new additive disc.
pdb.gimp_context_set_foreground(color)
pdb.gimp_edit_bucket_fill_full(bokeh_layer, 0,ADDITION_
MODE,100,0,False,True,0,0,0)
Once weve drawn all our discs in this way, we do a
Gaussian blur if requested on our copied layer. We said
that part of the image should stay in focus; you may want to
work on this layer later so that it is less opaque at regions of
interest. We deselect everything before we do the fill, since
otherwise we would just blur our most-recently drawn disc.
if blur > 0:
pdb.plug_in_gauss_iir2(timg, blur_layer, blur, blur)
Softly, softly
Finally we apply our hue and lightness adjustments, and set
the bokeh layer to Soft-Light mode, so that lower layers are
illuminated beneath the discs. And just in case any black
survived the bucket fill, we use the Color-To-Alpha plugin to
squash it out.
pdb.gimp_hue_saturation(bokeh_layer, 0, 0, lightness,
saturation)
pdb.gimp_layer_set_mode(bokeh_layer, SOFTLIGHT_
MODE)
pdb.plug_in_colortoalpha(timg, bokeh_layer, '#000000')
And that just about summarises the guts of our script.
You will see from the code on the disc that there is a little bit
of housekeeping to take care of, namely grouping the whole
After we apply
the filter, things
get a bit blurry.
Changing the
opacity of the
layer will bring
back some detail.
params, results,
function) # myplugin
main()
The proc_name parameter specifies what
your plugin will be called in the PDB; python_fu
is actually automatically prepended so that all
Python plugins have their own branch in the
taxonomy. The menupath parameter specifies
what kind of plugin youre registering, and where
your plugin will appear in the Gimp menu: in our
case <Image>/Filters/Artistic/LineSplodge...
would suffice. imagetypes specifies what kind
of images the plugin works on, such as RGB*,
GRAY*, or simply if it doesnt operate on any
image, such as in our example. The list params
139
Hacks
Android: Linux
on your phone
Learn how to unleash the computing power of your Android smartphone by
running a fully fledged Linux distribution on it.
Quick
tip
The LinuxOnAndroid
project is entirely
open source. You
can grab the source
code for the app,
as well as the
scripts, from the
projects website.
140
Hacks
Set up a distro
Once youve selected a distro, the app will display detailed
instructions broken down into four pages. On Page 1 the app
runs through the basic requirements your device must meet
to be able to run a Linux distro. The most important step is to
make sure that youve enabled the debugging support. To do
that, head to Settings > Applications > Development and
make sure the USB Debugging setting is toggled.
On the seond page you get links to download the image
for the selected distro. Tapping on the Download Image
button pops up a window with three additional buttons to
download one of the three supported image types explained
earlier Large, Small or Core. The page also mentions details
about the offered images, such as the size of the compressed
image that youll download as well as the size the image will
take on your SD card once its been extracted.
Tapping on the image you wish to download brings up
another pop up with buttons thatll either download the
image from a Sourceforge mirror or via torrent. If you choose
the torrent option, the app will download a torrent file, which
youll then have to feed to a torrent client to download the
actual image for your selected distro.
You can download the image on a computer and then
transfer it on to the SD card on your Android device. In this
case, you can safely skip the instructions on this page.
You can uncompress the downloaded file either on the
computer or on the device itself. For the latter, youll need a
versatile file manager such as the paid-for Root Explorer app
or the free ES File Explorer app.
While compressed files are smaller and are faster to
transfer than uncompressed ones, remember that they are
tightly compressed and (depending on the specs of your
Quick
tip
You can download
the distro images
from within the
app, or you can
grab them from the
projects website
and transfer them
on to the phone.
141
Hacks
Android device) can take some time to deflate. However, if
youre moving the images on to your device manually, its best
to house them inside a folder. For example, if youre
downloading the image for the Ubuntu 13.10 distro, its best to
uncompress it inside a folder called Ubuntu on your SD card.
Then move on to Page 3, which advises you on extracting
the downloaded files. The rest of the page talks about how to
boot the extracted images. Once booted, youll be dropped to
a terminal window. Page 4 lists instructions on how to connect
to this running Linux installation via a VNC viewer. Remember
to note the password listed on this page as youll need it to
connect to the VNC server running inside your distro.
The Installer
requires BusyBox
to boot Linux
which it will go
ahead and install
on first launch.
Youre now all set to boot the new distro. Bring up the
navigation menu by tapping on the apps icon or swiping from
left to right and tapping on the Launch item. This will bring up
the apps launcher which is responsible for booting up the
distros. Use the pull-down menu on the page to select the
distro you wish to boot.
If you get an error saying that the image for the selected
distro doesnt exist, it means that the app cant locate the
extracted image files for the distro. This can happen if you
havent extracted the downloaded file, or if youve kept it in a
non-standard location. In such a case, youll have to point to
the IMG file of the distro manually. Tap on Settings in the topright corner inside the Launch screen which brings up a pulldown menu. Tap on Add to open the page to add an entry for
your distro. Enter the
name for the distro in
the space provided and
tap on the box with
three dots to navigate
the filesystem on your
Android device and
point to the IMG file for
the distro. Tap on Save
Changes when youre
done.
This custom entry
from your distro will
now be listed in the
pull-down menu on the
Launch page. When you
now select the entry,
the app will show you a
button to start the distro. Tap on the button to boot the distro.
This will launch the terminal app and grant it super user
permission. Press the Enter key in the virtual keyboard to
boot the distro.
Since this is the first time you've started up the distro,
youll be asked to specify a password for the default user
(which in the case of the Ubuntu distro is named ubuntu).
Note that this is the password for the default user account
and not the password required to log into the VNC session.
Youll then be asked if you want the distro to start the VNC
server (for viewing the graphical desktop) and the SSH server
(for accessing the distro remotely over a secure connection).
We suggest you start them both to reap the full benefit of
running a Linux distro on your Android device.
Next, you'll be asked to enter the screen resolution of the
VNC session. Although you can set this to any size, for best
experience you should set it to the same resolution as your
device. Remember, however, that when you bring up the
virtual keyboard it will hide a part of your desktop. If you are
running this on a device with a big screen you can follow the
guide on the projects wiki to adjust the screen size to
accommodate the soft keys.
Thats all the configuration it requires. The app will then
prompt you to save the settings as default. Its safe to do so
to avoid answering the same questions every time you launch
the distro. Well show you how to alter these settings a little
later on the tutorial. For now you should just save the settings
as default and let the app boot your distro.
When its done booting your distro, youll see a note with
the relevant settings you need to connect via VNC to this
Linux distro, followed by the standard Linux root prompt.
If you're proficient with the Linux command line interface, you
can now use this shell to interact with the distro like any
desktop distro.
For security purposes, one of the first things you should
do is set a new password for the root user. Enter
passwd
in the shell and enter a new password for the root user. If
youve asked LinuxOnAndroid to start the SSH server while
booting your distro, you can now connect to it from any
computer on the network. Enter the
ifconfig
command inside the terminal on your Android device, which
will print the IP address of the device, such as 192.168.2.101.
To connect to the device launch a terminal on another
computer and enter
142
Enable use
of the distros
CLI package
manager tools
with GNURoot.
The developers
are currently
working to get
a graphical
interface for
the desktop.
Hacks
ssh [email protected]
This will prompt you for the password for the ubuntu user
which is the one you set when you first booted the distro.
To view the graphical desktop running on top of your Linux
distro on the Android device, tap on the home button to
minimise the terminal app, then tap and launch the VNC app
(such as androidVNC).
The VNC app will prompt you for various settings so it can
connect to the distro running on the device. Enter localhost in
the field that asks you for the IP address of the VNC server
and 5900 as the port. In addition to these youll also need a
password to authenticate with the VNC server. This varies
from distro to distro. For the Ubuntu images, the password is
ubuntu. For Arch Linux it's archlinux, for the Debian flavours
it's debian and so on. The password is listed on the distros
wiki page on the LinuxOnAndroid projects website.
Note that if you are using androidVNC, the app suggests
that you change the colour format to 24-bit color (4bpp). Tap
the Connect button to initiate the VNC session once youve
entered all the information and hey presto! The VNC client will
connect to your device and display the graphical desktop
thats running inside the distro youre currently running.
Again, the app developers advise androidVNC users to
change the input mode to touchpad. To do so, tap on the
menu button from inside the VNC session. This will bring up a
bunch of options; you need to tap on Input Mode and then
select the Touchpad radio button from the list of supported
input modes.
You can now interact with and operate the desktop just
like you would on a PC. On the androidVNC app, a single tap
equates to a left-click. Tap twice to simulate a right-click.
If you tap and hold, the app will display three buttons two to
zoom in and out, and one to display the virtual keyboard.
You can also use the package manager to install new apps.
Remember, however, that the distro will only be able to install
apps that have been ported for the ARM architecture, which
is true for almost every popular app.
When you've finished, close the VNC session by logging
out of the desktop. Now pull down the app drawer and tap on
the terminal session thats been running in the background.
Type exit to shut down the Linux distro. When the distro shuts
down youll have to type the exit command a couple more
times to exit and close the terminal session.
Advanced tweaks
You can use the steps described above to download, set up,
boot and use any of the supported distros on your device.
However, the app also offers some other options to further
customise the distros and tweak your user experience.
For starters, you may wish to change the settings of the
distro you specified when you first booted into it. To do so,
select the distro you wish to customise from the drop-down
list in the Launch section. In addition to the Start Linux
button, you'll also see a Configure Linux button. Tap on it to
bring up the settings page. Here you'll find checkboxes for
enabling and disabling the start of the SSH and VNC servers.
You can also modify the resolution of the VNC screen by
altering the values listed on this page.
The page offers a couple of interesting options, including
the Create 1GB SWAP File checkbox. As you can imagine,
when this is toggled, the app will create a swap file for the
distro to use. Make sure you have adequate free space on
your SD card before you enable this option.
The app can also mount folders from the Android
filesystem into the running Linux. Tap on the Configure
Quick
tip
To remove a distro,
make sure it isnt
in use and then
remove the folder
that houses the
relevant IMG file.
143
Hacks
Terminal:
Time-savers
The terminal has a host of handy tricks that will save you time and make your
life easier. We introduce you to a few of the most useful techniques.
Aliases save you typing and enable you to use more memorable command
abbreviations. You choose these yourself, so you have no excuse for forgetting!
144
Profiles
You can customise your terminal experience with aliases and
custom prompts, but to make them even more convenient
you need a way of applying these automatically when you
open a terminal. That can be done through your profile, which
is a file containing commands that are read and run whenever
you open a shell session.
There are several locations that are read, the first of which
is /etc/profile, which contains global profile settings. This
in turn runs any files in /etc/profile.d, which makes it easy
to add global settings without touching the default profile.
Then the users profile is read from one of ~/.bash_profile,
~/.bash_login and ~/.profile. Only the first of these files that
exists is run and any settings in here override those in the
global profile if the same thing is set in both.
The profile is simply a set of shell commands, one per line,
that are run when the shell starts up. These can set up aliases,
environment variables or set the command prompt. A typical
use of environment variables would be to change the default
text editor to nano:
EDITOR=/usr/bin/nano
Word completion
If, like me, you arent a particularly confident touch typist,
youll soon get fed up with typing out command and file
names in full, then dealing with the error messages resulting
from misspellings. Fortunately for us, the shell provides a way
to both save typing and avoid mistakes called tab completion.
The name is fairly self-explanatory it uses the Tab key to
complete the word you are typing. If this is the first word on
a line, it will be a command so it looks in the command path
for matches, for example typing chm and hitting Tab will
complete to chmod. Used after the command, the Tab
completes on file names, so instead of typing:
cat /pathto/somelongdirectory/someevenlongerfilename.txt
you can use:
cat /pa[press TAB]som[press TAB]som[press TAB]
Isnt that easier? When more than one file matches, the
Tab key will complete up to the point where it becomes
ambiguous, pressing Tab again at this point shows a list of
options, which you can cycle through with Tab, or add another
Hacks
As the name suggests, tab completion lets you use the Tab key to
complete the word youre typing, helping save time and avoid mistakes.
chosen one again. You can also edit the command before
running it, if you like. Thats fine if you want to use one of the
last few commands you ran, but most shells keep a history of
the last 500 or so commands that you an access again.
145
THE BEST
Z97 MOBO?
ASUS MAXIMUS
VII FORMULA RATED!
AMAZING DUAL
GPU LAPTOP
4K SCREENS
ON A BUDGET
17-INCH AORUS X7
V2 ON TEST
MAKE MOVIES
SECURE WI-FI
IIYAMA B2888
UHSU REVIEWED
iPhone 6
hands-on
START UP FAST
SHAVE VITAL SECONDS
OFF YOUR BOOT TIME
Bigger, slimmer,
faster better?
Pi vs WORLD
s for
Includes guide
:LQGRZVDVZHOO
8-CORE SENSATION!
FASTEST
EVER CPU
New Intel Haswell-E chip
redefines performance
DVD MISSING?
Speak to your newsagent!
Raspberry Pi
Virtual containers
Cloud storage
Mathematica Pi
Docker v1.0
OwnCloud 7
TOP WEB
BROWSERS
The must-have
alternatives to Firefox
and Chrome p24
TuxRadar.com
BUILD IT!
A FULL HD
GAMING PC
FOR 468
FREE
WINDOWS
THE BEST
for 21 years
PROGRAMS
50
2015 GAMES
4K BUDGET SCREENS
hidden
features
of iOS 8!
PREVIEW
WITCHER 3
TUTORIALS
ARKHAM KNIGHTS
Master Lightroom
Custom Mac gestures
Genealogy in Numbers
PACKED WITH
55 ESSENTIAL APPS
DO ALL THIS AND MORE
Free up drive space
Send better tweets
Beat net viruses
7XUQWRSQRZ
86 PAGES OF
EXPERT ADVICE!
FREE DISC!
Video editors
group test
The perfect
laptop bag
Windows tutorials
New things to do
Buying advice
SAVE UP TO 40%
SAVE UP TO 70%
SAVE UP TO 45%
SAVE UP TO 50%
FROM 25.49
FROM 25.49
FROM 15.99
FROM 23.49
FROM 23.49
9001
SAVE UP TO 45%
SAVE UP TO 57%
SAVE UP TO 55%
SAVE UP TO 40%
SAVE UP TO 35%
SAVE UP TO 50%
SAVE UP TO 50%
SAVE UP TO 40%
FROM 15.99
FROM 12.99
FROM 17.99
FROM 22.49
FROM 20.99
FROM 21.49
FROM 25.49
9000
Savings compared to buying 2 years worth of full priced issues from UK newsstand. This offer is for new print subscribers only. You will receive 13 issues in a year. Full details of the Direct Debit guarDQWHHDUHDYDLODEOHXSRQUHTXHVW,I\RXDUHGLVVDWLVHGLQDQ\ZD\\RXFDQZULWHWRXVRUFDOOXVWRFDQFHO\RXUVXEVFULSWLRQDWDQ\WLPHDQGZHZLOOUHIXQG\RXIRUDOOXQPDLOHGLVVXHV3ULFHVFRUUHFWDW
point of print and subject to change. For full terms and conditions please visit: myfavm.ag/magterms Offer ends: 31st January 2015