Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

TheHackersManual2015RevisedEdition

.pdf
Скачиваний:
51
Добавлен:
26.03.2016
Размер:
43.82 Mб
Скачать

Hardware hacks

program, and pressing p (key index 112) will take a screenshot.

k = mykeys.read() if k >-1:

if k==112: pi3d.screenshot(“earth1.jpg”)

elif k==27: mykeys.close() DISPLAY.stop() break

Blurred lines/spheres

So that covers the supplied Earth demo, feel free to mess with it in whatever manner you see fit. Alternatively, stick with us and follow our meddling. We shall start with some depth-

of-field blurring of the moon, so that it goes

Fear not weak-eyed reader, the moon really is out of focus, it’s not just you.

out of focus both when it gets close to us,

 

 

and when it is far away.

radius of 4 units, we’ll set the second

 

To work this magic we start by invoking the

parameter to 3. Setting the maximum blur too

 

Defocus module. Place the following line

high will cause banding, but experimentally 5

 

somewhere before the main loop, after the

seems to be a reasonable setting here. Enact

 

lines specifying the shaders is as good a place

all this with the following line:

 

as any:

defocus.blur(mymoon, 0, 3, 5)

 

defocus = pi3d.Defocus()

Man with a movie camera

 

Defocusing works by enclosing the

 

standard object draw() calls inside a block

But the fun doesn’t stop there, by adding a

 

delimited by start_blur() and end_blur().

Camera object to the proceedings we can

 

The objects ‘drawn’ inside this block are

immerse ourselves completely in our three

 

rendered into a buffer and won’t appear on

body system. Using only a tiny bit of

 

the screen. To make them visible use the

trigonometry, and our already implemented

 

blur() method, which will render them with

Keys object, we can move our celestial

All your Sherman tank driving dreams are

the appropriate distance blur. So wrap the line

observer and change our viewpoint. We’ll

just a few lines of code away.

 

beginning mymoon.draw as follows:

need to add the radians function to the

 

defocus.start_blur()

trigonometry functions which we have already

rottilt = False

mymoon.draw(shinesh, [moonimg,

imported from the math module. Now set up

Now we need to set up the keys to control

moonbmp], 6.0, 0.0)

a Camera object, and initialise some

the Earth-cam, we’ll use standard W,A,S,D for

defocus.end_blur()

properties for it after the DISPLAY

the rotations and +/- to zoom in and out.

The blur method, which does the actual

declarations:

So change the beginning of the key-handling

drawing, takes three additional arguments

CAMERA = pi3d.Camera()

block to the following:

(besides the name of the Shape object to

rot = 0

if k > -1:

draw): the focal distance, the distance beyond

tilt = 0

rottilt = True

(or nearer than) which everything will be

rottilt = True

if k == 112:

maximally blurred and the degree of

camRad =5

pi3d.screenshot(“earth1.jpg”)

maximum blurring. We’ll set the zero-plane to

We’ll use the rottilt boolean to trigger any

elif k == 119:

be z=0, and since our moon’s orbit has a

changes to the camera position or orientation.

tilt += 2.0

 

Rotating or tilting the camera is

elif k == 115:

 

straightforward, but changing its radius

tilt -= 2.0

 

(determined by camRad) requires the

elif k == 97:

 

standard spherical trigonometry ugliness

rot -=2

 

which we’ve covered in our Minecraft: Pi

elif k == 100:

 

Edition ballistic exercises [see Linux Format

rot +=2

 

185: Tutorials, p84]. So the beginning of the

elif k == 61:

 

main loop becomes:

camRad -= 0.5

 

while DISPLAY.loop_running():

elif k == 45:

 

if rottilt:

camRad += 0.5

 

CAMERA.reset()

So now you’ve got action and camera, why

 

CAMERA.rotate(tilt, -rot, 0)

not look into adding some lights as well, some

 

CAMERA.position(camRad *

kind of Distant Sun perhaps. You’ll find the

 

sin(radians(rot) * cos(radians(tilt)), camRad *

documentation at http://bit.ly/Pi3DDocs,

You can easily import 3D models in the

sin(radians(tilt)), -camRad * cos(radians(rot)) *

but the supplied demos do a great job of

Panda3D .egg archive file format.

cos(radians(tilt)))

introducing all of the available constructs. Θ

Pi3D | hacks Hardware

The Hacker’s Manual 2015 | 111

Hardware hacks | DD-WRT

Hardware hacks

DD-WRT: Hack a wireless router

Discover how to power up the device at the heart of your home network.

Quick tip

There are other firmwares that might reasonably vie for your attention. In particular, various forks of the Tomato project, Merlin’s take on AsusWRT (a halfway house between custom and stock firmware strictly for Asus routers) and even OpenWRT, which is the expansive base on which many others are built.

It’s a great time for home networking, which is to say that a decent router can now just about be relied on to do its own thing without bothering you. However, it can still be a

challenge to get it to do your thing instead. If you’re ready for a change, the world of custom firmware opens up an embarrassment of configuration choices, as well as an enticing catalogue of new functionality.

With DD-WRT as our firmware of choice, we’re going to firmly encourage these sleek and unassuming embedded devices to reach their full huffing, wheezing potential. There will be sweat, there may be tears, but we’ll guide you through the process of selecting and installing a firmware, show you some of the nattiest ways to trick it out, and open the door for your own challenges to follow.

DD-what?

DD-WRT is one among many custom firmwares available for wireless routers, but it beats right at the heart of the custom firmware movement, with a broad range of support, relative ease of use, consistent development, and a treasure trove of features. Installing DD-WRT isn’t a minor tweak, though – it

will completely rewrite the way your router operates, potentially opening up functionality such as SSH, file and media serving, guest networks, QoS, VLANs, and VPNs in more flavours than you could find in a bag of Revels.

However, there are risks commensurate with the scope of the change. While installing a custom firmware is almost always a beautiful learning experience, sometimes what you learn is how it feels to break a perfectly good router. It probably won’t even seem as though it’s your fault when it happens, but implicit in your willingness to continue is the understanding that it will be your fault, because you were the one who poked it. And now that this is explicit as well, we can continue with two key pieces of advice for minimising the risk. Firstly, don’t ever use a router you can’t afford to lose. Simple. Secondly, don’t use your only router – because you rely on it to connect to the internet, which is a resource that you’ll want to be able to tap like a rubber tree should things go south.

In this spirit, the most advisable way to enter the custom firmware fray is with an older router. Look at it this way – you’re going to end this process without a manufacturer’s warranty, so you may as well start it without one. You’re also less likely to feel a sense of gnawing, visceral guilt if you sneeze and pull out the power adaptor during a firmware update, and proportionally more likely to unlock new features. By contrast, it can take a reasonably long time for custom firmware such as DD-WRT to adapt to new technology (and longer still to make it run reliably), so you may be on a hiding to nothing with this year’s super router, even if you’re cavalier enough to try it.

Router support

We’ll deliver the bad news up front. With no notable exceptions, combination router/modems won’t work – BT’s famous range of Home Hubs, for example, aren’t supported. But all is not lost if you’re on VDSL/BT Fibre, because you should be able to arrange to use a standalone OpenReach modem instead, and connect up a router of your choice. Other ISPs’ combination devices may even have a modem-only mode that enables you to plug in your own router – Virgin Media’s Superhub offerings, for example, fall into this category.

If you do have a standalone router, you still can’t necessarily just go ahead and plonk a new firmware on it. Some routers don’t have the right chipset, some don’t have enough flash storage, and some don’t have the RAM. Some, frankly, don’t have the moxie. All that said, a surprisingly wide range of routers are supported. So how do you know whether yours is one of them?

Your first port of call should be DD-WRT’s router database (www.dd-wrt.com/site/support/router-database). Simply put your model number into the search field, and then cross

112 | The Hacker’s Manual 2015

Hardware hacks

your fingers. The database will usually give you a straight yes or no answer, but don’t jump for joy when you see your model appear in this list until you have checked that the revision column also matches up with your router – some manufacturers change out the internals almost completely between revisions of the same router model.

Just for fun, try searching for the WRT54G in the router database, and count the iterations. The WRT54G is the granddaddy of DD-WRT, and it has a lot of history. But note that at least one revision isn’t supported at all, and that the specs can be wildly different between others. Many have reduced flash storage space, for instance, and will be limited in which features they can support.

Firm friends

Once you’ve established that your router is supported, there are two major lights in the darkness: DD-WRT’s wiki, and the community forums.

The wiki is great for getting a baseline understanding of any issues which might affect your particular router. Start with the Supported Devices page (www.dd-wrt.com/wiki/ index.php/Supported_Devices). Links from this page often indicate that your router has a specific installation guide, which might just mean that it’s a popular model, but it could mean that the flashing process comes with some caveat or special requirement, so be aware.

The forums are the best place to find out what’s working, right now, for other people using the same hardware (www. dd-wrt.com/phpBB2/). You should pay particular attention to threads where users trade blows over their favourite or most stable builds. Look out for the guru posters, who often have long signatures containing details of the many different routers they run, and which firmware versions they’re running on them. These guys have done their homework, so make sure you do yours, too, even if that sometimes means leaning across the metaphorical desk to copy their notes.

DD-WRT is an ongoing beta, and the newest release is not always going to be the best release for your own particular hardware. There is no shame or loss in using a build which might be significantly behind the bleeding edge. If it’s the right fit for your kit, just go for it. With older releases, the main thing you need to concern yourself with is to make sure that you’re not exposing yourself and your hardware to any critical security flaws. As a starting point, build revisions between 19163 and 23882 are a poor vintage; any components making use of OpenSSL will be affected by the Heartbleed bug. The good news is that none of the vanilla builds are

The make or model is usually on a sticker, either on the back or the bottom of your router. Note any version information in addition to the model number.

affected by the Bash-specific Shellshock vulnerability; like many embedded device firmwares, DD-WRT relies on BusyBox to provide A Shell. Likewise, the use of uclibc means that the glibc GHOST vulnerability is no concern for today. However, running a custom firmware does put the security ball back in your court, so you really do need to keep abreast of emerging vulnerabilities.

Firm resolution

Let’s go through a worked example. We have a Cisco Linksys E3000 router, which treads a decent balance between age and relevance. It’s around five years old and there’s none of that new-fangled wireless AC technology, but it was a powerhouse in its day, with support for simultaneous 2.4GHz and 5GHz wireless bands. The router database shows a firm yes, and there is some specific information on the wiki relating to it. Particular points of note are the implications of it having 60K of NVRAM, and the requirement to flash a trailed build (see boxout over the page). We’ll need to take both of these things into account.

We’re lucky, as it happens; on the forums, a build from February 2015 (build 26138) is being touted as stable with the Linksys E series. There’s some debate about a bug in the Guest Wi-Fi implementation, but it sounds as though it’s going to be worth our time.

The main area for new DD-WRT releases is at ftp://ftp. dd-wrt.com/betas/ and we know from the wiki that E3000compatible builds are to be found in the broadcom_K26 subfolder. We can pick a mini trailed release for the E3000 from here with no problem, so we’ll get that now, but if we want to move to a larger general build afterwards, then we’ll need to remember our 60K NVRAM limit, and pick one of the 60K builds from the same folder. The mega 60K build is (just!) too large for our 8Mb flash storage – good job we checked that out, because it came down to counting the bytes – so we’ll go with the so-called big build instead.

Quick tip

DD-WRT gives you control but it doesn’t necessarily give

you performance. If blazing fast speed is the only thing that interests you, a manufacturer’s own firmware is often faster than the custom alternatives.

Flash! Aa-aa!

 

Now it’s time for us to check and double-check all our

 

sources of information, because we’re ready to do the

 

firmware update. The steps that follow are usually applicable,

 

but you should read up on your model to see where any

 

differences might occur.

 

First, you need to connect your computer to the router

Now is the time for a moment of quiet reflection…

using a wired connection, and then configure it to have a

WRT-DD | hacks Hardware

The Hacker’s Manual 2015 | 113

Hardware hacks | DD-WRT

Hardware hacks

Success looks like this. Or like Scrooge

McDuck’s money bin. But mainly like this.

Quick tip

NVRAM is the persistent memory in which variables are stored between resets, and it’s measured in kilobytes.The more features you use, the more variables you store (VPN certificates are particularly greedy). It’s both a limiting factor and a risk; if you reach the end of your NVRAM allocation and keep writing, you can reset or even brick the device.

static IP address on the same subnet as the router. Things are not guaranteed to go wrong if you don’t do this, but do you really want to leave the router in charge of business while you’re in the process of brainwashing it? The answer is a definite no. No, you don’t.

Do a 30-30-30 reset (see boxout opposite),and then log in to your router’s web configuration page (with the now factory default username and password).Find wherever your manufacturer has hidden the firmware update section,and browse your computer to find the DD-WRTfirmware file you prepared earlier,which is probably a trailed build specific to your router.

Go ahead and do the update using the built-in firmware updater. There may or may not be a progress bar, but ignore it either way. You’re going to wait at least five minutes. Use a clock and not your patience to gauge this. Then turn the router off and on again, giving it time to reboot and get its bearings – then, and only then, do another 30-30-30.

Open up a web browser and go to 192.168.1.1, which is the default IP address for a DD-WRT router, and check that you are indeed looking at a DD-WRT interface. That’s the first good sign, and the second is whether it’s asking you to change the password, which shows that the 30-30-30 reset after the update has also worked properly.

If all is well, decide whether you’re sticking with the build you’ve just installed or, if you were using a trailed build as an intermediary step, repeat the process again in full, until you have reached your final destination.

couldn’t do before?

How about logging directly into your router via SSH? Yeah, we can do that. We can even do it without a password, using the public key method. To generate an appropriate public/ private key pair, enter the following into a terminal on your local machine.

ssh-keygen -t rsa -f ~/.ssh/id_rsa_ddwrt

You’re prompted to set a passphrase, but hitting [Enter] twice enables you to continue without – choose your balance of security and convenience. Two new files are created under your home directory, in the ~/.ssh/ hidden folder: id_rsa_ ddwrt and id_rsa_ddwrt.pub, which contain your newly generated private and public keys, respectively. Make sure you keep prying eyes away from the private key, but we’ll use the public key to set up easy password-free access to your router.

Go to the Services tab in your new DD-WRT Web GUI, and then click the enable checkbox for SSHd. This expands some new options. It’s up to you whether or not you leave password authentication active, but what you do want to do is copy the contents of your id_rsa_ddwrt.pub file into the Authorized Keys box. Make sure the entire sequence occurs on a single line. Save and apply these changes. At this point, one simple terminal command on your local machine should let you in through the door:

ssh root@192.168.1.1

Substitute in the correct local IP of your router, if you’ve changed it. If you see the DD-WRT message in the terminal, well done, you’re in. But you didn’t think we were going to stop there, did you? Getting local access is only half the battle. How about an interesting and powerful way to manage your router from the outside world? Remote access to your

Stretching your legs

Now that you’re up and running, feel free to do some basic configuration. Get the router set up the way you like it;

that’s what we came here for. DD-WRT’s interface is neat and functional, and you should be able to find the options you’re comfortable with, albeit buddying along with a raft of new features. Get your wireless security set up, and then give it a test drive. Now are you ready to try something that you

Note that the only user for SSH is root, regardless of what username you set for the Web GUI. The password is the same, if you’re using one.

Trailed builds and tftp

A trailed build could quite accurately be described as a custom custom firmware. It’s a firmware that’s been built specifically for one particular model of router (which is mentioned in the filename). Trailed builds contain headers that check out as legitimate with the manufacturer’s own firmware, which then conveniently and quite cleverly enables you to use the existing interface to overwrite itself. A trailed build might not be your end point, however, but more like a transitional step

between using stock and custom firmware. Once you have installed a trailed build of DD-WRT, you’re generally able to move more freely between different firmware builds – you still need to pick the correct ones, though.

Now let’s take a look at tftp, which is quite literally a trivial file transfer protocol. This is necessary for the initial flash of a few routers – older Linksys, Buffalo and Belkin models being the prime examples. It’s comparatively rare to require this on Wireless N or newer routers. If

you don’t need to use tftp, then it’s not recommended, regardless of whether or not it’s available.

However, it’s worth remembering that lots of different routers have a tftp connection available for a limited window during the boot process, because it could be one of the first ports of call if you need to try to recover from a bad flash. Although it’s never to be relied upon, it may help bring you back from the brink in a pinch.

114 | The Hacker’s Manual 2015

Hardware hacks

The 30-30-30 reset

Do not underestimate how skew-whiff things can become when the vestigial variables of firmware A come out to play with custom firmware B. The 30-30-30 is a catch-all hard reset for clearing NVRAM and returning most routers to their firmware defaults, which you’ll do before and after flashing each new firmware version.

Your router’s reset button is probably on the back of the unit, sometimes inset. Grab a paperclip if you need one, and get into a comfortable position; you are going to be holding your router’s reset button down for 90 seconds or more, which is a long, long time for someone with cramp.

Start holding down your router’s reset button, and count a full 30 seconds. Not letting go of the reset button, pull the AC plug out of the back of the router. Count 30 more seconds. Keep holding that reset button, and plug the router back in. Count 30 more seconds. Finally, let go of the reset button and throw up some jazz hands to brighten the mood and get your circulation flowing again. Your router should be back to default values for whichever firmware you currently have installed. (You can put your hands down now.)

A handful of older routers, but an ever-increasing number of new AC routers, need to be hard reset in other ways. If the 30-30-30 doesn’t return yours to default values, check what does work for your router, and use that method instead.

router is always going to be a touchy subject but, let’s be honest, sometimes it’s useful enough to be worth the risks.

DD-WRT will happily support remote access to the GUI via HTTP or HTTPS. There’s no way in this life or the next that you’d want to give the world a shot at the core of your home network without a single security layer, but you might be thinking about allowing HTTPS connections.

Wait, though. Here’s a neat trick instead: why not disallow remote Web GUI access altogether, and just connect via SSH? You can then log in and administer the router remotely by command line or set up an SSH tunnel to give you, effectively, local access to the Web GUI. This will work from any location – and you only have to open one door to enable both types of access. Let’s look at how this can be done.

Firstly, setting up the remote access to SSH is done in a different part of the DD-WRT GUI to enabling the service. This time you want to go to the Management tab under Administration. There’s a remote access section here. Don’t bother enabling the remote Web GUI Management. Instead, enable SSH Management. You’re given the option to select

a port for this. You don’t need to – and, in fact, shouldn’t – use the typical SSH port 22; we’ll use port 19198 in this example. We made this up so feel free to make up your own, but don’t worry – the connection made on this port will forward through to the SSH service on your router without any extra work on your part.

Now you can SSH to your router from the outside world, in the same way that you do from your local network – the only differences are that you need to specify the port, and use the outward facing IP rather than the local one.

ssh -p 19198 root@WANIP

You should replace WANIP with the global address of your local network. This can be a DNS name, or an IP address. In the highly likely event that your ISP doesn’t provide you with a static IP address, you won’t necessarily need to keep track of every change of IP address. DD-WRT supports automatically updating a number of different dynamic DNS services – look

Yes, we have a tool for this!

at DDNS under the Setup tab for options.

So we’ve come this far, but what about that Web GUI? Well, try starting your SSH session with this command: ssh -p 19198 root@WANIP -L 8080:localhost:80

This starts an SSH session as before, but the last part of the command creates a tunnel from port 8080 on your local machine, to port 80 on the router. Now try opening a browser window to the following URL: http://localhost:8080/

Wow. Presto. There it is. You’ve got your Web GUI from a remote location, and it’s all encrypted through your SSH session. Now the world, quite literally, is at your disposal.

The gauntlet

Now you’ve got access via the Web GUI and SSH, what new things are worth trying? Actually, what new things are not worth trying? If that sounds like a challenge, read it as one. How about building on the SSH tunnelling method we looked at, to have your home router run a SOCKS5 proxy,

via which you can encrypt your traffic when you’re away from home?

If you’ve got a VPN account, how about connecting with your router as the client? (This can be great for hooking up other, less hackable embedded devices which might not support VPN natively.) Maybe you have a USB mobile broadband dongle? DD-WRT can play with those – why not try creating an alternative internet feed through your router, for those days when your main ISP puts its toes in the air?

If you really want to start playing with fire, you might even find a way to host your own cloud-style file service from a USB hard drive hanging off the back of your router. It’s not like you were planning on turning your router off, were you?

So there we have it. Some absolutely astounding possibilities that would previously have taken all kinds of wizardry to arrange, running on something you probably already had sitting in a cupboard. Remember that routing network traffic is this device’s bread and butter, so don’t be afraid to make it earn a living! Θ

WRT-DD | hacks Hardware

The Hacker’s Manual 2015 | 115

Network hacks

Take control of your LAN and servers with tools and code

118Master the basics

What do your know about IP networks? Nothing! Good, get started here.

122Go next-gen IPv6

The world has run out of IPv4 addresses, let’s play with its replacement.

126Build a log server

Run a lot of servers? Securely combine their logs into a single remote system.

130Monitor packets with Wireshark

Want to know what’s going on over your network? You need to run this, now.

134Samba and Windows

Get your Linux systems to play nicely with Windows ones, it’s not that painful.

141Docker and virtual servers

Now classed as the ‘next big thing’, if you run servers you need to run Docker.

150Ldap authentication

Dealing with a lot of users? Get Ldap working sweetly on all your systems.

156Discovering Dtrace

It’s the ultimate network diagnostic and analysis tool from Oracle.

Contents | hacks Network

The Hacker’s Manual 2015 | 117

Network hacks | The basics

Networks hacks

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 p130) 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 we’re going to see how IPv6 is going to take over (see p122) and build some none-trivial networks.

WireShark does a similar job to tcpdump capturing packets, but provides a nice colourful GUI to help you see what’s going on.

Most of the time we don’t use our computers as though they were a solitary box, but instead connect them together, sharing files and

information throughout our homes and across the internet. To help you put your Linux skills to use in this networked environment, we’re going to spend these pages introducing

you to the fundamentals of networking. Throughout, our focus will be on both the practical as well as the theoretical explaining the terminology as we go. We’ll get you using Linux

Packet switched networks

Let’s start by talking about what a network is. Simply, a network is two or more computers connected by some physical medium, whether that’s a copper wire (known as Ethernet), a fibre optic cable or a radio wave (known as Wi-Fi). By sending signals across this medium, computers are able to share information with one another.

It sounds simple enough – you run a conductive wire between two computers, and by sending electrical signals along it, the two computers can share information. The trouble is, even this simple model (which ignores questions of how the electrical signals are encoded and decoded) runs into problems quickly.

The data we share between two computers is usually large and complex, made of many millions of bits. This data could be sent in a continuous stream across the wire, which might take many minutes, hours or even days to send. With just two computers, this isn’t a big problem; one can just wait until it receives a signal saying it has all the information, then it can take its turn to send some information back.

In the case of a more complex network, however, with many dozens or hundreds of computers attached to the shared medium, you start to run into real problems. While one computer is sending information, none of the others can use the medium to transmit information. What’s more, when there’s an interruption to the network signal, you have to retransmit the entire thing – if the file being sent is big, this becomes a real pain.

The way computer networks get around these problems is by using packet switched networks: The large pieces of data are broken into more manageable chunks, called packets. As well as containing the information to be shared, these packets contain metadata that specifies, among other things, where in the stream of data the packet belongs.

If a packet gets lost in the depths of the interweb, the receiving computer will see that it’s missing a part of the stream, and can request for just that packet to be resent – instead of the whole thing. What’s more, because packets break the data into independent chunks, all the computers that share the medium can take it in turns to transmit their packets, rather than entire files, meaning everyone can share the medium more effectively.

Packets are more than just a theoretical construct, you can actually see individual ones being transmitted across the

118 | The Hacker’s Manual 2015

Network hacks

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. It’s 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

layer depends on the one below it to provide certain services, but it doesn’t need to know how any of the other layers are implemented, just how to interact with the lower layers. This means they can be created and tested separately, and you can have many different implementations of the different functions

(for example, fibre optic or Ethernet for the physical layer), without having to rewrite any other components.

In this article, we’ve covered the first three layers of the OSI model:

The physical layer This specifies how electrical signals can be transmitted across particular physical media;

The data link layer This specifies how hosts

are physically identified on the network – that is, with MAC addresses.

The network layer Specifies how packets are routed between networks and how logical addresses are assigned.

The remaining four layers concern managing reliable connections between machines, and the presentation and utilisation of transmitted data at the application level. Networking topics that you might be familiar with that fall into these layers include: the TCP and UDP protocols in layer 4; file encoding such as UTF, ASCII, JPG and so on that are all found in layer 6; and things such as the HTTP (web); FTP (file transfer) and SMTP (mail transfer) protocols, which are all network applications in layer 7.

network. To see these packets, install the tcpdump package using whichever package manager your Linux distribution provides. Once it’s installed, launch a terminal and first find out which device is currently providing your network connection. Assuming you’ve got only one active network connection on your computer, you can find this out by typing: ip a | grep “state UP”

The ip command is used for showing information about your network connections – we’ll cover this in more detail a little later – while the grep command filters the result to see only those network connections which are ‘up’ or active. The bit of information you’re interested in is near the beginning of the line, and probably reads eth0, wlan0 or em1, depending on your configuration.

With this information, you can now run tcpdump to watch a network conversation take place. As root, run:

tcpdump -i wlan0

where wlan0 is the device you discovered above. Then, open a web browser and visit a site. When you switch back to the terminal, you’ll see the screen filling up with lines of text. Each line represents a packet that was sent between your computer and the web server in order to load the page, and each provides bits of information about it, including the time it was sent or received, which computers (or hosts) it was sent from and to, and much more.

By passing the -w switch and a filename, you can save this output and the contents of the packets (not just the header information shown in the terminal) for later analysis by a graphical tool, such as Wireshark (see p102).

This can be a very useful tool for diagnosing network problems. For instance, if you can’t get DHCP working properly, running a packet dump on the DHCP server will enable you to see whether it’s receiving requests for

addresses, whether it’s responding, or whether packets are being blocked by a firewall, which will enable you to identify where the problem lies.

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 Bob’s computer, not Alice’s?

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, we’ve used Zenmap

to interpret the results of a scan to display the topology of

the network.

basics The | hacks Network

The Hacker’s Manual 2015 | 119

Network hacks | The basics

Networks hacks

Understanding IP addresses

IP addresses are a touch more complicated than suggested in the article’s 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.1

11000000.10101000.00000001.00000001

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

the network portion of the address, and can be thought of as another binary number overlaid on to the IP address, where a 1 represents a bit that belongs to the network portion of the address:

11000000.10101000.00000001.00000001

11111111.11111111.11111111.00000000

In this case, in the IP address 192.168.1.1, the first three octets represent the network portion of the address, so hosts can only be assigned unique numbers from the last octet.

This means that in the 192.168.1.0/24 network, there are only 255 unique addresses that can be given to hosts. In fact, there are only 253 unique addresses, because the first and last

addresses in a range are reserved for special purposes. The first address is the network address, and is used not to specify a host on that network, but the network itself. This is why you’ll see .0/24 in the output of your ip route command. The last address is used for broadcast messages that address every host on the IP network.

As another example, consider the network address 192.168.1.0/28; in this instance there are only 14 usable addresses, because

the maximum value representable in four binary digits is 16 (2^4), and the first and last of these are reserved.

This is an example of a network interface card; the device that mediates between your system and the physical medium.

The thing that stops them from reading it is that every network interface card (NIC – the thing that translates information from your computer in to a signal that can be broadcast across a physical medium, and decodes it again) has something called a MAC address.

Every packet includes the MAC address of the recipient, and when a computer receives a packet, it inspects the address to see if it matches its own NIC’s address – if it does match, it performs further processing to extract the information contained; if it doesn’t, it discards the packet to save it from wasting processor cycles.

You can see what your active NIC’s address is by using the ip command again:

ip link show dev wlan0

where wlan0 is the name of the device you discovered earlier. If you just type ip link show, you’ll see information on all the NICs attached to your computer. The MAC address is the 12-digit bit of information that comes after link/ether in the output. It will look something like: ea:34:43:81:02:7c. Of course, with a single piece of wire, you’re going to have a hard time connecting more than two computers. In order to

connect many computers to the same physical network,

a device known as a hub can be used. A hub has many pieces of Ethernet plugged in to it, and when it receives a packet on any of these interfaces, it retransmits the packet to all the other interfaces.

Even with clever packet-switched networks, you can, however, experience problems with contention if too many computers share the same physical medium – that is to say, if different computers try to transmit information at the same time, the information being sent gets corrupted as a result, and effective communication breaks down. This is because computers don’t actually take it politely in turns to send packets, but instead send their information randomly and use clever algorithms to help them recover from packet collisions.

To get around this problem, there’s another type of device, known as a switch. A switch is very much like a hub, in that it has many interfaces with Ethernet cables plugged in to it, but it’s more intelligent.

Rather than blindly retransmitting all the packets that it receives to all the other interfaces, the switch builds a table of what MAC addresses can be found through which interfaces. When a packet arrives at the switch, it inspects the destination MAC address and figures out which port it should be sent out of. This way, you reduce the amount of traffic being sent across the bits of Ethernet and reduce contention on the lines – that is to say, you reduce collisions and make communication more reliable.

Logical networks

The use of switches to extend networks and reduce collisions isn’t the end of the story, however. Another hurdle to jump over is the fact that MAC addresses have a flat structure, which means there’s no easy way to organise the addresses or group them together.

This isn’t a problem when you’re 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

120 | The Hacker’s Manual 2015

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]