Monthly Archives: October 2011

Linux counter client

http://linuxcounter.net
http://linuxcounter.net/user/207256.html

Register new machine and get LiCo “Machine ID” and “Update key”.

1. Login to your profile.

userid 207256
password xyz

2. Add user cron to launch Linux counter update script.
useradd -m cron

3. Install lico-update.sh script.

cd /usr/local/bin
wget -N --no-cache https://github.com/alexloehner/linuxcounter-update-examples/raw/master/_official/lico-update.sh
chown root:root /usr/local/bin/lico-update.sh
chmod 755 /usr/local/bin/lico-update.sh

4. Install cron.d job.
/etc/cron.d/linuxcounter

00 21 * * 0 cron /usr/local/bin/lico-update.sh -m >> /var/log/lico-update 2>&1
30 21 1 * * root /usr/local/bin/lico-update.sh -update && chmod 755 /usr/local/bin/lico-update.sh>> /var/log/lico-update 2>&1

chown root:root /etc/cron.d/linuxcounter
chmod 644 /etc/cron.d/linuxcounter
touch /var/log/lico-update
chown root:cron /var/log/lico-update
chmod 664 /var/log/lico-update
mkdir /root/.linuxcounter/
ln -s /home/cron/.linuxcounter/$(hostname) /root/.linuxcounter/

5. Register new machine, choose option [1] Create a new machine in your linuxcounter account.

su cron -
/usr/local/bin/lico-update.sh -i
cat /home/cron/.linuxcounter/$(hostname)
/usr/local/bin/lico-update.sh -m

Upgrade from version 0.3.20 to 0.0.4 😉

Proceed with steps 3. and 4. above.
Copy your ApiKey from your Profile.

su - cron

Keep your “update_key” and “machine_number” from already registered machine.
grep 'update_key\|machine_number' /home/cron/.linuxcounter/$(hostname)

/usr/local/bin/lico-update.sh -i

Choose option [3] Rescan the system and replace the current configuration with the scanned data.

Open your favorite editor:
vi /home/cron/.linuxcounter/$(hostname)

Use your “update_key” and “machine_number” you got above:

update_key='xxxxxxxxx'
machine_number='nnnnnn'

And paste values in new variables “machine_updatekey” and “machine_id”.

machine_updatekey=""
machine_id=""

Send new data to server:
/usr/local/bin/lico-update.sh -m

As user #root try script update function:
/usr/local/bin/lico-update.sh -update && chmod 755 /usr/local/bin/lico-update.sh

DynDNS Linux client

http://www.dyndns.com
janfai / moc]tod[liamgnull]ta[xiaf.naj

Linux Update Client
http://dyn.com/support/clients/linux/

Update Client Configurator
http://www.dyndns.com/support/tools/clientconfig.html

  • hosts:
  • faix.homelinux.net
    94.230.149.155
    zviretnik.dyndns.info
    94.143.171.101

    wget -N --no-cache http://cdn.dyndns.com/ddclient.tar.gz
    tar -zxvf ddclient.tar.gz
    cd ddclient-3.7.3
    
    cp ddclient /usr/local/bin/
    chown root:root /usr/local/bin/ddclient
    chmod 750 /usr/local/bin/ddclient
    
    mkdir /etc/ddclient

    /etc/ddclient/ddclient.conf

    daemon=600
    syslog=yes
    cache=/tmp/ddclient.cache
    mail-failure=jan.faix@gmail.com
    pid=/var/run/ddclient.pid
    use=web, web=checkip.dyndns.com/, web-skip='IP Address'
    login=janfai
    password=xxxxxxx
    protocol=dyndns2
    server=members.dyndns.org
    faix.homelinux.net

    chown root:root /etc/ddclient/ddclient.conf
    chmod 600 /etc/ddclient/ddclient.conf
    cp sample-etc_rc.d_init.d_ddclient.ubuntu /etc/init.d/ddclient

    /etc/init.d/ddclient

    DDCLIENT=/usr/local/bin/ddclient
    CONF=/etc/ddclient/ddclient.conf

    chown root:root /etc/init.d/ddclient
    chmod 755 /etc/init.d/ddclient
    update-rc.d ddclient defaults

  • test:
  • ddclient -daemon=0 -debug -verbose -noquiet
    /etc/init.d/ddclient start

    Linux mini-howto

    # Linux je operační systém s monolitickým jádrem.
    Moduly jsou objektové soubory, dynamické části jádra. Umožňují rozšířit
    za běhu funkce stávajícího jádra (LKM = Linux Loadable Kernel Module).

    # daemons basic operations
    /etc/init.d/apache status
    /etc/init.d/apache restart

    # filter file content
    cat /var/log/… | grep (192.168….) -v 9190 | grep 192.168…. | more
    tail -f /var/log/… | grep -v “FW-IN”
    grep 192.168.1.100 string
    grep “test string” -R /dir/*

    # network info
    netstat -an | more
    netstat -rn … show gateway
    netstat -tapn … show listening ports

    # DNS client configuration
    /etc/resololv.conf
    search mydomain.local
    nameserver 192.168.1.101
    nameserver 192.168.1.102

    # query DNS server
    dig www.nixcraft.com
    nslookup www.nixcraft.com

    # memory info
    top
    vmstat
    free

    # create file
    touch

    # chroot
    chroot /directory
    před chroot udělat:
    mount -o bind /proc /chroot/proc; chroot /chroot
    mount -t proc none /proc
    nebo
    for f in proc sys dev dev/pts run ; do mount –bind /$f /mnt/$f ; done

    # mv … move (rename) files
    if move error message Argument list too long, because move too much files do:
    ls -1 | xargs -n 10 -i mv {} /home/app/opt/app/log

    # ln … make links between files
    ln -s /home/app/opt/application/ application

    # copy file to remote
    scp file user@server:/home/dir

    # rsync – synchronizace / kopirovani slozek
    rsync -ave ssh server:/dir/ /mnt/dir/

    # create iso
    mkisofs -o /home/user/data/office /home/user/data/office_en

    # directory size
    du -s
    du -ch | grep total

    # mount (samba)
    mount -o loop -t iso9660 /home/user/data/office /mnt/iso
    mount -t cifs -o username=administrator,password=password //server/data /mnt/server
    mount server:/share /mnt/share
    mount -t cifs -o username=admin,workgroup=cybercity //192.168.1.100/home/user /mnt/user

    # ntfs-3g – mount ntfs partition
    mount -t ntfs /dev/xxx /mnt/windows -o ro
    ntfs-3g /mnt/sda1 /mnt/windows

    # sshfs
    sshfs 001]tod[1]tod[861]tod[291null]ta[resu:/ /mnt/backup

    # nfs
    Souborový systém NFS
    – CIFS ve windows ~ NFS v unixu
    v3- „standard“, podporován všude
    v4- zabezpečení, ale problémy s výkonem
    NFS není vhodné pro veřejné sdílení na Internetu
    Umožňuje sdílet celý OS (boot from net)
    Je třeba řešit synchronizaci UID/GID (LDAP, NIS)
    Konfigurace:
    /etc/exports:
    /data *(rw,no_root_squash)
    # exportfs -r
    – znovu načtení změněné konfigurace
    # rpcinfo -p server
    – informace o RPC službách přes portmapper
    # showmount -e server
    – zobrazí sdílené adresáře
    # nfsstat – list NFS statistics
    # nfswatch – monitor an NFS server

    vi /etc/exports
    /files 192.168.1.100/24(rw,no_root_squash,async)
    /etc/init.d/nfs-kernel-server restart
    exportfs -a
    /etc/init.d/portmap restart
    mount 192.168.1.100:/data /data

    # package manager
    smart –gui (http://www.labix.org/smart)

    # YaSt – instalace balíčů z příkazové řádky SuSE
    zypper in sysstat

    Souborový systém:
    /etc/fstab
    – ext3:
    nodiratime
    errors=remount-ro
    acl,user_xattr
    noexec, nosuid, nodev
    – lsattr, chattr
    chattr +i soubor
    – setfacl, getfacl
    setfacl -m u:username:r /var/log/httpd/acces.log
    – sparse files

    # fstab example
    server:/usr/local/pub /pub nfs rsize=8192,wsize=8192,timeo=14,intr
    //user at server/share_name /mount_point smbfs rw,-N
    //server/Data /mnt/server cifs username=administrator,password=password,us er,ro 0 0
    //1.1.1.1/Myfolder /mnt/mysharedfolder cifs
    username=user,password=pass,workgroup=workgroup,us er,ro 0 0
    //servername/sharename /smbshare smbfs
    ip=192.168.x.x,username=test,workgroup=domainname,password=password,noauto 0 0

    # nagios
    server:/var/spool/nagios

    # allow any traffic
    iptables -I FORWARD -s 192.168.x.x -j ACCEPT

    # NAT
    # test communication as another IP address
    telnet 192.168.1.100 80
    iptables -t nat -I POSTROUTING -d 192.168.1.100 -j SNAT –to 192.168.2.200
    telnet 192.168.1.100
    tcpdump -n -i any host 192.168.2.200

    # reset root password
    boot with grub, hit e, select kernel line, as parameters add: quiet single init=/bin/bash, press enter and than b
    mount -o remount,rw /

    # monitor ip traffic
    tcpdump -n -i vlan99 host 192.168.1.0
    tcpdump -i eth1 -n port 8888 or port 7777 and host 192.168.x.x
    tcpdump -n -i any host 192.168.1.100 or host 192.168.1.200 and not port 22
    tcpdump -n -i any host 192.168.1.100 or host 192.168.1.200 and not port 22 and not net 192.168.3.100/26
    tcpdump -n -i any host 192.168.1.100 or host 192.168.1.200 and not port 22 and not net 192.168.3.100/26 and not host 192.168.1.1 and not host 192.168.2.1 and not port 1215 and not port 1212
    tcpdump -n -i any -s 1500 -w test_dump_file.dump host 192.168.1.100 or host 192.168.1.200 and not port 22 and not net 192.168.3.100/26 and not host 192.168.1.1 and not host 192.168.2.1 and not port 1215 and not port 1212

    # ifconfig
    ifconfig eth0 192.168.1.14
    ifconfig eth0 netmask 255.255.255.128
    ifconfig eth0 broadcast 192.168.1.127

    # routing
    route -n … show gateway / genmask
    route add default gw 192.168.4.126
    route add -net 10.0.1.0 netmask 255.255.255.0 gw 10.10.0.1 dev eth1
    route add -net 10.0.2.0 netmask 255.255.255.0 gw 10.9.0.1
    arping -i vlan99 192.168.1.200
    ip route get IP
    ip route show … show gateway
    traceroute -I eth2 www.google.com

    # better traceroute
    mtr IP

    # who is logged on now / last login
    users
    who -a
    last (last -f /var/log/wtmp)
    w

    # display linux tasks
    top

    # Midnight Commander (mc)
    cd /#sh:user@machine/
    cd /#ftp:server
    cd ftp://[!][user[:pass]@]machine[:port][remote-dir]

    # gzip, gunzip
    gzip -r somedir Zip all files in the somedir directory.
    gunzip -r somedir Unzip all files in the somedir directory.

    gunzip something.tar.gz
    tar xvf something.tar

    tar czf – . | ssh server ‘(cd /muj/novy/adresar; tar xzf -)’

    gunzip -c something.tar.gz | tar xvf –

    # zip, unzip
    zip -r file.zip /directory
    unzip file.zip -d /directory

    # bzip2
    bunzip2 filename.txt.bz2
    bzip2 filename.txt

    #bzip untar
    tar xvfj file.tar.bz2

    #untar / tar
    tar -zxvf [filename with all extensions]
    tar -cvf mystuff.tar mystuff/

    tar cvzf foo.tar.gz foo/
    tar cv foo/ | gzip -9 > foo.tar.gz

    # tar / untar with gzip and same owner
    tar –acls –same-owner -cvpzf /tmp/app.tar.gz /opt/app
    tar –acls –same-owner -zxvpf app.tar.gz

    * -p – zajistí, že práva zustanou zachována
    * –same-owner -zajistí, že vlastníci zustanou zachováni
    * -P – neodstraouje úvodní lomítko z názvu
    * -owner uzivatel – zminí vlastníka souboru na uzivatel.
    * -mode opravneni – zminí oprávniní souboru na opravneni

    Old versions of the tar and dump commands do not backup ACLs.
    # star utility is similar to the tar utility in that it can be used to generate archives of files.

    star -xattr -H=exustar -acl -c -v -z -p -f=/tmp/test.star /dir
    star -x -v -p -z -acl -f=test.star

    star -xattr -H=exustar -acl -c -v -z -p -f=myarchive `cat /tmp/file_list`

    # umask, chmod, chown
    umask -S
    chmod ug=rw+ -R /folder
    chmod 700 /folder

    drwxrwxrwx 1 username users 2525 Feb 18 09:17 index.htm
    ^ / / / / /
    | V V V ”|”’ ‘|’
    | | | | | `– group the file belongs to
    | | | | `– user who owns the file
    | | | |
    | | | `– others (users who are neither you or in the group)
    | | `– group (people in the group)
    | `– user (you)
    |
    `– d=directory, -=file, l=link, etc

    0 = — = no access
    1 = –x = execute
    2 = -w- = write
    3 = -wx = write and execute
    4 = r– = read
    5 = r-x = read and execute
    6 = rw- = read and write
    7 = rwx = read write execute (full access)

    chown “root:domain users” file

    # OS version
    uname -a
    cat /etc/*-release

    # time and date settings
    date set=”STRING”
    date -s “25 AUG 2008 15:55:00”
    date [MMDDhhmm[[SS]RR][.ss]]
    hwclock –systohc, hwclock –hctosys
    ntpdate server
    stratum … vrstvy serveru pri casove synchronizaci

    # password policy
    chage
    deactive account (set expire in past day):
    chage -E 2008-09-23 username
    password expire in 1 year from today:
    chage -d 2008-08-01 -I -1 -m 0 -M 365 -E -1 username

    For example, set new data to 2 Oct 2006 18:00:00.

    # accounts info
    passwd -S “user”

    # hard kill proc
    killall -9 “licsrv” (proces se pise jeho jmenem)
    klidne 2x 3x pokud se neobjevi hlaseni:
    licsrv: no process killed

    # network readresace
    /etc/network/interfaces
    auto eth0
    iface eth0 inet dhcp
    iface eth0 inet static
    address 192.168.1.156
    netmask 255.255.255.192
    network 192.168.1.128
    gateway 192.168.1.190
    dns-nameservers 192.168.1.1 192.168.1.2

    /etc/init.d/network restart

    # network change hostname
    hostname=
    /etc/sysconfig/network
    /etc/sysconfig/network-scripts/ifcfg-eth0
    /etc/hosts

    # dhcp konfigurace
    dhclient

    # pridani noveho uzivatele a nove skupiny
    useradd uzivatel
    groupadd -g 50x skupina
    useradd -G skupina uzivatel

    # pridani existujiciho uzivatele do existujici skupiny
    usermod -a -G skupina uzivatel

    # overeni clenstvi uzivatele ve skupinach
    id uzivatel

    # pridani existujiciho uzivatele do existujici skupiny
    usermod -a -G skupina uzivatel

    # instalace a pouziti yum
    export http_proxy=http://192.168.1.129:8080
    /etc/yum.conf
    proxy=http://192.168.1.129:8080
    /etc/yum.repos.d/install.repo
    [os]
    name=Red Hat $releasever – $basearch – Base
    baseurl = http://192.168.122.30/mrepo/rhel4es-i386/RPMS.updates
    baseurl=http://192.168.122.30/mrepo/rhel4.6es-$basearch/RPMS.os
    baseurl=http://192.168.122.30/mrepo/rhel5.1-x86_64/RPMS.os
    enabled=1
    gpgcheck=0
    /etc/yum.conf
    [main]
    cachedir=/var/cache/yum
    keepcache=0
    debuglevel=2
    logfile=/var/log/yum.log
    pkgpolicy=newest
    distroverpkg=redhat-release
    tolerant=1
    exactarch=1
    obsoletes=1
    gpgcheck=1
    plugins=1
    metadata_expire=1800
    proxy=http://proxy:8080

    yum makecache
    yum list all
    yum update

    # Red Hat registration
    rhn_register

    # gentoo – emerge
    emerge -k
    emerge –sync … synchronizace portage stromu s mirrorem gentoo
    emerge portage … aktualizace baliku portage
    etc-update … aktualizace etc skriptu po instalaci

    python-updater

    # konfigurační soubor /etc/sudoers
    # pridani uzivatele ci skupiny do sudoers
    visudo – pouzit POUZE tento editor nikoliv vi
    %skupina ALL= NOPASSWD: /usr/bin/rootsh

    %chpass ALL = (root) /usr/bin/passwd [[:alnum:]_-]+, !/usr/bin/passwd root
    %mailadmin ALL = (root) NOPASSWD:/usr/sbin/rpm
    Použití aliasů :
    User_Alias WEBMASTERI = foo, bar
    Host_Alias VNITRNISIT = 192.168.10.0/16
    Cmnd_Alias WEBMASTER = (apache) ALL, (root) /usr/bin/su apache

    # LVM Logical Volume Management
    vgscan -> rozeznani LV
    lvs -> informace o logickych svazcich
    pvs -> informace o fyzickych svazcích
    pvdisplay -> informace o fyzickych svazcich
    vgdisplay -> informace o logickych svazcich
    lvdisplay -> informace o vlastnostech logickych svazcich
    vgchange -a y vg01 -> aktivace logickych svazku
    vgchange -a n vg01 -> deaktivace logickych svazku

    dmsetup – low level logical volume management

    parted /dev/sdX
    mklabel gpt
    mkpart primary 0 4096G

    umount /opt
    fsck -f /dev/VolGroup00/LogVol03
    resize2fs /dev/VolGroup00/LogVol03 3G
    lvreduce /dev/VolGroup00/LogVol03 -L 3G
    mount /opt

    vgchange VolGroup00 -a y

    lvscan -> File descriptor 3 left open:
    ACTIVE ‘/dev/VolGroup00/LogVol00’ [15.62 GB] inherit
    ACTIVE ‘/dev/VolGroup00/LogVol02’ [14.62 GB] inherit
    ACTIVE ‘/dev/VolGroup00/LogVol03’ [3.00 GB] inherit
    ACTIVE ‘/dev/VolGroup00/LogVol01’ [11.72 GB] inherit

    for root / use gparted live CD

    for swap partition use:
    swapoff -v /dev/VolGroup00/LogVol01
    lvm lvreduce /dev/VolGroup00/LogVol01 -L -512M
    mkswap /dev/VolGroup00/LogVol01
    swapon -va
    cat /proc/swaps # free

    # parted
    Label disk as msdos:
    parted /dev/sdx mklabel msdos
    Create primary ext4 partition:
    parted /dev/sdx mkpart primary ext4 0GB 100%
    Mark partition as LVM:
    parted /dev/sdx set 2 lvm on
    Mark paritition bootable:
    parted /dev/sdx toggle 1 boot
    Print free space:
    parted /dev/sdx print free
    Create swap:
    parted /dev/sdx mkpart primary linux-swap 14GB 16GB

    Format partition:
    Ext4: mkfs -t ext4 /dev/vg01/lv_name
    Swap: mkswap /dev/sda2

    # mdadm – manage MD devices aka Linux Software Raid.
    – kompletni sprava software raidu
    – v SW raidu je nutne zapsat grub na oba mirrorovane disky
    – pri pouziti fdisku oznacit partition jako typ fd (Linux raid auto)

    # VMWare Tools
    VMWare Console – Install VMWare Tools
    cd /media/cdrom

    cp VMwareTools-[version].tar.gz /root
    cd /root
    umount /mnt/cdrom
    tar zxf VMwareTools-[version].tar.gz
    cd /root/vmware-tools-distrib
    ./vmware-install.pl

    # install package
    # query insalled package
    rpm -qa | grep package_name

    rpm -ivh packagename
    upgrade a package
    rpm -Uvh packagename

    create a tar file
    tar -cvf myfiles.tar mydir/
    (add z if you are dealing with or creating .tgz (.tar.gz) files)

    standard install from source
    tar -xvzf Apackage.tar.gz
    cd Apackage
    ./configure
    make
    make install

    # FSArchiver
    # zalohovani dat linux systemu
    SystemRescueCD – Live Rescue CD obsahujici FSArchiver
    mount -t vfat /dev/sdb1 /mnt/usb
    fsarchiver savefs /mnt/backup/linuxsystem.fsa /dev/sda1 /dev/sda2 /dev/VolGroup00/LogVol00 /dev/VolGroup00/LogVol01
    fsarchiver archinfo /mnt/backup/gentoo-rootfs.fsa
    fsarchiver restfs /mnt/backup/home/user/archive.fsa id=0,dest=/dev/sda1 id=1,dest=/dev/sda2 id=2,dest=/dev/sda3
    fsarchiver probe simple

    # vytvoreni file systemu na USB disku
    mkfs.ext3 /dev/sda1
    e2label /dev/sda1 usb-backup

    # locate – nalezeni souboru
    locate vzor

    # find – nalezeni souboru a jeho obsahu
    find /adresar -name hledany_soubor -print
    find . -name ‘*2006*’
    find ~ -atime +365 -print
    find /home -user uzivatel
    find . | xargs grep ‘string’
    find /tmp -name ‘*.*~’ -print0 | xargs -0 rm
    grep ‘string’ ~/*
    find -print0 (ošetří zobrazení slepých znaků)
    -exec, jméno souboru {}
    find /tmp -name ‘*.*~’ -exec rm {} ;
    {} nahrazení jednoho daného nalezeného souboru
    ; expanduje daný znak shellu, escapovaní např. * napsat *

    # list all subdirectories
    ls -al | grep ‘^d’
    ls /etc/[Ss]* vypise vsechny soubory zacinajici pismeny Ss
    ls -dla /home/* | wc -l

    # delete / remove files and folders
    rm -rf *

    # man
    man -K aplikace … hledani aplikacniho manualu
    man vyuziva prikazu less pro prohlizeni man stranek
    /pattern * Search forward for (N-th) matching line.
    ?pattern * Search backward for (N-th) matching line.
    n * Repeat previous search (for N-th occurrence).
    N * Repeat previous search in reverse direction.

    # installed shells
    cat /etc/shells

    # vi
    (M meta klavesa je Alt)
    C-b presun o jeden znak vlevo
    C-f pres. o jeden znak vpravo
    C-a presun na zacatek radku
    C-e pres. na konec radku
    M-f pres. o jedn. slo. dopredu
    M-b jedn. slovo dozadu
    C-l smazani obrazovky
    C-u mazani radky
    C-k smazani znaku od kurzoru do konce radku
    C-y vlozeni smazaneho textu zpet
    C-d vlozeni znaku konce souboru
    C-h smazani znaku od kurzoru vlevo
    C-s pozastavení výpisu
    C-q pokračování výpisu
    C- ukončení procesu SIGQUIT
    C-d konec vstupu
    C-z suspend procesu
    C-j Enter
    yy Copy line
    P Paste above current line
    p Paste below current line
    dw Delete word
    cw Change word
    x Delete text at cursor
    X Delete (backspace) text at cursor
    a Insert text after cursor
    A Append text at line end
    0 Go to beginning of line
    $ Go to end of line
    h j k l Move left, down, up, right
    w b Scroll by word f/b
    ( ) Scroll by sentence f/b
    ?string Search backward for string
    /string Find next string

    # shell commands
    # expanzní znaky – přehled speciálních znaků
    | roura (pipe)
    ; ukončení na pozadí
    && spuštění při nulovém návratovém kódu předcházejícího příkazu
    || spuštění při nenulovém návratovém kódu předcházejícího
    – oznaceni itervalu napr a-z, 0-9
    * ? [] expanze názvů souborů
    ” potlačení všech spec. znaků uvnitř
    “” potlačení spec. znaků uvnitř mimo , $ a ”
    zástupný znak pro nový řádek
    < přesměrování std. výstupu >přesměrování std. vstupu
    ! negace
    # komentáře
    & spusteni na pozadi
    $ přístup k proměnným
    ; oddeleni prikazu
    () spusteni v kopii shellu

    # test – check file types and compare values
    test -f /etc/passwd && echo “Je to ono!” || echo “Smula”

    export prom=rodic2potomek
    echo ${prom}_neco

    Shell – kombinace příkazů
    cmd1 | cmd2
    cmd1 && cmd2 || cmd 3 – podmíněné spuštění
    {cmd1; cmd2} – skupina příkazů
    (cmd1; cmd2) – skupina příkazů v subshellu

    # history … zobrazeni historie prikazu
    !5 provede spusteni pateho prikazu v historii
    !-5 provede spusteni pateho prikazu v historii od konce
    !! provede posledni prikaz
    !cd hleda prikaz v historii zacinajici retezcem cd
    !?usr? hleda prikaz v historii obsahujici retezec usr
    C-r interaktivni hledani zpetne
    M-p neinteraktivni hledani zpetne historie prikazu
    M-n neinteraktivni hledani dopredne

    # cut, paste
    – remove sections from each line of files
    – paste – merge lines of files

    # aliasy
    alias zobrazeni nastaveni aliasu
    unalias zruseni alisau
    alias “cd+”=”moutn -t iso9660 /dev/hdd /mnt/cdrom”
    alias “cd-“=”umount /mnt/cdrom”

    # promenne prostredi (environment variables)
    hostname, term, shell, histsize, user, username, mail, path, lang, home … write UPPERCASE
    # nastaveni promenne
    A=”ahoj”
    B=$A
    zruseni promenne
    unset B
    export A nebo export A=ahoj … nastaveni promenne pro dalsi instance shellu
    set nebo env … zobrazeni promennych
    HISTSIZE pocet prikazu ulozenych v historii
    export PATH=$PATH:. pridani aktualniho adresare do promenne PATH

    # nastaveni globalnich promennych
    /etc/profile – je urcen pouze pro login shell (nebude vsak fungovat napr. v MC)
    /etc/bashrc – je urcen pro vsechny shelly
    . /etc/profile – znovu nacte profile nebo bashrc (. = prikaz source)

    # uzivatelske
    ~/.bash_profile
    ~/.bashrc
    ~/.bash_logout
    ~/.bash_history

    # Shell – proměnné prostředí
    PS1 – shell uživatele
    PS2 – login prompt
    TERM – typ terminálu (dobré použít s příkazem screen -T vt220)
    IFS – oddělovač polí (středník může být např. dvojtečkou)
    PATH – adresáře s programy
    SHELL – supštěný shell
    LOGNAME – login uživatele
    HOME domácí adresář uživatele

    # colors
    BLACK=”[33[0;30m]”
    BLUE=”[33[0;34m]”
    GREEN=”[33[0;32m]”
    CYAN=”[33[0;36m]”
    RED=”[33[0;31m]”
    PURPLE=”[33[0;35m]”
    BROWN=”[33[0;33m]”
    GRAY=”[33[0;37m]”
    # light colors
    LBLACK=”[33[1;30m]”
    LBLUE=”[33[1;34m]”
    LGREEN=”[33[1;32m]”
    LCYAN=”[33[1;36m]”
    LRED=”[33[1;31m]”
    LPURPLE=”[33[1;35m]”
    LBROWN=”[33[1;33m]”
    LGRAY=”[33[1;37m]”

    # set a fancy prompt
    if [ “$TERM” == “dumb” ]
    then
    PS1=’u@h:w$ ‘
    else
    PS1=$GREEN’u’$LBLUE’@’$LRED’h’$LCYAN’:’$LPURPLE’w’$LBLACK’$ ‘$RED
    fi
    # nebo zelena ?
    export PS1=”[e[36;1m]u@[e[32;1m]h:w> [e[0m]”

    # standardni vstup, výstup a chybový vystup
    STDIN … 0
    STDOUT … 1
    STDERR … 2
    viz /dev/fd, /dev/stdin, /dev/stdout, /dev/stderr

    # přesměrování std. vstupu ze souboru
    cat < vypis.txt ls /etc > vypis.txt 2>chyby.txt
    ls /bin > vypis.txt 2>&1
    ls /bin &>vypis.txt … přesměrování obou výstupů do jednoho souboru
    # nepojmenované roury (pipes)
    ls /etc | more
    ls -qa | grep “^k” | wc -l
    # pojmenované roury jsou specialni soubory
    mkfifo(1) /tmp/roura
    cat /tmp/roura
    echo ahoj | cat
    ahoj

    # processes
    pstree
    yes … vypisuje “y” na terminal
    C-z pozastavi beh programu
    C-c zastavi beh programu
    jobs … zobrazi procesy terminalu
    fg %1 … pokracovani pozastaveneho procesu – prevedeni procesu na popredi
    bg %1 … prevedeni procesu na popredi
    yes > /dev/null
    kill %1
    nohup yes > /dev/null … run a command immune to hangups, with output to a non-tty
    disown %1 … jobs is removed from the table of active jobs
    # stavy procesu (z pohledu planovace uloh)
    ps aux

    VSZ pocet alokovanych stranek virtualnich
    RSS pocet alokovanych stranek realne vyuzitych
    STAT stav procesu z pohledu scheduleru
    START datum vytvoreni procesu

    R … bezici uloha nebo uloha naplanovana k behu
    S … stav prerusitelneho cekani (sleeping)
    D … stav neprerusitelneho cekani
    T … pozastavena uloha
    Z … zombie

    Vytvoření procesu
    * fork () – vytvoří kopii rodičovskoého procesu
    * exec () – nahradí adresní prostor procesu nově spouštěným programem
    * wait () – rodič čeká na konec potomka
    * exit () – potomek končí a aktivuje rodiče

    ttyN – terminaly N, virtualni konzole /dev/ttyN
    pts/N – pseudo terminaly, dynamicky vytvarene terminaly /dev/pts/N
    echo “Nas novy terminal” > /dev/pts/4
    tty vypise virtuální zařízení terminálu připojeného na standardní vstup

    Prehled signalu (man 7 signal)
    signal value action comment
    SIGHUP 1 A hangup detected on controlling terminal
    SIGINIT 2 A interrupt from keyboard
    SIGQUIT 3 C quit from keyboard
    SIGKILL 9 AEF kill signal
    SIGTERM 15 A Terminal signal

    trap ‘rm -f /$TMPFILE > /dev/null 2>&1; exit’ 0 1 2 3 15
    – odchytí signál např. v bash skriptu při stisknutí Ctrl+C a provede daný příkaz

    kill [-n] PID [default n value 15 SIGTERM]
    killall [-n] process name
    pgrep, pkill – look up or signal processes based on name and other attributes
    pkill -u euid,… only match processes whose effective user ID is listed
    pgrep bash – vypise seznam vsech PID procesu bash

    top – klavesa 1 prepina mezi vice CPU
    load average: prumerny pocet procesu ve stavu R za 1, 10 a 15 min.
    PR priority schedulleru
    NI nice value (negative nice value means higher priority, whereas a positive nice value means lower priority)

    Priorita procesu PR je cislo n>0. Je neustale prepocitavana, uzivatel nemuze tuto hodnotu menit.
    Je mozno menit hodnotu NICE <-20,19>, PRI=f (NICE,…,…0
    Udava jak je proces “hodny” na ostatni (-20 je nejvice zly)
    Vyssi priorita zpusobi pridelovani vetsiho casoveho kvanta procesu.
    nice -n -20 yes> /dev/null&
    renice 19 PID

    # show RAM
    -m (megabajty), b,k,g,-h spravny rozmer -i obsazenost inodu
    free
    df

    # /etc/inittab
    id:runlevels:action:process
    unikátní seznam úrovní jaká akce proces, který
    identifikátor běhu, kterých se má provést se má spustit
    1-4 znaky se akce týká initdefault, sysinit,
    respawn, wait, once, …

    si::sysinit:/etc/rc.d/rc.sysinit … vola konfiguraci pro vsechny urovne

    mingetty … spousti terminaly tty 1-6
    ttyS0 … terminal na seriovem portu

    /etc/rc.d/init.d … obsahuje vsechny spousteci skripty
    /etc/rc.d/rcX.d … obsahuje symbolicke linky na vlastni ovladaci skripty

    Snn … skritpt start
    Knn … skript stop

    runlevel … zobrazi spustenou uroven behu systemu
    ln -s ../init.d/httpd S60httpd … vytvoreni sym. linku na spusteni httpd napr v runlevel 5
    chkconfig –list sshd … sprava startovacich skriptu
    upstart … nova nahrada initd napr. Ubuntu

    # atd … jednorazove spusteni ulohy
    atq … list que
    atrm … delete jobs

    # crond … periodicke planovani uloh
    /etc/crontab
    * * * * * příkaz
    0-59 0-23 1-31 1-12 0-6
    minuta hodina den měsíc den v týdnu
    0 … neděle
    0 20 * * * každý den ve 20:00 hodin
    0,30 20 * * * každý den ve 20:00 a 20:30 hodin
    0-30 20 * * * každý den ve 20:00-20:30 s krokem 1 minuta
    0-30/5 20 * * * každý den ve 20:00-20:30 s krokem 5 minut
    0 20 1-7 * 1 každé první pondělí v měsíci ve 20:00 hodin

    odkazuje na /etc/cron.xxxx, kam je mozne vlozit pozadovane skripty, ktere
    jsou spousteny programem run-parts

    # 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

    ./crontab -e (edit) -l (list) … uzivatelsky crontab (/var/spool/cron/)
    0 20 * * * /bin/echo “je prave 20 hodin”
    povoleni ci zakazani pouzivani cronu uzivatelum
    /etc/cron.allow
    /etc/cron.deny

    # Logy
    Logování „do syslogu“ vs. logování do souboru
    Syslog daemon:
    Různé zdroje logů: /dev/log, síť
    Logování na vzdálený logserver přes síť
    Různé implementace služby syslog
    syslog
    rsyslog
    syslog-ng
    Aplikace mívají možnost výběru zda logovat do souboru nebo syslogu
    logger – program pro logování z shellu
    vlastní program pro logování (např pro apache)

    # syslogd, klogd (data z kernelu)
    /dev/log … socket
    FACILITY (oblast sběru) :
    AUTH
    AUTHPRIV
    CRON
    DAEMON
    FTP
    KERN
    LOCAL0 – LOCAL7
    LPR
    MAIL
    NEWS
    SYSLOG
    USER
    UUCP

    LEVEL (stupeň důležitosti) :
    EMERG
    ALERT
    CRIT
    ERR
    WARNING
    NOTICE
    INFO
    DEBUG

    logger -p facility.level “Text zprávy” … uložení zprávy na vstup syslogu
    logger -p mail.info “Ctvrtecni zprava do logu”

    /etc/syslog.conf
    Jednotlivé řádky ve tvaru … selector (podminka) action
    selector = facility.level
    pokud logova zprava vyhovi vice podminkam, je provedeno vice akci
    none = tyto zpravy nebudou do logu zapsany napr. kern ma vlastni log a nebude v adm/critical

    *.=crit;kern.none /var/adm/critical
    kern.* /var/adm/kernel
    kern.crit @finlandia
    kern.crit /dev/console
    kern.info;kern.!err /var/adm/kernel-info
    mail.=info /dev/tty12
    mail.*;mail.!=info /var/adm/mail
    *.=info;*.=notice;mail.none /var/log/messages

    *.emerg * … rozeslani zpravy na vsechny terminaly
    *.alert * … zasilani zpravy po siti
    @finlandia (nebo IP) … zasilani zprav z klienta syslog po siti jinemu syslog serveru
    -r … spusteni syslogd aby prijimal zpravy ze site
    nahrada za syslog je rsyslog nebo syslog-ng

    # Logy – správa logů
    Rotace logů
    nutnost dát signál aplikaci aby logy uvolnila
    logrotate- spouštěné z cronu každý den, rotace logů, komprese, mazání starých logů
    Dohled nad logy
    logcheck – kontrola zda se v logu nenachází něco podezřelého (detekce např. útoku)
    rkhunter – rootkit hunter

    # Logserver – konfigurace
    Logovací server (syslog-ng):
    options {
    sync (0);
    time_reopen (10);
    log_fifo_size (1000);
    use_dns (yes);
    dns_cache (yes);
    use_fqdn (no);
    create_dirs (no);
    dns_cache_expire (120);
    use_fqdn (no);
    keep_hostname (yes);
    log_fifo_size(4096);
    stats(3600);
    bad_hostname(“gconfd”);
    };
    source s_net {
    udp(ip(192.168.1.10) port(514));
    };
    destination d_net{
    file(
    “/export/data/logs/$HOST/$YEAR/$MONTH/$DAY/$FACILITY”
    perm(0640)
    dir_perm(0710)
    create_dirs(yes)
    template(“$ISODATE <$FACILITY.$PRIORITY> $HOST $MSGn”)
    template_escape(no)
    );
    };
    log {
    source(s_net);
    destination(d_net);
    };

    # Klient (syslog):
    *.*@loghost

    # Logy – logger
    Logování z Apache do logserveru
    – nutnost použít syslog-ng na straně webserveru – nevkládá hlášky o opakování zprávy
    – konfigurace v httpd.conf:
    ErrorLog syslog:local5
    SetEnvIf Request_URI “^/checkha.txt$” dontlog
    CustomLog “|/usr/local/sbin/apache_log webserver1” combined env=!dontlog

    Skript /usr/local/sbin/apache_log:
    #!/usr/bin/perl
    use Sys::Syslog;
    $SERVER_NAME = shift || ‘www’;
    $FACILITY = ‘local1’;
    $PRIORITY = ‘info’;
    Sys::Syslog::setlogsock(‘unix’);
    openlog ($SERVER_NAME,’ndelay’,$FACILITY);
    while (<>) {
    chomp;
    syslog($PRIORITY,$_);
    }
    closelog;

    # logrotate … rotování logů, spoustene aplikaci cron
    /etc/logrotate.conf, /etc/logrotate.d/

    # swatch, logcheck, logwatch, … analýza systémových logů
    /usr/share/logwatch/ … copy to …/etc/logwatch/conf/logwatch.conf
    Service = All … jake logy jsou analyzovany

    # quota … souborový systém připojen s podporou kvót : /etc/fstab
    /dev/hda1 / ext3 defaults,usrquota,grpquota 1 1
    uživatelská skupinová
    kvóta kvóta

    quotacheck -uvgamc … vytvoření a kontrola databáze kvót

    V kořeni každého sledovaného adresáře:
    quota.user, quota.group (verze 1)
    aquota.user, aquota.group (verze 2)
    mount -o remount / … pri zmene fstab premountovani rootu

    quotaon -uvga, quotaoff -uvga … zapnutí, vypnutí systémů kvót :
    repquota -uvga … zobrazení stavu kvót

    Nastavení kvót:
    setquota [-u|-g] user|group block-softlimit block-hardlimit
    edquota user inode-softlimit inode-hardlimit filesystem

    setquota -u pepa 0 10000 0 0 /
    su – pepa
    quota
    yes > soubor.txt

    tune2fs … nastaveni parametru filesystemu
    -m reserved-blocks-percentage … set the percentage of reserved filesystem blocks
    dumpe2fs -h /dev/hda1 … zobrazeni parametru filesystemu

    POSIX ACL
    tradicni model prav – lze vytvaret smostatne skupiny uzivatelu pro jemnejsi pridelovani
    prav k souborum, ale je to nesystemove reseni
    POSIX 1003.1e/1003.2c
    jedna se o bezpecnostni dodatek standardu POSIX ktery mimo jine definuje pristupove seznamy
    k souborum, ktery bohuzel nebyl nikdy schvalen, jedna se odraft;
    * pristupovy seznam ACL umoznuje definovat libovolne dlouhe seznamy opravneni pro dany soubor,
    vlastni pristupva prava rwx zustavaji nezmenena
    * ruzni uzivatele tak mohou mit k souboru nastavena ruzna pristupova prava
    * Linux implementuje ACL jiz dlouhou dobu a lze je pouzivat pro soborove systemy ext2,3, jfs, xfs, reiserfs
    * pro ruzne soborove systemy muze mit implementace ACL jista omezeni, jedna se zejmena o omezeni pozcu zaznamu v ACL
    Struktura seznamu ACL:
    * pristupova prava souboru jsou urcena jednim seznamem rizeni pristupu ACL
    * seznam obsahuje libovoly pocet zaznamu
    * kazdy zaznam nese specifickou informaci o pristupovych pravech pro konkretni kategorii uzivatelu
    * nektere zaznamy jsou v ACL povinne
    * lze definovat implicitni zaznamy pro adresare, ktere ovlivni nasstaveni prav nove vytvarenym souborum podobne jako
    maska umask u tradicniho modelu

    getfacl soubor … zobrazeni pristupovych prav
    # file: soubor.txt
    # owner: root
    # group: root
    user::rw-
    user:pepa:rw-
    user:franta:rwx
    group::r–
    group:adm:rwx
    mask::rwx
    other::r–

    setfacl -akce zaznam soubor .. zmena pristupovych prav
    setfacl -m u:pepa:rw soubor.txt
    setfacl -m u:franta:rwx soubor.txt
    setfacl -m g:adm:rwx soubor.txt

    # změna přístupových práv
    Sticky bit – není soubor odstraněn z paměti a jeho spuštění bylo v dřevních dobách rychlejší
    Pro adresář je sticky bit užitečný, pokud má adresář právo x, může z něj každý smazat soubory, pokud je však nastaven sticky bit, může soubory vymazat pouze vlastník.
    SetUID on exec
    SetGid on exec
    Proces převezme práva vlastníka (binárního) souboru. Platí pouze pro binární soubory.
    Proces má dvě pole euid (efektivní) ruid (reálný uživatel), pokud je nastaven sticky bit, je efektivní
    uživatel změněn na vlastníka souboru a proces je spuštěn s jeho právy (reálný uživatel zůstává).

    chmod u+s … set the permissions to “-rwsr-xr-x”, or similar (note the “s” replacing the usual “x”). That means that you can run certain commands with the permissions of a different user (typically root).

    mask::rwx
    regular file 666
    directory 777
    777 – 111
    101

    022 101=5
    /
    644 755

    mkdir adr
    chmod 2755 adr
    mkdir adr2
    drwxr-sr-x 2 root root 4096 Sep 18 14:20 adr2

    setfacl -m d:u:pepa:rw ./adresar
    setfacl -m d:g:franta:rwx ./adresar

    # file … determine file type
    – zjisteni typu souboru

    # LKM = Linux Loadable Kernel Module
    lsmod (/proc/modules) … výpis modulů zavedených v jádře

    Umístění modulů : /lib/modules/`uname -r`/
    jednotlive moduly maji priponu .ko (kernel object)

    Zavedení modulu : insmod msdos.o (2.4), insmod msdos.ko (2.6)
    insmod ne.o io=0x300,irq=11
    Inteligentní zavedení modulu: modprobe msdos
    Informace o modulu : modinfo ne
    Odstranění modulu : rmmod msdos
    Soubory : /proc/ksyms (2.4), /proc/kallsyms (2.6) – exportované symboly jádra

    # automatické zavádění modulů
    /etc/modprobe.preload, /etc/modprobe.preload.d/, /etc/modprobe.conf, /etc/modprobe.d/
    alias sound-slot-0 snd-intel8x0
    alias eth0 eepro100
    alias net-pf-31 bluez
    alias bt-proto-0 l2cap
    alias bt-proto-2 sco

    /etc/modprobe.d/modprobe.conf.dist … seznam vsech aliasu hw možných instalovat do systému

    # lspci … identifikace hardware
    lspci -vm

    # dmesg … cteni zprav jadra (kernelu)

    # zálohování
    není nutné zálohovat /sys, /proc, /dev

    # dump [-dump_level] [-b velikost_bloku] [-B pocet_bloku] [-f soubor] [-u] adresář
    -dump_level úroveň zálohy (0-9, 0 – plná záloha)
    -b velikost bloku velikost bloku v bytech
    -B počet bloků počet bloků
    -f soubor soubor kam se má záloha uložit (většinou device /dev/nst0)
    -u uchová informace o záloze v souboru /etc/dumpdates, nutné
    v případě inkrementální zálohy
    adresář adresář nebo blokové zařízení (/dev/sda2), které chceme
    zálohovat
    -j compress_level komprese bzip2
    -z compress_level komprese gzip

    dump -0 -u -f /backup.hdb1.0 /dev/hdb1
    dump -3 -u -f /backup.hdb1.3 /dev/hdb1
    dump -0 -u -j 9 /home | dd bs=1024 of=/dev/rmt0

    # restore -mód_obnovy [další parametry]
    -r plná neinteraktivní obnova
    -i interaktivní obnova
    -R pokračování v přerušené obnově
    -C porovnání zálohy se současným stavem
    Použití nástroje restore :
    restore -rf /backup.hdb1.0
    Provede neinteraktivní obnovení zálohy do aktuálního adresáře.

    Použití nástroje restore v interaktivním režimu :
    restore -if /backup.hdb1.0

    # vytvořeni loop zařízení přes soubor a namontování jako disku
    dd if=/dev/zero of=disk.img bs=1024k count=150
    losetup /dev/loop0 /root/disk.img
    mkfs -t ext3 /dev/loop0
    mount /dev/loop0 /mnt/disk

    pro zapisovani
    /dev/full – reprezentuje plny disk
    pro cteni
    /dev/zero – stale generuje 0
    /dev/random – pro cteni nahodnych cisel
    /dev/urandom – stejne pro generovani pro pseudonahodnych cisel

    # PartImage
    rpm -Uhv http://apt.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpm
    yum install partimage
    partimage -z1 -o -d save /dev/loop1 ~/backup.img
    partimage restore /dev/loop1 /root/backup.img.000

    # dev – vytvoreni zarizeni
    mknod /dev/loop8 b 7 8
    block device – blokove zarizeni
    charakter device – znakove zarizeni

    # rsync [volby] zdroj cíl
    -a vytvoření archivu (parametry -rlptgoD)
    -v upovídaný režim
    –exclude nezahrnovat příslušné soubory do zálohy
    –delete odstraní z cílové složky soubory, které neexistují ve zdrojové
    složce
    rsync -av /home /mnt/backup/home
    rsync -av –exclude=”*c” /home /mnt/backup/home
    Pozn.: Pozor na zápis adresářů ve zdrojích. V případě, že za jméno adresáře
    napíšeme lomítko, je přenesen jeho obsah, nikoliv adresář samotný.

    Příklad vzdálené zálohy přes scp :
    rsync -ave ssh -delete –progress /home user@remotehost:/mnt/backup/
    rsync -ave ssh -delete –progress user@remotehost:/mnt/backup /home/
    Pozn.: Pozor na zápis adresářů ve zdrojích. V případě, že za jméno adresáře
    napíšeme lomítko, je přenesen jeho obsah, nikoliv adresář samotný.

    Místo scp může být použita metoda rcp klient / server.

    mirrordir – obdobný nástroj pro Unix

    # vipw, vigr – edit the password or group files

    #su … umožňuje spustit shell pod jiným uživatelským UID a skupinovým GID
    su [volby] [uživatel [argument]]
    -, -l spustí jako login shell
    -c=příkaz předá shellu příkaz
    -m nebude měnit proměnné prostředí
    -s=shell spustí zadaný shell (musí být uveden v /etc/shells)

    #Jazyky pro popis tiskové stránky :
    – PostScript (Adobe)
    – PCL Print Control Language (Hewlett-Packard)
    – ESC/P (Epson)
    – GDI (Microsoft)
    Před vytisknutím na rastrové tiskárně je třeba PostScript převést na rastr.
    Tento proces se nazývá Raster Imaging Process – RIP.
    PostScriptové tiskárny obsahují hardwarový RIP, některé velké profesionální
    tiskárny mají RIP softwarový implementovaný na rychlém počítači.
    PostScript je navržen jako nezávislý na výstupním zařízení !!!
    GhostScript je volně šířený interpret jazyka PostScript, softwarový RIP.
    Dokáže transformovat PostScript do různých formátů : různé formáty
    bitmapových souborů BMP, PCX, TIFF, jazyk PCL, …

    GhostScript používá systém filtrů, které popisují jakým způsobem má
    transformovat PostScript.
    Filtry : GimpPrint
    HPIJS
    HPLIP
    eplaser-jp
    ……….
    Popis specializovaných funkcí závislých na zařízení zajišťuje soubor
    PPD – PostScript Printer Description.
    Původně pouze pro PostScriptové tiskárny, dnes možnost použití
    i pro ostatní.
    Výborná integrace s CUPS !!!

    Konfigurace : /etc/cups
    WWW administrační rozhraní : http://localhost:631/
    RedHat konfigurační nástroje : printconf-tui, printconf-gui

    Ovládání :
    Vložení úlohy do tiskové fronty : lpr [-P fronta] soubor.txt
    Výpis obsahu fronty : lpq [-P fronta]
    Smazání zprávy z fronty : lprm [-P fronta] ID
    Zobrazení dostupných tiskáren: lpstat -a
    Nastavení výchozí tiskárny: lpoptions -d PRINTERNAME

    /etc/cups/printers.conf

    DeviceURI ipp://10.0.0.6/printers/LBP2900

    # ldd … print shared library dependencies
    ldd /bin/sh – slinkovani programu s knihovnou

    – configure dynamic linker run time bindings
    /etc/ld.so.conf
    cesty ke knihovnam systemu

    ldconfig = aktualizovani cache cest ke knihovnam

    # apropos … search the whatis database for strings

    # screen … manažerem pro práci v terminálu
    C-a ? … rychlá nápověda
    C-a c … vytvoří nové okno
    C-a ” … přehled oken ”
    C-a x … zamknuti session
    C-a d … odpojeni od session
    screen -r … přihlášení ke spuštěné session
    screen -d -r … odpojí již připojenou session a znovu připojí k současnému terminálu
    screen -x … přehled všech sezení
    C-a [ … copy/scrollback režim

    sdílení sezení více uživateli:
    C-a : … a následným zadáním příkazu multiuser on
    C-a : addacl uživatelé, … přidání práva zápisu do sdílené session
    C-a : sessionname nové_jméno
    C-a * seznam uživatelů připojených k sezení

    screen -r vlastník_sezení/[sessionname]

    # file … determine file type

    # tty … print the file name of the terminal connected to standard input

    # strace … trace system calls and signals, debugging shell commands

    # sum … checksum and count the blocks in a file

    # write … allows you to communicate with other users, by copying lines from your terminal to theirs
    write bdokot pts/1
    When you are done, type an end-of-file or interrupt character.

    # getent – get entries from administrative database

    # nscd – name service cache daemon

    # nsswitch – System Databases and Name Service Switch configuration file

    # Linux PAM – Linux Pluggable Authentication Modules (PAM) provide dynamic authorization for applications and services in a Linux system.

    # DRBD (Distributed Replicated Block Device) is a distributed storage system for the GNU/Linux platform.

    # Bacula is an open source, enterprise level computer backup system for heterogeneous networks.

    # tmpfs is a common name for a temporary file storage facility

    # /proc
    ps aux – zjistit id procesu
    /proc/3867 – exe – odkud byl proces spusten
    – cwd – pracovni adresar procesu
    – environ – prostredi procesu

    # iotop

    # iostat
    iostat -k 1 /dev/sd[abcd]

    # bash shell script
    #! /bin/sh
    – může být shell spustěn i s login či debug parametry

    # id – print user identity

    # shell – expanze proměnných
    ${proměnná}
    ${proměnná:-slovo} – pokud není definována proměnná (nebo je prázdná), použije se slovo

    DOPSAT

    # Shell – speciální proměnné
    $# – počet parametrů skriptu
    $0 – název skriptu
    $n – n-tý parametr
    shift [n] – posun číslování parametrů
    $* – všechny parametry
    $@ – –//–
    $? – návratový kód posledního programu
    $$ – PID aktuálního shellu
    $! – PID poslední úlohy na pozadí

    # getopt – parse command options (enhanced)

    # read promenna
    – načtění řádku ze vstupu
    – read nastavuje návratový kód, který je možné otestovat (kontrola zda proběhl vstup)
    – je možné načíst více argumentů najednou
    echo -n “Zadej login:”;read login
    # eval $promenna
    – argumenty se zpracují a znovu provedou

    # shell – řídící struktury
    if příkaz; then příkazy
    [elif příkazy]
    [else příkazy]
    fi

    while příkaz; do příkazy; done
    for a [in text]; do příkazy; done

    case text in
    vzor1 | vzor2)
    příkazy;
    *)
    příkazy;
    esac

    ls * | while read soubor; do echo $soubor; done

    # Regulární výrazy
    „maska“ pro definici řetězců
    využití: vi, sed, grep, awk, perl…
    – Speciální znaky:
    . libovolný znak (mimo konce řádku – LF)
    ^, $začátek a konec slova
    [seznam]jakýkoliv znak z výčtu
    [^seznam]jakýkoliv znak z doplňku výčtu
    – Opakování:
    * libovolný počet opakování (i žádné) předchozího výrazu
    + minimálně jeden výskyt předchozího výrazu
    (, ), nvymezení části vzoru a její následné použití

    [^.] výrazu odpovídají všechny znaky krome . (musi byt escapovano )
    [] – pokud jsou zavorky jako vycet a je pouzit znak ^ napr. [^] jedna se jakykoliv znak krome ^…

    vypíše uživatele, kteří mají stejné UID a GID:
    getent passwd | egrep ‘^[[:alnum:]_-]+:x:([[:digit:]]+):1’

    nevypsání záznamů od spamd a CRONu:
    tail -f /var/log/syslog | egrep -v “(spamd|CRON[|”

    načtení pravidel ze souboru:
    … | egrep -v -f soubor

    # tr ‘[[:upper:]]’ ‘[[:lower:]] | …
    Převedení velkých písmen na malá:

    find . -type f | while read soubor; do mv “${soubor}” “`echo $soubor | tr ‘[[:upper:]]’ ‘[[:lower:]]’`”; done

    Převedení CR v textovém souboru z DOSu do Unixu (translate)
    tr -d ‘r’ < input.file > output.file

    # sed – filtr pro práci s texty – neinteraktivní editor
    Spuštění: sed [adresa]příkaz
    Příkazů může být více
    Adresa:
    prázdná – pro všechny řádky
    /exp/ – pro odpovídající vzorek (reg. výraz)
    n – n-tý řádek
    $ – poslední řádek
    Příkazy:
    s/vzorek/náhrada/[g|n] – nahrazení vzorku (reg. výraz), g = všechny výskyty, n = n-tý výskyt
    y/vzorek/náhrada/ – ekvivalent programu tr
    p vypsání textu

    sed -i.bak ‘s#:/home/#:/home/users/#g’ /etc/passwd
    hromadné přestěhování domácích adresářů uživatelů
    -i bude editovat primo soubor a vytvori jeho zalohu .back
    bezne je oddelovac / a muselo by byt escapovano, tudiz jako oddelovac
    slouzi znak #

    echo “Ahoj, Tondo.” | sed ‘s/^([a-zA-Z]+), ([a-zA-Z]+)./2/g’
    – zameni textove retezce

    sed -n ‘10,11,12p’ soubor
    – vypásní konkrétních řádků ze souboru

    # awk – postupně zpracovává řádky souboru a aplikuje na ně příkazy
    [BEGIN{příkazy}][/regexp/]{příkazy}[END{příkazy}]
    Předdefinované proměnné:
    RS- oddělovač záznamů/řádků
    FS- oddělovač polí
    NR- počet záznamů
    NF- počet polí
    ENVIRON[“HOME”]- přístup k prom. prostředí
    – je možné provádět přesměrování do souboru (print > file), spouštět externí programy (fce system())

    cat /etc/passwd | awk -F: ‘/^s/{print $1 “ma UID “$3” a jeho GID je “$4}’
    – zobrazi UID a GID kazdeho uzivatele zacinajiciho na pismeno ‘s’
    – parametr F urcuje oddelovac

    cat /etc/passwd | awk -F: ‘/^s/{print $1 “ma UID “$3” a jeho GID je “$4}; /^r/{print “uzivatel “$1″ zacina na r”}’
    cat /etc/passwd | awk -F: ‘/^s/{print $1 “ma UID “$3” a jeho GID je “$4}; /^r/{print “uzivatel “$1″ zacina na r”}; END{ print “celkem zpracovano: “NR}’

    cat > counter
    BEGIN{
    FS=”:”
    r=0
    }
    /^s/{
    print “uzivatel: “$1″ zacina na s”
    r++
    }
    END {
    print “Vypsal jsem ” r ” zaznamu s pismenkem s”
    }

    cat /etc/passwd | awk -f counter

    BEGIN{
    FS=”:”
    r=0
    }
    $4 == “1000” {
    print “uzivatel: “$1″ je ve skupine 1000”
    r++
    }
    END {
    print “Vypsal jsem ” r ” zaznamu”
    }

    BEGIN{
    FS=”:”
    r=0
    }
    {
    if ($4 == “1000”) {
    print “uzivatel: “$1″ je ve skupine 1000”
    r++
    }
    else {
    print “uzivatel “$1″ neni ve skupine 1000”
    }
    }
    END {
    print “Vypsal jsem ” r ” zaznamu”
    }

    # Skripty
    – Skripty neumožňují používat SUID bit
    vyjimka: perl
    Řešení:
    SUDO
    /etc/sudo
    editace visudo (ekvivalent vipw,vigr)

    # make
    – Generátor příkazů – automatizace opakujících se postupů.
    – GNU make, cmake
    – autoconf, automake, configure
    – python/perl/java mají své specifické postupy
    Makefile:
    all: singlesingle: clean ldap.xml xhtml-onechunk.xsl xhtml-common.xsl
    xsltproc -o html/ xhtml-onechunk.xsl ldap.xml
    clean:
    @rm -f html/*.html

    make – Makefile
    Závislosti cíle:targets: [files|targets]
    Prováděné příkazy:command
    Komentář:#komentář
    Pokračování na dalším řádku:
    Nezáleží na pořadí definic, podpora maker, dostupnost systémových proměnnýchs

    # X Window systém
    Různé implementace, různé OS:
    Xorg
    XFree86
    cygwin, proprietární X servery
    klient-server
    síťově transparentní, lze provést přesměrování výstupu

    X Window systém x uživatel
    X umí vykreslovat základní grafické prvky (bod, úsečka) a neví co je menu, tlačítko, nestará se o okna
    pro vykreslení grafických prvků je nutné použít vhodný toolkit
    pro správu oken window manager

    X – konfigurace
    statická konfigurace v /etc/X11/xorg.conf
    Možnost ovlivnění konfigurace při startu případně za běhu
    Modulární systém

    X – vzdálený přístup
    VNC
    různé implementace, klientský SW
    sdílení aktuálního sezení uživatele i samostatné sezení
    XDMCP
    využití: X terminál
    nezabezpečený protokol – pouze lokální síť
    vysoké nároky na propustnost sítě
    neumožňuje sdílet sezení uživatelů
    SSH a forward aplikací skrz tunel

    # MySQL
    mysqladmin kill status processlist
    while true; do mysqladmin status; sleep 1; done

    # watch – execute a program periodically, showing output fullscreen
    watch -n 1 — mysqladmin status
    watch -n 1 cat /proc/mdstat

    # —
    touch — –ahoj
    rm — –ahoj

    # Troubleshooting
    chování OS:
    balíček sysstat:
    -iostat -k 1
    -vmstat 1
    -sar
    iotop, top
    iftop
    iptraf
    htop
    mtop
    apachetop
    process accounting
    http://tldp.org/HOWTO/Process-Accounting/index.html
    balíček acct
    sa /var/log/pacct
    sa –print-users /var/log/account/pacct
    # sar – Collect, report, or save system activity information.
    /etc/init.d/sysstat statrt

    Troubleshooting 2
    – zjistí typ souboru, ale i zařízení
    file -s
    file -s /dev/sda
    Trasování volání:
    strace systémová volání
    strace -ff -o /tmp/stracelog cat /etc/shadow
    – trasování více vláknových procesů např. apache (param. -ff)
    strace -o /tmp/stracelog -p 123 (připojení na běžící proces)
    ltrace volání knihoven
    ltrace getent passwd root

    Knihovny:
    ldd ldconfig
    Soubory:
    lsof -n otevřené soubory
    fuser zjištění kdo „drží“ FS
    fuser -m -u /var/log

    Troubleshooting 3
    síť:
    tcpdumpodchytávání provozu
    wiresharkodchytávání provozu, analýza
    openssl s_client -host server -port 443 = test SSL spojení
    openssl s_client -host mojedatovaschranka.cz -port 443
    telnettest TCP spojení
    netstat -tpln zobrazení TCP „listenerů“
    netstat -tpaun zobrazení všech spojení
    ip r lroutovací tabulka
    ip a lIP adresy lokálních rozhraní
    iptables -L -v -n [-t nat|-t mangle] stav iptables
    mtr
    ethtool – ovládání síťové karty
    ethtool -p eth0 = např. identifikuje blikáním síťovou kartu
    dmidecode = reports information about your system’s hardware as described in your system
    smartctl -a /dev/sda = vypíše informace o SMART či provede test

    # Pošta
    – SMTP server bývá na každém serveru
    sendmail, postfix, exim, qmail a další
    – Zabezpečení komunikace
    – šifrování
    -TLS – 25/tcp
    -SSL
    – autorizace/autentizace
    -SASL
    – uživatel → SMTP server
    – SMTP server → SMTP server
    -Implementace (používané s Postfixem)
    – Cyrus – saslauthd
    – Dovecot

    # Doručování pošty – filtry
    Filtrování zpráv na straně serveru zajišťuje LDA
    procmail
    ~/.procmailrc
    maildrop
    ~/.maildroprc
    dovecot
    -sieve filtry, možnost zpravovat vzdáleně
    – Autoodpovídač (vacation)
    externí program, sieve skripty

    # Zpřístupnění pošty klientům
    Lokální soubory
    klientský sw: mail, mutt, pine
    IMAP/POP3
    Courier IMAP/POP3, Dovecot
    Zabezpečení komunikace
    -TLS (IMAP, POP3)
    -SSL (IMAPs/POP3s)
    Existují proxy pro IMAP/POP3

    # Pošta – antispam/antivir
    Antispam:
    Spamassassin, dspam
    razor, pyzor
    greylisting (gld, postgrey)
    Antivir:
    clamav
    Integrace s mailserverem:
    Amavis
    -zajišťuje základní filtrování, správu karantény

    # Pošta – odeslání
    Odesílání pošty
    SMTP
    lokálně
    -využívají systémové služby
    – Náhrada za /usr/sbin/sendmail
    SSMTP
    – Postfix – nástroje:
    mailq, qshape- zobrazení stavu fronty
    postsuper- správa fronty
    postcat -q ID- vypsání zprávy ve frontě
    sendmail -bv adresa – test doručení komu email finálně bude doručen (kontrola rewrite) – na postfixu

    Doručování pošty do schránek
    – Formát schránky
    mbox
    Maildir
    – LDA (local delivery agent)
    – mailserver
    – postfix -local, virtual
    – většinou velmi omezené možnosti filtrování
    – procmail
    – maildrop
    – dovecot
    – MDA (mail delivery agent)

    # postfix
    qshape – zobrazí počet čekajících mailů na jednotlivé domény
    postsuper – umí mazat z fronty emaily
    přes mailq zjistit ID a přes postsuper -d E83WF44DD
    postcat -q D8FUD88F23 | less – vypíše detaily emailu včetně obsahu
    postsuper -h ID zprávy – pozastavení zprávy a její opětovné unholdnutí -H
    postsuper -d ALL deferred
    mailq | awk ‘/marketing@adrsa/{print $1}’ | awk -F* {print $1}| while read id; do postsuper -h id;
    pro testování nahradit postsuper echo id
    pfqueue – sledování a modifikování poštovní fronty

    # mail klient – pine, mutt
    ~/.muttrc
    echo Ahoj Tondo… | mail -s “Pozdrav z hor” zc]tod[anemodnull]ta[letavizu
    cat /etc/config.conf | mail ….

    # gdb – The GNU Debugger (ddd)

    # Různé nástroje
    DNS:
    nslookup
    host
    dig
    whois, geoiplookup (GeoIP)
    nmap
    nessus
    cheops-ng a alternativy

    Monitoring služeb
    Různé nástroje:
    – hotsanic (lokální historie zatížení serveru)
    – munin (server vs daemon – zobrazí grafy monitoringu)
    – smokeping (změří latenci linky)
    Nagios
    – Centreon (nástavba pro Nagios – využívá jeho backend), nagiosgrapher
    – CFEngine (cfengine.org) – standalone, datacenter management platform
    Nagios:
    – Aktivní kontroly – NRPE – lokální agent
    – Pasivní kontroly – NSCA – pasivní příjem notifikací
    – Notifikace uživatelům – email, sms, vlastní
    – Závislosti, eskalace

    # Nagios – pluginy
    Velký výběr pluginů pro konkrétní služby
    – Vlastní moduly
    nezávislé na programovacím jazyku
    využití externích programů – možnost kontrolovat např. HW
    – Návratová hodnota
    0 = OK
    1 = warning
    2 = critical
    3 = unknown
    – Textový výstup

    # Debian Administration Utilities
    apachetop – Realtime Apache monitoring tool
    arping – Tool to send ICMP echo requests to an ARP address
    busybox – Tiny utilities for small and embedded systems
    cpbk – a mirroring utility for backing up your files
    cutter – disconnect routed IP connections
    di – advanced df like disk information utility
    disktype – detection of content format of a disk or disk image
    etherwake – A little tool to send magic Wake-on-LAN packets
    falselogin – False login shell
    fcrackzip – password cracker for zip archives
    htop – interactive processes viewer
    httping – ping-like program for http-requests
    hwinfo – Hardware identification system
    idswakeup – A tool for testing network intrusion detection systems.
    ifrename – Rename network interfaces based on various static criteria
    installwatch – Track installation of local software
    ipsc – IP Subnet Calculator for console
    iptraf – Interactive Colorful IP LAN Monitor
    knockd – small port-knock daemon
    labrea – a “sticky” honeypot and IDS
    linuxinfo – Displays extended system information
    lsscsi – list all SCSI devices (or hosts) currently on system
    memtester – memtest is a utility for testing the memory subsystem
    mindi – creates boot/root disks based on your system
    mtop – MySQL terminal based query monitor
    multitail – view multiple logfiles windowed on console
    notifyme – A program to notify the user when other one logs in
    rpl – intelligent recursive search/replace utility
    tiger – Report system security vulnerabilities
    tripwire – file and directory integrity checker
    shc – Shell script compiler
    wall – Prints a message to each user
    wcd – saves time typing when you want to change directories
    wipe – Secure file deletion
    whowatch – Real-time user logins monitoring tool
    zsafe – Password manager with encryption

    # Informations
    Open Computer and Software Inventory Next Generation, the open source automated inventory and deployment system

    Frontpage EN

    AWK examples: http://www.ibm.com/developerworks/library/l-awk1.html

    Linux ArmOps (American Army) Game: http://www.americasarmy.com/

    Cedega (Point 2 Play) Distro: http://www.transgaming.com/products_linux.php

    CXOffice (Wine, CrossOver) Apps: http://www.codeweavers.com/products/cxoffice/

    Spacewalk – Linux systems management: http://www.redhat.com/spacewalk/

    Slax Distro: http://slax.linux-live.org/screenshots.php

    DSL Distro: http://www.damnsmalllinux.org/index.html

    Gentoo Distro: http://www.gentoo.org/

    ABC Linuxu: http://www.abclinuxu.cz/ucebnice/zaklady/zakladni-soucasti-systemu/procesy

    Linux Man: http://linux.die.net/man/1/top

    Linux CZ: http://www.linux.cz/

    Knoppix Bootable USB Key: http://www.knoppix.net/wiki/Bootable_USB_Key

    Linux Printing: http://www.linuxprinting.org

    Linux Security: http://www.grsecurity.net/

    Linux Advanced Routing & Traffic Control: http://lartc.org/

    KeyPass: http://keepass.info/

    Installation of new computer

    Installation

    Installation of new computer (Debian Testing)
    Installation images (Debian Testing)
    Installation images AMD64 (unofficial / non-free / including-firmware)

    Create installation USB:
    dd if=debian-testing-amd64-netinst.iso of=/dev/sdX
    During installation, do NOT fill in root password, account will be disabled and new user will be member of sudo group.

    New disk partitions:

    /
    /home
    /opt
    

    /etc/fstab

    /dev/sda1 / ext4 errors=remount-ro 0 1
    /dev/sda2 /home ext4 defaults 0 2
    /dev/sda5 /opt ext4 defaults 0 2
    192.168.122.1:/disk /disk nfs rw,rsize=8192,wsize=8192,timeo=14,intr   0  1
    

    Skeleton:
    /etc/default/useradd

    HOME=/home
    SHELL=/bin/bash
    SKEL=/etc/skel
    CREATE_MAIL_SPOOL=yes
    

    Users:

    useradd -G users username
    usermod -a -G users username
    

    Sudo:
    visudo
    Add or modify following line.

    %sudo ALL=(ALL) NOPASSWD:ALL
    

    Firmware:
    apt-get install firmware-linux-free firmware-linux-nonfree firmware-iwlwifi

    Multimedia:
    apt-get install deb-multimedia-keyring

    XFCE + Web browser:
    apt-get install xorg lightdm xfce4 iceweasel iceweasel-l10n-cs gksu

    XFCE tools:
    apt-get install network-manager-gnome ttf-mscorefonts-installer unrar flashplayer-mozilla openjdk-7-jre icedtea-7-plugin

    System core tools:
    apt-get install apt-utils adduser sudo aptitude base-files bash coreutils cups-bsd debconf findutils grep grub-pc gzip hostname ifupdown iptables iproute less lsof menu locales netbase passwd portmap tar time mtr-tiny wget curl ncdu whois hwinfo traceroute logrotate lshw lsof postfix procinfo inxi

    Optional core tools:
    apt-get install ntp vim nmap htop iotop iftop iptraf acpid eject screen usbutils pciutils ethtool cryptsetup openssh-server lshw ufw ipcalc mc parted hddtemp smartmontools numlockx rsyslog lm-sensors links logrotate pm-utils speedometer sysv-rc-conf bsdutils btrfs-tools fuse-utils hddtemp hdparm smbclient cups-client atop fsarchiver sysstat logwatch fail2ban mutt needrestart

    Basic operator tools:
    apt-get install p7zip gnome-system-monitor libreoffice-bundled brasero deluge cheese skype vlc gnome-mplayer totem pidgin guake openvpn baobab epiphany-browser tsclient libwebcam0 gnome-disk-utility network-manager-openvpn-gnome libwebcam0 rdesktop gimp

    HP printer dependencies:
    apt-get install cups cups-client cups-bsd system-config-printer hplip hpijs foomatic-db-compressed-ppds hplip-cups

    Non-free tools:
    apt-get install flashplayer-nonfree

    Virtual box dependencies:
    apt-get install fakeroot linux-headers-$(uname -r) busybox initramfs-tools gcc cpp dkms binutils make

    Java dependencies:
    apt-get install java-common openjdk-7-jre

    HP LIP Debug:
    apt-get install libcups2 cups libcups2-dev cups-bsd cups-client libcupsimage2-dev libdbus-1-dev build-essential ghostscript openssl libjpeg-turbo8-dev libsnmp-dev libtool libusb-dev python-imaging policykit-1 policykit-1-gnome python-qt4 python-qt4-dbus python-dbus python-gobject python-dev python-notify python python-reportlab libsane libsane-dev sane-utils xsane

    Optional international fonts:
    apt-get install xfonts-thai

    Configuration

    Skype:
    https://wiki.debian.org/skype

    dpkg --add-architecture i386
    apt-get update
    wget -O skype-install.deb http://www.skype.com/go/getskype-linux-deb
    dpkg -i skype-install.deb
    apt-get -f install
    

    Logwatch:
    mkdir /var/cache/logwatch
    /usr/share/logwatch/default.conf/logwatch.conf

    Detail = High
    

    Locales:
    (Debian)
    /etc/locale.gen
    (Ubuntu)
    /var/lib/locales/supported.d/local

    cs_CZ.UTF-8 UTF-8
    en_US.UTF-8 UTF-8
    

    /etc/default/locale

    LANG="en_US.UTF-8"
    LANGUAGE="en_US.UTF-8"
    LC_TIME="cs_CZ.UTF-8"
    LC_NUMERIC="cs_CZ.UTF-8"
    LC_MONETARY="cs_CZ.UTF-8"
    LC_PAPER="cs_CZ.UTF-8"
    LC_NAME="cs_CZ.UTF-8"
    LC_ADDRESS="cs_CZ.UTF-8"
    LC_TELEPHONE="cs_CZ.UTF-8"
    LC_MEASUREMENT="cs_CZ.UTF-8"
    LC_IDENTIFICATION="cs_CZ.UTF-8"
    

    locale-gen

    Timezone:
    /etc/timezone

    Europe/Prague
    
    dpkg-reconfigure tzdata

    NTP:
    /etc/ntp.conf

    server tik.cesnet.cz
    server tak.cesnet.cz
    service ntp restart

    Postfix:
    /etc/postfix/main.cf
    /etc/aliases

    SSH – restore keys:
    /etc/ssh/
    sshd_config ssh_host_dsa_key.pub ssh_host_ecdsa_key.pub ssh_host_ed25519_key.pub ssh_host_rsa_key.pub ssh_host_dsa_key ssh_host_ecdsa_key ssh_host_ed25519_key ssh_host_rsa_key

    UFW rules:
    copy from backup /lib/ufw/user.rules

    Autologin:
    /etc/lightdm.conf
    autologin-user=username

    Multisystem:

    deb http://liveusb.info/multisystem/depot all main
    deb-src http://liveusb.info/multisystem/depot all main
    

    Virtualbox:
    deb http://download.virtualbox.org/virtualbox/debian wheezy contrib

    Google Talk plugin:
    apt-get install google-talkplugin

    deb http://dl.google.com/linux/talkplugin/deb/ stable main
    

    Add apt keys:
    apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 54422A4B98AB5139 07DC563D1F41B907 3EE67F3D0FF405B2 A040830F7FAC5991 4E940D7FDD7FB8CC

    /etc/apt/sources.list

    deb http://ftp.cz.debian.org/debian/ testing main contrib non-free
    deb-src http://ftp.cz.debian.org/debian/ testing main contrib non-free
    
    deb http://security.debian.org/ testing/updates main contrib non-free
    deb-src http://security.debian.org/ testing/updates main contrib non-free
    
    deb http://ftp.cz.debian.org/debian/ jessie-updates main contrib non-free
    deb http://ftp.cz.debian.org/debian/ jessie-backports main contrib non-free
    
    deb http://packages.linuxmint.com/ debian main upstream import backport
    
    deb http://ftp.cz.debian.org/debian/ wheezy main contrib non-free
    deb-src http://ftp.cz.debian.org/debian/ wheezy main contrib non-free
    
    deb http://www.deb-multimedia.org/ jessie main non-free
    deb-src http://www.deb-multimedia.org/ jessie main

    Notebook tools:
    apt-get install cpufreqd

    Xfce4-sensors plugin:
    chmod u+s /usr/sbin/hddtemp

    What to backup

    /home/
    /root
    /usr/local/bin/
    /var/spool/cron/
    /var/cache/apt/
    /var/lib/apt/
    /var/lib/mysql
    /var/www/
    /etc/*
    (hostname, passwd, shadow, group, gshadow, fstab, crypttab, sudoers, mailname, aliases, networks, crontab, issue, motd, ssh/*, apt/*, ufw/*, cups/*, ntp.conf, rsnapshot.conf)

    /etc/network/interfaces

    192.168.122.1 / 255.255.255.224 / 192.168.122.30
    

    /etc/resolv.conf

    nameserver 8.8.8.8
    nameserver 8.8.4.4
    

    /etc/hosts

    127.0.0.1 localhost
    192.168.1.30 home-router home-router.local router
    192.168.1.1 home-laptop home-laptop.local laptop

    Post install configuration

    Sensors (sensors-detect)
    Postfix
    Securing a New Linux Installation (Logwatch, RKHunter, HostsDeny, Fail2Ban)
    SmartmonTools (/etc/default/smartmontools, start_smartd=yes)
    HDD temp (/etc/default/hddtemp, RUN_DAEMON="true")
    CUPS
    GRUB
    SSH server
    UFW firewall
    NFS server-client
    Aptitude unattended-upgrades
    Linux counter
    DynDNS client

    Repair blank boot splash screen (Ubuntu / Mint):

    sudo -s
    echo FRAMEBUFFER=y>>/etc/initramfs-tools/conf.d/splash
    update-alternatives --config default.plymouth
    update-initramfs -u
    

    Change repository source (fast czech mirror):
    /etc/apt/sources.list
    deb http://mirrors.nic.cz/linuxmint-packages/ debian main upstream import backport

    Clean unused packages:
    apt-get autoremove

    List of all packages

    acpi acpid adduser airport-utils alsa-base and apt apt-utils aptitude aptoncd apturl at aufs-tools autoconf automake avahi-utils baobab base-files base-passwd bash bind9-host bleachbit brasero bsd-mailx bsdmainutils bsdutils btrfs-tools busybox bzip2 cabextract cheese chromium-browser chromium-browser-l10n cli-common coreutils cpio cron cryptsetup cups-pdf curl dash dconf-tools debconf debian-archive-keyring debianutils debootstrap deluge dia diffutils dkms dmidecode dnsutils dpkg duplicity dvd+rw-tools e2fsprogs ed efibootmgr eog fail2ban fetchmail file findutils fonts-liberation fonts-thai-tlwg foomatic-db-gutenprint fortune-mod fortunes-husse fortunes-min ftp fsarchiver fuse-utils gcalctool gedit gettext-base ghostscript-x git gksu gnupg gparted grep groff-base growisofs gthumb gtkvncviewer guake gucharmap gufw gvncviewer gzip hello host hostname htop hwinfo iftop ifupdown info initramfs-tools ioping iotop ipcalc iperf iproute iproute2 iptables iptraf iputils-arping iputils-ping iputils-tracepath keyboard-configuration kismet kmod krb5-locales laptop-detect laptop-mode-tools less locales login logrotate logwatch lsb-base lshw lsof ltrace lxc lynx m4 makedev man-db mawk mbr mc memtest86+ menu mime-support mint-x-icons mlocate mount mountall mplayer2 mtools mtr-tiny mutt myspell-cs namebench nano nbtscan ncurses-base net-tools netbase netcat-traditional network-manager-openvpn network-manager-openvpn-gnome network-manager-pptp network-manager-pptp-gnome nfs-common nmap npm ntpdate numlockx openssh-client openvpn p7zip passwd pastebinit patch pciutils perl pidgin pinta pkg-config postfix pppconfig pppoe pppoeconf pptp-linux procinfo procmail procps psensor pulseaudio pulseaudio-utils python rdesktop rdiff-backup readline-common reiser4progs reiserfsprogs rpcbind rsnapshot rsync rsyslog samba screen sed smartmontools sshfs strace sudo syslinux syslinux-common sysstat sysv-rc-conf tar tcpdump telnet texinfo time traceroute ttf-freefont ttf-ubuntu-font-family tzdata ucf udev ufw unattended-upgrades unicode-screensaver unrar unshield update-notifier-common usb-imagewriter usbutils user-setup util-linux uuid-runtime vim vim-common vim-tiny vinagre vino vnc4server w3m wavemon wget whois winetricks wireshark wodim xchat xclip xfce4-screenshooter-plugin xinput xrdp xtightvncviewer xtrans-dev xvnc4viewer zip mintupdate-debian gnome-media
    

    Linux on USB flashdisk

    http://www.cyrius.com/debian/nslu2/linux-on-flash.html

    If you are running your Linux system on a USB flash key, there are a number of things you might want to do in order to reduce the wear and tear on the underlying flash device (as it only supports a limited number of writes).

    The ext3 filesystem per default writes metadata changes every five seconds to disk. This can be increased by mounting the root filesystem with the commit=N parameter which tells the kernel to delay writes to every N seconds.

    The kernel writes a new atime for each file that has been read which generates one write for each read. This can be disabled by mounting the filesystem with the noatime option.

    Both of the above can be done by adding e.g. noatime,commit=120,… to /etc/fstab. This can also be done on an already mounted filesystem by running the command:

    mount -o remount,noatime,commit=120 /

    The system will run updatedb every day which creates a database of all files on the system for use with the locate command. This will also put some stress on the filesystem, so you might want to disable it by adding
    exit 0
    early in the /etc/cron.daily/find script.

    syslogd will in the default installation sync a lot of log files to disk directly after logging some new information. You might want to change /etc/syslog.conf so that every filename starts with a – (minus) which means that writes are not synced immediately (which increases the risk that some log messages are lost if your system crashes). For example, a line such as:

    kern.*                          /var/log/kern.log
    

    would be changed to:
    kern.*                          -/var/log/kern.log
    

    You also might want to disable some classes of messages altogether by logging them to /dev/null instead, see syslog.conf(5) for details.
    In addition, syslogd likes to write -- MARK -- lines to log files every 20 minutes to show that syslog is still running. This can be disabled by changing SYSLOGD in /etc/default/syslogd so that it reads

    SYSLOGD="-m 0"
    

    After you’ve made any changes, you need to restart syslogd by running
    /etc/init.d/syslogd restart

    If you have a swap partition or swap file on the flash device, you might want to move it to a different part of the disk every now and then to make sure that different parts of the disk gets hit by the frequent writes that it can generate. For a swap file this can be done by creating a new swap file before you remove the old one.
    If you have a swap partition or swap file stored on the flash device, you can make sure that it is used as little as possible by setting /proc/sys/vm/swappiness to zero.

    The kernel also has a setting known as laptop_mode, which makes it delay writes to disk (initially intended to allow laptop disks to spin down while not in use, hence the name). A number of files under /proc/sys/vm/ controls how this works:

    /proc/sys/vm/laptop_mode: How many seconds after a read should a writeout of changed files start (this is based on the assumption that a read will cause an otherwise spun down disk to spin up again).

    /proc/sys/vm/dirty_writeback_centisecs: How often the kernel should check if there is “dirty” (changed) data to write out to disk (in centiseconds).

    /proc/sys/vm/dirty_expire_centisecs: How old “dirty” data should be before the kernel considers it old enough to be written to disk. It is in general a good idea to set this to the same value as dirty_writeback_centisecs above.

    /proc/sys/vm/dirty_ratio: The maximum amount of memory (in percent) to be used to store dirty data before the process that generates the data will be forced to write it out. Setting this to a high value should not be a problem as writeouts will also occur if the system is low on memory.

    /proc/sys/vm/dirty_background_ratio: The lower amount of memory (in percent) where a writeout of dirty data to disk is allowed to stop. This should be quite a bit lower than the above dirty_ratio to allow the kernel to write out chunks of dirty data in one go.

    All of the above kernel parameters can be tuned by using a custom init script, such as this example script. Store it to e.g. /etc/init.d/kernel-params, make it executable with

    chmod a+x /etc/init.d/kernel-params
    

    and make sure it is executed by running
    update-rc.d kernel-params defaults
    

  • Note
  • Most of these settings reduce the number of writes to disk by increasing memory usage. This increases the risk for out of memory situations (which can trigger the dreaded OOM-killer in the kernel). This can even happen when there is free memory available (for example when the kernel needs to allocate more than one contiguous page and there are only fragmented free pages available).

    As with any tweaks, you are advised to keep a close eye on the amount of free memory and adapt the tweaks (e.g. by using less aggressive caching and increasing the swappiness) depending on your workload.

    Ubuntu Security

    In an effort to reduce the number of stickies, this sticky is what I consider “the basics” and if you are new to Security on Ubuntu / Linux you should start with this thread.

    Additional security related threads would include:

    Introduction to AppArmor – This thread will get you started using Apparmor.

    Host-based Intrusion Detection Systems (HIDS)– This thread will introduce to monitoring your system for unauthorized access / system changes.

    Network Intrusion Detection Systems (Snort) – This thread will introduce you to network monitoring options.

    If anyone is interested in helping maintain this information or has feedback / changes / updates / or other suggestions please send me a PM on these forums ~ bodhi.zazen
    I am writing this guide as a concerned member of the Ubuntu Community. Security is a concern for us all and in welcoming new (and experienced) users to Ubuntu I would like to demystify the complexities of security that come with your new OS.

    Disclaimer : I am not an expert in security. This document is intended as a security overview for new users. This thread is not intended as an all inclusive how-to or discuss the merits of any particular security measure. I offer no guarantee that by running Ubuntu with any or all of these suggestions your security will be foolproof or that you will never be cracked.

    I would like to direct any general security discussions to the Servers & Security and any comments on this introductory sticky here.

    I would like to thank the Ubuntu Staff, especially jdong and compiledkernel for their review and suggestions.

    The two most common cracks posted on these forums are ssh and vnc, both running with password authentication.

    If you wish to run these services, please secure them.

     
    Introduction : Security is an ongoing process and, like an onion, it has layers and stinks. The best defense you have is to read and learn how to secure your OS.

    Alas, there is no single action you can take to achieve absolute security (the only safe computer is one that is turned off, disconnected from the Internet, and in a locked vault) and security concerns and “ease of use” are sometimes competing concerns.

    Clarification of terms:

    The “Windows Mindset” is intended as exactly that. I assume most new users are coming from Windows and the issues under this section are both most familiar to them and areas of FAQ on the forums (how often do we see questions from the “Ubuntu Mindset” on ABT?).

    The “Ubuntu Mindset” is thus likely new information for most new users.

    Those divisions/titles are intended to divide security information into familiar/unfamiliar territory (assuming the reader comes from a Windows background) or to lighten up an otherwise dry topic. Specifically it is my intention that the “Windows mindset” will help users new to Linux (Ubuntu) feel more at home by starting with familiar themes. These titles or divisions are certainly not intended to convey more or less importance to any particular issue, those decisions I leave for “self determination”.
    Summary: There is no such thing as “security in a box ™”. Information security is an active job — it is not installing some product on the system and sitting back and relaxing.

    The good news ~ Ubuntu (Linux) is fairly secure “out of the box”.

    How to proceed: Prepare to read, read, read … do not expect to get through this document in one session.

    Contents:

    1. Intro

    Basics

    2. Windows mindset

    Antivirus

    Wine

    Firewall

    Adware

    3. Ubuntu mindset

    Permissions and Encryption

    GPG

    Truecrypt

    Installation into an Encrypted Partition

    Root kits

    Intrusion detection

    compiledkernel’s suggested applications

    Secure servers

    Hardened kernels

    Logs

    How to perform a hardened installation

    Screening your system for potential security holes

    4. Forensics

    5. References

    Basics

    This advice is fairly generic and applies to almost any OS. These simple steps offer a solid foundation that you should be able to implement almost immediately.

    • Enforce strong passwords http://en.wikipedia.org/wiki/Password_strength
    • In general, do not write your passwords down, and if you must, keep them in a secure place (Do not put them on a sticky note attached to your monitor for example).
    • Limit root access (Do not log in or run programs as root). Ubuntu accomplishes this by locking the root account and the use of sudo.

       

    • Physical access (physical access = big security hole). Physical access allows root access to your system (via a live CD if necessary).
    • Do not install software or add repositories from untrusted sources (See also “Social engineering” below).
      • This includes running scripts that modify your /etc/apt/sources.list Take care not to let the “need” to run the newest/latest/greatest compromise security.

       

    • Likewise, do not run code or enter commands into the terminal from untrusted sources. If you are unsure of what a command might do best do a google search first.
    • Keep your system up to date. Updates, particularly security updates, bring you the newest and latest fixes.
    • If you run a server, it is your responsibility to learn how to secure it.

    Psychocats ~ Security on Ubuntu

    Thanks to Johan! for the advice on 3rd party repos

    Note: Social Engineering. Click here for more information.

    Social engineering is a collection of techniques used to manipulate people into performing actions or divulging confidential information.[1] While similar to a confidence trick or simple fraud, the term typically applies to trickery for information gathering or computer system access and in most cases the attacker never comes face-to-face with the victim.

    ~ Quote from Wikipedia

     

    The Windows Mindset

    If you are coming from a Windows background you are used to terms like antivirus, spyware, and firewalls. Linux is different and these are not as important. They are discussed first because these are FAQ on the forums. Unfortunately, it is sometimes difficult for new users to wade through some of the FUD (some of which is produced by anti-virus companies) …
    Viruses

    The fact of the matter is: viruses/worms take advantage of flaws or holes in the code. At this time of this writing, there are no significant Linux viruses “in the wild”. Linux boxes are no less targets than any other OS, many of the large (ie valuable) Internet sites run on *nix so there is no lack of motivation to crack into *nix.

    Do not believe the suggestion that the Linux community is complacent or “behind the times” in terms of viruses, or any other security issue. Linux developers have not “ignored” viruses, rather the OS is built to be highly resistant to them and since the code is “Open” there are literally thousands of eyes watching …

    This is an example of what it would take to install malware on an Ubuntu box :

    Install evilmalware

    (Don’t worry, that link will NOT install anything )

    For the most part, Linux anti-virus programs scan for Windows viruses which do not run on Linux. There are increasing reports, however, that Windows malware may run in wine, as such I added a section reviewing what I feel you should know about security if you choose to install and run wine (see below).

    Please understand, anti-virus programs, and in fact most HIDS, are “reactive” in that they can only protect you from known viruses. They can only protect you against malware after it is developed and incroporated into HIDS, not before. Furthermore the “fix” will be to close any hole(s) in the code, these fixes will be available through security updates (which are more frequent in Linux then your previous OS if you are coming from Windows).

    Reasons AGAINST antivirus on Ubuntu:

    1. They scan primarily for Windows viruses.
    2. There is a high rate of false positives.
    3. Isolation/inoculation is poor.
    4. And currently there are no known active Linux viruses (so there is essentially nothing to detect).

    Reasons FOR antivirus on Ubuntu:

    • You are running a file or mail server with Windows clients.
    • You wish to scan files before transferring them, by email, flash drive, etc., to a Windows machine.

    Running antivirus can make some sense if you are intending to “protect” Windows users, however, IMO, for a variety of reasons, it is best if Windows users learn to protect themselves.

    Note: There have been many documented cases in Windows and Linux that a buffer overflow in an antivirus product has been an attack vector!

    If you would like to run an antivirus program on Ubuntu you have several choices :

    A few comments on wine

    Discussions about running Windows viruses on wine crop up from time to time and it is possible to run some Windows viruses on wine.

    See these links :

    So what do you need to know about Windows viruses if you want to run wine?

    1. First, the “golden rule” : DO NOT RUN WINE AS ROOT. If you are NOT running wine as root then wine will not have the necessary permissions to affect system files.

    2. So, if you are running wine as a user, a Windows virus will be confined to your home directory.

    3. You can further confine the “fake c drive” located at ~/.wine if you remove any symbolic links outside ~/.wine. With a default installation there is link with a default installation / configuration of wine :

    • ~/.wine/dosdevices/z: -> links to /

    A link from ~/.wine/dosdevices to the root directory ( / ) should concern you for obvious reasons.

    You can remove it with :

    Code:

    unlink ~/.wine/dosdevices/z:

    Do not worry, that command will not affect wine at all, I run it all the time

    You may need to make a link in ~/.wine/dosdevices to your cdrom and/or you may be tempted to link to your home directory, but I advise against keeping using these links (beyond the time needed for actually installing applications).

    I advise against any links to removable devices (it should not be *that* difficult to copy files needed to the appropriate location in ~/.wine/drive_c ).

    4. Consider running an antivirus program and scanning ~/.wine and any removable devices or other locations you use outside of ~/.wine to store programs or data to be used with wine. Scan any data / applications you use with Windows.

    5. Consider confining wine with Apparmor.

    6. Be sure to file a bug report with the wine project as they have a very active security team (it is unrealistic, however, to expect the wine team to be able to protect you from all Windows viruses all the time). Wine Bug Reports

    7. Take the same precautions with wine as you would with Windows. Do not install untrusted applications from untrusted sources.

    If you follow the above advice, Windows viruses will be confined to ~/.wine and they do not have permission to change system files. This means to remove them you simply:

    Code:

    rm -rf ~/.wine

    Please take care, this command deletes everything in your wine directory including all data and all applications.

    You then need to restore your wine directory from a known good backup (you do keep backups ?).
    Firewall

    Edit: I posted a series of 3 blogs introduction firewall configuration :

    GUFW (gui)

    UFW – Desktops

    UFW – Servers

    Discussions about firewalls often are passionate (just search the Ubuntu forums). By default, Ubuntu includes a firewall, iptables, but by default nothing is engaged. This is reasonable as a default Ubuntu install opens zero ports to the outside world, so a firewall is redundant. However, installing “server software” will cause ports to open, so some people like to use a firewall as a catch-all layer to find mistakes in their configuration.

    Another use for firewalls is for the administrator to forcibly impose network policies on the user. For example, users may not talk to example.com, open up a listening port for remote connections, and so on.

    Also, a periodic audit of the system for open ports is a good practice. For example, running the “nmap” command from another machine, or using one of many online port scanners:

    http://nmap-online.com/

    https://www.grc.com/x/ne.dll?bh0bkyd2

    Remember, what you care about are open ports. Closed ports and stealth ports are equally secure, in that they are inaccessible to the public.

    Iptables references :

    update: I wrote an iptables reference here : bodhi’s iptables primer.

    The “problem” with iptables is that it is not particularly friendly to new users. Fortunately, there are several more user friendly interfaces available to allow you to manipulate your firewall (UFW, Firestarter, and Guarddog) :

    A source of confusion sometimes occurs when users feel the need to be running firestarter/Guarddog for their firewall to be active. This is untrue ! Keep in mind that these applications are not firewalls, but rather configuration tools for ip tables. These applications should be run only to configure your firewall. Once configured, IP tables (the actual firewall) is active (at boot) without having to run firestarter/guarddog. firestarter will monitor traffic, but it runs as root and there are better monitoring programs, so configure you firewall, shut down firestarter/grauddog, and let IP tables do the rest .
    Browser / Spyware : Java/Flash/Ad-ware/Trackers/Cookies

    This is where most users will have the most risk. We all want Java/Flash, but our Internet browser opens us to attacks.

    I advise :

    1. Deny all cookies and add trusted sites, allowing only for session.
    2. Install NoScript. Again block all and add trusted sites to a white list.
    3. Install Safe History
    4. Adblocking : I block with a hosts file rather then Adblock Plus or Adblock Filterset.G because a hosts file protects more then just firefox.

       

    Edit: Thank you Seisen for pointing out that No Script also blocks flash.
    See this link for additional information : How to Secure Firefox

     

    The Ubuntu Mindset

    Permissions and Encryption

    The first layer of defense is file permissions. Permissions are used to set access and thus protect both system and user files.

    Basic permissions

    Ubuntu wiki File Permissions

    See also umask at the bottom of that link. The umask value can be set in ~/.bashrc.

    To set a “private home”, as a user,

    Code:

    chmod 700 $HOME

    Sharing files in UNIX

    Encryption is used as an additional layer of protection. One limit of encryption is that protection is only offered when mounting an encrypted partition (once the partition is mounted it is accessible/crackable just like any other file). The tools included with Ubuntu include GPG, LUKS, and ecryptfs.

    GPG

    Advanced GnuPG Concepts – Advanced Key Generation

    LUKS

    LUKS is available as an option on the “alternate” CD.

    How to install Ubuntu into an encrypted partition using the Alternate CD

    Herman’s guide – Ubuntu Encrypted Flash Memory Installation ~ Thank you Herman

    Additional links on LUKS:

    Ecryptfs

    With ecryptfs you can encrypt your home directory (both desktop and alternate CD as of Ubuntu 9.04 Jaunty), swap, a private directory, or any other directory.

    bodhi.zazen’s Ecryptfs tutorial

    Truecrypt

    http://www.howtoforge.com/truecrypt_data_encryption

    Root kits

    From http://en.wikipedia.org/wiki/Rootkit :

    The term rootkit (also written as root kit) originally referred to a set of recompiled Unix tools such as ps, netstat, w and passwd that would carefully hide any trace of the intruder that those commands would normally display, thus allowing the intruders to maintain root access (highest privilege) on the system without the system administrator even seeing them.

    The term is no longer restricted to Unix-based operating systems …

    Root kit detection:

    rkhunter

    chkrootkit

    Intrusion Detection

    Note: Adding an intrusion detection system like Snort that analyzes network traffic for attack patterns, it can potentially introduce additional vulnerabilities. There have been documented examples of vulnerabilities in Snort’s preprocessor that granted hackers Snort user, or even root user, access to the system!

    My initial suggestions are OSSEC HIDS and Snort.

    See : Ubuntu Forums ~ Intrusion Detection

    How to’s:

    Compiledkernel’s Suggested Applications

    compiledkernel’s suggested applications (Nagios, ntop, and darkstat are in the Ubuntu Repositories, check the home page to see if newer versions are available):

    • Nagios ~ A host and service monitor designed to inform you of network problems.
    • ZenOSS ~ An open source IT monitoring product that delivers the functionality to effectively manage the configuration, health, performance of networks, servers and applications through a single, integrated software package.
    • ntop ~ A network traffic probe that shows the network usage, similar to what the popular top Unix command does.
    • darkstat ~ A packet sniffer that runs as a background process on a cable/DSL router, gathers all sorts of statistics about network usage, and serves them over HTTP.

    Running Server(s)

    Part of setting up a server is reading/learning how to secure it. Common servers include NFS, Samba, FTP, SSH, VNC, RDP, and HTTP. If the “how-to” you are following does not review security, you need to keep looking …“Desktops” become “Servers” if server software is installed.

    Questions to ask yourself include:

    1. What port(s) or services does this software provide?
    2. Who will be able to connect to this? (i.e. is it restricted to a range of IP addresses Password protected?)
    3. What level of access will the visitor have to the system? (i.e. does the server run under a restricted user, or the root acount? What can this restricted user do in a worst case scenario?)
    4. Does this service expose any additional information that’s useful to a hacker? (i.e. does it allow users to transmit their passwords in cleartext? Does it have a ‘statistics’ view that reveals logged-in users, ip addresses, network configuration, or other potentially helpful information?)
    5. What is the security history of this software? Does it have a history of vulnerability and patch after patch? Or has it had a relatively unmarred history?

    Examples :

    SSH

    VNC

    Apache
    Hardened Kernels

    Hardened kernels are modifications to the Linux kernel that add additional security measures. This could include:

    1. The randomization of ports, memory addresses, process ID’s, and other information that is typically predictable. This can thwart off many types of common attacks.
    2. Identify and prevent buffer overflow attacks from resulting in compromise by killing compromised processes (PaX bundled with grsecurity, or Redhat’s Exec-Shield combined with prelink randomization). Edgy and higher contain GCC stack protection enforced in most applications, but is unable to respond to several kinds of attacks that a kernel-layer enforcer could. Likewise, PaX and friends have weakness that GCC stack protection helps cover, so the two work great as a duo.
    3. Hiding information that Linux usually allows everyone to see, including all running processes on the system, load averages, CPU info, IP addresses, etc. Obscuring this information can help keep attackers “in the dark” so to speak.
    4. More aggressive enforcement of buffer overflow protection than what Ubuntu’s standard gcc stack protector can do.
    5. Adding additional restrictions on the capabilities of regular users that prevent channels of attack.
    6. Additional permissions systems that allow finer-grained tuning of various aspects of Linux.

    These techniques combined have been shown to be very effective in the real world in guarding against unknown attacks. For example, many administrators of hardened kernel servers either report or even prove that their hardened systems were invulnerable to newly discovered security holes, or that the severity of a breach was significantly reduced.

    The most common hardened kernel patch is called “grsecurity2” (http://grsecurity.org/), which does everything on this list. This requires, however, that you manually patch and recompile the kernel. SELinux and AppArmor do the “additional permissions systems” part. The basic theory is that by providing finer definitions of permissions than UNIX users and the “chmod” bits, even a successful attack against one service is virtually useless to attacking the rest of the system.

    Note: AppArmor is installed by default as of Hardy, Ubuntu 8.04. There are , however, minimal profiles and they are set to complain mode.

    AppArmor Links

    AppArmor ~ Ubuntu Community Wiki

    AppArmor Geeks (OpenSUSE)

    bodhizazen’s (and others) AppArmor repository

    All of these hardened systems, however, take effort on the administrator’s behalf to implement. They also take a lot of trial-and-error to find the correct balance of user functionality and security restrictions. Tightening the rules too much could cause various applications to stop working, and not tightening them enough could lead to a weaker security setup.

    If you run a large multiuser system where you must grant people shell access, or run services that have that unfortunate long history of attacks, then it is highly recommended that you look into setting up a hardened kernel.
    Reading the Logs

    Learn how to read your system logs and become familiar with “normal” activity. It should go without saying, your first introduction to system logs should *not* be when you suspect your system has been compromised.

    You should also be aware that if someone has root access they can alter system logs. This is when it is most helpful to be aware of “normal” activity.

    Ubuntu wiki ~ Linux Log Files

    There is a package called “logwatch” that e-mails to you the new portions of your log every night. This can help make log reading more enjoyable.
    How to perform a hardened installation

    This how to will walk you through a hardened install with an encrypted root partition and other goodies.

    This is a link to a how to for Debian :

    Towards a moderately paranoid Debian laptop setup

    You will need to use the “Alternate” install disk.

    How to Alternate Install

    Thank you to Uwe Hermann for posting a How-to for the moderately paranoid and hermanzone for the How-to with the alternate CD
    Screening your system

    There is a package, tiger, which will screen your system for potential security holes. While not complete it may be an excellent place to start (tiger does not check your firewall for example).

    For an overview of tiger see man tiger , scroll to the bottom and you will see a listing and brief description of the tests performed (modules).

    Install by any means, tiger john chkrootkit

    Code:

    sudo apt-get install tiger john chkrootkit

    Run tiger from the command line with :

    Code:

    sudo tiger -H

    The -H flag will produce a very nice HTML document.

    The command tigexp can be used to explain the results.

    $ /usr/sbin/tigexp pass014w

    The listed login ID is disabled in some manner (‘*’ in passwd field, etc),

    but the login shell for the login ID is a valid shell (from /etc/shells

    or the system equivalent). A valid shell can potentially enable the

    login ID to continue to be used. The login shell should be changed to

    something that doesn’t exist, or to something like /bin/false.

    Tiger should give you some ideas on things to research. As always there can be false positives so take care not to either panic or blindly make system changes without understanding what you are doing and how to undo your changes (ie make backups of system files before you edit them).

    Forensics

    What to do when you think you have been cracked :

    1. Power off.
    2. Disconnect/disable your Internet connectivity.
    3. Now take a deep breath, re-boot, and read the logs. Ask for help if needed, but you really need to confirm that your system has been compromised.
    4. If you have been compromised, and have the time and interest, boot a live CD and image your hard drive. This image can then be used for forensic analysis.
    5. Re-install. Unfortunately, IMHO, there is no way to trust a compromised system.
    6. When you install, be sure to install off line, use a stronger password, and research intrusion detection.

    Intrusion References

    CERT® Coordination Center (CERT/CC)

    CERT® Coordination Center ~ Intruder Detection Checklist

    Linux Forensic Analysis Part 1

    Linux Forensic Analysis Part 2

    Linux Distro listing – Penetration Testing Specific
    Whew …
    Further Reading:

    Ubuntu wiki ~ Security page

    Ubuntu wiki ~ Installing Security Tools

    UDSF Security Analysis Tools

    The Big Ol’ Ubuntu Security Resource

    Locking Down Ubuntu

    Ubuntu geek ~ Security category

    Security references Topics include Basics, firewall, Intrusion detection, Chroot, Forensics/Recovery, and Securing networked services.