Friday, 19 November 2010

LDAP

Port 389 talks to the local AD server, and can see the local AD tree. Port 3289 talks to the 'Global Directory' on the AD server - if the option is enabled, and can see the whole forest if you have more than one tree in the directory - of course the other trees would be on other servers - but the info is consolidated into one forest.

Jxplorer - good open source LDAP browser

sAMAccountName attribute is used to store user name in Active Directory

"protocol://hostname:port/base?attribute?scope?filter" NONE

Thursday, 11 November 2010

Tuesday, 5 October 2010

Kerberos

Here made I some notes during configuration of Kerberos authentication on Dokuwiki web app via Active Directory, it was quite a big challenge for me :)

Kerberos is based on 3 things: key distribution server(KDC), kerberized server and client. For example let's look how it works in AD. In AD environment KDC is domain controller.
There are two abstraction layers to choose from: GSSAPI and SSPI. GSSAPI, or the “Generic Security Services API,” is the API provided by Unix-based Kerberos 5 implementations. SSPI, the “Security Support Provider Interface,” is Microsoft's answer to GSSAPI and, of course, available only for Windows 2000 and above.
Microsoft uses SPNEGO, the Simple and Protected Negotiation mechanism. SPNEGO provides a method where server and client can mutually negotiate the best authentication mechanism to use (in this case, NTLM and Kerberos). The use of SPNEGO for web-based authentication is referred to as the HTTP Negotiate protocol. Once the negotiation is finished, then the mutually agreed upon authentication mechanism can begin. In this case, we'll only be compatible with the Windows Kerberos authentication mechanism; it will fail if Windows attempts to use NTLM instead.


When user enters domain, he recieves Ticket Granting Ticket(TGT). Whe he tries to enter web server with kerberos authentication, IE sends request HTTP/DNS_name_of_plug-in_server@Active_Directory_domain_name to domain controller. After this user gets Session Ticket, encrypted with password of user, that is bind to the service.  Then this Session ticket would be sent to web server. Web server decrypts it with keytab file.

To see users binded to services this manual can be used:  When multiple accounts are binded to one service
To bind user to service, ktpass command is used:

ktpass -out wiki.keytab -princ HTTP/wiki.test.ru@TEST.RU -mapuser fil -pass 123




Monday, 4 October 2010

Writing a security policy


Every security policy should have:

  • policy statement

  • standards

  • guidelines

  • procedures


To write security policy, first of all you need a base for it. 
For instance, you may use PCI DSS requirements: 2.1, 2.2.1, 2.2.2, 2.2.3, 2.2.4, 2.3, 5, 8.4, 8.5.9-8.5.15, 10.2, 10.3, 10.5, 10.7, 10.4, 11.5.
Another good practice is using standards and best practices from vendors and security organizations, such as:
http://iase.disa.mil/stigs/checklist/

Thursday, 23 September 2010

Virtualization

Vmware Server uses two ports: 8333/TCP(HTTPS) for web administration and 902/TCP for console.


To fix error when trying to install VMWare Server 2.0 on Windows:
Start > Control Panel
Open Administrative Tools
Open Local Security Settings
Click Software Restriction Policies a. If no software restrictions are defined, right click the Software Restriction Policies node and select New Software Restriction Policy
Double click Enforcement
Select “All users except local administrators”
Click OK
Reboot the machine or run gpupdate /force

Resize virtual hard disk. 
You can do this using vmware-vdiskmanager program. For example to set new size to 20 GB:
vmware-vdiskmanager -r 20GB disk.vmdk

Show running virtual machines in Vmware server:
vmrun -T server -h http://127.0.0.1:8222/sdk -u root -p password list

Tuesday, 21 September 2010

Printing tips in Linux


  • lpr sends print jobs to specified queue

  • Usually queue is a directory /var/spool/cups

  • CUPS daemon monitors queues and connections from network

  • Old printer daemon is LPD

  • CUPS sends print queues to printers

  • Ghost script translates from Postscript to specific printer language

  • Ghost sript is injected into the print queue via smartfilter

  • CUPS has it's own collection of smartfilters

  • CUPS is available via http://localhost:631

  • U can print some pages on one sheet using mpage command

  • lpq command is used to display print queues

  • lprm command is used to delete jobs from print queue

  • lpc command and CUPS web panel are used to manage print queues

  • Enable, disable queue: cupsenable, cupsdisable

  • lpmove command moves jobs from one queue to another

Friday, 17 September 2010

DPKG & APT

In order not to always read mans, I have collected these short tips.

dpkg database: /var/lib/dpkg
Apt cache, that stores packages: /var/cache/apt/archives
To clean this cache:
aptitude clean

Only download package, without installing:
aptitude download package_name

List all installed packages:
dpkg -l
or
apt-cache pkgnames

List all files of the package:
dpkg -L package

What package contains a file?
dpkg -S path_to_file

Print information about package:
dpkg -p package

What packeges are upgradeable?
apt-show-versions -u

Shows what packages are installed partially and suggests, how to correct this situation
dpkg -C

Verify package, showing what files(including configuration) are changed:
debsums -ac package_name

Backup and restore list of installed soft:
dpkg --get-selections > /backup/installed-software.log
dpkg --set-selections < /backup/installed-software.log

Remove package with configuration files:
dpkg -P package

Reinstall package:
aptitude reinstall package

Add CD-ROm to source file
apt-cdrom add

Upgrade the whole distro:


  • Backup everything important

  • Do everything using “screen” command, if you control server via SSH.

  • dpkg --audit

  • Change sources in /etc/apt/sources.list

  • aptitude update

  • aptitude install aptitude

  • aptitude safe-upgrade

  • aptitude full-upgrade




Configure update servers
# apt-setup

Missing key for updates
gpg --keyserver pgpkeys.mit.edu --recv-key  010908312D230C5F
gpg -a --export key_ID |  apt-key add -

Before installing Vmware tools
apt-get install build-essential linux-headers-`uname -r` psmisc

RPM

Main RPM configuration file is /usr/lib/rpm/rpmrc. This file sets a variety of options, mostly related to the CPU optimizations used when compiling source packages. You shouldn’t edit this file, though; instead, you should create and edit /etc/rpmrc (to make global changes) or ~/.rpmrc (to make changes on a per-user basis). The main reason to create such a file is to implement architecture optimizations—for instance, to optimize your code for your CPU model by passing appropriate compiler options when you build a source RPM into a binary RPM.

What package contains file?
rpm -qf /sbin/iptables

Show information about the packege:
rpm -qi package

List all installed packages
rpm -qa

List files in package
rpm -ql package

List configuration files of the package:
rpm -qc package

View changelog of the package:
rpm -q --changelog package

Upgrade or install package:
rpm -U packagename

Upgrade package only if it exists:
rpm -F packagename

Install package older than existing one:
rpm -i --oldpackage

Yum


Update package:
yum update or upgrade package

Check updates:
yum check-update

Remove package with yum:
yum remove or erase package

Information about package:
yum list package

Discovery alive hosts using nmap

This script searches alive hosts, using ping, tcp and udp scanning. Nmap input syntax is accepted, for example 192.168.1.0/24.
Two files are generated at the end:
network_number_alive_hosts - results of script, list of alive ip addresses
network_number_log - log of the scan

#!/bin/bash
#variables
name=$(echo $1 | tr '/' '_')_alive_hosts
log=$(echo $1 | tr '/' '_')_log
tcp_ports=21,22,23,25,53,80,88,110,135,137,148,139,443,445,990,8080,3128
udp_ports=53,88,123,137,138,161,500,514
echo -e "$(date)\nDiscovery of network $1 started" > $name

#ping scan
nmap -sP -oG ping.txt $1 > $log
cat ping.txt | grep Up | cut -d" " -f2 >> $name
cat ping.txt | grep Down | cut -d" " -f2 > nmap.txt
#tcp&udp scan
nmap -PN -T4 -sT -sU -p T:$tcp_ports,U:$udp_ports -iL nmap.txt -oG ports.txt >> $lcat ports.txt | egrep "open/|closed" | cut -d" " -f2 >> $name
echo "Finish of discovery: $(date)" >> $name
#delete temp files
rm nmap.txt ping.txt ports.txt
Search alive hosts from network list and compares with list of existed addresses

#!/bin/bash
folder=$(date +%d-%m-%g)
mkdir $folder
while read line
do
#variables:
name=$(echo $line | tr '/' '_')_alive_hosts
log=$(echo $line | tr '/' '_')_log
tcp_ports=21,22,23,25,53,80,88,110,135,137,148,139,443,445,990,8080,3128
udp_ports=53,88,123,137,138,161,500,514
echo -e "$(date) - Discovery of network $1 started" > $folder/$name
#ping scan
nmap -sP -oG ping.txt $line > $folder/$log
cat ping.txt | grep Up | cut -d" " -f2 >> $folder/$name
cat ping.txt | grep Down | cut -d" " -f2 > nmap.txt

#tcp&udp scan
nmap -PN -T4 -sT -sU -p T:$tcp_ports,U:$udp_ports -iL nmap.txt -oG ports.txt >> $folder/$log
cat ports.txt | egrep "open/|closed" | cut -d" " -f2 >> $folder/$name
echo "Finish of discovery: $(date)" >> $folder/$name
cat $folder/$name | egrep -iv "discovery" >> $folder/final

#delete temp files
rm nmap.txt ping.txt ports.txt

done

sort ips > ips2\
sort $folder/final > final
comm -23 final ips2 > newhosts

rm final ips2

Friday, 10 September 2010

Linux backup

Backup files and databases to Linux box via scp with encryption and email notification

#!/bin/sh.
#Backup server options
server=11.11.11.111
user=user
key=/path/key.key
port=22222
backup_dir=/path/


#Archive options
date=`date +%F`
arc_name=arc_$date
tar_dir=/path
data="/var/www/ /etc"
days=22
logfile=/var/log/backup.log
admin=admin@domain.com



#Database options
mysql_u=user
mysql_p=password
databases=database




#Encryption options
gpg_key=email 



mysqldump --add-drop-table -u $mysql_u -p$mysql_p $databases > $tar_dir/$date.db 2>>$logfile &&

tar czf - --exclude={*.tar.gz,*.sql} --ignore-failed-read $tar_dir/$date.db $data > $tar_dir/$arc_name.tar.gz  | gpg -e -r $gpg_key > $arc_name-$date.tar.gz.gpg 2>>$logfile


 /usr/bin/scp -P $port -i $key $tar_dir/$arc_name.tar.gz.gpg $user@$server:$backup_dir 2>>$logfile &&
find $tar_dir -mtime +$days -exec rm {} \; 2>>$logfile &&
echo "$date - Backup successfull" >> $logfile ||
echo "There are some problems with backup on $arc_name" | mail -s "Backup: $arc_name problems" $admin

Backup data and databases to windows share folder

This small script encrypts and backups data and mysql databases to windows share using CIFS protocol. It also logs it's operations and sends notifications to administrator in case of problems.


#!/bin/sh 



#CIFS server options 

server= 

folder= 

user= 

pass= 

domain=DOMAIN 



#Logs and notifications options 

admin=Administrator e-mail 

logfile=/var/log/backup.log 



#Encryption options 

key=GPG public key ID

#Archive options 

arc_name=The name of archive 

backup_dir=where to store database copies 

data="what files and directories to backup" 

mountpoint=/mnt/backup days=10 - how many days to store archives 

date=`date +%d-%m-%Y` - date format 



#Mysql options 

databases="database1 database2" 

mysql_user=root 

mysql_pass=root 



mount.cifs //$server/$folder $mountpoint -ouser=$user,pass=$pass domain=$domain 2>>$logfile &&
/usr/bin/mysqlhotcopy --addtodest --user=$mysql_user --password=$mysql_pass $databases $backup_dir/db 2>>$logfile && 

tar czf - $data $backup_dir/db | gpg -e -r $key > $mountpoint/$arc_name-$date.tar.gz.gpg 2>>$logfile &&
find $mountpoint -mtime +$days -exec rm {} \; 2>>$logfile &&

umount -f $mountpoint 2>>$logfile || 

echo "There are some problems with backup on $arc_name" | mail -s "$arc_name backup problems" $admin

Tuesday, 31 August 2010

Iptables

Iptables is a very powerfull firewall. It is included in all linux distributives nowdays.
The most detailed and comprehensive iptables manual: http://www.frozentux.net/documents/iptables-tutorial/
Here, on my page, are just some brief notes about this firewall.
Iptables consist of:
  • Tables, there are 4 tables: nat, filter, mangle, raw
  • Chains, which are part of tables
  • Matches
  • Commands
Typical iptables configuration
If you are planning to use NAT, you need to switch on IP packets forwarding in /etc/sysctl.conf file:
net.ipv4.ip_forward=1
and reboot your system, or just launch command:
sysctl -w net.ipv4.ip_forward=1
Here is the sample script for basic firewall configuration with some comments.

Setting variables and flushing all rules
#!/bin/bash 
iptables="/sbin/iptables" 
$iptables --flush

Configuring policies:
iptables -P INPUT DROP 
iptables -P OUTPUT DROP 
iptables -P FORWARD DROP 

Configuring NAT
iptables -t nat -A POSTROUTING -o $inet_int -j SNAT --to-source $inet_addr 

Rules for transit packets
iptables -A FORWARD -i $lan_int -p tcp -m multiport --dport 25,110,5190 -j ACCEPT 
iptables -A FORWARD -i $lan_int -p udp --dport 53 -j ACCEPT
iptables -A FORWARD -o eth1 –i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT 
iptables -A FORWARD -i $inet_int -p udp --sport 53 -j ACCEPT 

Drop all packets from reserved private networks
iptables -A INPUT -i $inet_int -s 10.0.0.0/8 -j DROP 
iptables -A INPUT -i $inet_int -s 192.168.0.0/16 -j DROP 
iptables -A INPUT -i $inet_int -s 172.16.0.0/12 -j DROP

Limiting bandwidth and number of connections
For example let's limit the number of new connections to our SSH server to 5 connections per minute:
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set 
iptables -A INPUT -p tcp --dport 220 -m state --state NEW -m recent --update --seconds 60 --hitcount 5 -j DROP

First line adds to a list of “recent” module information(timestamp and source ip address) abot every NEW packet with destinantion port TCP/22. In this example DEFAULT list is used, but you can use your own one:
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name ownlist 
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 5 --name ownlist -j DROP

The second line tells iptables to drop the packet if it is fith or more packet for last 60 seconds.

Limit number of connections from one IP
For example let's set limit to 10 connections from one IP address:
iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 10 -j REJECT --reject-with tcp-reset

Another example, let's limit the number of connections from Class C network:
iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 --connlimit-mask 24 -j REJECT --reject-with tcp-reset

Redirecting ports
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

Enable FTP
iptables -A INPUT -p tcp --dport 21 -m state --state NEW -j ACCEPT
Remember, kernel module nf_conntrack_ftp must be enabled.

Wednesday, 28 July 2010

MySQL tips

Create database
create database employees;

Grant permisssions to database for user
GRANT ALL ON database.* TO user@localhost IDENTIFIED BY "password";

Set root password for the first time
mysqladmin -u root password NEWPASSWORD

Change user password
UPDATE mysql.user SET Password=PASSWORD('foobar') WHERE User='john' AND Host='localhost';
FLUSH PRIVILEGES;

Show information about table including engine and character set:

show create table table_name;

Change character set for table 

alter table table_name convert to character set utf8 collate utf8_general_ci;

Show character set and collation for database
select your database, use database and then type


show variables like "character_set_database";
show variables like "collation_database";

Restore database from sql file 

mysql -u user -pozttbNUfQx -h hostname database < dump.sql

Make a backup of database with mysqldump

mysqldump -u $mysql_u -p$mysql_p $databases > db.sql

Watch permissions:


show grants for user@host;

Grant reload privilege, it is impossible to grant it for one database, it's global privilege:

GRANT reload ON *.* TO user@localhost;

mysqlhotcopy programm needs the following user rights: SELECT, RELOAD, LOCK TABLES, for example:

grant lock tables, select on database.* to user@localhost;

grant reload on *.* to user@localhost;

Show users:

SELECT Host,User from mysql.user;

Delete user:

drop user user@host;

Revoke grants from user
revoke all on db.table from user@localhost;

Show MySQL error codes description:
perror number_of_code

Error 24If during mysqldump or mysqlhotcopy you recieve error 24, that file not found, you can resolve this issue in two ways. First, you can edit option open_files_limit in mysql.cnf. It's default value is 1024. Another way is to add --single-transaction to mysqlhotcopy.

Linux tips

User name maybe 32 characters maximum

Find all files older than 10 days in /var/backup folder and delete them, excluding folders /var/backup/server1 and /var/backup/servers/server2
find /var/backup \( -path '/var/backup/server1' -o -path '/var/backup/servers/server2' \) -prune -o -mtime +10 -exec rm {} \;

Change file creation date to 11 days ago
touch -d "11 days ago" filename

Show GID of user, that runs a process 
ps -eo uid,gid,args

Show detailed information about software raid array
mdadm --detail /dev/md1

When was the last reboot?
root#server:/#last reboot

Create list of directories in tar archive
tar -ztvf file.tar.gz | grep "^d" | awk '{ print $6}' | sort | uniq

Clone a partition table fast
sfdisk -d /dev/sda > partition.txt

Edit the text file to match the other disk (in this example /dev/sdb).
sfdisk /dev/sdb < partition.txt

Remount filesystem for writing
mount -o remount,rw /

Back for reading
mount -o remount,ro /
 
Add route
route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.1 dev eth1
ip route add 192.168.1.0/24 via 192.168.1.1 dev eth1


Add proxy server temporally
export http_proxy=http://127.0.0.1:3128/

Add proxy server persistently
echo "export http_proxy=http://127.0.0.1:3128/" >> /etc/profile

Routers from box


  • Endian
  • pfSense
  • ClearOS
  • SmoothWall
  • ipcop
  • ebox
  • ZeroShell
  • Microtik

Friday, 23 July 2010

Permissions bits in Linux

SUID:
S instead of x in user permissions
It sets the process user owner to the file's user
It has no effect on directories
Set SUID:
chmod 4000 file
chmod u+s file

SGID:
S instaed of x in group permissions
It sets the process group owner to the file's group
Sets group for all new files in the directory, the same as directory's group
Set SGID:
chmod 2000 file
chmod g+s file



Sticky bit:
T instead of x in other permisiions
Files with sticky bit can be deleted onle by root ans files owner
Files in directory with sticky bit can be deleted only by root, file owner or directory owner, regardless of file permissions.
Set sticky bit:
chmod 1000 file
chmot o+t file

ProFTPd tips

Proftpd is very flexible FTP server. This post contains some ready-to-use examples of Proftpd configurations.

Hide FTP server version
ServerName "FTP"
ServerIdent on "FTP server"
DeferWelcome on


Allow only certain user to connect to Proftpd, no Anonymous access
<Limit LOGIN>
AllowUser barb
AllowUser dave
AllowGroup ftpusers
DenyAll
</Limit>


Script to add FTP user
This scripts is very simple and accepts two parameters: user's login and password
#!/bin/bash
useradd $1 -G ftpusers -d /ftp -s /bin/false
echo $1:$2 | chpasswd

Configure default user folder and allow /bin/false shell
DefaultRoot ~
RequireValidShell off

Allow writing files for only certain group
<Directory /ftp>
<Limit WRITE>
AllowGroup ftpusers
DenyAll
</Limit>
</Directory>

Deny writing and listing files during anonymous sessions
In <Anonymous ~ftp> section:
<Directory /ftp>
<Limit WRITE>
DenyAll
</Limit>
<Limit LIST NLST MLSD MLST STAT>
DenyAll
</Limit>
</Directory>

Forbid deleting files for a particular user in particular directory
<Directory /ftp/upload>
<Limit DELE>
      DenyUser ftpuser
</Limit>

</Directory>

DNS tips

Detect BIND version
dig @server_address -c CH -t txt version.bind

or via fpdns
fpdns server_address

Hide BIND version
version "DNS server";

Sample master server
/etc/bind/conf.local:

options
{
recursion no;
version "DNS server";
};

zone "domain" { 
type master;
file "/etc/bind/db.zone";
allow-transfer { slave_server;};
};


/etc/bind/db.zone
$TTL 3h
@ IN SOA ns1. email.domain (
2
12h
1h
1w
1h
)
@ IN NS ns1.
ns1 IN A 11.11.11.11
@ IN A 11.11.11.11
www IN A 11.111.11.111
@ IN MX 10 mx
mx IN A 11.111.11.111

  • @ - alias for domain
  • ns1 - name of NS server
  • email - email address of administrator
  • 2 - serial number
  • 12h - update interval, that would be used by slave DNS server
  • 1h - time between retries by slave to retrieve information, if connect failed
  • 1w - indicates that zone data is no longer authoritive, used only by slaves. They stop responding queries, after this time expires and no contact with master
  • 1h - this time interval determines how long ckients will store in cache error replies
Sample slave server
Create directory for backup file and grant permissions on it for user bind:

mkdir /var/bind
chown root:bind /var/bind
chmod 770 /var/bind


/etc/bind/conf.localoptions 
{
recursion no;
version "DNS server"; };
zone "domain" {
type slave;
file "/var/bind/db.zone";
masters { master; };
allow-transfer { none;};
};


Forward only server

/etc/bind/conf.local:
options {
directory “/var/named”;
forwarders { 10.9.16.30; 10.13.16.30; };
listen-on{ 192.168.1.1; 172.24.21.1; };
forward only;
recursion no;
version "DNS server";
};


Reverse zone sample

$TTL 1D
1.168.192.in-addr.arpa. IN SOA dns1.example.com. \ admin.example.com. 
( 2010022003 ; serial 3600 ; refresh 600 ; retry 604800 ; expire 86400 ; default_ttl ) 
1.1.168.192.in-addr.arpa. IN PTR dns1.example.com.
2 IN PTR horus.exmaple.com.
3 IN PTR ra.example.com.
@ IN NS dns1.example.com.


Monitor DNS requests
dnstop -l 3 eth0

http://www.zytrax.com/books/dns/

Bash

Links with good documentation about bash

Quoting in bash
There are two types of quoting: strong quotes(' ') and weak quotes(” ”). Strong quotes mean to treat all symbols inside them as literally symbols. Weak quotes treat some special characters as special characters… :) For example dollar sign:

echo "$SHELL" /bin/bash

Also, you can quote a single character using backslash(\), it's called backslash-escaping.

Hot keys in Bash
  • Ctrl-z - suspend key, puts the currently running process in background and pause it
  • Ctrl-c - kills the current command or process, by sending to it SIGINT(2) signal
  • CTRL-\ - stops command
  • Ctrl-d - kills the shell an End of file in commands
  • Ctrl-m - similar to press enter
  • To see al your control keys: stty -a
Builtin variables
  • $! - PID of last background job
  • $_ - final argument of previous command executed
  • $? - exit status of last command
  • $$ - Process ID (PID) of the script itself
  • $# - amount of arguments
  • $0 - the command itself
Read file line by line
while read line
do
echo "$line"
done


Create alias
For example to launch “ls –color” instead of “ls”.In .bashrc file:
alias ls="ls --color"
alias ..='cd ..'
alias d='ls -l | grep -E "^d"'


To redirect standard output and standard error to one file
program > file 2>&1


Logical operations
Double bars || mean logical OR.
For example command2 will be launched only if command1 fails:
command1 || command2

Double ampersands && mean logical AND.
For example, command 2 will be launched only if command1 is successful:
command1 && command2

Thursday, 22 July 2010

Best security practices for Apache, PHP, MySQL server

Set permissions to all configuration files
root:root 600

Restrict access to service files
files *.bak
order deny, allow
deny from all
/files

Files *.tmp
order deny,allow
deny from all
/Files

Files *.log
order deny,allow
deny from all
/Files
Directory ~ ".*\.svn"
Order allow,deny
Deny from all
Satisfy All
/Directory

Disable autoindex module or disable directory index, in virtual host or directory context
Options -Indexes

Limit usage of methods

Order allow,deny
Allow from all Order deny,allow
Deny from all

Configure fault tolerance
Timeout 60KeepAlive
OnKeepAliveTimeout 12
LimitRequestBody 1000000

Options IncludesNoExec

Options SymLinksIfOwnerMatch


Configure file integrity monitoring

Disable magic_quotes_gpc, allow_url_fopen, display_errors  in php.ini

Set open_basedir in Virtual host context to document root of the site + some sites require to include /tmp dir to openbase_dir

Set max_connections in my.cnf to appropriate value, for example 100 for small site.
Set max_connect_errors in my.cnf to 10
Disable LOCAL INFILE syntax: set-variable=local-infile=0
Disable show databases command: skip-show-database

Hide Apache version
ServerTokens Prod
 ServerSignature Off

Disable TRACE method:


RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^TRACE
RewriteRule .* - [F]

or
TraceEnable off

Apache 2.0 Hardening Guide
About SSL cipher suite


Hide PHP version:

In php.ini:
expose_php = Off

Allow PHP to access only certain dirs

in Virtualhost:
php_admin_value open_basedir

php_admin_value upload_tmp_dir

php_admin_value session.save_path


But if just enable these options, PHP will publish Warnings to the page with undesireable information. To prevent it you need to disable warnings. First method is to write ”@” before function. Another method is to specify in php.ini:
display_errors = Off

Third method is to add to the script: ini_set('display_errors', 'Off');

allow_url_fopen=no

Thursday, 15 July 2010

Filesystems, files


  • ext2 - filesystem without journaling.

  • ext3 - pre-allocates number of inodes at creation time.

  • jfs - journaled file system from IBM

  • xfs

  • reiserfs - is a good choice for handling filesystems with many small files.

  • FAT(12,16,32) - msdos name is used for variant of this filesystem, that supports only 8.3 filenames. vfat name designates version, that supports long names.

  • NTFS

  • HFS, HFS+ - Hierarchical File System from Apple

  • ISO-9660 - The standard filesystem for CD-ROMs, Rock ridge extensions are available

  • Joliet - filesystem for CD-ROM's was created by Microsoft for use by Windows

  • UDF - The Universal Disc Format (UDF) is the next-generation filesystem for optical discs



Determine superblock location:
dumpe2fs /dev/sda1|grep -i superblock

Repair filesystem, using alternative superblock:

e2fsck -f -b 8193 /dev/sda1

XFS tools:
xfs_info - provides info about xfs partition, requires that the filesystem be mounted
xfs_metadump - copies the filesystem’s metadata (filenames, file sizes, and so on) to a file.
xfs_admin - tuning xfs partition

To tune ext2/ext3 filesystems you can use tune2fs utility

debugfs is a swiss army knife for ext2/ext3 file systems,This program provides the abilities of dumpe2fs, tune2fs, and many of Linux’s normal file-manipulation tools all rolled into one. It is possible to undelete files, extract files from damaged systems, get information and much more using this programm.

Get information about filesystem:

dumpe2fs -h /dev/sda1
or

tune2fs -l /dev/sda1

Search for bad blocks:

e2fsck -c
or

mkswap -c



There are several methods of locating files in linux:

  • find - search files using your patterns(size, owner, name, mtime, atime)

  • locate - search only names, it returns all names, containing the specified string. It works from a database that it maintains. Most distributions include a cron job that calls locate with options that cause it to update its database periodically, such as once a night or once a week. (You can also use the updatedb command to do this task at any time.) For this reason, locate may not find recent files, or it may return the names of files that no longer exist. If the database-update utilities omit certain directories, files in them won’t be returned by a locate query.

  • whereis - searches for files in a restricted set of locations, such as standard binary file directories, library directories, and man page directories.

  • which - searches your path for the command that you type and lists the complete path to the first match it finds.

  • type - This command isn’t really a search command; instead, it tells you how a command you type will be interpreted—as a built-in command, an external command, an alias, and so on.


Finding files based on certain permission bits
To search files, containing certain permissions, we use find command:
find path -perm permissions
Permissions can be described in symbolic or octal form. By default find will search the exact permissions, you have defined, for example

find . -perm u=r
will search files with permissions 400. To perform more flexible search you can use / or - symbols. / means match any of permissions. - means exact match. + earlier used, but now is deprecated, / is used instead. For example:

find . -perm /og=r
will search files with o=r or g=r or both. And

find . -perm -og=r
will search only files with g=r and o=r.
Find files larger than 100 kilobytes:

find . -size +100k



Inode
As we know, in Linux everything is a file. Every file is described by inode (index node). Inode consist of:

  • File type (executable, block, character, named pipe, socket, directory, link, etc)

  • Permissions

  • Owner

  • Group

  • File Size

  • File access, change and modification time (UNIX or Linux never stores file creation time)

  • File deletion time

  • Number of links (soft/hard)

  • Extended attribute such as append only or no one can delete file including root user (immutability)

  • Access Control List (ACLs)

To see file's inode you can use command:
ls -i /etc/passwd 131260 /etc/passwd

To see all information you can use stat command:

stat /etc/passwd


Show inode usage of file system: 

df -i /dev/sda1




Timestamps
There are 3 types of types of timestamps:
Access timestamp(atime) - it is set during any read or write operation, you can see access time, using command:

ls -lu file
Change timestamp(ctime) - it is set during changing status of the file, for example changing permissions or ownership, you can see this time using command:

ls -lc file
Modification tymestamp(mtime) - it is set during any write operation, you can see this tyme using command:

ls -l file

Touch program is used to change atime and mtime to current or specified time. If you just run touch without options, it would change atime and mtime of the file to current time. To change only atime -a option is used: touch -a file

To change only mtime -m option is used:

touch -m file

If you want to change timestamps to specified time, you need to use -t or -d options:

touch -t 200812012300.23 file 

touch -d '25 Jan 2008 10:22' file



Tips

Delete file using it's inode:
find . -inum [inode-number] -exec rm -i {} \;

Show directory tree:

tree -d /etc | less

Change file/directory permissions separately:

Directories: 

find . -type d -exec chmod XXX {} \; 

Files: 

find . -type f -exec chmod XXX {} \;

Create hierarchy of directories:

mkdir -p dir1/dir2/dir3

Determine type of the file:

file filename

Create FAT32 partition:
mkdosfs -F 32 /dev/***

Find files, containing “text”
grep -Hlr "text" /path 



Delete old files:
find /backups/tars -mtime +10 -exec rm {} \;

Shared Libraries in Linux

The main administrative task for shared libraries is to tell programs how to find libraries. It can be done by setting a library path. You can set it systemwide or temporarily.
To change or add path systemwide, you need to add path or conf file, containing path, to /etc/ld.so.conf:/path include /etc/ld.so.conf.d/*.conf
For changes take effect you need to launch ldconfig
/lib and /usr/lib are always in library path, even if they aren't listed in /etc/ld.so.conf
To add or change path temporarily you need to set the LD_LIBRARY_PATH environment variable:
$ export LD_LIBRARY_PATH=/usr/local/testlib:/opt/newlib
You can use ldd command to see what libraries the program links to.

Linux kernel


  • Kernel version consist of Major version.Minor version(even numbers for stable, odd numbers for develpment).Patch version. For example: 2.6.26

  • Modules directory: /lib/modules

  • Tools to control modules:

  • insmod - insmod is a trivial program to insert a module into the kernel. This version of insmod is for kernels 2.5.48 and above. If it detects a kernel with support for old-style modules (for which much of the work was done in userspace), it will attempt to run insmod.old in its place. Most users will want to use modprobe(8) instead, which is cleverer.

  • rmmod - simple program to remove a module from the Linux Kernel. Most users will want to use modprobe(8) instead, with the -r option.

  • lsmod - is a trivial program which nicely formats the contents of the /proc/modules, showing what kernel modules are currently loaded. The lsmod command displays information only about kernel modules, not about drivers that are compiled directly into the Linux kernel.

  • modinfo - program to show information about a Linux Kernel module.

  • modprobe - program to add and remove modules from the Linux Kernel

  • depmode - program to generate modules.dep and map files. Starts with a system.

  • System.map file - is a listing of all symbols along with their address.

  • Config file - kernel configuration file generated by make menuconfig/make xconfig/make gconfig

  • initrd.img file - contains device drivers which are required to boot and load rest of operating system from disk. Usually SCSI and IDE drivers are stored in this file.

  • /etc/modules file contains list of modules, that are loaded during system boot

  • /proc/cmdline - options provided to kernel by bootloader

Linux boot


  • Inside the Linux boot process
  • Directories /etc, /bin, /sbin, /lib, and /dev—should never be placed on separate partitions. These directories host critical system configuration files or files without which a Linux system can’t function. For instance, /etc contains /etc/fstab, the file that specifies what partitions correspond to what directories, and /bin contains the mount utility that’s used to mount partitions on directories.
  • Super GRUB disk
  • System rescue CD

Hardware in Linux

Links




Devices

  • Block devices - is an abstraction layer for any storage device that can be formatted in fixed-size blocks; individual blocks may be accessed independently of access to other blocks. Such access is often called random access.

  • Character device

  • ATA devices - /dev/hdx

  • SATA devices - /dev/hdx or /dev/sdx

  • SCSI devices - /dev/sdx

  • ATA magnetic tape devices - /dev/htx or /dev/nhtx

  • SCSI magnetic tape devices - /dev/stx or /dev/nstx



Information about hardware

  • /proc/partitions - shows all block devices

  • /proc/dma - shows which DMA channels are in use

  • /proc/cpuinfo - all information about CPU

  • The sysfs virtual filesystem, mounted at /sys, exports information about devices so that user space utilities can access the information.

  • HAL -  Daemon The Hardware Abstraction Layer (HAL) Daemon, or hald, is a user space program that runs at all times (that is, as a daemon) that provides other user space programs with information about available hardware.

  • D-Bus - The Desktop Bus (D-Bus) provides a further abstraction of hardware information access. Like hald, D-Bus runs as a daemon. D-Bus enables processes to communicate with each other as well as to register to be notified of events, both by other processes and by hardware (such as the availability of a new USB device).

  • udev -  Traditionally, Linux has created device nodes as conventional files in the /dev directory tree. The existence of hotplug devices and various other issues, however, have motivated the creation of udev: a virtual filesystem, mounted at /dev, which creates dynamic device files as drivers are loaded and unloaded. You can configure udev through files in /etc/udev, but the standard configuration is usually sufficient for common hardware.



Tools



  • lspci - lists all PCI devices.

  • lspnp - display information about PnP devices

  • lsusb - shows all usb devices

  • usbmodules - list kernel driver modules available for a plugged in USB device

  • hotplug - relies on kernel support added with the 2.4.x kernel series. This system uses files stored in /etc/hotplug to control the configuration of specific USB devices. In particular, /etc/hotplug/usb.usermap contains a database of USB device IDs and pointers to scripts in /etc/hotplug/usb that are run when devices are plugged in or unplugged. These scripts might change permissions on USB device files so that ordinary users can access USB hardware, run commands to detect new USB disk devices, or otherwise prepare the system for a new (or newly removed) USB device.

  • usbmgr - a program that runs in the background to detect changes on the USB bus. When it detects changes, it loads or unloads the kernel modules that are required to handle the devices. This package uses configuration files in /etc/usbmgr to handle specific devices and /etc/usbmgr/usbmgr.conf to control the overall configuration.

  • setserial - configures serial interface

  • pnpdump - Dump ISA Plug-And-Play devices resource information

  • sndconfig - easy configuration of sound card

  • scsi_info, sginfo, sg_map - shows information about scsi device

  • hdparm - dispalys information about hard drives and configure them.

  • setpci - utility to directly query and adjust PCI devices’ configurations


Tips
If USB device is self disconnected during boot and you see for example the following in dmesg:
usb 2-1: USB disconnect, address 9
removing kernel module ehci_hcd can help you:
sudo modprobe -r ehci_hcd


Saturday, 10 July 2010

Hiding open ports using SPA and port knocking


SPA(Single Packet Authorization) and port knocking are technologies with the same goal: hide Internet services. In most cases they are used to conceal remote management services such as SSH and RDP.
Both technologies have a common principle: you send specially created packet or packets to a host and host opens defined port or ports on its firewall. The main distinction between these two technologies consists of type of packets. In SPA technology you send an encrypted packet with information what to open. And in Port Knocking technology you send just empty packets with specific destination ports(you may use both TCP and UDP protocols) in particular order, server analyses the incoming traffic, recognises these packets and sends command to the firewall to open access for your IP address.
The great advantage of both technologies that they do not open any services during listening, they just sniff the traffic.
There are 2 main drawbacks of Port Knocking. Firstly, there is no encryption.  Sequence of packets can be sniffed. Secondly, it is not very reliable. Quite often some of packets are lost and you have to resend the whole sequence several times.

Example of port knocking configuration
In the capacity of port knocking daemon I used knockd
You can install it from standard Ubuntu repositories. Here is the example of main configuration file
/etc/knockd.conf:

[SSH]
sequence = 26515:tcp,8924:tcp,58666:tcp,32342:tcp,5427:tcp
seq_timeout = 15
start_command = /sbin/iptables -A INPUT -s %IP% -p tcp --syn --dport 22222 -j ACCEPT
cmd_timeout = 60
stop_command = /sbin/iptables -D INPUT -s %IP% -p tcp --syn --dport 22222 -j ACCEPT

[Osiris]
sequence = 9674:tcp,54190:tcp,25668:tcp,19684:tcp,35056:tcp
seq_timeout = 15
start_command = /conf/ssh %IP%
cmd_timeout = 60
stop_command = /conf/ssh_del

Sequence time out defines time limits in which server must get all packets. Command time out determines how long the door will be opened.

As you can see in the second section there are no iptables commands. This is because this section is for windows server. I didn't find appropriate knock daemon for windows that's why I had to create such workaround. User knocks to Linux server and subsequently Linux server sends firewall commands to Windows server via SSH. Here is the contents of ssh script:

/usr/bin/ssh -i /conf/id_rsa -l user 212.176.29.163 ipfw add 1000 allow tcp from $1 to me 3389 in setup

As you can see, ipfw for Windows is installed :) Very complicated scheme.

Example of SPA configuration based on passwords
A Comprehensive Guide to Strong Service Hardening with fwknop
Here we use fwknop-server. It is also available in Ubuntu repositories. Main configuration file /etc/fwknop/access.conf: 

SOURCE: ANY;
OPEN_PORTS: tcp/22
KEY: secret;
FW_ACCESS_TIMEOUT: 30;
SOURCE: ANY;
ENABLE_EXTERNAL_CMDS Y;
KEY: key;
EXTERNAL_CMD_OPEN /conf/ssh $SRC;
EXTERNAL_CMD_CLOSE /conf/ssh_del;
FW_ACCESS_TIMEOUT: 30;

Here everything is pretty simple. The second Source section again describes workaround for windows server with outward commands. Instead of knock sequences KEYs are used.
To send SPA packet we use fwknop client:

fwknop -D 192.168.1.1 -A tcp/22 -s 10.10.0.1


Thursday, 8 July 2010

Linux security tips

Here are some general security tips concerning Linux





Kerberos auth for SSH via PAM
auth sufficient pam_unix.so
auth required pam_krb5.so




pwconv - converts passwd file to shadow file

sudo example
User_Alias users = %friends
Cmnd_Alias commands = /bin/test
users ALL = NOPASSWD: commands








Monday, 5 July 2010

Command line in Windows world

To delete files older than X days through command line Forfiles can be used:
forfiles /p s:\Backups /d -10 /c "cmd /c del @path"

To redirect error output to standard output:
mingw32-make 1 > output.txt 2>&1

Check error level:
if errorlevel 1 command

Change network configuration with netsh command Show configuration: 
netsh interface ip show config

Configure interface "LAN": 
netsh interface ip set address name="LAN" static 10.64.167.191 255.255.255.0 10.64.167.1 1

Dump configuration of interface:
netsh -c interface dump > c:\location1.txt

Load saved configuration:
netsh -f c:\location1.txt

Configure interface to DHCP mode:
netsh interface ip set address "LAN" dhcp

Configure DNS to DHCP mode:
netsh interface ip set dns "LAN" dhcp

Add scheduled task via command line:

schtasks /create /d thu /sc weekly /tn backup_thursday /tr f:\Admin\thursday_backup.bat

Copy directories:
xcopy F:\dir1 F:\Backup\dir2 /s /y

Show open ports on firewall:
netsh firewall show portopening ENABLE


Show user's OU and other information:
adfind -sc u:nagios dn
Configure NTP synchronisation with Linux

w32tm /config /update /manualpeerlist:"192.168.1.2,0x8" /syncfromflags:MANUAL
net stop w32time
net start w32time

Friday, 2 July 2010

NAT in Cisco IOS

Here I would like to describe some NAT variants based on real life example.
First, some definitions:
  • Inside global - public ip address of NAT router. 
  • Inside local - ip address of host in enterprise network. 
  • Outside local - outside host with private address. 
  • Outside global - public internet address.
For instance, we have a router with Internet address 1.1.1.1 and local address 192.168.1.1
In our internal network we have a web server with address 192.168.1.2
We need to forward port 1.1.1.1:80 to 192.168.1.2:80 that people from the Internet are able to reach our web server.
First, mark interface 1.1.1.1 as outside:
Router(config-if)#ip nat outside

Then mark interface 192.168.1.1 as inside:
Router(config-if)#ip nat inside

Next configure NAT for port forwarding:
ip nat inside source static tcp 192.168.1.2 80 1.1.1.1 80
That's all, port forwarding is ready.
I suppose, our web server will need to access the Internet as well, for example in order to get software updates. To configure it, we are going to use NAT overload or PAT(Port Address Translation).
In the beginning, we add an access list, where we define what networks can access the Internet via PAT:
Router(config)#access-list 1 permit 192.168.1.0 0.0.0.255

In this case network 192.168.1.0/24 will have access.
After this we add NAT rule:
Router(config)#ip nat inside source list 1 interface FastEthernet 0/0 overload

Where FastEthernet 0/0 is the name of the interface which is connected to the Internet.
This is the end, now web server can reach Internet hosts.

To sum up, there are only 5 rows to configure port forwarding and Internet access via one public address. I consider this is quite simple. Based on this configuration it is possible to configure access to other servers form the Internet.

Wednesday, 30 June 2010

SSL


Generate private RSA key without password
openssl genrsa -out server.key 1024

Remove password from the key
openssl rsa -in server.key -out server.key.insecure

Make CSR, based on server.key private key
openssl req -new -key server.key -out server.csr

Selfsign CSR
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Generate a self-signed certificate with private key in one command
openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout privateKey.key -out certificate.crt

Generate your own CA
openssl genrsa -des3 -out ca.key 4096
openssl req -new -x509 -days 365 -key ca.key -out ca.crt

Decode CSR
openssl req -in server.csr -noout -text

Examine the components if you're curious
openssl rsa -noout -text -in server.key

openssl req -noout -text -in server.csr

openssl rsa -noout -text -in ca.key

openssl x509 -noout -text -in ca.crt


CSR generation process


A CSR or Certificate Signing request is a block of encrypted text that is generated on the server that the certificate will be used on. It contains information that will be included in your certificate such as your organization name, common name (domain name), locality, and country. It also contains the public key that will be included in your certificate. A private key is usually created at the same time that you create the CSR.
A certificate authority will use a CSR to create your SSL certificate, but it does not need your private key. You need to keep your private key secret. What is a CSR and private key good for if someone else can potentially read your communications? The certificate created with a particular CSR will only work with the private key that was generated with it. So if you lose the private key, the certificate will no longer work.
Most CSRs are created in the Base-64 encoded PEM format. This format includes the ”—–BEGIN CERTIFICATE REQUEST—–” and ”—–END CERTIFICATE REQUEST—–” lines at the begining and end of the CSR. A PEM format CSR can be opened in a text editor.

CSR contents




  • Common Name - The fully qualified domain name (FQDN) of your server. This must match exactly what you type in your web browser or you will receive a name mismatch error.It is important that this field be filled in with the fully qualified domain name of the server to be protected by SSL. If the website to be protected will be https://public.akadia.com, then enter public.akadia.com at this prompt.



  • Organization - The legal name of your organization. This should not be abbreviated and should include suffixes such as Inc, Corp, or LLC. Google Inc. foe example.



  • Organizational Unit - The division of your organization handling the certificate. IT Department for example.



  • City/Locality - The city where your organization is located.



  • State/County/Region - he state/region where your organization is located. This shouldn't be abbreviated.



  • Country - The two-letter ISO code for the country where your organization is location. RU for example.



  • Email address - An email address used to contact your organization.



  • Public Key - The public key that will go into the certificate. The public key is created automatically.


X509 certificate formats




DER (Distinguished Encoding Rules - method for encoding a data object) - The DER format is simply a binary form of a certificate instead of the ASCII PEM format. It sometimes has a file extension of .der but it often has a file extension of .cer so the only way to tell the difference between a DER .cer file and a PEM .cer file is to open it in a text editor and look for the BEGIN/END statements. All types of certificates and private keys can be encoded in DER format. DER is typically used with Java platforms





PEM - The PEM format is the most common format that Certificate Authorities issue certificates in. PEM certificates usually have extentions such as .pem, .crt, .cer, and .key. They are Base64 encoded ASCII files and contain ”—–BEGIN CERTIFICATE—–” and ”—–END CERTIFICATE—–” statements. Server certificates, intermediate certificates, and private keys can all be put into the PEM format. Apache and other similar servers use PEM format certificates. Several PEM certificates, and even the private key, can be included in one file, one below the other, but most platforms, such as Apache, expect the certificates and private key to be in separate files.



P7B/PKCS#7 - The PKCS#7 or P7B format is usually stored in Base64 ASCII format and has a file extention of .p7b or .p7c. P7B certificates contain ”—–BEGIN PKCS7—–” and ”—–END

PKCS7—–” statements. A P7B file only contains certificates and chain certificates, not the private key. Several platforms support P7B files including Microsoft Windows and Java Tomcat.


PFX/PKCS#12 - The PKCS#12 or PFX format is a binary format for storing the server certificate, any intermediate certificates, and the private key in one encryptable file. PFX files usually have extensions such as .pfx and .p12. PFX files are typically used on Windows machines to import and export certificates and private keys.

Convertion





These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software. For example, you can convert a normal PEM file that would work with Apache to a PFX (PKCS#12) file and use it with Tomcat or IIS.

Convert a DER file (.crt .cer .der) to PEM
openssl x509 -inform der -in certificate.cer -out certificate.pem

Convert a PEM file to DER
openssl x509 -outform der -in certificate.pem -out certificate.der

Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM
openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes
You can add -nocerts to only output the private key or add -nokeys to only output the certificates.

Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt

Convert PEM to P7B
openssl crl2pkcs7 -nocrl -certfile certificate.cer -out certificate.p7b -certfile CACert.cer

Convert P7B to PEM
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer

Convert P7B to PFX
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
openssl pkcs12 -export -in certificate.cer -inkey privateKey.key -out certificate.pfx -certfile CACert.cer

If you need to convert a Java Keystore file to a different format, it usually easier to create a new private key and certificates.

Checking


Check a Certificate Signing Request (CSR)
openssl req -text -noout -verify -in CSR.csr

Check a private key
openssl rsa -in privateKey.key -check

Check a certificate
openssl x509 -in certificate.crt -text -noout

Check a PKCS#12 file (.pfx or .p12)
openssl pkcs12 -info -in keyStore.p12

Check an MD5 hash of the public key to ensure that it matches with what is in a CSR or private key
openssl x509 -noout -modulus -in certificate.crt | openssl md5
openssl rsa -noout -modulus -in privateKey.key | openssl md5
openssl req -noout -modulus -in CSR.csr | openssl md5

Check an SSL connection. All the certificates (including Intermediates) should be displayed
openssl s_client -connect https://www.paypal.com:443






 

Tuesday, 1 June 2010

IOS


IOS functions

These are some important things that the Cisco router IOS software is responsible for:
  • Carrying network protocols and functions
  • Connecting high-speed traffic between devices
  • Adding security to control access and stop unauthorized network use
  • Providing scalability for ease of network growth and redundancy
  • Supplying network reliability for connecting to network resources
  • Defines the network topology
  • Access to network resources
  • Routing and switching functions

IOS tips

Show total and free memory
show processes memory

Add privileged user with SHA256 password hashing
username admin privilege 15 secret 4 strong_password

Show brief information about all IP addresses
show ip interface brief

Enable VLAN interface on a switch or router manually, even if there are no ports in it
(config-if)#no autostate

Disable pause and breaks during show run
For routers
terminal length 0
For ASA
Pager 0




Privilege levels

There are 16 different privilege levels that can be used. Level 0 is user mode. Level 15 is the privileged mode. Level 1 through 14 are available for customization and use. The command used are:


Cisco(config)#privilege mode level level command
Cisco(config)#enable secret level level password

The privilege command is used to add authorized IOS commands to each customized levels. The enable secret command defines the secret password needed to access this particular privilege level. The options for these commands are:


  • mode: it selects an exec or configuration option that will be included with this privilege level

  • level: it defines the privilege level (number between 1 and 14)

  • command: it is a specific IOS command at the specified mode that is included in this privilege level

  • password: it is the password associated to the level

An example of privilege level configuration:




Cisco(config)#privilege interface level 2 ip address
Cisco(config)#privilege configure level 2 interface



Some facts



  • Blinking System led after POST signal means that there is internal problem, that prevent IOS loading.

  • Show interfaces shows you broadcast addresses.

  • show running requires privileged EXEC mode

  • If you enter a major command, Cisco router switches you from one configuration mode to another.

  • If both the enable secret and the enable password commands are configured on your router you can enter either the enable secret or the enable password

  • Banner login: The first nonblank character after the banner login phrase is interpreted as the beginning delimiter character.

  • Banner motd - dispalys message before login

  • Banner login - shows messagr before login, but after motd

  • Banner exec - shows message after login

  • The extended ping command works only at the privileged EXEC command line. The normal ping works both in the user EXEC mode and the privileged EXEC mode.

  • terminal monitor - shows everything on monitor

  • Ctrl+C and CTRL+Z are the same - returns to enable EXEC mode from anywhere. END returns to enable EXEC from anywhere. Exit rerturns one level up.

  • You can exit setup mode by pressing Ctrl-C

  • The commands show protocols, show interfaces, and show ip interface will show you the layer 1 and 2 status and the IP addresses of your router’s interf aces



Booting

There are 4 types of memory in router:




  • ROM - read only memory, stores:



  1. POST (power-on self-test) - self check test, it checks hardware.

  2. ROM monitor - software for testing and troubleshooting.

  3. Mini-IOS - уменьшенная версия IOS, предназначена для технического обслуживания

  4. Bootstrap - загрузчик, отвечает за поиск IOS и его загрузки



  • RAM - stores running configuration, buffers, arp tables, route tables and etc.

  • Flash - stores IOS. It is also possible to store any files here.

  • NVRAM(non volatile random access memory) - stores router configuration and configuration register.


First, POST is launched from ROM. If POST is ok, bootstrap is loaded. Bootstrap searches for IOS image and launches it. Ususally IOS is loaded from FLASH, but it can be configured, using configuration register. This is 16 bit register in NVRAM. This register defines options of booting router.

Bits in register are numbered from 15 to 0, from left to right. By default this register is 2102 in decimal.

Other possible values of configuration register:


  • 2100 - boot into ROM monitor

  • 2101 - boot mini IOS from ROM


  • 2002 - enable Break function(this means that, if you push CTRL+Break during work, you will enter ROM monitor mode

  • 2142 - ignore NVRAM(configuration), it is usually used to restore passwords





PIPE


  • Append – add to url

  • Begin

  • Exclude

  • Include

  • Redirect – redirect to url

  • Section

  • Tee – copy output to url

Telnet

By default, all Cisco routers support up to five simultaneous Telnet sessions

To use multiple telnet connections:

Ctrl+Shift+6 and then X

To go back to the connection, just hit enter twice

Or select connection number from



show sessions


and hit enter..

To end telnet session type exit!

to resume session:



resume 4


To disconnect session:



disconnect 3


To apply access list:



access class 1



CDP
CDP provides:


  • Device ID

  • Capabilities

  • Platform



Monday, 31 May 2010

Linux monitoring, log and traffic analysis

First of all, here is a good link with a comprehensive list of monitoring tools for Linux:
20 Linux System Monitoring Tools Every SysAdmin Should Know

Monitoring performance
  • top - standard utility for monitoring CPU, processes, memory and load average.
  • htop - enhanced top program, it's more comfortable, I think.
  • ps - command can be used to monitor memory and CPU too, for example: ps ux
  • free - shows information about RAM. Usually, the most interesting is amount of free RAM in megabytes without buffers:
server:/home/user#free -m
total used free shared buffers cached
Mem: 2003 1330 673 0 83 865
-/+ buffers/cache: 381 1621
Swap: 3514 0 3514
 
In our example amount of free RAM is 1621 megabytes.
  • Load average - consist of 3 numbers: load average for last 1,5 and 15 minutes. The load average tries to measure the number of active processes at any time. As a measure of CPU utilization, the load average is simplistic, poorly defined, but far from useless. A system with one program running CPU-intensive tasks has a load average of 1. Higher load averages reflect programs competing for available CPU time. You can also find the current load average via the uptime command, which displays the load average along with information on how long the computer has been running. The load average can be useful in detecting runaway processes. For instance, if a system normally has a load average of 0.5 but it suddenly gets stuck at a load average of 2.5, a couple of CPU-hogging processes may have hung—that is, become unresponsive. Hung processes sometimes needlessly consume a lot of CPU time. You can use top to locate these processes and, if necessary, kill them.

  • uptime

  • sar - very powerful tool, it can monitor almost all parameters, including disk, network, ram, cpu….. It launches periodically and stores statistics in /var/log/atsar.

  • iostat - monitors nfs, cpu and disks.

  • vmstat - monitors virtual memory.

  • hdparm - shows information about hard disk, tests HDD speed

  • hddtemp - shows HDD temprature

  • smartd - SMART Disk Monitoring Daemon

  • Monitorix

logs analysis
  • logcheck

  • logwatch

users monitoring
  • w

  • whoami

  • who

  • last

  • lastlog

  • finger

traffic analysis
  • iptraf - very cool programm. It's interactive, it monitors in real time various network parameters.

  • iftop - monitors bandwidth by hosts

  • bwm-ng - very simple command-line interactive bandwidth monitor

  • tc - monitors and shape traffic

  • dsniff - package of various tools, including urlsnarf - for monitoring HTTP requests in real time

  • ntop

  • darkstat - very nice traffic graphing tool with embedded web server.

  • Bandwidth Monitoring Tools For Linux

Security
  • OSSEC -  Open Source Host-based Intrusion Detection System. It performs log analysis, file integrity checking, policy monitoring, rootkit detection, real-time alerting and active response.

  • OSSIM - Open Source Security Information Management.

  • Samhain


Friday, 28 May 2010

RIP, RIP2, IS-IS

RIP



  • Performs autosummarization by default

  • Doesn't support manual route summarization

  • Doesn't support authentication

  • Sends periodic routing updates over the broadcast

  • Four equal paths are supported by default (6 maximum)


RIP2




  • Is best for VLSM and minimum overhead.

  • Support manual route summarization

  • Performs autosummarization by default

  • Multicast 224.0.0.9, FF02::9

  • Supports authentication


IS-IS



  • Link state

  • Supports VLSM

  • Doesn't support auto summarization

  • Supports manual summarization



EIGRP(Enhanced Interior Gateway Routing Protocol)

Some facts


  • It’s enhanced distance-vector protocol.

  • It’s classless.

  • Supports manual route summarization

  • Performs autosummarization by default

  • Network layer.

  • The range of valid AS numbers is 1 through 65,535

  • The fastest convergence

  • It uses the concept of an autonomous system.

  • Wildcards are used

  • Supports MD5 auth

  • It’s hybrid routing protocol because it has characteristics of both distance-vector and link-state protocols.

  • EIGRP has a maximum hop count of 255 (the default is set to 100).

  • It provides routing support for multiple Network layer protocols: IP, IPX, AppleTalk, and now IPv6

  • Communication via Reliable Transport Protocol (RTP) - Cisco proprietary protocol, is used for transmitting EIGRP messages between routers. It can provide reliable packet delivery when necessary, by using sequence number, acknowledgement, and retransmission with unicast (a packet will be retransmitted up to 16 times if no acknowledgement is received, before declaring the neighbor router is dead).

  • Diffusing Update Algorithm (DUAL).It is used to determine a route to network, when successor failed and there is no feasible successors. This algoritm just asks neighbor routers for route.

  • Technologies: Split horizon, Poison Reverse.

  • Conseptions:



  1. Reported distance - distance to the remote network, reported by the neighbor router.

  2. Feasible distance - This is the best metric along all paths to a remote network, including the metric to the neighbor that is advertising that remote network. This is the route that you will find in the routing table because it is considered the best path.

  3. Successor - next hop router with the best metric, is placed in routing table of router, there might be several successors, if they have equal metrics.

  4. Feasible successor - backup next hop router. EIGRP will keep up to six feasible successors in the topology table. If a nonsuccessor route’s RD is less than the FD, the route is a feasible successor route.


  • All data is stored in three tables:


  1. Neighbor table - stores data about neighboring routers.

  2. Topology table – stores contains the aggregation of the routing tables gathered from all directly connected neighbors. There also may be successors and feasible successors for some routes in this table. Destination may be passive or active. Passive means that route is stable. Active means that route is updating. In Cisco routers route may be: Passive, Active, Update, Query, Reply.

  3. Routing table – contains all actual routes with their successors and possible feasible successors, if load balancing is enabled.


  • It uses 4 metrics(by default delay and bandwidrth are used):


  1. Total Delay (the sum of all the delay values for all links in the route, with a unit of “tens of microseconds.”)

  2. Minimum Bandwidth ( the lowest-bandwidth link in the route,using a unit of kilobits per second)

  3. Reliability (number in range 1 to 255; 255 being most reliable)

  4. Load (number in range 1 to 255; 255 being saturated)


  • The router uses formula to calculate overall metric:

metric=(107/least-bandwidth + cumulative delay)*256

Bandwidth - kilobits per second.

Delay - tens of microseconds

In this case k1=1,k2=0,k3=1,k4=0,k5=0 by default(only Bandwidth and Delay is used). You can change their value with command:

Router(config-router)#metric weights …


  • Administrative distance - 90 for internal route(in one AS) an 170 for external route(in different AS or from other protocol).

  • Multicast 224.0.0.10 for Hello messages, but updates can also be sent to unicast address. FF02::A for IPv6.

  • EIGRP can provide equal-cost load balancing of up to four links by default, but it is possible to use 16 links with command:


(config-router)#maximum-paths

  • EIGRP can provide unequal-cost load balancing with command

variance.

  • First routers have to establish neighborship , to do it, three conditions must be met:



  1. Hello or ACK received

  2. AS numbers match

  3. Identical metrics (K values)

  4. Auth passed

  5. The same subnet


Show commands

show ip eigrp topology all-links

Shows all routes, not only successors and feasable successors.



Debuging

debug eigrp packets

Displays the contents of EIGRP packets.



debug eigrp fsm

Displays changes to the EIGRP successor and feasible successor routes.

debug ip eigrp

Displays similar output to the debug eigrp packets command, but specifically for IP.



EIGRP packet types


  • Hello packet It is used for discovering neighbors and maintaining neighbor relationship. It is sent to neighbors periodically (hello interval). The default hello interval is: Non-broadcast multi-access (NBMA) network with bandwidth Other networks (e.g. Ethernet, point-to-point serial links, high speed frame relay, etc.) - 5 seconds . A neighbor is assumed dead if no hello message from that neighbor is received before the hold timer expires (default = 3 times of the hello timer value). All routes learned from that neighbor will also be deleted. Neighbor routers can use different hello and hold-time intervals. A router informs the neighbors its hold-time interval through hello packets. It is sent as multicast. Acknowledgement is not required (i.e. unreliable delivery).

  • Update packet It is used for sending routing information to neighbors as follows: Full routing updates (i.e. the whole topology table) during initialization of the routing process. Incremental routing updates (i.e. routing updates about the paths that have been changed) when there is a change in the network topology or metric. It is sent to the relevant routers as unicast or multicast. Acknowledgement is required (i.e. reliable delivery).

  • Query packet It is used for querying neighbors if they have feasible successors for a destination network. It is sent during a diffusing computation (to be explained later in this Section). It is sent as multicast. Acknowledgement is required (i.e. reliable delivery).

  • Reply packet It is used for replying a query with the requested routing information (e.g. information of the best path to the destination network, or destination unreachable). It is sent as unicast. Acknowledgement is required (i.e. reliable delivery).

  • Acknowledgement (ACK) packet It is used for acknowledging the receipt of an update / query / reply packet. It is sent as unicast. Acknowledgement is not required (i.e. unreliable delivery).

  • Redistribution is required when more than one EIGRP session or process is running and they are identified with different ASNs. Redistribution shares topology information between EIGRP sessions.


Ping does not work

Today I would like to discuss a banal situation: host A is directly connected to host B, ping from host A to host B does not work. What are...