суббота, 18 февраля 2012 г.

RHCE prepare...


IMPORTANT STEPS:
1. REMEMBER to ENABLE list of services!
can use system-config-services
2. /etc/inputrc
"\e[A": history-search-backward
"\e[B": history-search-forward
3. find /var/log -cmin -1
4. ... BRAIN ...

********************************************
TIPS&TRICKS:

*/2 5-10 * * 1,5 free
Every 2 minutes from 5am to 10am Monday and Friday

Xorg -configure

Report: sar -A
Data path: /var/log/sa (sar -f saDD)
Schedule definition: /etc/cron.d/sysstat

directories for collaboration:
chmod g+s dir
create group shared_grp
chgrp shared_grp dir
Add users to shared_grp

rpm -ivh new_kernel.rpm

****************************************
CHAGE UTILITY :
Change aging: chage -E YYYY-MM-DD user
-m Specifies the minimum number of days between which the user must change passwords. If the value is 0, the password does not expire.
-M Specifies the maximum number of days for which the password is valid. When the number of days specified by this option plus the number of days specified with the -d option is less than the current day, the user must change passwords before using the account.
-d Specifies the number of days since January 1, 1970 the password was changed
-I Specifies the number of inactive days after the password expiration before locking the account. If the value is 0, the account is not locked after the password expires.
-E Specifies the date on which the account is locked, in the format YYYY-MM-DD. Instead of the date, the number of days since January 1, 1970 can also be used.
-W Specifies the number of days before the password expiration date to warn the user.
Examples:

List a users passowrd expiration info

[root@rhel ~]# chage --list username
Set an expiration based on a maximum number of days for which the password should be valid.

[root@rhel ~]# chage -M 120 username
To only allow a user to change their password every 10 days, and no more

[root@rhel ~]# chage -m 10 username
Apply immediate expiration

[root@rhel ~]# chage -d 0 username

*****************************************
HTTP/APACHE:

AuthType Defines the authentication type
AuthName Adds a comment for the user to see on login
AuthUserFile Specifies the file used to define username and password
AuthGroupFile Is similar to the user file but for groups
Require Specifies the users or groups that can log in

service httpd configtest

HTTP/HTTPS

Configure a virtual host
NameVirtualHost *:80
ServerName docs.example.com
DocumentRoot /path

Configure private directories
AuthType basic
AuthName “private rhel1?
AuthUserFile /www/.rhel1_priv_user
Require user name
Order deny,allow
Deny from all
Create user/password file:
htpasswd -c /www/.rhel1_priv_user user

Deploy a basic CGI application
Directory Options +ExecCGI
AddHandler cgi-script .pl .cgi
cgi-bin/hello.pl:
print “Content-type: text/html\n\n”;
print “hello!”;

Configure group-managed content
groupadd webdesigners
add users to webdesigners
mkdir /www/site1
chgrp apache.webdesigners /www/site1
chmod 775 /www/site1
chmod g+s /www/site1


context:
httpd_sys_content_t=content
httpd_sys_script_exec_t=scripts
httpd_log_t=logs

AConfigure host-based and user-based security for the service
Host
use iptables
/etc/httpd/conf/httpd.conf:
Allow from good_ip
Deny from all
Order deny,allow
User
/etc/httpd/conf/httpd.conf:
Use AuthType Basic

# semanage fcontext -a -t httpd_sys_content_t "/www/testsite(/.*)?"
Next we restore context recursively...

# restorecon -F -R -v /www/testsite
# setsebool -P httpd_enable_cgi on

****************************************
ISCSI :

# iptables -I INPUT -p tcp -m tcp --dport 3260 -j ACCEPT

server:
# service tgtd start
# chkconfig tgtd on
adding an XML entry to the /etc/tgt/targets.conf
backing-store /dev/virtstore/virtimage1 #LUN1
backing-store /var/lib/tgtd/virtualization/virtimage2.img #LUN2
write-cache off

# service iscsid start
# chkconfig iscsid on
/var/lib/iscsi/ifaces
discovery:
# iscsiadm -m discovery -t st -p IP
192.168.1.10:3260,1 iqn.2011-07.com.example.server1:trial
login:
# iscsiadm -m node -T iqn.2011-07.com.example.server1:trial -p 192.168.1.10 -l
/var/lib/iscsi...
umount:
# iscsiadm -m node -T iqn.2011-07.com.example.server1:trial -p 192.168.1.10 -u

For permanent add string to /etc/fstab

****************************************
KICKSTART:

Kickstart source Option format
DVD drive ks=cdrom:/directory/ks.cfg
Hard Drive ks=hd:/device/directory/ks.cfg
Hard Drive ks=hd:LABEL=FOOBAR:/path/to/ks.cfg
Other Device ks=file:/device/directory/ks.cfg
HTTP Server ks=http://server.mydomain.com/directory/ks.cfg
FTP Server ks=ftp://server.mydomain.com/directory/ks.cfg
NFS Server ks=nfs:server.mydomain.com:/directory/ks.cfg
linux ks=http://server.mydomain.com/kickstart.cgi kssendmac

#ksvalidator

****************************************
LDAP/KERBEROS:

yum install openldap openldap-clients nss_ldap

system-config-authentication : both LDAP or Kerberos
dc=example,dc=com
ldap://server1.example.com
download certificate:
ftp://server1/pub/EXAMPLE-CA-CERT

service sshd restart
ssh ldapuserX@stationX.example.com


TLS checking :
#openssl s_client -connect server1.example.com:PORT

/var/log/messages
/var/log/secure

ldapsearch -x Z

****************************************
LUKS CRYPTO F.S:

# cryptsetup luksFormat /dev/sdb1
# cryptsetup luksOpen /dev/sdb1 mynew_data
# mkfs.ext4 /dev/mapper/mynew_data
In the /etc/crypttab
mynew_data /dev/sdb1
In the /etc/fstab
UUID=f8b694a6-916d-4ffa-8e5c-a7ed8ab25b5d /mynew_data ext4
#mount -a

****************************************
MOUNT:

# mount -t cifs //server/share /mnt --verbose -o user=username
# mount -o rw -t nfs hostname:/mountpoint /mnt

in /etc/sysconfig/autofs --timeot
chkconfig autofs on; service autofs start

automount
/etc/auto.master
/misc /etc/auto.misc
/etc/auto.misc
cd -fstype=iso9960,ro,nosuid,nodev :/dev/cdrom
w/NIS * -fstype=nfs server1:/home/user/&
w/LDAP * -rw,soft,intr 192.168.0.1:/home/guests/&
myprojectv -rw,soft,intr 192.168.0.1:/home/guest :NFS

****************************************
NDS/NAMED:

/etc/named.conf
options
{
forwarders { 192.168.0.254; };
forward only;
}

chown root:named .zone
chmod 640 .zone
restorecon .zone

service named configtest
netstat -tulpn | grep named

chmod 640 `find ./ -type f -print`
chown named.named `find ./ -type f -print`


Configure a caching-only name server
named.conf:
allow-query { good_ips; };
recursion yes;

Configure a caching-only name server to forward DNS queries
named.conf:
allow-query { good_ips; };
forward only;
forwarders { forwarder_ip; };
recursion yes;

****************************************
Networking acces, basic services/utilites:

/etc/hosts.allow
in.telnetd@192.168.0.254:192.168.0.
sshd:ALL EXCEPT .cracker.org EXCEPT trusted.cracker.org
[bin,bin,bin...]:.example.com 127. [::1] !!!NOCIDR [fe80::]/64
sshd:[fe80::]/64
trailing dot - network
leading dot - domain

used /etc/services
includedir /etc/xinetd -overwritten by individual conf
/etc/xinet.d/.
#default off
{ disable = yes }
#need on ?:
{ disable = no
server = /path/to/bin}

/var/log/secure -xinetd
/var/log/messages -iptables

xterm -e "cd /var/log; tail -f messages secure" &
iptables -I INPUT 1 -j LOG

netstat -tulpn | grep service
ip addr show

/sbin/sysctl -w net.ipv4.ip_forward=1
sysctl -p
iptables -A FORWARD -i eth0 -o eth1 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -j LOG
iptables -t NAT -A POSTROUTING -o eth0 -j MASQUERADE

iptables -t nat -A PREROUTING -p tcp --dport 5001 -j DNAT --to-destination 10.10.10.10:25
iptables -t nat -A POSTROUTING -p tcp --dport 25 -j MASQUERADE

iptables -t nat -I PREROUTING -p tcp –dport 8800 -j DNAT –-to-destination 192.168.101.3:80
iptables -I INPUT -p icmp --icmp-type echo-request -j DROP :IPv4only
iptables -I INPUT -p icmp --icmp-type destination-unreachable -j DROP

iptables -nvL --line-numbers
./route-eth0
10.10.10.0/24 via 192.168.0.1 dev eth0

Server /etc/rsyslog.conf
$ModLoad imudp.so
$UDPServerRun 514

CLient /etc/rsyslog.conf
*.* @IP

DHCP:
DHCPDARGS="eth0"
dhcpd.conf.sample
service dhcpd configtest

NTP:
1.modify /etc/ntp/conf
2.start ntp
3.enable ntp at startup
4.cofig firewall udp 123
5.verify
open udp port 123 on server
Synchronize time using other NTP peers
Test:
ntpdate -q 123.123.56.123
Configure ntp.conf:
server 123.123.56.123 [iburst]

ping6 -c1 1:2:3 -I eth0
ssh 1:2:3%eth0
hot -t AAAA host.name.com
sysctl -a | grep ipv4

****************************************
NFS:

NFS v4. No tcpwrappers.

service nfs restart
-A -INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 2049 -j ACCEPT

# yum install nfs-utils nfs4-acl-tools portmap
in /etc/exports
/directory3 192.168.1.0/255.255.255.0!(options) *.redhat.com(no_root_squash)

# chkconfig nfs on; service nfs on
# chkconfig netfs on; service netfs on

# exportfs
# showmount -e
service nfs status

chcon -R -t public_content_t /nfs/share

Install service
“Provide network shares to specific clients”
Configure the service to start when the system is booted
Configure SELinux support
Configure static lockd, statd, mountd, rquotad ports in /etc/sysconfig/nfs
Update /etc/sysconfig/iptables:
open those ports

RQUOTAD=875
LOCKDTCP=32803
LOCKDUDP=32769
MOUNTD=892
STATD=662
rpcbindTCP=111
rpcbindUDP=111

****************************************
NSS/PAM:

Ключевое слово
Описание
Required («Обязательно») Если модуль срабатывает успешно, то PAM продолжает вычислять остающиеся записи для группы управления, и результаты будут определены результатами остающихся модулей. Если нет, то PAM продолжит вычисление, но возвратит сбой вызывавшему приложению.
Requisite («Необходимо») Если модуль срабатывает успешно, PAM продолжает вычислять записи группы управления. Если нет, то PAM произведет возврат вызывавшему приложению без дальнейшей обработки.
Sufficient («Достаточно») Если модуль сработает успешно, то PAM возвратит успешный результат вызывавшему приложению. Если нет, то PAM продолжит вычисление, но результаты будут определены последующими модулями.
Optional («Необязательно») PAM игнорирует результаты модуля, если это не единственный модуль, указанный для группы управления.
Include («Включить») PAM включает в себя содержимое файла настройки PAM, на который дается ссылка, а также содержащиеся в нем процессы и записи.

Откройте файл the /etc/pam.d/system-auth, затем прокрутите экран вниз и вставьте строку "session optional map_mkhomedir.so skel=/etc/skel umask=0644" перед последней строкой в разделе сеанса (см. рис. 16).
Эта строка настраивает PAM на создание домашнего каталога для пользователя, если такового еще не существует. Она будет использовать /etc/skel в качестве «скелета» шаблона и назначит маску прав 0644 (чтение и запись для владельца, чтение для основной группы и чтение для всех остальных) новой папке.

Модуль переключателя блока преобразования имен (NSS) скрывает конкретные сведения о хранилище данных систем от разработчика приложения, примерно так же, как PAM скрывает подробности проверки подлинности.
NSS позволяет администратору указать способ, которым хранятся базы данных системы. В частности, администратор может указать, как хранится информация об имени пользователя и пароле.

****************************************
SAMBA/SMB:
User access:
Configure users permissions in smb.conf and DAC!!!
Host access:
Use iptables

Global conf is overwriten by local.
Users must have local accounts.
useradd -a student
By default users can access to home dirs:
smbclient //IP/student

root mount:
mount -t cifs /host/dir -o user=student

/etc/fstab
credentials=/etc/red.txt

chcon -R -t samba_share_t /smb/share
setsebool -P samba_export_all_rw on

grep -E 'netbios|microsoft-ds' /etc/services
iptables -I INPUT -p tcp --dport 137:139 -j ACCEPT
iptables -I INPUT -p tcp --dropt 445 -j ACCEPT

mkdir /legal
chgrp legal /legal
chmod 3770 /legal
[legal]
path=/legal
valid users = @legal,user :can access
write list=@legal :can write
create mask=3770
directory mask =3775
Provide network shares suitable for group collaboration
add group workers (groupadd name; net rpc group add name)
add users to group (useradd name; net rpc user add username)
In smb.conf create a section like:
[shared]
path = /shared
force group = +workers :ctr as primary group workers
valid users = @workers viewer
write list = @workers

writeable = yes :can write any if=DAC > writelist
guest ok = yes :can access w/o pass

****************************************
SELinux:

# getenforce
# setenforce 0|1
# vim /etc/selinux/config
SELINUX=disabled

#/usr/sbin/getsebool -a
/usr/sbin/setsebool -P httpd_use_nfs on
/usr/sbin/setsebool -P httpd_use_nfs off
/usr/sbin/semanage boolean -l | grep nfs

grep vsftpd /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypool

chcon --reference shablon target
semanage fcontext -a -t public_content_t "/var/ftp(/.*)?"

example:
# setsebool -P httpd_enable_cgi on
Notice the -P we add in there, that is to make the change persistant across a reboot

#ps -Z
#ls -lZ

****************************************
SMTP
(MTA) to accept inbound email from other systems:

Configure /etc/postfix/main.cf:
myhostname Defines the full hostname of the Postfix server
mydomain Defines the domain name
myorigin Defines the name that outgoing mail originates from
inet_interfaces Identifies the interface on which to receive mail
mydestination Defines the domains for which Postfix accepts mail
mynetworks Lists trusted networks
virtual_alias_maps Defines virtual aliases for incoming mail

Configure an MTA to forward (relay) email through a smart host
Configure /etc/postfix/main.cf:
relayhost = host

Install the packages needed to provide the service
yum install postfix

Configure SELinux to support the service
getsebool -a | grep postfix

Configure the service to start when the system is booted
chkconfig postfix on

Host:
Use iptables
Update /etc/sysconfig/iptables:open tcp ports 25

Configure host-based and user-based security for the service
User:
/etc/postfix/main.cf:
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination

service saslauthd start
service saslauthd start
chkconfig saslauthd on

Dovecot:
login trusted networks = id.net
mail_location = mbox:~/.mail:INBOX=/var/spool/mail/%u
then second times to log as user for DOVECOT crt files

****************************************
SSH:

ssh bringing X (required to run programs like system-config-users remotely)

# ssh -X user@host

Display debugging messages as it connects. Useful if you have having some issues connecting to a certain machine.

# ssh -v user@host

ssh to a custom port:

# ssh -p port_number user@host
1. Local port forwarding

ssh -L 1111:localhost:2222 username@remotehost
все пакеты приходящие на порт 1111 локалной машины (localhost) отправляются на порт 2222 удаленной машины (remotehost).

2.Remote port forwarding

ssh -R 2222:localhost:1111 username@remotehost
все пакеты приходящие на порт 2222 удаленной машины перенаправляются на вшау локальную машину, на порт 1111

Для того чтобы перенаправлялись и внешние пакеты, пришедшие на локальный порт 1111, нужно добавить опцию -g

****************************************
KVM/Virtualizations :

#virt-manager

To start a vm type:
# virsh start machninename01

To shutdown:
# virsh shutdown machninename01

To destroy:
# virsh destroy machninename01

To gain access to a virtual console:
# virsh console machninename01

To congifure the machine to launch at boot:
# virsh autostart machninename01

****************************************
VNC:

#vncpasswd
#vncserver
~/.vnc/xstartup
#!/bin/sh

# Uncomment the following two lines for normal desktop:
unset SESSION_MANAGER
exec /etc/X11/xinit/xinitrc

[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &
xterm -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" &
twm &


in /etc/sysconfig/vncservers
VNCSERVERS="2:myusername"
VNCSERVERARGS[2]="-geometry 800x600 -nolisten tcp -nohttpd"

****************************************
VSFTPD/FTP:

# iptables -I INPUT 5 -p tcp -m tcp --dport 20 -j ACCEPT
# iptables -I INPUT 5 -p tcp -m tcp --dport 21 -j ACCEPT

semanage fcontext -a -t public_content_t "/var/ftp(/.*)?"
restorecon -F -R -v /var/ftp
chcon -R -t public_content_t /nfs/share

setsebool -P allow_ftpd_full_access on

/etc/sysconfig/iptables
IPTABLES_MODULES="ip_conntrack_ftp"

users access:
user_list -add users
userlist_deny = NO
userlist_enable=YES
local_enable=YES

anonymous-only download:
anonymous_enable=YES
anon_upload_enable=NO
local_enable=NO

****************************************
YUM/REPO:

# yum groupinstall "Virtualization"
# yum update kernel


*/repomd.xml -time stamp, chksum
*/primary.xml.gz -list of RPM
*/filelists.xml.gz -file list
*/other.xml.gz -other inf
*/comps.xml -group RPM install

rpm -ql aide -list of files
rpm -qi aide -package information
rpm -V aide -verify integrity
rpm -qf /var/lib/aide -which package provide

Local repos:
[mylocal]
name=mylocal
baseurl=file:///directory/path/to/repo/
enabled=1
gpgcheck=0

# createrepo -v .


Network repos:
cp -a /mnt/cdrom/. /var/ftp/pub/repo :FTP
ln -s ../../pub/repo /var/www/html/repo :HTTP
chcon -h -R -t httpd_sys_content_t /var/ftp/pub/repo
/etc/exports
/var/ftp/pub *(ro) :NFS


# createrepo -v .

Build a simple RPM that packages a single file
rpmdev-setuptree
cd ~/rpmbuild
rpmdev-newspec SPEC/hello.spec
edit SPEC/hello.spec
rpmbuild -ba SPEC/hello.spec


****************************************