Questions about this topic? Sign up to ask in the talk tab.

Gentoo Installation

From NetSec
Revision as of 15:13, 2 June 2012 by DPYJulietowbaijc (Talk | contribs) (CHROOT)

Jump to: navigation, search
RPU0j.png You are viewing an article in progress. This entry is unfinished.

Introduction

Gentoo is a source-based linux distribution, source-based means every application is compiled locally.

You can download a copy of Gentoo here

To install Gentoo, you will need to create a Bootable LiveCD or LiveUSB.

There are many ways one could create a LiveCD or LiveUSB, but that is outside of the scope of Gentoo Installation.

Virtual Machine Setup

If you are not using VM software like VMWare or Virtualbox, you can safely ignore this. Otherwise, make sure your VM has:

  • Around 512mb to a gig of RAM
  • At least 10GB HDD
  • Networking features enabled
  • Preferably multiple cores on an x86_64 processor

Hard Drive Setup

Enter the following:

<syntaxhighlight lang="bash"> ls /dev | grep sd cfdisk /dev/sda </syntaxhighlight>

cfdisk will proceed to enter into an ncurses gui.

Use cfdisk to:

  • Create 100MB Partition Bootable at the Beginning
  • Create 2048MB Partition at the beginning
  • Create remaining free space partition at the beginning

Choose to Write tables to disk, and then exit.

<syntaxhighlight lang="bash"> mkfs.ext2 /dev/sda1 mkswap /dev/sda2 mkfs.reiserfs /dev/sda3 mount -t reiserfs /dev/sda3 /mnt/gentoo ; cd /mnt/gentoo wget http://gentoo.arcticnetwork.ca/releases/x86/current-stage3/stage3-i686-20110614.tar.bz2 </syntaxhighlight>


For the below line, you can simply press the TAB button after stage3 and it will automatically complete the command, just press enter to confirm it:

<syntaxhighlight lang="bash"> tar xvpjf stage3* swapon /dev/sda2 cp /etc/resolv.conf /mnt/gentoo/etc/resolv.conf </syntaxhighlight>

Once your hard drives are set up, you are ready to proceed. Before continuing make sure you can access the internet.

You can test this by pinging google:

ping -c 2 google.com

If you are unable to access the internet, try the following:


c3el4.png You may need to do this each time you reboot, or set up a boot-up script to automate it.
   
ifconfig eth0 down && ifconfig eth0 up
dhcpcd eth0

Base installation and Configuration

c3el4.png Remember the number in the output of this command, you will need it later.
grep -ci "processor" /proc/cpuinfo

Download & Extract portage to /mnt/gentoo/usr/

cd /mnt/gentoo/usr/
wget http://gentoo.arcticnetwork.ca/releases/snapshots/current/portage-latest.tar.bz2
tar xvjf portage-latest.tar.bz2

Open make.conf in nano.

cd /mnt/gentoo/etc/
nano make.conf

Modify make.conf as follows:

RPU0j.png Do not modify the CHOST, this will cause problems!
 CFLAGS="-fstack-protector-all -fforce-addr -Os -pipe -march=native"
    CXXFlags="${CFLAGS}"


    FEATURES="metadata-transfer sandbox candy parallel-fetch"

    USE="gtk truetype postgres freetype jpg jpeg png gif imap ttf winscp passwd scp X gnutls mysql v4l2 extras lisp threads ithreads acpi bash-completion bzip2 crypt cracklib css ctype apache2 curl curlwrappers dbus encode ftp gcj gd geoip udev ipv6 lua ncurses nsplugin python readline sockets socks5 sqlite sse sse2 ssl suid unicode vim-syntax xml php perlsuid"

    #Replace Y with the output of the grep command and X with the returned number +1. For one core, you'd have "--jobs=1" and "-j2".

    MAKEOPTS="-jX -s"
#   Only use the below line if you have a multicore CPU or multiple processors
#   EMERGE_DEFAULT_OPTS="--jobs=Y --load-average=1.5"
    PORTAGE_NICENESS="12"

Now press ^x Y Enter to save and quit, this is CTRL+X -> Y -> ENTER

CHROOT

c3el4.png You will have to return to this part each time you reboot until the installation is finished.


<syntaxhighlight lang="bash">

   mount /dev/sda3 /mnt/gentoo
   swapon /dev/sda2
   mount /dev/sda1 /mnt/gentoo/boot
   mount -o bind /dev /mnt/gentoo/dev
   mount -t proc none /mnt/gentoo/proc
   chroot /mnt/gentoo /bin/bash --login

</syntaxhighlight>

You only need to run gcc-config the first time around.

gcc-config 1 
env-update

The following line helps remember where you are.

export PS1="chroot) $PS1"

Installing Software

This requires a working internet connection, test your connection with ping:

 ping -c2 google.com

If you cannot ping, try issuing the following:

echo nameserver 4.2.2.1 > /etc/resolv.conf
echo nameserver 4.2.2.2 >> /etc/resolv.conf

Sync your repos:

 emerge -q --sync

if it tells you that an update to portage is availible then do the following

 emerge -q portage

otherwise, continue from here:

emerge -q axel

Let's edit make.conf again:

nano -w /etc/make.conf
# put this at the bottom of make.conf
FETCHCOMMAND="/usr/bin/axel -n 8 -o /\${DISTDIR}/\${FILE} -a \${URI}"
RESUMECOMMAND="/usr/bin/axel -n 8 -o /\${DISTDIR}/\${FILE} -a \${URI}"

Press CTRL+X -> Y -> ENTER to quit

Now that you're package manager is set up, execute the following command:

emerge -qN pciutils coreutils baselayout hardened-sources world


Encrypted Home Dir

create /crypt/ directory to store home.dm

mkdir /crypt
touch /crypt/home.dm

Install cryptsetup

 
echo "sys-fs/cryptsetup static-libs" >> /etc/portage/package.use
emerge -q cryptsetup


replace XXX in the command below with the size in GB (Gigabytes) you want your home to be. if you are not sure, run 'df -h' and use perhaps a quarter of the size of sda3

  
dd if=/dev/zero of=/crypt/home.dm bs=1024 count=$(head -1 /etc/make.conf|awk '{print XXX * 1024^2}')
losetup /dev/loop1 /crypt/home.dm
cryptsetup luksFormat -h whirlpool -c blowfish /dev/loop1
cryptsetup luksOpen /dev/loop1 home
emerge -q reiserfsprogs
mkfs.reiserfs /dev/mapper/home
mount -o loop /dev/mapper/home /home

open /etc/init.d/home in nano: nano /etc/init.d/home


make the file look like this:

#########
#!/sbin/runscript
# Copyright 1999-2011 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: $
depend() {
true
}
start() {
losetup /dev/loop1 /crypt/home.dm
cryptsetup luksOpen /dev/loop1 home
mount -o loop /dev/mapper/home /home
}
stop() {
umount /home
cryptsetup luksClose home
losetup -d /dev/loop1
}
restart() {
stop
start
}
##########


Once you're done with that:

chmod +x /etc/init.d/home
rc-update add home default
c3el4.png If you have rebooted, do the following:
mount /dev/sda3 /mnt/gentoo
mount /dev/sda1 /mnt/gentoo/boot
swapon /dev/sda2
mount -t proc none /mnt/gentoo/proc
mount -o bind /dev /mnt/gentoo/dev
chroot /mnt/gentoo /bin/bash --login

Kernel

RPU0j.png DOUBLE CHECK THAT YOU ARE IN A CHROOT BEFORE DOING THIS! ls /mnt/gentoo should return FILE NOT FOUND
c3el4.png If ls /mnt/gentoo returns something other than file not found, do the following
mount /dev/sda3 /mnt/gentoo
mount /dev/sda1 /mnt/gentoo/boot
swapon /dev/sda2
mount -t proc none /mnt/gentoo/proc
mount -o bind /dev /mnt/gentoo/dev
chroot /mnt/gentoo /bin/bash --login

Otherwise continue on here:

cd /usr/src/linux
groupadd audit 
grep audit /etc/group 
groupadd blackhole 
grep blackhole /etc/group
RPU0j.png confirm you get stuff returned to you after each grep. these numbers you're seeing are GIDs for RBAC
 
groupadd clients 
grep clients /etc/group 
groupadd services
grep services /etc/group


RPU0j.png Again, confirm you are getting information when you grep. you probably want to write those id's down
wget http://paste.pocoo.org/raw/430946
mv 430946 .config

Now you can

emerge -q wgetpaste
lspci -n | wgetpaste

Open provided url in browser, paste into the following website or:

passwd

Now type in a password twice.

To start the SSHD run:

/etc/init.d/sshd start

download PuTTy on your main/host pc and use it to connect to the ipaddress of the vm/box, you can find out the ip with

ifconfig

you connect on port 22 (ssh)

lspci -n

copy and paste this to the following website: http://kmuto.jp/debian/hcl/


if you need to, take a note of each entry under 'drivers'

make menuconfig

search for 'dm_crypt' with the / key from the main menu - this should open a search box. you will see the location of dm_crypt in the menu, and whether it is [=y] (enabled) or [=n] (disabled) you want to find it and enable it. do not set it as 'M', that will make it a module and for security reasons you are not using loadable modules. do this for each driver on the above website, and make sure that they are all enabled some, such as graphics, can be safely missed out (get vesa, instead) - if you have any worries, ask in #questions on irc replace every - in a driver name with a _

Also, verify that all the following settings are correct:

  • Disable loadable module support
  • Disable virtualization on the kernel
  • Under general options, change kernel compression mode to lzma
  • Under processor type and features, you'll want to either A. Put the processor type, if it's in the list or B. Select generic if unsure
  • In filesystems, you only want reiserfs depending on how you set it up. You do not want ext2 -- if it is enabled, (Second Extended FS Support), DISABLE THIS.
  • Under security options, enable grsecurity
  • Under address space protection
  • Enable active kernel exploit response
  • Under RBAC,enable 'Hide Kernel Processes'
  • Under filesystem protections, restrict /proc to user only
  • Under kernel auditing, enable every option except 'ELF TEXT Relocation
  • Put the gid to 'audit'
  • Enable everything under network protections
  • Put the gid to 'services' in 'deny client sockets for group' gid
  • Put the gid to 'clients' in 'deny server sockets for group' gid
  • Put the gid to blackhole in the 'deny all sockets to any group' gid
  • Under logging options, "Add source ip addresses to AVC SeLinux messages"
  • Under pax control, change 'MAC system integration' to hook
  • Under misc. hardening features, You'll want to enable everything
  • Under non-executable pages,Enforce non-executable pages' is enabled
  • Back in the main security options window, enable 'Restrict unpriviledged access to the kernel syslog'
  • Enable Integrity Measurement Architecture
  • Under cryptographic api, we want aes of all flavors, whirlpool, and blowfish
  • Uncheck the Hardware Crypto Devices support
  • Under device drivers -> multi device support, enable dm_crypt
  • Block devices ->loopback device support, enable cryptoloop support
  • Under kernel hacking enable strict copy size checks and disable kernel debugging
  • Under kernel hacking disable kernel debugging
  • Put the gid to 'audit' in the proc gid as well as the kernel auditing pid

now exit, saving the config

put the number of processors you have +1 instead of ?, for example -j5 if you have 4 cores

make -j?

make sure boot is mounted, this should NOT say file not found, exit from chroot and remount /mnt/gentoo/boot, then chroot in again if you get an error

ls /boot

Replace XXX below with your architecture (x86 for 32bit, x86_64 for 64bit)

cp /usr/src/linux/arch/XXX/boot/bzImage /boot/bzImage

if you ever need to repeat this, make clean before reconfiguring your kernel and adding/removing stuff You can read much more about kernel configuration at http://kernel-seeds.org, this website contains premade, stripped kernels and step-by-step guides on configuring your own kernel from scratch, with detailed notes on every option. It's great to check out if you are unsure about anything, and will really help the learning process.

Final Configurations

Install the syslog-ng, vixie-cron, strace, gdb, ruby, and nemesis by issuing

 emerge -q syslog-ng vixie-cron strace gdb ruby nemesis

Once emerge finishes, fill in your mtab:

  grep -v rootfs /proc/mounts > /etc/mtab 



Replace "XXX" below with either "x86" or "x86_64" depending on your processor architecture. (32bit, 64bit. respectively.)

  cp arch/XXX/boot/bzImage /boot
    nano /etc/fstab
    change the ROOT and SWAP lines to look like the following
    /dev/sda3               /               reiserfs                noatime         0 1
    /dev/sda2               none            swap           sw              0 0
    

delete the /dev/BOOT line and CTRL+X -> Y to exit.

Bootloader

Install the GRUB Bootloader

   emerge -q grub

Install grub to /dev/sda

   grub-install --no-floppy /dev/sda


Now it's time to edit our grub configuration

   nano -w /boot/grub/grub.conf

uncomment the splash image and ensure the below is in the file

   kernel /boot/bzImage root=/dev/sda3
   root (hd0,0)

Exit by hitting CRTL+X, then Y.

Set your root password.

   passwd root


   emerge -q pump
   rc-update add vixie-cron default
   rc-update add syslog-ng default
   rc-update add home default
   source /etc/profile
   env-update

now exit from the chroot for the final step

exit and ensure you have all the device nodes you need

   umount /mnt/gentoo/dev
Notice: make sure you do NOT accidentally umount /mnt/gentoo above, we just want to umount dev!
   cp -a /dev/* /mnt/gentoo/dev/

Once that is done, restart your system.

After restarting, we need to get networking up and running.

   ifconfig eth0 down && ifconfig eth0 up
   pump -i eth0

to get the network working, you may need to overwrite resolv.conf as mentioned earlier

   echo nameserver 4.2.2.1 > /etc/resolv.conf
   echo nameserver 4.2.2.2 >> /etc/resolv.conf

c3el4.png 4.2.2.1/2 are DNS servers, one could use Google's public DNS servers as well, which are 8.8.8.8 and 8.8.4.4
   # install vim
   emerge -q vim
   # or emacs
   emerge -q emacs
   # and you'll have to look up a tutorial on these yourself or ask for help in choosing in #questions :) try getting vim and typing vimtutor



X Server

RPU0j.png Never run the X Server as root!
c3el4.png Make sure your home directory is encrypted before we begin
nano /etc/make.conf

Add the following line with the correct driver for your card, ie. noveau for nvidia, radeon for radeon, vmware for vmware, virtualbox for virtualbox or intel for intel:

VIDEO_CARDS="driver"

Also add the following line if you are on a PC or VM:

INPUT_DEVICES="evdev"

Or this line if you are on a laptop:

INPUT_DEVICES="evdev synaptics"
  • Make sure that the correct driver for your graphics card is built into the kernel, return to the kernel section to do this if you have not already.
  • Make sure you have udev in your USE flag in /etc/make.conf

now to install the X server and window manager

emerge -q xorg-drivers
emerge -q xorg-server
emerge -q fluxbox
emerge -q aterm # transparent terminal!
emerge -q conky # system monitoring tool
emerge -q sudo

Now edit /etc/sudoers to your own preference, you only need to remove the comment before the %wheel sudo access with NOPASSWD, OR the one using password. make sure to add the user to the wheel group with

gpasswd -a wheel username

Also add the following line:

  • 32 bit users:
%wheel ALL = (firefox) NOPASSWD: /usr/lib64/firefox/firefox
  • 64 bit users:
%wheel ALL = (firefox) NOPASSWD: /usr/lib32/firefox/firefox

To make fluxbox start with the x server:

mkdir -p /etc/X11/xinit
echo "exec startfluxbox" > /etc/X11/xinit/xinitrc

For virtualbox, check out <a href="http://en.gentoo-wiki.com/wiki/Virtualbox_Guest">http://en.gentoo-wiki.com/wiki/Virtualbox_Guest</a> for a guide to enable copy-paste between host/vm etc.

/etc/init.d/udev start
rc-update add udev sysinit

If you don't have a basic user account already, make one now.

now exit from root, login as a normal user and type:

startx

This will run the x server.

O a terminal by right clicking and choosing to open xterm

sudo useradd -m -G clients -U firefox
c3el4.png The following script is a little buggy and prevents firefox from launching if it takes more than 1 second for it to read the Xauthority file, so if that happens just bump up the sleep value.

You could also create sandfox in your ~/bin as described under the security section below, in that case just replace /usr/bin/sandfox with ~/bin/sandfox from now on.

sudo nano /usr/bin/sandfox

Add the following:

cp $HOME\/.Xauthority /tmp/$USER\.firefox.Xauthority
chmod 777 /tmp/$USER\.firefox.Xauthority
( ( env XAUTHORITY=/tmp/$USER\.firefox.Xauthority sudo -u firefox /usr/lib64/firefox/firefox $1 & ) & )
sleep 1
rm /tmp/$USER\.firefox.Xauthority

Now to make it executable

sudo chmod +x /usr/bin/sandfox
c3el4.png All history and profiles will be saved in firefox's home directory instead of yours, take note of this. you can pass paramaters such as -private by running, eg /usr/bin/sandfox -private
sudo mkdir -p /etc/portage
sudo echo "www-browser/firefox hardened" >> /etc/portage/package.use
sudo emerge -q tint2 tintwizard
nano ~/.fluxbox/init

Change change session.screen0.toolbar.visible: to false

To enable dropshadows and fading:

sudo emerge -q xcompmgr
~/.fluxbox/startup

Add, at the end of Applications you want to start with Fluxbox:

xcompmgr -c -r 6 -f -D 5 -t -9 -l -9 & 
tint2 &

Make sure the last line is exec fluxbox

nano ~/.fluxbox/menu

Change every occurance of xterm to 'aterm -tr -trsb -sh 40' without the , if xterm is being used to execute something else, add -e so 'aterm -tr -trsb -sh 40 -e sudo -s' for an automatic root terminal.

Add sandfox, it should be pretty easy to figure out.

For fluxbox themes you can check out box-looks.org.

BASH

Part 1: Reading files

Cat The basic file reader is cat. Cat means conCATonate, and it displays a file. It doesn't actually alter the displayed text in any way, so is useful for small files, but does not scale well.

More A step up from cat is the more command. It allows you to read page by page. Extended versions can allow searching aswell

Less The less command is again, one step up from more. Less is a newer version of more that allows for scrolling. This is great for larger files and logs that won't fit in the backbuffer.

Head & tail head and tail will display just the first or last couple of lines, depending on the value of the -n switch you pass to them. tail -n 2 /etc/passwd, for example, will show the last two lines from the file /etc/passwd. You can use head and tail in more advanced ways, for example tail -n +2 will skip the first line of a file.

Grep Grep will find patterns in files, ie. grep root /etc/passwd will find any lines in /etc/passwd that contain root and print them to stdout (standard out, ie they will be pritned on the screen by default).

Part 2: Navigation

cd cd is to change directory, using cd /usr/src/linux will set your current working directory (viewable in prompt or with pwd) to /usr/src/linux, or cd ~ will set your working dir to /home/<youruser>


Other useful commands

touch [filename] &&

This will create the named file if it doesn't exist, or exit if it does exist and is read only. Otherwise it updates the timestamp.

time [command]

This will 'time' the command, it will give you the cpu time in real terms that it took to execute that command, allowing you to do a sort of rudimentary benchmark.

tac [filename]

This will print a file in reverse, tac is to tail what cat is to head.

Directing output

To file:

Using > or >> you can direct stdout (standard output, ie text) to any file. > will overwrite any currently existing file, >> will append the text to the end of an existing file or create a file if it doesn't exist. An example is
lspci > hardwaredevices
or
man bash >> /root/bashmanual

To another command:

Using | (a pipe), you can direct the output of one command to another, and even chain multiple commands together, using both pipes and appends/overwrites. An example of this would be
cat /usr/src/linux/.config | wgetpaste | grep pocoo >> kernelurl
(this would print your kernel config to wgetpaste, which would upload it and print a url and some extra info. Only the url line would match the grep, and this line would be added onto the end of the kernelurl file in the current working directory.

Screen

Screen is a useful terminal multiplexer, similar to BSD's tmux. It allows you to open multiple virtual console sessions in the same shell, and detach-attach to them at will. Sessions in screen preserve through logouts and connection drops, in fact, it's very hard to lose a session unless you shutdown the machine. Screen sessions are extremely useful when connecting to a server through ssh, as if you lose your session you need only re-attach to your screen.

To start using screen, you must first install it:

emerge -q screen

Now start a screen session called 'testsession'

screen -S testsession

A new terminal will open - this is your screen session. Press the following key combination:

CTRL+a then d

The terminal will disappear - don't worry, it's just running in the background. List your screens with:

screen -ls

Notice the numbers.testsession - this is the ID of your screen session. Since you only have 1, you can now reattach to it with:

screen -r

Now create another tab in your screen. Use the following key combination:

CTRL+a then c

Check the window list:

CTRL+a then SHIFT+' # ie. CTRL+a then "

Notice the pattern? CTRL+a tells screen to wait for a command. You will now have a list of windows, showing your terminals. Choose one and press return to switch to it.

    ls -l

    CTRL+a then "

    CTRL+a then SHIFT+a

You can now give your current tab a name - call it 'ls' or something. Note that if you forget any of these commands, you can type:

    CTRL+a then ? 

for a list of commands

You can now switch between your screens, start some new ones. Let's go off on a tangent for now:

pwd

This shows your current working directory, where you are at the moment. You can type ls -l to list the files in this directory - you probably know this already. You may not know, though, that the prompt is stored in an environment varible - PS1. Let's change this, just because we can - this only lasts as long as your session (ie. until you exit screen or logout)

export PS1="test! $PS1"

What we did there was tell our system to change the prompt to test! followed by what it was previously. You can add many useful things to your prompt, and save changes by adding the above line in your ~/.bashrc, but let's stick to screen for now.

    CTRL+a then n
    CTRL+a then p

These commands switch between tabs on screen - n for next and p for previous. These are useful for quickly switching between screen windows, without worrying about names or menus.

CTRL+a then d

Now you've detached from your screen. It's still there, so we can return to it at any time we want. Sav has provided some useful scripts at this point: http://slexy.org/view/s2iSNjfnfr and http://slexy.org/view/s2ODvLiUFo, if you feel comfortable about it, adapt them to your environment and distribution.

Back on screen, here's a useful real life example: You were attached to your screen over an ssh connection, and it dropped. screen -r isn't letting you back on, because it thinks your screen is still attached.

screen -x screenname

The above command will attach you back to the screen, but it won't detach it from the dead session. If your ssh crashed due to an issue with the screen, the crash might happen again! You don't want this, so let's do this one instead:

screen -Dr

-D stands for DETACH and -r stands for reattach. -Dr is just a compound command that detaches it from the old session and reattaches it - think of it as screen doctor to remember it easier.

CTRL+a then k

The above will KILL the screen. Use this if it crashes - it only kills the window or tab you are on, so it won't destroy your other tabs. At this point, xochipill suggests checking out ratpoison which is the screen equivilent in X windows. doxtor suggests looking at tmux as an alternative or to use alongside screen, as it offers vertical and horizontal window splitting, whereas screen only offers horizontal by default. We'll explain window splitting soon. tmux also uses CTRL+b as opposed to CTRL+a in screen, so commands do not conflict with each other. doxtor suggests that in a dual setup you use tmux locally and screen remotely, ie screen on ssh and tmux on your laptop.

screen -S testsession2
CTRL+a then d

Now you want to actually specify which screen we want to connect to, because we have multiple ones. You can use screen -r xxxxx.testsession with the full number from screen -ls, or just use screen -r testsession.

screen -r testsession

This is especially useful if you are, for example, talking in irc and debugging a web server at the same time - you can have all your webserver stuff on the webserver screen, with tabs open for each log, and irc client with a log parser and client config in the irc screen.

CTRL+a then SHIFT+s

This will split the screen, as we mentioned earlier. It will split it into two screens, horizontally.

CTRL+a then TAB

You just switched to the other window in the split screen! This is a great way to multitask, maybe watch a log while you try sending emails to your webserver. Great for comparing information, too.

    CTRL+a then +
    CTRL+a then -

These commands are used to resize the current partition, making it vertically bigger or smaller. You could, for example, make a small prompt to emerge python > pythoncompilelog.log in while you tail -f pythoncompilelog.log in the larger parition!

To delete or close a screen, you just need to exit until it closes - if, for whatever reason, you can't then:

CTRL+a then k

and the screen window/tab will be killed, along with any program running within it. Another useful thing is multi-user screen sessions! razor elaborated on this after the class:

    CTRL+a then :
    multiuser on
    CTRL+a then :
    acladd username

username above should be the username of the user you want to access the session.

Now you just need to ask that user to:

    screen -x yourusername/yourscreenname

...and they will be on the same screen! This is useful for collaborative stuff, or a quick tutorial on a console-based program.

Services

Services are stored in /etc/init.d/ in files called runscripts, these are just shellscripts made to start, restart and stop applications. Applications run at different runlevels, anything from 0 (shutdown on nearly all Linux systems, 5 on some UNIX systems) up to 6 (reboot on Linux systems). The default runlevel is 3 on gentoo, you can type runlevel to see your current runlevel. init 0 will shutdown, as will shutdown or halt. init 6 will usually reboot.

To set up services in specific runlevels, use rc-update on gentoo. rc-update add script default will add script to run on the default runlevel (3 in gentoo). init 0 is always halt and init 6 is always shutdown, generally the next init is single-user mode, the one after that is single-user mode with networking and the one after that is multi-user mode with networking. In some configurations, though not by default, one of the init levels becomes a kernel state which provides a direct command line interface to the kernel itself.

rc-update add networking 5
will add networking to runlevel 5,
rc-update del networking 5
will remove it from runlevel 5. If you write a script in /etc/init.d, you will need to ensure that it is executable - ie.:
chmod +x /etc/init.d/scriptname
To add something to the default runlevel, you can rc-update add script default (which is, in this case, 3). rc-update will refuse to change the runlevel of a script.

The common /etc/init.d runscript commands are start, stop, restart and status (and often reload). There may be others too, just run /etc/init.d/scriptname for a list.

Network Services

Once your networking is up and if you have internet or LAN connectivity, you can track connections with netstat. Unfortunately, netstat is pretty illegible if you're not used to the syntax so start with.
netstat -pant
this will tell you the IPs, pid and process name of TCP connections (TCP is the most common connection-orientated protocol used on the internet).

Note that on most processes, such as apache or sshd, you can kill a connection by killing the pid of it's process, without taking out the whole daemon and killing services for the other users.

To see a list of services that are listening for connections on your system, use:
netstat -pant | grep -i listen
Grep is a useful little program that filters text, in the most basic use it grabs lines of text containing specific patterns. The -i switch makes the grep command case insensitive.

Debugging Services

When you are debugging a service, use the 'start' function and run netstat with the grep for listen. If the service shows up, but there are still issues, the problems are likely in the server configuration. Otherwise, there may be issues with the configuration of the service itself. Using strace helps to debug services, if you look for ENOENT within the output of strace you may see permission denied or files don't exist errors that you have to correct manually. You can look at the script and edit it with emacs or vim to confirm the exact commands the script is trying to run, e.g. if cryptsetup luksOpen /dev/loop1 home is in the start function then you may want to strace -s 2000 cryptsetup luksOpen /dev/loop1 home and read it from the end back.

If a file doesn't exist, it may mean that you need to symlink a library in /lib or /usr/lib. For example, if a script is looking for glibc.so.1.2 and you only have glibc.so.1.3 (locate glibc.so or find /lib -iname glibc.so) you could do something like ln -s /lib/glibc.so.6.1.3 /lib/glibc.so.6.1.2 which would create a shortcut or link to the file, directing any queries for it to your glibc.so.6.1.3.

We mentioned file permissions earlier, this is a very important concept in Linux - you have three sets of permissions, the user that owns the files, the group that owns the files and everybody else. For each of these, you have read, write and execute. To change permissions on a file, you can use one of two formats - chmod u=rwx,g=rx,o=r filename or chmod 751 filename. You can see that the first one is easier to use (u stands for user, rwx for read write and execute, for example), but you really should learn the octal permissions - these are pretty simple. 4 is read, 2 is write, 1 is execute and 0 is nothing. To create the numeric permissions, just add them together - 7 for read, write and execute, 6 for read and write, 3 for write and execute for example. You could then chmod 763 filename to give owner rwx, group rw and others wx. chmod 0 with chown root:root (chown takes ownership for a file for user:group) will lock a file permenantly, or until the root user unlocks it.

Permissions & Security basics

Changing permissions to your home folder to 750, a common mask for /home/username, will ensure that nobody that is not in your group or is not you can access it (aside from root, that can access anything). One of the main reasons for not using a root account all the time, is that it ensures that you do not accidentally modify files that you would not normally have the permission to.

Note that in security, more functional means less secure - being secure is not about a couple of commands, it's a whole philosophy of computer use - you must ensure that you do not enable functionality that you don't need.

In your home directory, you should create the file .bashrc and add the following line to it:

unset HISTFILE ; unset HISTSAVE ; unset HISTFILESIZE ; unset HISTCONTROL ; unset HISTCMD

this will unset all the environment varibles related to bash history, so your commands will not be logged in .bash_history. If you want to add scripts and commands into your home directory, do the following:

# ~ is simply an alias to the current logged in user's home directory
mkdir ~/bin
vi (or emacs) ~/.bashrc
### add the below to your .bashrc, replacing yourusernamehere with your username
export PATH="$PATH:/home/yourusernamehere/bin"

You will need to remember to chmod +x every script you put in ~/bin, or it will not execute. You could also chmod 750, so that owner gets rwx, group gets rx and others get nothing.

To get general information about the system, try the following:

For information on network interfaces and configuration:

ifconfig

Hardware devices connected to the system:

lspci
lsusb

Kernel and architecture information and version:

uname -a

loaded drivers. none when you don't have modules enabled in kernel:

lsmod

See logged in users:

who

login history:

last
lastlog

running processes:

top
ps faux

RAM usage:

free -m (in MB)
free -g (in GB)

HD usage:

df -h

permissions:

file [filename]
stat [filename]
ls -lash 

filesizes:

du -sh

/proc contains a lot of this information - for example, /proc/version always contains the kernel version and /proc/modules always has module information (when it's compiled within the kernel). /proc even has memory maps, open files, cpu information (/proc/cpuinfo) and ram information (/proc/meminfo) etc.

If you have any problems with devices, you can type dmesg | less then scroll around with the arrow keys, and hit q to exit when you are done. This has a lot of general hardware operational information and is a great resource for debugging. You can search in less with /, just like menuconfig.

One command that is often used to watch files for changes is tail -f filename. This will keep updating the file within the window, so you don't need to continually cat or less it, which is very useful in cases such as debugging a php script, as every refresh will automatically update the apache log. It's most useful when used in conjunction with software such as tmux or screen, which will be covered later.

Remember that Fluxbox/Gentoo/Linux are not Windows. Not everything will be in the same place, look the same or even neccessarily be compatible - you've really got to hand-pick what you install, to make sure you don't pull a load of unnecessary stuff or break your system. Just be careful, get one package at a time. Don't be afraid to remove things if they're not to your liking, there's almost always multiple ways to do things. And you will always need to configure as you go, there's few 'drop-in' programs - one of the main benifets of using a Gentoo Linux system is it's customization, which isn't hampered in the least by taking a security perspective.


Getting Help

Type man command (command being the command you want help on) for a manual page, these are generally very verbose but will most likely contain what you're looking for. If you don't know exactly what command you want, try info coreutils. You can use the arrow keys to navigate topics, and press enter to select one to read more about it. If the man command takes you to the manpage for bash, try the help/info command - help read or info read, for example.

A great place to find guides for most common applications online is the gentoo wiki. You can find this at http://en.gentoo-wiki.com/. Other good places are the gentoo forums at http://forums.gentoo.org/ and the Gentoo Handbook at http://www.gentoo.org/doc/en/handbook/.

Troubleshooting

  • Unbootable disk error
   You need to do the grub part above, again.
   
  • Hangs on boot

These are usually caused by a bad kernel, cd to /usr/src/linux and make clean then try reconfiguring the kernel, be careful so you don't miss anything

  • Disk errors

If you get an error using cfdisk, type fdisk /dev/sda then o then w and this will wipe the disk to try again.

  • Errors after deleting encrypted storage

If you get problems after creating and deleting a crypted store, try rebooting after you've deleted it and rc-update del home default. remember to rc-update add home default again when you're done setting it back up.

  • Problems with emerge
If you get emerge errors, first check your make.conf to ensure it's as above. Now, try env-update && emerge -qN $PACKAGE ($PACKAGE being the package(s) you are trying to emerge, ie. emerge -qN screen). If this doesn't work, try revdep-rebuild or if the problem has perl in it, try perl-cleaner reallyall. If you get a python problem, try python-updater and to ensure GCC is working use gcc-config -l (if you get an error about not being able to build executables, GCC needs fixed - try gcc-config 1 && emerge -qN gcc after fixing make.conf). Another thing to try is FEATURES="-sandbox -usersandbox" emerge -q sandbox then attempting the emerge again, if this works make sure to echo "sys-apps/sandbox -sandbox -usersandbox" >> /etc/portage/package.use to ensure you don't break portage on upgrading sandbox.
  • Problem emerging cryptsetup

If you get a package mask (static-libs) error while doing emerge -q cryptsetup, try the following commands:

    mkdir /etc/portage
    echo "sys-fs/cryptsetup static-libs" >> /etc/portage/package.use
    env-update && emerge -q cryptsetup
  • General problems with emerging mesa

Unfortunately, it seems that the mesa package is not happy with -fstack-protector-all. Although we do NOT reccomend this (for security reasons) it is possible to install mesa by removing this from your CFLAGs in make.conf and recompiling the system. We do NOT recommend this, please wait for a better fix.

  • Problem emerging mesa on vmware

Check your build log (emerge should tell you where it is) and see if it gives you an error about XML parser, if so you may need to emerge XML_Parser


Gentoo Installation is part of a series on administration.