Wednesday, March 31, 2010

Misc 18

Now suppose that we switch the relay router with a Windows 2008 server, like this:

The first question is, can Windows 2008 server actually act as a DHCP relay agent? That is definitely a YES. However, unlike what most might think, DHCP relaying is NOT a feature of the DHCP role at all.

Just think of it this way, if you want your Windows Server to route packets like a router, there is only one role that could do that. Depending on your edition, you need to install Routing and Remote Access (on 2003) or Network Policy and Access Services (on 2008). Features like NAT, RIP, DHCP Relaying and IGMP are all found in RRAS/NPAS.

I will now walk you through the installation of NPAS on Windows 2008. I'll assume that your server is already joined to the active directory domain (this is not important for DHCP relaying, but will come into play when we go into NPS and PPTP VPN later on).

Now I'll begin with a clean installation with ADDS enabled. (You can also join another domain. You need not be the domain controller) The first thing to do is to set up the network connections. I'm currently on the W2K8 server depicted in the topology, so I have these two interfaces:

Outside -
Inside -

The DNS for both is set to

Now we'll need to set up NPAS. Simply select this role and click next.

Now we'll need to install NPS and RRAS. Even if don't select NPS, it will be automatically installed after RRAS is set up (without notifying you).

After installing, browse over to the RRAS console from Administrative Tools.

Now you'll have to enable the service. To do this, right click on your computer name and select Configure and Enable RRAS.

If you need access lists automatically set up for you to block non-VPN traffic, select VPN. If you still want to allow normal traffic to go through, select Custom Configuration. In this case, we want something simple so we'll select Custom Configuration.

At this screen, select VPN and LAN routing:

At this point your server should route packets through from 192.168.1.x to 172.16.1.x. It was not possible previously to ping from 192.168.1.x. Now add a new interface to the relay agent list. This interface is the one that will relay DHCP requests (or in other words, this interface is where clients will request).

Note that upon setting up your RRAS service, you may suddenly have a chunk of addresses leased from the inside interface. Do not worry as this is not a bug. This is due to the RRAS server pre-leasing IP addresses for assignment to VPN users. This behavior only applies to the VPN agent. The normal DHCP Relay Agent will relay requests as per normal. Now you will need to add the Relay Agent listener to the outside interface as shown:

Finally you'll have to populate the DHCP list. Press OK and go to the relay agent's properties:

Add in the IP address of your DHCP server here. Now you're done!

In the next article I'm going to talk about enabling PPTP VPN connectivity. By going through this article, you're already 80% done, so the next article is going to be short.

Monday, March 29, 2010

Misc 17

DHCP stands for Dynamic Host Configuration Protocol. DHCP is typically used for large implementations where manually typing in IP addresses for individual hosts are not feasible. DHCP is used to configure hosts for basic connectivity by setting up its IP address and subnet mask. DHCP Options can also be employed to push information such as the default gateway and domain name-server.
When a host (which in this case would be the DHCP client) boots up, it sends a DHCPDISCOVER packet as a local broadcast packet to If a DHCP server in the subnet (or VLAN) receives the DHCPDISCOVER packet, it would respond with a DHCPOFFER. The DHCPOFFER packet contains an unleased IP address, the subnet mask, and several other options like the default gateway, DNS server and so on. If the client is okay with it, he would reply with a DHCPREQUEST containing the IP address, which shows its acceptance of the IP address. The server finally sends a DHCPACK containing information similar to the ones contained in DHCPOFFER.

However, since a DHCPDISCOVER packet can only stay within its subnet, the client would not be able to obtain an IP address if there are no DHCP servers. This is where a relay comes in. A DHCP relay takes any DHCPDISCOVER packets it hears and convert it into unicast form, sending it to the DHCP server specified during configuration.

The process is similar. Any broadcast messages are relayed to the DHCP server via unicast. The replies are received via unicast and broadcasted back out to the originating subnet. The relay agent modifies the GIADDR field to reflect the IP address that it heard the broadcast from, so the DHCP server could properly allocate IP addresses from the correct subnet. Therefore, the DHCP server would need to have the scopes of all the subnets that it needs to serve.

Below is a simple topology to illustrate the setting up of a DHCP server and a relay agent through the IOS.

To set up a simple DHCP server using the IOS, use:
conf t
ho DHCPServer
ip dhcp pool POOL01
network /24
domain-n syraxius.ath.cx
ip dhcp excluded

Next we're going to set up the relay. The relay should be configured at the interface that the agent should be listening to. In this case, to give the host an IP, he should listen to the interface connected to the switch. To activate the relay pointing to (the DHCP Server), use:
conf t
ho DHCPRelay
in f0/1
ip add
no shut
ip helper

Saturday, March 27, 2010

Misc 16

We'll now set up Music and Video streaming. This can be done through an apache mod known as ampache. Ampache uses MySQL to store user and media information and is mostly configured through a web-based GUI. Users also access the streaming server through a web-based GUI.
Make sure apache is installed. Then, install ampache:
apt-get install ampache

During installation, you will be prompted to enter a password for the root MySQL user. Remember this as you will need it to configure ampache properly later on. For this purpose, I'll use "root" as the password. Next, select to automatically configure apache2.

Once it's done, you'll need to configure the ampache server. To do this, connect to localhost or from another system. If you're using a non-GUI system, you can the built-in use www-browser to access the web:
www-browser localhost/ampache

After clicking on "Start configuration", scroll down and enter the parameters as follows:

Desired Database Name: ampache
MySQL Hostname: localhost
MySQL Administrative Username: root
MySQL Administrative Password: root
Create Database User for New Database? * (tick)
Ampache Database Username: ampache
Ampache Database User Password: ampache
Overwrite Existing: * (tick)

Finally, click Insert Database to proceed.

Now you will need to enter the MySQL username and password for the ampache database. This will be what you specified at the previous screen. For me, I'm using ampache:

Web Path: /ampache
Desired Database Name: ampache
MySQL Hostname: localhost
MySQL Username: ampache
MySQL Password: ampache

When you click on Write Config, you will be able to save the ampache.cfg.php file. This file is to be placed in /etc/ampache/. If you're using www-browser, you'll have to press "S" (Shift+s) to save the file. Save it as ampache.cfg.php. (For www-browser, type "B" (Shift+b) to go back)

Now scroll down and click on the verification button. Both boxes should show "OK". When that's the case, proceed to step 3. At step 3 you just have to create an admin account that will be used for the first logon.

When you're done, access the server from a real web browser and it should be all working and dandy.

One of the first things you need to do is to add a catalogue. To do this, create a folder to contain your music or videos (videos are supported only from version 3.5. If you're running 3.4.1, videos are not officially supported and you'll have to add the extensions into ampache.cfg.php yourself for it to work properly). For me, I'm using /etc/ampache/music/. Inside the music folder, I have the follow structure:
Artist/Album/Track Title.mp3

To add a catalogue, click the grey chassis on the left navigational panel and click on Add a Catalog. According to my folder structure, I should have these settings:

Catalog Name: Music
Path: /etc/ampache/music/
Catalog Type: Local
Filename Pattern: %T %t
Folder Pattern: %a/%A

I'll now add video files into the directory. To do this, you'll have to add the extensions that you want in ampache.cfg.php under catalog_file_pattern. When you're done, it's time to add a catalog for videos like how you added it for audio.

Note that video will only work when it is streamed in a media player. The flash player only supports playing of mp3 files (or files transcoded into mp3).

Note that if you've set up apache2 for SSL support, you can also access the site through https.

Misc 15

I said I wanted to make this post a few articles ago but I forgot. It's time to implement samba! Samba is a reimplementation of the SMB/CIFS protocol for Linux. SMB/CIFS is the file sharing protocol used by Windows. Implementing samba allows your Windows clients to connect to Linux through the network as if you're connecting to another Windows client.
Let's begin by installing samba:
apt-get install samba

After installation, you already have the necessary settings. The next step is simply to assign a password to accounts that you wish to allow access through the samba server and you're done! To do this, type:
smbpassword user

You need to do this as root. After you're done, you should be able to log in from Windows by typing \\ in front of your IP address. For me, I'll type \\ You will now be able to log in as users in your Linux box.

By default you'll have access to only your files in your home folder. To add more folders, you'll need to edit the /etc/samba/smb.conf file. Before we do anything, we may want to change the netbios name. At the time of typing, the config does not allow any specification of the netbios name. To fix this, type this anywhere in smb.conf (I usually type this above workgroup):
netbios name = KELVIN-DEBIAN

Now, scroll all the way down till you're at the Share Definitions section. This is where you create a new share. To share /etc/apache2/ to everyone, type this just above the sample share for CDROM at the bottom:
comment = The Apache 2 configurations folder.
read only = no
path = /etc/apache2/
guest ok = no
browseable = no
valid users = root

Setting browseable to no will remove it from the list. You'll have to manually type in \\ to go to the location.

The read only attribute will prevent modifications.

To restrict access to only the root user, the "valid users" attribute is used. Use spaces as a delimiter for multiple users.

Misc 14

Now we're going to talk about integrating GPG in Windows and Hotmail with Linux and Alpine. First of all, grab yourself a copy of the Windows GPG here.
From CLI, browse into the directory containing the gpg.exe file (For me, it's C:\Program Files\GPG\). Similarly, generate a key with:
gpg --gen-key

I'm now going to make one for my Hotmail account, which is syraxius@hotmail.com. Now, export your public key from Linux and mail it to your Hotmail account. To export the keys, type:
gpg --export kelvin@syraxius.ath.cx > public.key

Now send it to your guy in Windows through FTP (remember to set it to binary) or any other means. Now your public.key should be in the same folder as your gpg.exe. Type this to import the key:
gpg --import *.key

Now you should be able to encrypt files that are only readable by kelvin@syraxius.ath.cx. I'm going to type a message and echo it into encrypt like this:
echo Hello this is a test message! | gpg --encrypt -r kelvin@syraxius.ath.cx -a > message.asc

Now you should have a message.asc. Open it with notepad and paste it into Hotmail, just make sure that you have Plain Text as the text mode. Once you receive the mail, Alpine should prompt for your private key password, and the message would be decrypted.

Misc 13

From now on, all Debian related articles will use the topology found in Misc 3 unless otherwise specified. This will save me a few bytes in the future!
Now I'm going to go into using GnuPG with a mail client such as Alpine. GnuPG (which would be referred to as GPG for the rest of the article) stands for Gnu Privacy Guard. It is a replacement for Pretty Good Privacy (PGP). GPG allows you to generate keypairs which you can then freely distribute (of course, you distribute your public keys only). These keypairs can be used to encrypt mails or files.

Since we're going to use Alpine with GPG, download them both:
apt-get install alpine gnupg

I will not go into the configuration of Alpine and your MTA. Refer to Misc 5 for setting up a basic MTA and getting Alpine to work with it (It's easy! Trust me!).

Now that both are set up, you'll need to generate your own keypair. To do this, use the command:
gpg --gen-key

Follow through with the process. All key settings will work. Just make sure that your email is put correctly. This is very vital. In this exercise, I will mail myself with an encrypted mail and see if I can read it again.

During the key generation process, you may encounter a message that says that they have not enough random data. To fix this, spam on your keyboard (literally). I usually have to spam for a minute or two for it to work, be patient. (You may end up with a whole screen of gibberish. Just hit enter to clear it if you want).

Now at this point you should have a public and a private key for yourself. To see the keys, type:
gpg --list-keys
gpg --list-secret-keys

To encrypt a file, type:
gpg --encrypt -r kelvin@syraxius.ath.cx File.txt

Now you'll get a file that has the extension .gpg. These files can be decrypted if you have the private key for them (which you coincidentally have). To decrypt the .gpg file, type:
gpg --decrypt File.txt

Notice that if you do a cat of the .gpg file, you'll see a whole bunch of gibberish. There is also a chance of your shell getting text corruption. To prevent this, you can actually add a padding to the top and bottom of the file. This padding is also important for your mail later. The padding is called armouring, and you can do this through the -a parameter:
gpg --encrypt -r kelvin@syraxius.ath.cx -a File.txt

If you did it correctly, you'll have a .asc file. If you cat the .asc file, you'll notice that the file looks quite clean, and it has a -----BEGIN PGP MESSAGE----- header and a -----END PGP MESSAGE----- trailer. Notice that there's no longer any shell corruption.

A recap on theory. When you encrypt a file with your public key, only your corresponding private key can decrypt it. When I want to send you a file and no one else is supposed to read it, I will encrypt it with your public key and send it to you. You will then decrypt it with your private key. This satisfies the confidentiality part of the equation.

However, you can also turn the keys around. If you encrypt the file with your private key, only your public key can decrypt it. This is known as signing. This ensures not much of confidentiality (unless you restrict the spreading of your public key) but it ensures that the message source (you) is genuine, unless someone else has your private key.

To sign a file, simply use:
gpg --sign File.txt

You will get a .gpg file. Recall that a .gpg file has a chance to corrupt your shell when you cat it. Also recall that the -a parameter performs armoring which adds a header and trailer to the encrypted file. The armoring equivalent of signing is the clearsign, which is activated through:
gpg --clearsign File.txt

Now you'll have a .asc file. To decrypt both the signed and clearsigned file, use:
gpg --decrypt File.txt.gpg
gpg --decrypt File.txt.asc

Now it's time to set up Alpine to work with it. Boot up Alpine and press S then C to get into the configuration mode. Now, hit "End" to get to the bottom, then hit "Page Up" twice. You should see two parameters: Display Filters, Sending Filters.

Display Filter matches a pattern. If the pattern is matched, the mail is piped into the specified process. Add an entry as follows:
_LEADING("-----BEGIN PGP")_ /usr/bin/gpg --decrypt

This will pipe any files that begin with the two specified patterns into the /usr/bin/gpg --decrypt process.

Now it's time to set up the sending filters. To do this, add in these two entries:
/usr/bin/gpg --encrypt -r _RECIPIENTS_ -a
/usr/bin/gpg --clearsign

The _RECIPIENTS_ will be replaced by Alpine automatically. Now send a mail to yourself. You should be getting a message to use filters. Use CTRL+N or CTRL+P to scroll through them.

Note that since we're using the same programs to encrypt and sign, then the filters will just show "gpg". To fix this, make symbolic links to /usr/bin/gpg as "encrypt" and "sign", then add them into the filters. When you receive the mail, it should automatically decrypt it upon opening. It would ask for a PEM password if the message is encrypted (instead of signed).

In the next article, I will talk about utilizing GPG in Windows and Hotmail.

Misc 12

(This uses the topology from Misc 3)
Picking up with where we left off with FreeRadius. Now we want to perform authorization of users by kicking them into a failed or guest VLAN if they are not properly authenticated, and sending them into a authenticated VLAN if they provide correct credentials.

There are a few things we need to do:
1) Configure users file to provide users with the proper reply
2) Configure EAP to use tunneled reply (for authorization to work properly)
3) Configure switch to use settings

I have three VLANs. VLAN 1 is where all the servers reside (which is not a good idea). VLAN 2 is where failed users get kicked to, and VLAN 3 is where authenticated users live.

First, we do a quick nano of the users file found in /etc/freeradius/:
nano users

Scroll down to the user and modify him/her as follows:
kelvin Cleartext-Password := "kelvin"
Service-Type = Framed-User,
Tunnel-Type = VLAN,
Tunnel-Medium-Type = IEE-802,
Tunnel-Private-Group-ID = "3"

Private group ID is the VLAN that the user will go into if he is properly authenticated. Notice that I enclosed the private group ID with quotes. FreeRadius would properly understand, but just put it there to be sure. Certain RADIUS servers require the group ID to be a String or else it would not work properly.

Now, it's time to turn on tunneled reply. Do a quick nano of the eap.conf file:
nano eap.conf

Use F6 to search for the line that contains "_reply". Note that there are two. The one you need to modify should be the one in the PEAP section, not the TLS one. When you find it, modify it to reflect:
use_tuneled_reply = yes

After saving, do a restart of your FreeRadius and it should be working quite well!

Misc 11

(This uses the topology found in Misc 3)
Alright right now I'm going to show you how to use the FTP client in Linux as one of the means of getting files into Debian. The next post I'll probably go into setting up samba to make Debian accessible from Windows.

First of all, follow the guide here to get a basic FTP server set up. I have one set up right now with the following settings:

Control Port: 14147
User: F1s5Us3r
Password: P@55w0rd
Access: C:\, Full-Control

Now, to initiate a connection to your FTP server, simply type in:
ftp 14147

Alternatively, you can type in:
open 14147

Once connected, you would be shown the MOTD (depending on what server you're using) and you'll be asked for credentials. Type it in as per normal.

At this point you should see a success connection message. The first thing you should do in an FTP session is to list the folder contents. FTP commands are quite similar to Linux ones. For example, to do a listing, simply type:

Similarly, you can change directories through:
cd directory/

To download files, simply use:
recv filename

To upload files, you can use:
send filename

recv can be substituted with get, and send can be substituted with put.

If you want to download more than one file at a time, use:
mget *.txt

If you want to upload more than one file at a time, use:
mput *.txt

Note that when sending non-cleartext files, it is best to switch to binary mode by typing:

If you receive a non-cleartext file in ASCII mode, they will become truncated and unreadable. ASCII mode is the default. To switch back to ASCII mode, use:

Sunday, March 21, 2010

Misc 10

(This uses the topology found in Misc 3)
Now that you've installed FreeRadius with OpenSSL support, it's time to set it up. First of all, we'll need to generate a keypair. To do this, type:
cd /etc/freeradius/certs/
/usr/lib/ssl/misc/CA.pl -newcert

This procedure should be quite familiar to you if you've set up for Apache2 HTTPS support.

Now, you'll need to generate the DH ciphers for use in TLS. To do this, remain in the certs folder and type:
openssl dhparam -out certs/dh 1024

You do not need to memorize that line. You can refer to it from the eap.conf file at the DH section.

Now, it's time to point the server to use PEAP. Modify /etc/freeradius/eap.conf and change the default EAP type to peap:
default_eap_type = peap

Scroll to the TLS section and make changes similar to this:
tls {
certdir = ${confdir}/certs
cadir = ${confdir}/certs

private_key_password = cisco
private_key_file = ${certdir}/newkey.pem
certificate_file = ${certdir}/newcert.pem
CA_file = ${cadir}/newcert.pem
dh_file = ${certdir}/dh
random_file = ${certdir}/dh

Now your server should be able to start and read all the certificates and ciphers properly.

Do note that changing the default_eap_type to PEAP doesn't restrict it to only using PEAP. It just tries to use PEAP first. If a client specifies MD5, authentication would still go through.

To truly remove MD5, you'll have to comment out MD5 in sites-available/default in the authorize{} and authenticate{} tags.

Misc 9

(This uses the topology found in Misc 3)
As previously mentioned, FreeRadius lacks any sort of SSL support due to licensing issues with OpenSSL. This means that EAP types such as PEAP/TLS/TTLS would not work and would be ignored in configuration files. This has been a source of great frustration for those who didn't know.

In this entry I will attempt to recompile FreeRadius to include OpenSSL. Be warned that this is only for educational purposes and is illegal for use in production environments.

First of all, make sure that the repositories are properly set up. To do this, edit /etc/apt/sources.list and add in the NUS mirror:
deb http://mirror.nus.edu.sg/Debian lenny contrib main non-free
deb-src http://mirror.nus.edu.sg/Debian lenny contrib main non-free

The deb-src entry is very important as this is what we'll need to use to get FreeRadius's source code. Now, we'll install all necessary packages for compilation of software:
apt-get install build-essentials apt-src

Now you'll have apt-src at your disposal. Apt-src allows you to quickly retrieve an application's source from a repository. Create a folder in your home directory and browse to it:
mkdir ~/build_freeradius
cd ~/build_freeradius

Now you should download the source of freeradius. To do this, do an update, then install it with apt-src:
apt-src update
apt-src install freeradius

When you do a listing of your current directory, you should see a bunch of files and a folder. Get into the debian folder like this:
cd freeradius-2.0.4+dfsg/debian

Now there's two files which we need to edit to make it work. The first file is the rules file, which tells the compiler which rules it must follow. Coincidentally, it's this file that tells the compiler that OpenSSL cannot be used on a Debian system. We must remove all such rules. To do this, edit the rules file and look for these lines:
--without-rlm_eap_tls \
--without-rlm_eap_ttls \
--without-rlm_eap_peap \
--without-openssl \

Ignore OTP and IKEv2 because they do not work for some reason. Now, edit it to reflect:
--with-rlm_eap_tls \
--with-rlm_eap_ttls \
--with-rlm_eap_peap \
--with-openssl \

Next, do a search for "openssl". You should find a chunk of code that looks like this:
for pkg in $(shell grep ^Package debian/control | awk '{print $$2}') ; d
o \
if dh_shlibdeps -p $$pkg -- -O | grep -q libssl; then \
echo "$$pkg links to openssl" ;\
exit 1 ;\
fi ;\

This is the part that restricts libssl from being installed as part of the dependencies. This is very bad, so remove the whole section.

Now edit the control file, and look for the dependency list for freeradius (should be the first line). Add in libssl-dev at the back like this:
Build-Depends: autotools-dev, debhelper (>= 6.0.7), libgdbm-dev, libiodbc2-dev, libkrb5-dev, libldap2-dev, libltdl3-dev, libmysqlclient15-dev | libmysqlclient-dev, libpam0g-dev, libpcap-dev, libperl-dev, libpq-dev, libsasl2-dev, libsnmp-dev, libtool, python-dev, libssl-dev

Now you're done, simply browse back to the ~/build_freeradius folder and type:
apt-src build freeradius

You should go through smoothly. After the whole process (which would take some time depending on the system), you should have a few deb package files in your folder. To install them all, simply type:
dpkg -i *.deb

Misc 8

(This uses the topology found in Misc 3)
However, at times we may want to allow Windows clients to log in as well. Windows doesn't use PAP. Instead, we would have to use the various methods available such PEAP and MD5. By default, MD5 is already set up, so I'll walk you through authentication through MD5.

First, set up the router to use the radius as both the authentication and authorization source:
aaa authentication dot1x default group radius
aaa authorization network default group radius

Now, we must turn on dot1x. From global configuration, type:
dot1x system-auth-control

Now, go into any switchports and type in:
dot1x port-control auto

The keyword "auto" sets it to query the radius for authentication. The other options are force-authorized, or force-unauthorized.

Note that if you encounter any problems during set up, use "freeradius -X" to run in debug mode. Alternatively you can check in /var/log/freeradius/

Note that FreeRadius currently does not support any authentication in the SSL layer. This is due to certain licensing problems of the OpenSSL library. To fix this, you will have to manually rebuild the package.

Friday, March 19, 2010

Misc 7

(This uses the topology found in Misc 3)
I will now begin elaborating on how you can set up FreeRadius to do simple PAP authentications required for AAA Login Authentication for Cisco routers/switches. You can build on this knowledge to set up more advanced features like EAP/MD5.

FreeRadius is an open-source RADIUS server capable of using local LDAP or integrate with Active Directory. FreeRadius listens to standards-based ports like TCP 1812 for Authentication/Authorization and TCP 1813 for Accounting.

To not bore you with too much of the details, let's install FreeRadius:
apt-get install freeradius

The procedures required are similar to Windows. We first have to add a RADIUS client. To do this, modify the /etc/freeradius/clients.conf and add in the following:
client C2600 {
ipaddr =
secret = cisco

Next, we add in the users. To do this, modify the /etc/users file and add in:
Kelvin Cleartext-Password := "kelvin"

Now do a restart or a reload of the freeradius server and it's time to set up the router.

First of all, enable the new AAA model:
aaa new-model

Now, create some local users:
user cisco pass cisco

Now, set up AAA Login Authentication to use the Default Radius Group, then fall back to Local database if Radius is not available:
aaa authentication login default group radius login

Add the server and the key:
radius-server host auth-port 1812 acct-port 1813 key 0 cisco

Finally, set up Telnet to use the Radius group:
line vty 0 4
login authentication radius default

Now login authentication for Cisco should be working fine!

Misc 6

(This uses the topology found in Misc 3)
Now I'm going to touch on Squid. Squid is a HTTP proxy server that normally listens to port 3128. Since it's a HTTP proxy, I'll walk you through on how to change it to the standard 8080, change permissions, as well as do some router configuration to make sure that a user must connect through the proxy.

First of all, do a basic installation of squid:
apt-get install squid

The good thing about squid is that it has only one configuration file. The bad thing is that everything is cramped into that configuration file. We first need to change the port to 8080. The configuration file is located in:

The keyword to look for here is the http_port. Press F6 and search for "TAG: http_port". There should be a line that looks like "http_port = 3128". Modify it so it reflects:
http_port = 8080

By default no traffic is allowed through the proxy. We have to define what is allowed through the proxy. Now we'll do a simple permit for our network. Look for a the localnet access-list declaration in the acl section. Add the network above the first line as shown:
acl localnet src

Next, scroll down and look for the following line and uncomment it:
http_access allow localnet

It should be above "http_access allow localhost". Right after you do this, do a restart and you'll have a fully functional HTTP proxy at your disposal. Use the http_access directive to specify the conditions which are allowed or disallowed. Check the "TAG: acl" section for syntax.

If you are in an environment similar to Temasek Polytechnic and wish to set up the squid to test for real internet connectivity in an environment with a proxy, you'll need to set up your squid proxy to connect to a proxy. A proxy hierarchically higher than your system is a parent cache peer, while one hierarchically equal or lower is a sibling.

Suppose we wish to point to Temasek Polytechnic's proxy.tp.edu.sg:80 proxy. Browse to the "TAG: cache_peer" section and add the following in:
cache_peer proxy.tp.edu.sg parent 80 80 proxy-only default

Next, you'll need to specify so that the proxy server will not try to connect directly. To do this, browse to the "TAG: never_direct" section and add in:
never_direct allow all

Finally, you'll want to allow only your proxy server through the router. To do this, use the following commands:
conf t
ip access-l standard PROXY
permit ip
in f0/0
ip access-g PROXY out

This will make it so that only requests from the proxy are let through. This is very strict but is a default starting point. Such proxy access-lists are usually deployed on the final router at the edge of your network perimeter. If anything breaks, just add them to the PROXY access-list.

Misc 5

(This uses the topology found in Misc 3)
I will now focus on enabling Debian to function as an SMTP server. Natively, Debian installs exim4 as the MTA (Main Transfer Agent). MTAs such as exim4 and postfix both operate on SMTP TCP port 25. As I go through this article, I will cover both exim4 and postfix.

We'll begin with exim4. SMTP is a ASCII based protocol, so you can actually telnet into the server to perform mail sending. To access the server through telnet, use:
telnet localhost 25

I will now walk you through the basics of the SMTP protocol. At first you will receive code 220. Code 220 is the success response that notifies the application (or telnet user) that he can proceed. To proceed, type:
helo localhost

You will now be in code 250. Code 250 means that the SMTP server is ready for mail processing. First you must specify the sender:
mail from: kelvin@syraxius.ath.cx

Next, you specify the recipient:
rcpt to: syraxius@hotmail.com
rcpt to: 0800893j@student.tp.edu.sg

Finally, you tell the server that you are ready to specify the data:

At this point, you would be in code 354. In 354, the server is ready to receive the message body. Type anything you like, and end with a . on its own line. To send the mail, type:

Notice that it's troublesome to do this, so we employ a mail client such as alpine to assist us. To install alpine, use:
apt-get install alpine

When alpine is first invoked, you will need to configure the mail server manually. To do this, press S followed by C from the main menu. Use "localhost" as the SMTP server. Now quit back out to main menu and hit C to compose a mail. Notice that you can send mails only to users local on the computer by default (not even in your network). If you attempt to send to anything outside of your network, you will receive a mail delivery failure from exim4.

To fix this, type:
dpkg-reconfigure exim4-config

Simply select the "Internet" option and leave the rest as default to allow sending to the internet. However, don't expect to be able to reach severs like Hotmail as they block dynamic IPs.

To be able to receive mails from the internet, leave the listening field blank during the dpkg-reconfigure. Simply send (from Hotmail or anywhere else) the mail to your fully qualified email address, like kelvin@syraxius.ath.cx.

Postfix is similar to exim4, but it natively supports encryption through TLS. To install Postfix, use:
apt-get install postfix

If you've previously set up alpine for exim4, then you would not need to reconfigure it for postfix. Just make sure that it's postfix running instead of exim4 by stopping the exim4 daemon then starting the postfix.

If you've accidentally chosen to restrict to local sending, simply invoke:
dpkg-reconfigure postfix

Like exim4, you can select Internet to be able to send to the network.

Misc 4

(This uses the topology found in Misc 3)
Now I'll be moving on to web-servers. We'll first set up basic HTTP, then move on to HTTPS. We'll need to install apache2 web-server through:
apt-get install apache2

The web-server should be functional upon installation so it's not too much configuration going on here. HTTP stands for Hyper-Text Transfer Protocol. It listens to TCP port 80, and it is an application layer protocol. When you browse to localhost, you should see a message that says "It works!". The file shown is actually stored in /var/www/.

After you fiddle around with the index.html file, it's time to begin the real work of securing the web access through HTTPS. HTTPS listens to TCP port 443. The 'S' in HTTPS means Secure. This security is provided through SSL/TLS, so you will need to install openssl if you haven't:
apt-get install openssl

Now we'll need to use a provided script to generate an RSA keypair for use in apache2. The script generates the keypair in the directory it's being invoked from, so create an "ssl" folder in /etc/apache2/ and type:
/usr/lib/ssl/misc/CA.pl -newcert

Fill in the information as accurately as possible. Do not forget the PEM pass phrase because you'll need it every time you start your web-server. After the wizard, you should have two files: newcert.pem (Public) and newkey.pem (Private)

Before we assign the keys, we'll need to enable the SSL module. By default apache2 only listens to port 80. To enable the SSL module, use the Apache 2 Enable Module command:
a2enmod ssl

You'll should have a default-ssl file in sites-available. That is the file you need to use to specify the certificate. It also contains various parameters for SSL. Modify the file so that the lines containing "SSLCertificateFile" and "SSLCertificateKeyFile" look like:
SSLCertificateFile ssl/newcert.pem
SSLCertificateKeyFile ssl/newkey.pem

Now you'll need to enable the sites using:

Doing so will enable both HTTP and HTTPS access. To allow only one, use a2dissite to disable.

Misc 3

For the next few entries, I'll be making use of a topology similar to the one you see below:

I'll be focusing on Debian and the deployment of several services not already covered in the existing Debian articles. The Windows XP takes on more of a client role, while the Debian would be the main server here.

This guide assumes that you are able to set up your own connectivity scheme (including NAT, Port-Forwarding, etc.).

Here is the breakdown of the interfaces:
eth0 -
Windows XP:
eth0 -
f0/0 -
f0/1 -

The WRT54G router provides connectivity to the internet.I'll add on more topological details later when required. Now that we have the basic topology, I'll begin on the meat.

We'll start up by setting up remote access through telnetd, and later on upgrading it to secure remote access through sshd. (Note that SSH does not depend on Telnet; I just want to make sure I cover the common methods of access)

Telnet is one of the most basic methods of remotely controlling a system. Telnet makes use of the client/sever model, and operates through port 23. Telnet is easy to set up, but is also easily compromised through packet sniffing.

We'll need to install telnetd. But before we do so, it's wise to update the repository information. To do this, we'll need to run the "apt-get update" command. "apt-get update" retrieves repository information from the sources specified in /etc/apt/sources.list. Entries in sources.list follow this syntax:
deb http://mirror.nus.edu.sg/Debian lenny contrib main non-free

http://mirror.nus.edu.sg/Debian is the directory that contains the "dist" folder. The directory following the deb keyword must always contain the "dist" folder.

"lenny" is the entire path for the distribution relative to the "dist" folder. The folder specified here must contain folders such as main, contrib, etc. Some mirrors may be multiple folders deep, but in this case main is in /Debian/dist/lenny/main/ so you only need to specify "lenny".

Finally, contrib, main, and non-free are the software categories found in the lenny folder. Adding that line into sources.list effectively adds:

The general syntax is:
deb directory-containing-dist directory-containing-main main [contrib] [non-free]...

After invoking "apt-get update", install telnetd through:
apt-get install telnetd

If you wish, you can also sudo that command. But you'll have to set up your account for sudo through a root user through:

telnetd is launched by inetd. After initial installation, /etc/inetd.conf should contain the telnet entry. However, inetd is only invoked at start-up so you will need to restart the system for telnet to work.

After reboot, you should be able to telnet yourself through:
telnet localhost

Now it's time to set up sshd. SSH works on TCP port 22 and provides a secure channel for telnet-like communication. To install sshd, use apt-get again:
apt-get install ssh

Unlike telnetd, sshd does not require a reboot to start working. Simply connect to the server through an SSH client like PuTTY.

If for some reason you require a new key for sshd, simply delete the keys and reconfigure sshd through:
rm /etc/ssh/ssh_host_*
dpkg-reconfigure openssh-server

To remove telnetd from start-up, simply comment out the line that starts with "telnet" in /etc/inetd.conf.

Tuesday, March 16, 2010

TP-Secure Introduction

If you're a Temasek Polytechnic student and you wish to connect to TP-Secure with your Symbian but you're too shy to approach the Cyber Centre, you're at the right place!
If you're using a rather automated phone, then great! However, if you're with Nokia S60, you'll need some configurations. Today, I'll walk you through the configuration for a Symbian S60v5 phone (5800XM), but it should be similar for most other Nokia phones (It should look very, very similar for S60v3 as well).

If you're using any other phones operating systems, the order of the steps may be different but the parameters will definitely be the same.

First of all, we'll need to add the network into the AP list. To do this, browse to:
Settings > Connectivity

Next, scroll down and select Destinations

In here, select "Add new acc. pt"

Right now, the phone will ask you if you want to search check for available access points. Since TP-Secure is a hidden network, you'll not be able to find anything. Choose no.

Then select Wireless LAN since that's what we're trying to connect to.

Now enter TP-Secure (case-sensitive!):

Now you'll be asked a series of questions. First of all, if you're not anywhere in TP (like me right now), you'll be given the choice to select between Hidden or Public Infrastructure mode. Otherwise, you'll only see Infrastructure (hidden). Either way, choose Infrastructure (hidden).

Next you'll be asked for the authentication method. Don't listen to what you're friends are telling you! Choose 802.1x here!

Now you'll be able to select the WPA2 mode. Select EAP!

Finally, the destination is the internet:

After adding TP-Secure into the list, browse into its properties from the Internet list. You should see this:

Make sure your settings match these:
Connection name: TP-Secure
Data bearer: Wireless LAN
WLAN network name: TP-Secure
Network status: Hidden
WLAN network mode: Infrastructure
WLAN security mode: 802.1x
Homepage: None
Use access point: Automatically

The connection name and whether to use the access point automatically is just my preference. Now it's time to set the proxy. Press Options and browse to Advanced Settings:

Set the proxy as follows:

Proxy server address: proxy.tp.edu.sg
Proxy port number: 80

Exit back out and go to WLAN Security settings:

You should see EAP here. If not change it to EAP. Then go into the EAP plug-in settings:

Disable everything except PEAP:

You should be at this screen:

Make your configuration mirror this:
Personal certificate: Not defined
Authority certificate: Entrust.net Secure Serv... (Choose the lowest one)
Use name in use: From certificate
User Name:
Realm in use: User defined
TLS privacy: Off
Allow PEAPv0: Yes
Allow PEAPv1: No
Allow PEAPv2: No

When you're done, hit the small white arrow at the top right corner. Depending on your phone you may need to do something different to get to the following screen. Disable everything except MSCHAPv2:

Go into EAP-MSCHAPv2 settings and type in accordingly:

What you enter in this screen is actually your email login without the domain name at the back. For example, if my email is 0800893j@student.tp.edu.sg, then enter:
User name: 0800893J
Prompt password: No
Password: asdfghjk

When you're done, hit back and press the small white arrow on the top right corner again. This time, just make sure all Ciphers are ticked. After that, you're done!

Now you should be able to connect to the internet through TP-Secure flawlessly. Note that if you're trying to access services local to the school (e.g. You're hosting something on a school computer, naughty boy), the firmware (as of today) is not able to handle exceptions. You'll have to manually remove the proxy.

The guide is working as of today (check the date of the post), but if you find missing steps or you have updated parameters, be sure to leave me a comment below!

Sunday, March 14, 2010

CCNA Security 3

There are three general deployment scenarios for a Cisco IOS router:1) Single Perimeter - The router establishes the trusted network boundary at the Internet and protects a single LAN.
2) Two Perimeters - A firewall establishes a second perimeter behind the router.
3) Screened Subnet - A DMZ is established on a firewall that, in turn, is deployed inside the Cisco IOS router.

Cisco ISRs features include:
1) USB Port - USB eToken, USB Flash
2) Unified Network Services - PVDM modules, Media Authentication and Encryption with SRST
3) Integrated Security - 3DES and AES, NAC
4) Mobility - 3G WAN, Wireless LAN
5) Application Intelligence - Performance routing, Cisco WAAS

Cisco router passwords can be a minimum of 0 characters by default, but best practices require 10 characters or more. You can apply a weak encryption to the passwords (Type 7) through:
service password-encryption

However, the encryption is so weak that we can decrypt them simply by putting them on certain Internet decryption service sites. However, this helps with shoulder surfing.

You can create views much analogously similar to the ones we have in Database Design. Views are created from the global configuration mode:
conf t
parser view ISP
secret 0 secretlongpassword
commands exec include ping
commands exec include all show
commands exec include all configure
commands configure include access-l
commands configure include all interface
commands configure include all ip

To log into the view, use:
enable view ISP>

The five basic services that SDM manages are:
1) Wireless
2) Routing
3) Security
4) Switching
5) QoS

AAA stands for Authentication, Authorization and Accounting.

Cisco Secure ACS Solution Engine is an appliance-based solution. Cisco Secure ACS provides RADIUS and TACACS+ services. It also works with many external databases including Active Directory, LDAP, Novell Directory Services and ODBC. It is configured through a Web-based GUI.

RADIUS has rich accounting, and TACACS+ is capable of customizable user-level policies such as command authorization. RADIUS uses UDP:1812/1813/(Cisco's Default are 1645/1646) for transport and TACACS+ uses TCP:49. RADIUS is open source while TACACS+ is proprietary.

When designing an AAA solution, remote administrative access is also known as character mode. Another name for remote network access is packet mode. Exec policies are those that define access rules to the router. Network policies are those that define access through the router.

To display a list of all local AAA users who have been locked out, use:
show aaa local user lockout

To display detailed statistics of all logged in users:
show aaa user all

To display current sessions of users have been AAA'ed by the AAA module:
show aaa sessions

The three main tasks in setting up external AAA is:
1) Configuring the AAA Network (Client and Server)
2) Setting up users in Cisco Secure ACS (Or other servers)
3) Identify Traffic to which AAA will be applied (Client)

Saturday, March 13, 2010

CCNA Voice 2

The telephone component responsible for detecting an off-hook condition is the switch hook. The switch hook is closed when the receiver is picked up, resulting in an off-hook condition. In the off-hook condition, the -48Vdc 20ma circuit from the CO switch is completed, which notifies the switch to send the dial tone.
Traditional analogue signaling types are FXO (Foreign Exchange Office), FXS (Foreign Exchange Station) and E&M (Earth & Magneto or Ear and Mouth). The FXO port is connected to the CO switch, while the FXS is connected to the telephone. E&M is a trunk link typically used to connect from a router interface card to the PBX.

When a user picks up a phone before it rings and realizes that he is already connected to the caller, a "glare" has occurred. Loop start circuits are the most susceptible to glares. Ground start circuits are designed to prevent glares, but are typically only used in business lines. The names of the wires used in the loop start circuit is the ring and the tip.

Ground start circuits uses two mechanisms to prevent glares:
1) Answer Supervision
2) Disconnect Supervision

These two supervision mechanisms removes glare completely.

There are currently 5 E&M signaling types. Type 1 is currently the most popular in the United States. The two sides of the E&M are known as the signaling-unit and the trunk side. The trunk side signals an off-hook condition through the E-lead (typically a PBX), while the M-lead is used by the signaling side (typically a router).

In E&M, there are three mechanisms for line seizure (aka Start Dial Supervision):
1) Wink Start - Provides Answer supervision to reduce glare.
2) Delay Start - Solves the problem of Wink Start dialing too soon with some equipment.
3) Immediate Start - Most basic Start Dial Supervision. Does not provide Answer supervision. The originating end goes off-hook after 150ms and begins transmitting.

CCNA Security 2

The steps of Cisco Secure Network Life Cycle are:1) Initiation
2) Acquisition and Development
3) Implementation
4) Operations and Maintenance
5) Disposition

In the SDLC (Cisco's Secure Development Life Cycle for Secure Networks), initiation is used to categorize risks (recall that risks are chances that a vulnerability may be exploited). Risk categories include:
1) Catastrophe - A business process is destroyed
3) Disaster - A business process is disrupted for an entire day or more
4) Non-Disaster - A business process is disrupted for a finite period of time

In network security, there is a principle known as the SoD (Separation of Duties). SoD states that no one person should be able to compromise the whole system. SoD also states that there should be two-man and dual operator controls in place.

In a two-man control situation, multiple individuals audit and approve of each other's work. This is an administrative control. On the other hand, the dual operator control is when a certain task requires two user's approval to carry out, such as a safe deposit box which requires the customer's and the bank's keys to open. This is a technical control.

There are many types of testing techniques, including:
1) Network scanning
2) War driving
3) Penetration testing
4) Log analysis
5) Password cracking
6) Vulnerability detection
7) Integrity checkers
8) Virus detection
9) War dialing

Scanners probe a network for vulnerabilities and can even simulate an attack, while probes take a more passive role of monitoring a network for signs of probes, scanners and attacks.

Warm sites are redundant sites without real-time copies of data and software. Most of the time a disaster recovery team needs to be dispatched to restore data to the site for it to become fully functional. This is different from hot sites which are synchronized real-time and is able to continue operation immediately.

Policies are made up of many components. The first level hierarchy can be split into:
1) Technical policies - General, Email, Remote-access, Telephony, Application, Network, Wireless etc.
2) End-user policies - Policies such as the AUP.

The AUP is the Acceptable Use Policy, which is most visible to users. It sets out rules as to what is allowed and what isn't to prevent misinterpretation. Things that an AUP contain include the list of websites not allowed during work, etc.

Policies are very general. For a more specific plan for the implementation and actualization of policies, we need to use Standards, Guidelines and Procedures.

Policies specify the overall statements of direction, management position on security issues, organization goals in the context of security, definition of roles an so on.

Standards define the measuring stick against which the efficacy of security controls is judged, resulting in the consistent, uniform application of specific technologies. Usually mandatory.

Guidelines are used to ensure adherence to more general security policies, usually not mandatory.

Finally, procedures are detailed steps to accomplish certain tasks.

There are two broad categories of risk analysis:
1) Qualitative - Using the asset value as a starting point, and develop a mathematical model to come up with a monetary figure of expected losses.
2) Quantitative - This is a scenario-based model which is useful for countries, large cities, and places where it is impractical to list all assets.

Quantitative risk assumes that risk can be determined mathematically, therefore we have a Quantitative Risk Analysis Formula:
ALE = SLE*ARO where SLE = AV*EF.

AV stands for the Asset Value. It is the cost of an individual asset. EF is the exposure factor represented as a percentage the threat is expected to occur. ARO is the annualized rate of occurrence, which is the estimated frequency a threat is expected to occur annually. SLE is the result of AV*EF, which stands for the cost of a single instance of a threat. ALE is the expected loss an individual threat will cause an organization.

ALE itself is useless. ALE of every asset groups should be calculated to show the relative risks to develop a more effective security policy.

Firewalls used to be the definitive element as the security perimeter of a network, but due to the advent of new tunneled services as vectors of attacks, the perimeter of a network is said to be blurring.

Cisco Security Agent, AVS and MARS are threat control for endpoints. ISRs, IPSs and ASA are threat control for both infrastructure, and endpoints. NAC appliances are threat control for infrastructure.

CCNA Voice 1

In traditional PSTNs, calls from analogue telephones are routed through CO switches. CO switches use the SS7 signaling protocol to do call setup. SS7 is a standard used by carriers to set up calls between CO switches, even across multiple vendors. ISDN places calls on the PSTN using the Q.931 protocol.
A PBX system refers to one or more private switch connected to the edge of the PSTN. PBX systems have a single trunk link to the CO switch. Unlike PBX systems, key system phones have multiple lines connected to the phones. Because of this, key systems have less advanced features and are not scalable (typically for smaller organizations <20 br="" employees="">
Analogue phones use DTMF for call dialing (also known as "address signaling"). Before DTMF was used (aka "tone"), the "pulse" was used. DTMF allows creation of 12 unique numbers through a combination of a high and low frequency tone:
      1209Hz 1336Hz 1477Hz
697Hz 1      2      3
770Hz 4      5      6
852Hz 7      8      9
941Hz *      0      #
A numbering plan is a set of rules used to construct numbers. A numbering plan has an authority that regulates number distribution in its territory. An authority like NANP (North American Numbering Plan) organization governs the istribution and formatting of numbers in US and Canada.

An example of a numbering plan is the E.164 numbering plan. It is made up of three items:
1) Country code
2) National destination code
3) Subscriber number

The standard voltage and current deployed on local and ground loops directly connected to the CO is -48 volts DC and 20ma of current. When the phone is picked up, it is said to be off-hook. This closes the circuit and allows the CO switch to know that the phone is picked up.

When a call is routed to the phone, a 40 Vrms AC voltage is sent to the phone ringer. The service also provides a ringback to the caller to let him know that the call is being established.

Ringback is an example of a Supervisory call signaling. There are three types of call signaling categories:
1) Supervisory
2) Address
3) Informational

Supervisory signaling include:
1) On-hook - When the handset is on-hook, the circuit is broken.
2) Off-hook - When the circuit is closed, the CO detects the current flow and plays a dial tone for 15 seconds. When the first digit is dialed, the tone is stopped.
3) Ringing - When a subscriber receives a call, the CO sends an AC 40 Vrms signal to the phone ringer. At the same time, the caller receives a ringback which is described later.

Address signaling are:
1) DTMF - Dual tone multifrequency sine waves that make up 12 unique combinations.
2) Pulse - Pulse created by a rotary-dial telephone which produces "make" and "break" pulses to open and close the local loop circuit to convey the number dialed.

Informational signaling:
1) Dial tone - To indicate that the CO switch is ready to receive the digits
2) Busy - To indicate that the call cannot be established
3) Ringback - To indicate that the call is being established
4) Congestion - To indicate that a long-distance call is not established due to congestion
5) Reorder tone - To indicate that local lines are busy
6) Receiver off-hook - To indicate that the phone has been off-hook for more than 15 seconds without placing a call
7) No such number - To indicate that the number doesn't exist
8) Confirmation tone - To indicate that the CO or PBX is attempting to complete a call

CCNA Security 1

Confidentiality, Integrity and Availability constitutes the elements in the C-I-A triad. This is recognized industry wide and security policies build upon these three components.
According to Cisco, there are tow major categories of threats: internal and external threats. Examples of internal threats are unauthorized access and network misuse, while examples of external threats are viruses and social engineering.

The best definition for integrity safeguards is ensuring that only authorized entities can change sensitive data. Confidentiality is ensuring that only authenticated users have access to those data. Ensuring that the data is available to authorized users is part of maintaining availability.

There are 5 classification levels for the public sector:
1) Unclassified - Data with minimum CIA. Little effort is made to secure it.
2) Secret - Data that requires concerted effort to keep secure.
3) Confidentiality - First level of classified data. This data must comply with confidentiality requirements.
4) Sensitive but Unclassified - Data that would cause some embarrassment if revealed, but not enough to constitute a security breach.
5) Top Secret - Greatest effort is used to secure this data and to ensure its secrecy.

There are three broad categories of security controls:
1) Administrative - Security policies, education, patches
2) Technical - Device hardening, encryption, passwords
3) Physical - Physical access, environmental regulation

These security controls can be further divided into types:
1) Deterrent
2) Preventive
3) Detective

There are three types of laws found in most countries:
1) Civil - Concerned with righting wrongs that do not concern crime. Usually ends with monetary compensation.
2) Criminal - Concerned with crimes. Typically ends with a fine, imprisonment, or both.
3) Administrative - Typically government agencies in the course of enforcing regulations. Monetary awards are divided between the government agencies and the victim of the contravened regulation.

An exploit is an attack that takes advantage of a vulnerability. A risk is the likelihood of the exploit being executed.

The steps for compromising targets and applications are:
1) Perform footprint analysis
2) Enumerate applications and operating systems
3) Manipulate users to gain access
4) Escalate privileges
5) Gather additional passwords and secrets
6) Install back doors
7) Leverage the compromised system

If an attacker were simply guessing at connection sequence numbers, usually using tools to calculate them, this attack is known as blind spoofing. Physical access to the network is not required.

MiTM or MiM stands for Man-in-the-Middle. It describes an attack where an attacker compromises a network's integrity and confidentiality. Attacks against availability are DoS attacks.

Trust attacks are attacks whereby an attacker leverages on a trust relationship between the devices in a network. An example of this type of attack is port redirection. Mitigation against these attacks involve installing firewalls and IPS in the network. HIPS should also be installed wherever possible. ACLs should also be in place to make sure devices that don't need to communicate aren't communicating.

Monday, March 8, 2010

Java 02

I'm short of time so I'm going to make this quick. I'll now implement communication through Java. To demonstrate this, I'll have a client and a server. The server will actually echo whatever the client sends.
To do this, we'll need to import the following packages:
import java.net.*;
import java.io.*;

java.net.* is for the Socket class mainly, and java.io.* is for the PrintStream.

We begin by declaring and instantiating a Socket. The socket will be the object you communicate to the opposite through, therefore the socket specifies the IP and Port (which makes a "Socket") of the peer. The socket is instantiated as shown:
Socket socket = new Socket("",13337);

Now we'll have to work with input and output streams. When you instantiate a socket, you have access to both an input and an output stream. To send, write to the output stream. To read, assign a BufferedReader to handle an input stream and read from the BufferedReader.

First we'll set up the input stream. Instantiate as follows:
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

The above code instantiates an InputStreamReader which reads the input stream of the socket, which then passes the output to the BufferedReader.

Next, we'll set up the output stream. To write to a stream, we use the PrintStream class. PrintStream can then be used similarly to System.out.println(). To instantiate a PrintStream to use the output stream of the socket, do:
PrintStream printStream = new PrintStream(socket.getOutputStream());

To write to the output stream, use:

Right after writing, we'd expect the server to echo back the reply. The reply is then read by the InputStreamReader and stored in the BufferedReader. We can expect to read from the BufferedReader right after writing, through:

When we're done, close as usual:

Now that the client is done, we'll set up the server. In this example, the server will await a connection, and once a connection is made, it will echo any data received back to the client. We'll now import the packages as usual:
import java.net.*;
import java.io.*;

We now specify to listen to connections coming into port 13337:
ServerSocket serverSocket = new ServerSocket(13337);

There is a method called serverSocket.accept() which would return a Socket (remember, with an input and output stream) whenever data is received on the listening port. To read and reply data, we'll first have to instantiate a null Socket object, then repeatedly attempt to assign the output of accept() to it. accept() will block until a connection is made, so no sleep in between each attempt is required.

Implementation is like this:
ServerSocket serverSocket = new ServerSocket(13337);
Socket socket = null;
socket = serverSocket.accept();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream printStream = new PrintStream(socket.getOutputStream());
printStream.println(bufferedReader.readLine()); //Echoes whatever is read

This post isn't as short as I want it to be but oh well :)

Sunday, March 7, 2010

Java 01

Over the next few entries, I'm going to show you how to do a simple integrity check. Implementation will be done in Java, so we will need to learn how to do hashing, how to transmit a message through TCP, and how to implement a basic integrity check that involves a PSK.
So now we're going to talk a little bit about hash. What is a hash? A hash is a complex function, usually recursive, that takes a variable length input and outputs a fixed length output. A small change in the input (such as a change in a few bits) can result in drastically different results, due to an avalanche effect.

For example, the MD5 hash of "The quick brown fox jumps over the lazy dog" gives 9e107d9d372bb6826bd81d3542a419d6. If we add a fullstop at the back, the hash would become e4d909c290d0fb1ca068ffaddf22cbd0.

The two most popular hashing functions are MD5 and SHA-1. One may believe that MD5 is the stronger among the two due to its omnipresence, but SHA-1 is actually more secure. MD5 gives a 128-bit output while SHA-1 returns 160-bit. MD5 is typically used for file integrity checks while SHA-1 is more popular in situations where security is key, such as in IPSec.

Today we'll learn how to implement SHA-1 in Java. There are already packages that does the complex algorithms for us, so all we'll have to do is to implement the classes provided.

First we'll import the MessageDigest class:
import java.security.MessageDigest;

We then instantiate it:
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");

Notice that I put "SHA-1" as the parameter for the getInstance method. To change the hashing algorithm, simply change that parameter. The list can be found here.

After that, we can start adding the input we wish to hash. To do this, use:

message in this case is a String containing the message to be hashed. You can use various other data-types, as long as you cast them into byte. You can concatenate more input if you wish; simply call the update() method multiple times.

When you're ready, call the digest() method to retrieve the output:
byte[] messageDigestDigest = messageDigest.digest();

To show it in String form, concatenate it with a for-loop:
for (int i=0;i<messageDigestDigest.length;i++)

Debian 20

You can use Linux as both an NTP client or server. NTP is installed through:apt-get install ntp

NTP uses port 123. It synchronizes clocks and relies upon tiered systems (strata). You can sync with numerous NTP servers as well.

NTP is configured in:

To return the queue of NTP clocks:
ntpq -p

+ means usable as primary clock, and * means usable as secondary clock.

There are 16 strata, 1-16 where 1 is the most accurate (atomic clock). Each level of sync will increase the strata by 1. Define at least 3 NTP time soures for accuracy.

To force an NTP update, use:
ntpd -g

To add NTP servers, modify /etc/ntp.conf like this:
server 0.us.pool.ntp.org
server 1.us.pool.ntp.org
server 2.us.pool.ntp.org

Debian 19

DHCP uses port UDP:68 to request address information from the server. The server replies using UDP:67. DHCP lease information are stored in:/var/lib/dhcp3/dhclient.eth0.leases

To force a DHCP renew, use:

DHClient renews all interfaces by default, ignoring non-broadcast interfaces if possible. You can also specify interfaces like this:
dhclient eth0

To use ifconfig to reveal all interfaces, use:
ifconfig -a

To use ifconfig to set up interface, use:
ifconfig eth0
ifconfig eth0 netmask
route add default gw
ifconfig eth0 up

You can also configure sub-interfaces, like this:
ifconfig eth0:1

When Debian first starts, it reads:

The file contains the available interfaces and how to configure them.

To permanently switch an interface to use static address, modify /etc/network/interfaces. You should see the following code:
iface eth0 inet dhcp

Change it to:
iface eth0 inet static

We can also add additional nameservers by modifying /etc/resolv.conf:

You can also use ifup and ifdown to bring an interface up or down like this:
ifup eth0
ifdown eth0

Use the -a parameter to bring all up or down, like this:
ifdown -a

Debian 18

To determine if a remote host is alive, use:ping hostname

To change ping packet size, use:
ping -s 32 hostname

To change interval and count, use -i and -c parameters respectively.

To query open ports, use:
telnet hostname port

To look at network connection information from the kernel (/proc/), use:

/proc/ is stored in memory. By default netstat does not return listen sockets. To dump all sockets (for services based in /etc/services), use:
netstat -a

To dump all sockets without name resolution, use:
netstat -an

To dump all TCP sockets with programs:
netstat -ntlp

To dump all UDP sockets with programs:
netstat -nulp

To dump kernel routing table:
netstat -rn

To dump interface status:
netstat -i

To determine packet path, per-hop and round-trip times, use:
traceroute hostname

Traceroute makes use of the TTL field in IP.

An advanced version of traceroute is mtr (My Traceroute) which integrates ping as well:
mtr hostname

To resolve IP given a FQDN, use:
nslookup hostname

Dig is similar to nslookup, and it gives more output:
dig hostname

To perform a reverse lookup, use:
dig -x

To find information about a certain domain, use:
whois www.google.com

Thursday, March 4, 2010

Misc 2

Authentication for EIGRP is similar to RIP. First we create a key-chain as follows:key-chain KEYCHAIN
key 1
key-string cisco

Then we apply to the interfaces participating in EIGRP (which needs to be authenticated):
ip authe mode eigrp 10 md5
ip authe key eigrp 10 KEYCHAIN

Similar to RIP, we can do route summarization at any router through:
ip summary eigrp 10

We can have multiple route summaries.

PPP CHAP authentication can be done through:
encap ppp
ppp auth chap
ppp chap pass cisco
user R5 pass cisco

When other routers try to authenticate, his hostname is used. The local database is then checked for the password the opposite specifies with the "ppp chap pass" command. CHAP authentication can be one sided. You can also mix authentications.

You can create a definition for a specific range of interfaces through:
define interface-range DEFINE f0/1, f0/3, f0/5-6

You can then access the interfaces through:
int ran mac DEFINE

You can also create macros which do a list of commands, like:
macro name MACRO
in f0/1
sw m a
sw a v 5

Macros can be run from global or interface. From global, use:
macro global apply MACRO

From an interface, use:
macro apply MACRO

You can have parameters passed into macros, like:
macro name MACRO
in $1
sw m a
sw a v $2

To change f0/2 to vlan 35, simply:
macro apply MACRO $1 f0/2 $2 35

$1 and $2 can be anything, as long as they don't occur in the code unless you want it to.

If you want to input symbols like ? in password, use the CTRL+V escape character before the symbol like:

Misc 1

To configure an NTP master:1) Set the timezone
conf t
clock time SGT 8

2) Set the time
clock set 7:12:00 4 March 2010

3) Specify that the router is the master
conf t
ntp master

To specify an NTP server:
1) Set the timezone
conf t
clock time SGT 8

2) Specify the server
ntp server

To do NTP authentication, type this in global configuration:
ntp authenticate
ntp authentication-key 1 cisco
ntp trusted-key 1

If the logging happen to use the wrong timezone, manually set the service through:
service timestamp log datetime msec local
service timestamp debug datetime msec local

In RIP, to manually change the hop count of certain paths, we must first manually disable auto summary:
conf t
router rip
no auto

Next, proceed to create a standard access-list that matches the affected routes:
ip access-l standard OFFSET

Finally, apply the list to RIP as an offset-list:
conf t
router rip
offset-list OFFSET 8

Likewise, to prevent certain routes from coming in or out, create a standard access-list that matches the affected routes, then apply it as a distribute-list either inbound or outbound.

To do RIP authentication, first set all routers to use RIP version 2:
router rip
ver 2

Then create a key-chain:
key-chain KEYCHAIN
key 1
key-string cisco

Next, apply it the affected interfaces:
int f0/0
ip rip authentication mode md5
ip rip authentication key KEYCHAIN

To do route summarization in RIP, go to participating interface and type:
ip summary-address rip

To make RIPv2 use broadcast, go under the interface and type:
ip rip v2-broadcast

To use RIP unicast, specify all participating interfaces as passive:
router rip
passive-interface f0/0
passive-interface f0/2

Next, specify the neighbors you want to send unicast updates to:

To change RIP timers:
timers basic update invalid holddown flush

By default, update is 30, invalid is 180, holddown is 180, and flush is 60.

To restrict the version of updates allowed through an interface, go under the interface and type:
ip rip send version 2
ip rip receive version 2

Tuesday, March 2, 2010

Debian 17

Syslog is included in most Linux distributions. It features the ability to log daemon/service/application information. It can also log to and from other hosts in the network.
By default it listens to the Unix Domain Sockets. But you can also enable it to log from network messages via UDP 514. Syslog is run through the sysklogd daemon. Syslog automatically prepends messages with timestamp.

Syslog's configuration is in /etc/syslog.conf. It is also known as the rules configuration file. The syslog.conf file contains two columns. The left column contain the rules (facilities and levels), and the right column specifies the destination (file, pipe, program, remote host).

Facilities include:
3) LOCAL[0-7]
5) LPR

Levels are as follows:
0) Debug
1) Informational
2) Notice
3) Warning
4) Error
5) Critical
6) Alert
7) Emergency

*.* is a catch-all rule for ALL facilities and ALL levels. Anything .none will prevent messages from that facility from being routed to the destination.

We want syslog to listen to the internet socket. To do this, we add a -r into /etc/default/syslogd. There is a hint as to where to put the -r inside the file. After this, we need to restart sysklogd:
/etc/init.d/sysklogd restart

After that, confirm that sysklogd is listening to UDP 514:
netstat -nulp

To configure your box to send syslog messages to another system:
1) Configure it to listen to UDP 512
2) Modify the rules to route to another box
3) Restart syslog

For example, if I have a Debian listening to UDP 514 with the IP of, then I should have the following rule to send cron syslog messages to it:
cron.* @

You can also use host names like @debiansystem1, but we will need to update the /etc/hosts file: debiansystem1

Cisco routers typically send messages using the "local" facility. To log Cisco messages, add the rule:
local0.* /var/log/cisco

After doing this, do a restart. Then configure the router as shown:
conf t
logging host
logging facility local 0
logging trap 6
logging on

Logging is always done for the selected trap level and higher.

Monday, March 1, 2010

Debian 16

Runlevels are like distinct profiles. Runlevels range from 0-6, which are:0) Shut Down
1) Single-User Mode (No networking)
2) Multi-User Mode (Normal)
3-5) Multi-User Mode Alternatives
6) Reboot

Single-User mode is used for debugging, disk administration and updating the kernel.

Runlevels can be invoked using:
init #

You need to be a privileged user to run init. shutdown does init 0, but similarly you need to be root. The default runlevel can be found in:

The line id:2:initdefault: tells us that runlevel 2 is the default. Before booting into any runlevel, init first runs /etc/init.d/rcS which runs the first Run Control script.

If updates are made to /etc/inittab, you can update init through:
init -Q

/etc/init.d contains services/daemons that are run on the system. The Run Control scripts are referenced via /etc/rc# where # is for runlevel. Services in init.d tend to be BASH shell scripts with instructions on how to start, stop, reload, restart etc.

/etc/rc#.d contains symbolic links to services/daemons that are to be executed in the desired run-level. This directory contains K* and S* scripts. K* scripts stops services/daemons, while S* starts them. K* scripts are run before S*. Services are stopped or started in numeric order from low to high.

The K* or S* files are actually symbolic links of the script files found in init.d, and they are started or stopped based on K* or S*.

/etc/rc.local contain scripts that are to be run after any Multi-User mode. By default the script does nothing.

Cron scheduler lets you run tasks/jobs at predetermined times. Tasks can be per-user or system-wide. Cron is located in:

Cron can be run in all runlevels, and checks every minute for new jobs/schedules to execute. Cron can be used to run 'at' jobs, which executes at a specific time once. There are 4 classes for system-wide recurring jobs:

The system-wide cron table is at:

The per-user cron table is at:

There are 7 fields in the cron table:
1) Minute (m) 0-59
2) Hour (h) 0-23
3) Day of the Month (dom) 1-31
4) Month (m) 1-12
5) Day of the Week (dow) 1-7
6) User - The user to run the job as
7) Command - The full syntax for the command

To extract the date, use:
date +%Y%m%d

To create a script that runs every 5 minutes putting the load averages into a file named after the date, create a script like this:

uptime | awk '{print $8,$9,$10,$11,$12}' >> `date +%y%m%d`.txt

After setting the execute flag, it's time to add per-user jobs. If nano is not the default editor, use:
export $EDITOR=nano

Now, execute crontab to add per-user jobs:
crontab -e

That would run the default editor (which is set to nano now). To view a user's jobs, use:
crontab -l kelvin

To make it run every 5 minutes, use */5 for the minute field. We should have this in the crontab -e:
*/5 * * * * uptime | awk '{print $8,$9,$10,$11,$12}' >> `date +%y%m%d`.txt

To specify that the job should be run on specific minutes like:

You can also specify a range, like:

You can also specify an interval which we used above, like:

Cron supports any type of executable for a job including BASH, Perl, PHP, Python, etc.

Notice that in the /etc/crontab file, there is a reference to anacron. anacron runs programs that were not run either because of system failure or because the computer was not on at the time. The Administrator can also add system-wide tasks in the /etc/crontab file.

Debian 15

We will now go into how to add, remove, and maintain programs. The package system supports multiple package sources (CDs, DVDs, File System, HTTP, FTP). Applications like apt-get and aptitude automatically resolves dependencies. They also maintain a package repository database of all installed packages.
Applications to manage programs include dpkg*, apt-* and aptitude. Apt-get is a front-end to dpkg, and it is not interactive. On the other hand, aptitude is interactive.

You can list the packages installed on the system through dpkg:
dpkg -l

Typically, the output of dpkg -l is piped into grep to selectively show lines of interest.

To list the package a file came from, use:
dpkg -S filename

To see a package's status:
dpkg -s openssh-client

To display a list of files included in the package:
dpkg -L openssh-client

To install a package:
dpkg -i package1.deb [package2.deb...]

To uninstall a package:
dpkg -r package1 package2

In this example, we will install tofrodos, which converts a text file to and fro DOS format. In DOS systems, each line terminates with a CR/LF, but in Unix, lines terminate with LF. todos can replace all LF with CR/LF.

First, browse to debian.org. Click on Debian Packages, then search for "tofrodos". Download the tofrodos .deb package for your arthitecture.

Now, browse to the folder containing the file in a terminal, and use dpkg -i tofrodos... to install the package.

After installing, you can check if it's successfully installed through:
dpkg -l | grep tofrodos
dpkg -s tofrodos

A typical file name would look like:

The package name is tofrodos.
The version is 1.7.8.debian.1-1 (Major, Minor, Patch Release/Build)
The platform is i386
Package suffix is .deb

To use tofrodos to convert from *nix to DOS:
todos test.txt

After doing so, verify the file through:
file test.txt

To uninstall tofrodos, use:
dpkg -r tofrodos

The apt-get is a front-end to dpkg. It provides all features of dpkg, and also maintains a configuration file which contains package sources. The sources of apt-get is stored in /etc/apt/sources.list.

Package sources are arranged in the following categories:
1) Main - Free programs included with the production build of Debian
2) Contrib - Free programs that rely upon Non-Free programs
3) Non-free - Non-Free programs only

Free in this case represents not only the cost of the program, but also the availability of the source code (e.g. open-source).

By default, configuration settings of a program isn't removed when it is uninstalled through apt-get or aptitude. To clear those configurations (in /etc), use:
apt-get purge

To add a CDs/DVDs source, use:
apt-cdrom add

To install tofrodos using apt, use:
apt-get install tofrodos

To uninstall a package, use:
apt-get remove tofrodos

In Aptitude, you can search for packages through '/'. Aptitude tallies tasks (install/remove), then execute them sequentially. Aptitude trees are rearranged in the following manner:
-Node (Installed/Not-Installed etc.)
--Package Group (Administrative, Communication, etc.)
---Branch of Package (Main, Contrib, Non-Free)

Use the tasks node in Aptitude to install common classes of software, e.g. (Desktop Environment, Laptop, Server, etc).

Use + and - to add and remove packages from queue. Next, press 'g' to see the queue, and 'g' again to execute. Bolded packages are installed.

Debian 14

Logical Volume Management, or LVM, allows us to create abstractions of storage. Two different types of abstractions are volume sets and stripe sets. LVM allows consolidation of storage and presents a unified image of storage. It hides underlying storage technologies from file systems (You can combine IDE, SATA, SCSI, etc. as one storage unit).
Stripe sets improves performance by spreading data across multiple disks. LVM is also not recommended for doing RAID. The physical circuit on the motherboard is more suitable for this. After configuring RAID, you can overlay LVM on the RAID. LVM also allows resizing of partitions.

LVM is not installed by default. There are two packages required for LVM:
1) lvm-common
2) lvm2

There is an LVM storage hierarchy that comprises of Logical Volumes, Physical Volume Groups and Physical Volumes. The file system is configured at the Logical Volume level. The Logical Volume is similar to a partition in a non-LVM world. Volume groups represent one or more physical volumes (hard disks, partitions etc). Physical Volumes represent devices or partitions (e.g. /dev/sdb1). The physical volumes must be created as type 'lvm(8e)'.

The concept behind LVM is that physical volumes are first merged into one large volume group, then divided into many smaller logical volumes.

Here's a list of tools for use:
Physical Volumes - pv*
Volume Groups - vg*
Logical Groups - lg*

Replace * with create, display, extend, etc.

The 6 steps to create a LVM system are:
1) Create LVM partitions via fdisk
fdisk /dev/sdb

t changes the type and 8e refers to Linux LVM.

2) Create LVM Physical Volume
pvcreate /dev/sdb1

Use pvdisplay to confirm that you've created the physical volume.

3) Create Volume Group
vgcreate volumegroup01 /dev/sdb1

Similarly, use vgdisplay to confirm that you've created the volume group.

4) Create Logical Volume
lvcreate -L 4GB volumegroup01
lvcreate -l 100%VG volumegroup01

At this point, you should have a 4GB device node at:

5) Overlay the file system on /dev/volumegroup01/lvol0
mke2fs -j /dev/volumegroup01/lvol0

We can remove logical volumes through:
lvremove /dev/volumegroup01/lvol0

We can rename logical volumes through:
lvrename volumegroup01 lvol0 sales

To resize a logical volume:
lvresize -L 3GB /dev/volumegroup01/sales

To add more members into a volume group:
vgextend /dev/sdb2

We can enable striping through:
lvremove /dev/volumegroup01/sales
lvcreate -i 2 -L 8GB -n sales volumegroup01

Where -i specifies the number of disks to stripe across.

After we're done, remember to overlay the file system and map mount point in /etc/fstab.

Debian 13

Partitioning allows provisioning of additional space via mount-points. Debian features the Gnome Partition Editor which performs partitioning. To enumerate connected disks, and optionally partition them, use fdisk.
To enumerate a list of connected hard disks and partitions:
fdisk -l

Linux hard disks typically begins with hd[a-z] or sd[a-z]. hd stands for IDE drives, while SD represents SCSI or SATA drives. Partitions begin with numeric values after sd/hd, like /dev/sda1, /dev/sda2, /dev/hda1, /dev/hda2.

Hard disks must be formatted to be used. There are three steps to provision storage:
1) Create partitions
2) Create file systems
3) Mount file systems at a location in the tree (beneath '/').

Gnome Partition Editor is a GUI interface that does what fdisk does. The Gnome Partition Editor is called GParted.

We will now use fdisk to create 3 partitions, create 3 file systems, and then mount them automatically. To create the file systems, we need to use mk2fs to overlay the file system over the partitions.

To remove partitions using fdisk, use:
fdisk /dev/sdb
d 1

fdisk /dev/sdb will bring up an interactive prompt. d will delete the specified partition, and w will write changes.

To create a partition:
fdisk /dev/sdb

Enter the interactive prompt, create a new partition, choose primary, create partition 1, and start from first and last cylinder.

Now you would have an empty partition. We will now make the file system a journaling e2fs (e3fs). Use the following syntax:
mke2fs -j /dev/sdb1

To mount the file system, use:
mount /dev/sdb1 /var2

To automatically mount during boot, use:
nano /etc/fstab

Simply copy any existing entries and rename accordingly.

We will now focus on creating swap space for kernel and user applications. There are two forms of swap: Dedicated Partition, Dedicated File. It can be created within Primary or Extended partitions. Paging too much, however, will negatively affect system performance.

To create a swap partition:
1) Identify possible storage
fdisk -l
parted print
df -h

2) Calculate desired swap space based on physical RAM.
Swap Space =~ 1.5 * RAM

3) Create Partitions

4) Overlay partition with swap file system
mkswap /dev/sdb1

5) Turn on swapping
swapon /dev/sdb1

To see the current swap configuration:
swapon -s

To enable swapping on all partitions:
swapon -a

To disable swapping:
swapoff /dev/sdb1

To create a swap FILE on an existing partition, we first write zeroes to a file using the zero device:
dd if=/dev/zero of=/home/swapfile bs=1024 count=524288

Note that 524288 is 512*1024. This will create a 512MB file. Next, we use mkswap to make the file a swap file:
mkswap /home/swapfile

We then turn on the swap file:
swapon /home/swapfile

We then make sure that the file cannot be modified by anyone else except root:
chmod 0600 /home/swapfile

Update the fstab with new swap locations:
/home/swapfile swap swap default 0 0