rhce - apuntes del curso

51
1.- INSTALACION AUTOMATIZADA CON KICKSTART Kickstart soporta todas las features de anaconda, durante la instalacion se autogenera un fichero /root/anaconda.ks-cfg [root@station2 ~]# more anaconda-ks.cfg # Kickstart file automatically generated by anaconda. install nfs --server=192.168.0.254 --dir=/var/ftp/pub key --skip lang en_US.UTF-8 keyboard us xconfig --startxonboot --resolution 1024x768 --depth 16 network --device eth0 --bootproto dhcp rootpw --iscrypted $1$XxTOgHLX$Ag.XKutFr/mTxeUI/WvHU1 firewall --disabled authconfig --useshadow --enablemd5 selinux --enforcing timezone --utc Europe/Madrid [...] Otra manera de generar los ficheros kickstart es usando system-config-kickstart : utilidad gráfica de configuración ksvalidator : verificador de sintaxis de ficheros .ks Para usar instalacion kickstart es pasar el parámetro ks: 1.- ks=url_fichero_kickstart 2.- ks=hd:device:/path/to/file 3.- ks ; y buscará mediante DHCP un servidor que pueda responder con la URL del fichero kickstart. En el fichero kickstart se pueden poner comandos que queremos que se ejecuten antes de la instalación (sección %pre) o después de la misma (sección %post). Ejemplos: [...] %include /tmp/mis_paquetes %pre echo firefox > /tmp/mis_paquetes <<< genero un paquete para instalar %post useradd amaya [...] Además, se puede cambiar el intérprete de comandos que se desee usar (bash, sh, perl, etc). Red Hat Certified Engineer

Upload: cibeles

Post on 07-Apr-2015

458 views

Category:

Documents


3 download

DESCRIPTION

Apuntes en castellano del curso RHCE tomados al vuelo, por tanto, no sustituyen a ninguna guía, son simples apuntes que se pueden usar como resúmenes útiles.

TRANSCRIPT

Page 1: RHCE - Apuntes del curso

1.- INSTALACION AUTOMATIZADA CON KICKSTART Kickstart soporta todas las features de anaconda, durante la instalacion se autogenera un fichero /root/anaconda.ks-cfg [root@station2 ~]# more anaconda-ks.cfg# Kickstart file automatically generated by anaconda. installnfs --server=192.168.0.254 --dir=/var/ftp/pubkey --skiplang en_US.UTF-8keyboard usxconfig --startxonboot --resolution 1024x768 --depth 16network --device eth0 --bootproto dhcprootpw --iscrypted $1$XxTOgHLX$Ag.XKutFr/mTxeUI/WvHU1firewall --disabledauthconfig --useshadow --enablemd5selinux --enforcingtimezone --utc Europe/Madrid[...] Otra manera de generar los ficheros kickstart es usando system-config-kickstart : utilidad gráfica de configuración ksvalidator : verificador de sintaxis de ficheros .ks Para usar instalacion kickstart es pasar el parámetro ks:1.- ks=url_fichero_kickstart2.- ks=hd:device:/path/to/file3.- ks ; y buscará mediante DHCP un servidor que pueda responder con la URL del fichero kickstart. En el fichero kickstart se pueden poner comandos que queremos que se ejecuten antes de la instalación (sección %pre) o después de la misma (sección %post). Ejemplos: [...]%include /tmp/mis_paquetes %preecho firefox > /tmp/mis_paquetes <<< genero un paquete para instalar %postuseradd amaya[...] Además, se puede cambiar el intérprete de comandos que se desee usar (bash, sh, perl, etc).

Red Hat Certified Engineer

Page 2: RHCE - Apuntes del curso

Ejercicios1. Crear una VMOJO: Al crear el volumen, no se tiene que crear el FS, Xen lo necesita raw. [root@station2 ~]# virt-install -n vcracker -r 256 -p -l http://instructor.example.com/pub -x ks=http://instructor.example.com/vcracker.php?S=2 -b xenbr0 -f /dev/vol0/lv.vcracker

2.- GESTIÓN DE PAQUETES La herramienta por defecto introducida en RHEL5 es YUM (que reemplaza a up2date). YUM se conecta a un servidor e instala el paquete indicado y además resuelve las dependencias que éste tuviera. Tambien tiene un gestor gráfico llamado system-config-packages Los repositorios están en /etc/yum.repos.d/ con la extensión .repo. Un fichero .repo típico tiene las siguientes opciones típicas: [rhel-debuginfo]name=Red Hat Enterprise Linux $releasever - $basearch - Debugbaseurl=ftp://ftp.redhat.com/pub/redhat/linux/enterprise/$releasever/en/os/$basearch/Debuginfo/enabled=1 <<< Habilitar o deshabilitar un repositoriogpgcheck=1gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release

2.1 Comandos típicos de YUM * yum clean dbcache|all <<< Limpiar la cache* yum list [all] [patron] <<< Para buscar paquetes* yum list [installed|available|updated]* yum provides fichero <<< Indica qué paquete incluye el fichero especificado* yum search paquete <<< Busca paquetes, pero buscando también en la descripción y no sólo en el nombre* yum groupinstall <<< Instala un grupo de paquetes* yum localinstall <<< Instala un rpm local y sigue resolviendo dependencias en red* yum remove paquete <<< Borra un paquete y todos los que dependen de él* yum update <<< Actualiza todos los paquetes de mi sistema* yum upgrade <<< Actualiza todo mi sistema a la siguiente versión mayor

Red Hat Certified Engineer

Page 3: RHCE - Apuntes del curso

Al buscar con YUM un patrón, hay que usar '' pues sino, la shell será quien interprete el patrón y le pase la salida a YUM [root@station2 ~]# yum list installed 'xorg*'Loaded plugins: rhnpluginThis system is not registered with RHN.RHN support will be disabled.Installed Packagesxorg-x11-apps.i386 7.1-4.0.1.el5

installedxorg-x11-drivers.i386 7.1-4.1.el5

installedxorg-x11-drv-acecad.i386 1.1.0-2.1

installedxorg-x11-drv-aiptek.i386 [...] Para crear un repositorio, hay que usar la herramienta createrepo, que se encarga de crear el índice para que yum pueda hacer las distintas operaciones.

2.2 Instalaciones avanzadas con RPM RPM es una base de datos que lleva un control sobre todos los RPMs instalados en el sistema* rpm -i <<< Instala un paquete si no está instalado* rpm -F <<< Actualiza un paquete sólo si está instalado* rpm -U <<< Actualiza un paquete aunque no esté instalado* rpm -e <<< Borra un paquete ya instalado* rpm -ivh --replacepgks <<< Sirve para poder reinstalar un paquete ya instalado, útil para paquetes dañados* rpm -ivh --oldpackage <<< Para poder bajar de versión* rpm -ivh --replacefile <<< Para instalar todos los archivos, en caso de conflictos* rpm -ivh --nodeps <<< Para poder instalar evitando las dependencias* rpm -qa patron <<< Para hacer queries sobre los paquetes intalados siguiendo un patrón* rpm -qp fichero_rpm <<< Hace la query sobre un paquete dado que aún no está instalado, es muy útil para saber qué contiene el fichero* rpm -qf fichero <<< Para saber de qué paquete viene el fichero especificado* rpm -qi paquete <<< Para hacer una búsqueda en su descripción* rpm -q --docfiles paquete <<< Para hacer búsquedas sólo de los ficheros de documentación de un paquete dado* rpm -q --configfiles paquete <<< Para hacer búsquedas sólo de los ficheros de configuración de un paquete dado* rpm -ql paquete <<< Para saber qué ficheros contiene el paquete especificado* rpm -V paquete <<< Sirve para comparar lo que dice la BBDD y el paquete que de verdad está instalado, es útil para saber si se nos ha reemplazado nuestro paquete por algún otro malintencionado.

Red Hat Certified Engineer

Page 4: RHCE - Apuntes del curso

* rpm --import /path/a/firma <<< Para verificar si el paquete está correctamente firmado. Las opciones vh son para poder ver algo más de información sobre el progreso de instalación del paquete.La base de datos esta en /var/lib/rpm, se debe incluir este directorio en el backup, si este directorio está corrupto no podremos instalar/borrar/actualizar nunca más paquetes. Los paquetes del kernel siempre se han de instalar con -i, puesto que de otra manera (usando -F o -U), reemplazará el kernel existente y borrandolo, con lo cual si hay algún problema con el kernel nuevo, la máquina no arrancará.

Ejercicios:1. ¿Qué ficheros tiene el paquete initscripts?[root@server2 Server]# rpm -qpl initscripts-8.45.30-2.el5.i386.rpm/bin/doexec/bin/ipcalc/bin/usleep/etc/X11/prefdm/etc/adjtime/etc/initlog.conf[...]2. ¿En qué host se empaquetó el RPM 'bash' y cuál es su tamaño de instalación?[root@server2 Server]# rpm -qi bashName : bash Relocations: (not relocatable)Version : 3.2 Vendor: Red Hat, Inc.Release : 24.el5 Build Date: Tue 21 Oct 2008 02:15:55 PM CESTInstall Date: Fri 17 Sep 2010 02:16:25 PM CEST Build Host: hs20-bc1-7.build.redhat.comGroup : System Environment/Shells Source RPM: bash-3.2-24.el5.src.rpmSize : 5349546 License: GPLv2+Signature : DSA/SHA1, Mon 08 Dec 2008 01:25:44 PM CET, Key ID 5326810137017186Packager : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla>URL : http://www.gnu.org/software/bashSummary : The GNU Bourne Again shell (bash) version 3.1.Description :The GNU Bourne Again shell (Bash) is a shell or command languageinterpreter that is compatible with the Bourne shell (sh). Bashincorporates useful features from the Korn shell (ksh) and the C shell(csh). Most sh scripts can be run by bash without modification. Thispackage (bash) contains bash version 3.1, which improves POSIXcompliance over previous versions. 3. ¿Ha cambiado el paquete PAM desde que se instaló?[root@server2 Server]# rpm -V pam....L... c /etc/pam.d/system-auth

Red Hat Certified Engineer

Page 5: RHCE - Apuntes del curso

4. ¿Cuáles de los paquetes instalados contienen "gnome" en sus nombres?[root@server2 Server]# rpm -qa | grep gnomebluez-gnome-0.5-5.fc6libgnome-2.16.0-6.el5gnome-python2-2.16.0-1.fc6gnome-python2-gconf-2.16.0-1.fc6gnome-python2-bonobo-2.16.0-1.fc6libgnomecanvas-2.14.0-4.1gnome-vfs2-2.16.2-4.el5gnome-mount-0.5-3.el5gnome-python2-canvas-2.16.0-1.fc6gnome-mime-data-2.4.2-3.1gnome-doc-utils-0.8.0-2.fc6gnome-keyring-0.6.0-1.fc6libgnomeui-2.16.0-5.el5gnome-python2-gnomevfs-2.16.0-1.fc6rhn-setup-gnome-0.4.20-9.el5 5. ¿Qué paquete RPM provee el fichero /etc/inittab?[root@server2 Server]# rpm -qf /etc/inittabinitscripts-8.45.30-2.el5

3.- ACCESO ADMINISTRATIVO Y SERVICIOS DEL SISTEMA Es necesario exportar las X por SSH, puesto que por defecto en RHEL el servidor X se levanta de manera que no se puedan atender peticiones TCP, por motivos de seguridad. Sin embargo, si la seguridad de nuestra máquina está comprometida, cualquiera puede ver lo que escribo en él, por tanto, para evitar enviar la contraseña, ssh permite autenticar con parejas de claves en vez de con contraseña.[root@server2 Server]# ssh-keygen -t dsa -b 1024Generating public/private dsa key pair.Enter file in which to save the key (/root/.ssh/id_dsa):Enter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in /root/.ssh/id_dsa.Your public key has been saved in /root/.ssh/id_dsa.pub.The key fingerprint is:0b:8f:5b:c7:f9:a6:a7:61:6f:a3:13:2f:88:d9:95:45 [email protected] [root@server2 Server]# ssh-copy-id -i /root/.ssh/id_dsa.pub root@station3The authenticity of host 'station3 (192.168.0.3)' can't be established.RSA key fingerprint is b8:1c:94:40:73:0e:fe:6b:25:41:b1:31:ab:af:81:da.Are you sure you want to continue connecting (yes/no)? yes

Red Hat Certified Engineer

Page 6: RHCE - Apuntes del curso

Warning: Permanently added 'station3,192.168.0.3' (RSA) to the list of known hosts.root@station3's password:Now try logging into the machine, with "ssh 'root@station3'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting. [root@server2 Server]# ssh station3 Sin embargo, el tener acceso de root en una máquina tiene como inconvenientes que cuando se hace algo indebido, no se puede auditar, por tanto es mejor limitar el acceso de root a las máquinas y escalar privilegios o bien utilizar sudo, limitando los privilegios. El fichero /etc/sudoers se debe editar con el comando visudo:[student@station2 ~]$ visudo## Sudoers allows particular users to run various commands as## the root user, without needing the root password.#### Examples are provided at the bottom of the file for collections## of related commands, which can then be delegated out to particular## users or groups.#### This file must be edited with the 'visudo' command. ## Host Aliases## Groups of machines. You may prefer to use hostnames (perhap using## wildcards for entire domains) or IP addresses instead.# Host_Alias FILESERVERS = fs1, fs2# Host_Alias MAILSERVERS = smtp, smtp2 ## User Aliases## These aren't often necessary, as you can use regular groups## (ie, from files, LDAP, NIS, etc) in this file - just use %groupname## rather than USERALIAS# User_Alias ADMINS = jsmith, mikem ## Command Aliases## These are groups of related commands...[...] Estas lineas se han de leer de la siguiente manera:usuario MAQUINA=ROLES COMANDOSstudent ALL=(ALL) ALL El usuario student en cualquier máquina se puede convertir en cualquier usuario y puede ejecutar cualquier comando.

Red Hat Certified Engineer

Page 7: RHCE - Apuntes del curso

3.1 Monitorición de logs del sistema Los ficheros de log más importantes son:/var/log/dmesg/var/log/messages/var/log/maillog/var/log/secure/var/log/audit/audit.log Para configurar el demonio del syslog, hay que tocar el fichero /etc/sysconfig/syslog. Por ejemplo para que syslog escuche mensajes remotos hay que poner esta línea:SYSLOGD_OPTIONS="-m 0 -r" Posteriormente en /etc/syslog.conf, se indican en funcion de la facility y la severity, en qué fichero he de guardar el log:[root@server2 ~]# more /etc/syslog.conf# Log anything (except mail) of level info or higher.# Don't log private authentication messages!*.info;mail.none;authpriv.none;cron.none /var/log/messages # Log cron stuffcron.* @miservidordelogs.example.com

3.2.- Automatización de tareas con cron El formato del fichero cron (ha de editarse con crontab -e) es:minuto hora dia_mes mes dia_semana comando Por tanto, para borrar un fichero cada 5 minutos es*/5 * * * * rm -f /tmp/basura.txt Sin embargo, para ejecutarlo cada hora en el minuto 55 * * * * rm -f /tmp/basura.txt Hay que tener cuidado, pues si se ponen los parámetros DIA_MES y DIA_SEMANA, lo que hace cron es ejecutar de manera que se cumplan cualquiera de estas dos condiciones, en vez de las dos. Anacron se encarga de ejecutar las tareas que no se han podido ejecutar a la hora prevista por cron. Las tareas de cron no se recuperan, sin emabargo, las tareas del sistema sí, anacron lo hace mediante el arranque del sistema.

Red Hat Certified Engineer

Page 8: RHCE - Apuntes del curso

3.3.- Configuración de impresoras con CUPS Se puede hacer con la herramienta gráfica system-config-printer, mediante la web cups (http://localhost:631) o en la linea de comandos con lpadmin. El directorio de spool para cups esta en /var/spool/cups y los ficheros de configuración /etc/cups/cupsd.conf y /etc/cups/printers.conf.

3.4.- Configuración del tiempo con NTP Se puede hacer con la herramienta gráfica system-config-date o bien con la línea de comandos ntp. El fichero de configuración es /etc/ntp.conf Para ver los servidores que nos sirven hora: [root@station2 ~]# ntpq -p remote refid st t when poll reach delay offset jitter==============================================================================*instructor.exam LOCAL(0) 11 u 7 64 377 0.148 -0.262 0.093 Ejercicios1. Crear, habilitar y poner como impresora por defecto una impresora solo texto local:[root@server2 ~]# lpadmin -p server2-lp -v "lpd://localhost/dummy" -m textonly.ppd[root@server2 ~]# lpadmin -p server2-lp -E[root@server2 ~]# lpadmin -d server2-lp[root@server2 ~]# lpr fichero_imprimier

4.- INICIO DEL SISTEMA Y TROUBLESHOOTING RunlevelsVan del 0 al 6, además del S y emergency:

● 0: Parada del sistema (halt)● 1: Single user (rc.sysinit)● 2: Multiuser sin NFS● 3: Multiuser, modo texto, típico de servidores● 4: Oficialmente sin definir● 5: Multiuser, modo gráfico, típico de escritorios● 6: Reinicio del sistema● S: Alternativa a single user (1)● Emergency: Se hace un bypass a rc.sysinit, sulogin pregunta por password de root

Red Hat Certified Engineer

Page 9: RHCE - Apuntes del curso

El proceso de arranque del sistema es el siguiente:

BIOS GRUB

KERNEL + INITRD MONTAR / (RO)

INIT (LEE INITTAB) SYSINIT (RC) MONTAR FS

REMONTAR / (RW) RC5.D

RC.LOCAL TTYS

X

4.1.- GRUB Se encarga de cargar en memoria el kernel. Tiene 2 etapas:1st stage: es un pequeño programa que se añade a la MBR durante la instalación. Simplemente se encagarga de cargar la segunda etapa del GRUB. El comando /sbin/grub-install se usa para repararlo.2nd stage: Se carga desde el FS que contiene a /boot. Carga el kernel en memoria. Se configura en /boot/grub/grub.conf. El entorno de rescate es un LiveCD que viene con RHEL y se arranca desde el prompt de GRUB escribiendo "linux rescue". Este entorno de rescate provee un mínimo conjunto de herramientas y que monta nuestro FS bajo /mnt/sysimage. Si he tenido que arrancar la máquina en modo rescate y tengo que reinstalar un paquete que está corrupto, la manera de hacerlo es:# rpm --root /mnt/sysimage -qf /bin/lscoreutils-5.97-23.el5# rpm --root /mnt/sysimage --replacepkgs -ivh /path/to/coreutils-5.97-23.el5.rpm Problemas típicos en el arranque tienen que ver con el FS, para lo que se usan los siguientes comandos:# fsck /# mount -o remount,rw /

Red Hat Certified Engineer

Page 10: RHCE - Apuntes del curso

5.- KERNEL Y CONFIGURACIÓN DE RED El kernel se encarga de hablar con el hardware. Todos los módulos disponibles para cada versión del kernel se encuentran bajo /lib/modules.[root@station2 ~]# ls /lib/modules/2.6.18-164.el5 2.6.18-164.el5xen Para ver los módulos cargados en memoria se usa lsmod:[root@station2 rules.d]# lsmodModule Size Used byxt_physdev 6993 2ipt_MASQUERADE 7617 1iptable_nat 11077 1 Para cargar nuevos módulos se usa modprobe:[root@station2 rules.d]# modprobe snd Para eliminar un módulo del kernel se usa rmmod:[root@station2 rules.d]# modprobe -r snd Para ver qué hace un módulo se usa modinfo:[root@station2 rules.d]# modinfo dm_logfilename: /lib/modules/2.6.18-164.el5xen/kernel/drivers/md/dm-log.kolicense: GPLauthor: Joe Thornber, Heinz Mauelshagen <[email protected]>description: device-mapper dirty region log[...] El fichero de configuración es /etc/modprobe.conf Para modificar las opciones del kernel, se usa el comando sysctl, sin embargo, para que el cambio sea persistente, se debe editar el fichero /etc/sysctl.conf. Dichos parámetros son los mismos que los ficheros que se encuentran bajo /proc, por tanto, para añadirlos a /etc/sysctl.conf hay que quitar el /proc y reemplazar los '/' por '.'[root@station2 ~]# cat /proc/sys/vm/swappiness60[root@station2 ~]# sysctl -w vm.swappiness=45vm.swappiness = 45[root@station2 ~]# cat /proc/sys/vm/swappiness45 Para que nuestra máquina pueda hacer IP FORWARDING:[root@station2 ~]# cat /etc/sysctl.conf# Controls IP packet forwarding

Red Hat Certified Engineer

Page 11: RHCE - Apuntes del curso

net.ipv4.ip_forward = 1 Para que el fichero se relea y por tanto, el cambio sea efectivo hay que ejecutar "sysctl -p"

5.1.- Monitorización de procesos y recursos Algunas herramientas útiles son:* Estado del kernel: uname, iptime, tload* Procesos: ps, top, gnome-system-monitor* Memoria: free, vmstat, swapon -s, pmap* Uso de disco: df, fdisk -l, iostat, lsof Todas estas utilidades, obtienen su información leyendo del pseudo sistema de ficheros /proc El comando watch sirve para monitorizar la salida de un comando repitiendo el mismo cuantas veces deseemos:[root@station2 ~]# watch -n.5 -d 'ifconfig eth0'

5.2.- Hardware Todos los dispositivos hardware están mapeados a ficheros en /dev, sin embargo este directorio es volátil, representa los dispositivos que el kernel tiene cargados (lo que está en RAM). Para poder reconocer dispositivos, existe udev, que es quien se encarga de crear el mapeo al fichero que se almacena en /dev. udev puede ser configurado con reglas: [root@station2 rules.d]# pwd/etc/udev/rules.d[root@station2 rules.d]# cat 90-hal.rules# pass all events to the HAL daemonRUN+="socket:/org/freedesktop/hal/udev_event"

5.3.- Initial Ram Disk (initrd) Un "Initial Ram Disk" es específico de un hardware concreto y de una plataforma software. Típicamente se crea en tiempo de instalación y sólo se incluyen aquellos módulos necesarios para montar los FS. initrd debe ser re-creado cuando hay cambios en el sistema de ficheros, en el hardware o en el kernel. Se especifica manualmente la version del kernel.

Red Hat Certified Engineer

Page 12: RHCE - Apuntes del curso

#mkinitrd /boot/initrd-2.6.18-164.el5.img 2.6.18-164.el5 El 90% de los problemas de arranque en Linux tienen que ver con el initrd.

5.4.- Configuración de red Es recomendable usar la herramienta gráfica system-config-network. Sino, se puede modificar el fichero /etc/sysconfig/network-scripts/ifcfg-ethX[root@station2 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0# Broadcom Corporation NetXtreme BCM5751 Gigabit Ethernet PCI ExpressDEVICE=eth0BOOTPROTO=dhcpDHCPCLASS=HWADDR=00:10:18:30:BD:6BONBOOT=yes De manera general, podemos buscar información sobre un comando cuando el man no nos ayuda:[root@station2 rules.d]# man ifupNo manual entry for ifup[root@station2 rules.d]# which ifup/sbin/ifup[root@station2 rules.d]# rpm -qf /sbin/ifupinitscripts-8.45.30-2.el5[root@station2 rules.d]# rpm -qd initscripts-8.45.30-2.el5/usr/share/doc/initscripts-8.45.30/ChangeLog/usr/share/doc/initscripts-8.45.30/changes.ipv6/usr/share/doc/initscripts-8.45.30/ipv6-6to4.howto/usr/share/doc/initscripts-8.45.30/ipv6-tunnel.howto/usr/share/doc/initscripts-8.45.30/static-routes-ipv6/usr/share/doc/initscripts-8.45.30/sysconfig.txt/usr/share/doc/initscripts-8.45.30/sysvinitfiles/usr/share/man/man1/consoletype.1.gz/usr/share/man/man1/doexec.1.gz/usr/share/man/man1/genhostid.1.gz/usr/share/man/man1/getkey.1.gz/usr/share/man/man1/initlog.1.gz/usr/share/man/man1/ipcalc.1.gz/usr/share/man/man1/netreport.1.gz/usr/share/man/man1/usleep.1.gz/usr/share/man/man5/crypttab.5.gz/usr/share/man/man8/fstab-decode.8.gz/usr/share/man/man8/ppp-watch.8.gz/usr/share/man/man8/service.8.gz/usr/share/man/man8/sys-unconfig.8.gz/usr/share/man/man8/usernetctl.8.gz[root@station2 ~]# more /usr/share/doc/initscripts-8.45.30/sysconfig.txtFiles in /etc/sysconfig

Red Hat Certified Engineer

Page 13: RHCE - Apuntes del curso

======================= /etc/sysconfig/authconfig used by authconfig to store information about the system's user information and authentication setup; changes made to this file have no effect until the next time authconfig is run[...] Para añadir una ruta estática se usa el comando:[root@station2 ~]# ip route add 10.1.0.0/24 via 192.168.0.254 Sin embargo, para que el cambio sea persistente, hay que añadirlo al fichero de ruta del interfaz concreto:[root@station2 ~]# cat /etc/sysconfig/network-scripts/route-eth010.1.0.0/24 via 192.168.0.254

Ejercicios1.- Evitar que la máquina responda a ping:[root@server2 ~]# echo “net.ipv4.icmp_echo_ignore_all = 1” >> /etc/sysctl.conf[root@server2 ~]# sysctl -pnet.ipv4.icmp_echo_ignore_all = 1net.ipv4.ip_forward = 0[student@station2 ~]$ ping server2PING server2.example.com (192.168.0.102) 56(84) bytes of data. --- server2.example.com ping statistics ---4 packets transmitted, 0 received, 100% packet loss, time 3001ms 2.- Ver la configuracion IP y máscara de subred actual[root@server2 ~]# ifconfig eth0eth0 Link encap:Ethernet HWaddr 00:16:36:4E:97:47 inet addr:192.168.0.102 Bcast:192.168.0.255 Mask:255.255.255.0 inet6 addr: fe80::216:36ff:fe4e:9747/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:8188 errors:0 dropped:0 overruns:0 frame:0 TX packets:1658 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:4281456 (4.0 MiB) TX bytes:210877 (205.9 KiB)[root@server2 ~]# ip addr show eth02: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast qlen 1000

link/ether 00:16:36:4e:97:47 brd ff:ff:ff:ff:ff:ffinet 192.168.0.102/24 brd 192.168.0.255 scope global eth0inet6 fe80::216:36ff:fe4e:9747/64 scope link

valid_lft forever preferred_lft forever 3.- Ver el gateway por defecto[root@server2 ~]# route -n

Red Hat Certified Engineer

Page 14: RHCE - Apuntes del curso

Kernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth00.0.0.0 192.168.0.254 0.0.0.0 UG 0 0 0 eth0[root@server2 ~]# ip route show192.168.0.0/24 dev eth0 proto kernel scope link src 192.168.0.102169.254.0.0/16 dev eth0 scope linkdefault via 192.168.0.254 dev eth0 4.- Ver el servidor DNS[root@server2 ~]# cat /etc/resolv.confsearch example.comnameserver 192.168.0.254 5.- Crear un fichero initrd:Identificar el fichero initrd:[root@server2 boot]# pwd/boot[root@server2 boot]# file initrd-$(uname -r).imginitrd-2.6.18-164.el5xen.img: gzip compressed data, from Unix, last modified: Fri Sep 17 14:18:22 2010, max compression Descomprimirlo, sin modificarlo!![root@server2 boot]# zcat initrd-$(uname -r).img | file -/dev/stdin: ASCII cpio archive (SVR4 with no CRC) Listar los contenidos del archivo cpio[root@server2 boot]# zcat initrd-$(uname -r).img | cpio -itv | lessdrwx------ 2 root root 0 Sep 17 14:18 sysroot-rwx------ 1 root root 2383 Sep 17 14:18 initdrwx------ 2 root root 0 Sep 17 14:18 procdrwx------ 2 root root 0 Sep 17 14:18 bin-rwx------ 1 root root 858276 Sep 17 14:18 bin/kpartxlrwxrwxrwx 1 root root 10 Sep 17 14:18 bin/modprobe -> /sbin/nash[...] Ver los módulos cargados actualmente:[root@server2 boot]# lsmod | moreModule Size Used byautofs4 29253 3hidp 23105 2rfcomm 42457 0l2cap 29505 10 hidp,rfcommbluetooth 53925 5 hidp,rfcomm,l2caplockd 63209 0sunrpc 145533 2 lockd[...]

Red Hat Certified Engineer

Page 15: RHCE - Apuntes del curso

Crear el fichero initrd incluyendo el módulo raid1.ko (dar un nombre nuevo, para no sobreescribir el existente)[root@server2 boot]# mkinitrd --with=raid1 initrd-raid1-$(uname -r).img $(uname -r)

6.- Particiones y Sistemas de Archivos Para ver las particiones dentro de nuestro sistema hay que consultar el fichero /proc/partitions, es lo que el kernel reconoce:[root@station2 ~]# cat /proc/partitionsmajor minor #blocks name 8 0 78150744 sda 8 1 104391 sda1 8 2 18434587 sda2 8 3 522112 sda3 253 0 8388608 dm-0 253 1 491520 dm-1 253 2 5242880 dm-2 253 3 2097152 dm-3 Y por otro lado, podemos ver lo que hay en el disco:[root@station2 ~]# fdisk -l /dev/sda Disk /dev/sda: 80.0 GB, 80026361856 bytes255 heads, 63 sectors/track, 9729 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytes Device Boot Start End Blocks Id System/dev/sda1 * 1 13 104391 83 Linux/dev/sda2 14 2308 18434587+ 8e Linux LVM/dev/sda3 2309 2373 522112+ 82 Linux swap / Solaris También se puede consultar a blkid, es útil para identificar particiones cuando lo tenemos montado todo con etiquetas:[root@station2 ~]# blkid/dev/mapper/vol0-home: UUID="87789b94-1396-480d-a200-e43eef723825" TYPE="ext3"/dev/mapper/vol0-root: UUID="fde1b3e3-b4a7-487e-9ced-4c73a5b46614" TYPE="ext3"/dev/sda3: LABEL="SWAP-sda3" TYPE="swap"/dev/sda1: LABEL="/boot1" UUID="60d546e1-2624-4506-9a25-56b38a00376e" TYPE="ext3" SEC_TYPE="ext2"/dev/vol0/root: UUID="fde1b3e3-b4a7-487e-9ced-4c73a5b46614" TYPE="ext3"

Si necesitamos desmontar un FS y no podemos porque algo lo está bloqueando tenemos que usar fuser tanto para ver quién lo bloquea como para desbloquear:[root@station2 ~]# fuser -v /ptoMontaje

Red Hat Certified Engineer

Page 16: RHCE - Apuntes del curso

[root@station2 ~]# fuser -km /ptoMontaje Para crear un FS hay que seguir los siguientes pasos:[root@station2 ~]# cat /proc/partitions o fdisk -l[root@station2 ~]# fdisk /dev/sda (p,n,w)[root@station2 ~]# partprobe[root@station2 ~]# mkfs.ext3 /dev/sdaX[root@station2 ~]# mount /dev/sdaX /ptoMontaje[root@station2 ~]# echo mount /dev/sdaX /ptoMontaje >> /etc/fstab[root@station2 ~]# mount -a Siempre, después de crear una particion con fdisk, hay que teclear partprobe para que el kernel relea la tabla de particiones, sino no funcionará hasta el siguiente reinicio. El comando tune2fs sirve tanto para cambiar como var ver opciones del FS:[root@station2 ~]# tune2fs -l /dev/sda1tune2fs 1.39 (29-May-2006)Filesystem volume name: /boot1Last mounted on: <not available>Filesystem UUID: 60d546e1-2624-4506-9a25-56b38a00376eFilesystem magic number: 0xEF53Filesystem revision #: 1 (dynamic)Filesystem features: has_journal ext_attr resize_inode dir_index filetype needs_recovery sparse_superDefault mount options: user_xattr aclFilesystem state: cleanErrors behavior: ContinueFilesystem OS type: LinuxInode count: 26104Block count: 104388Reserved block count: 5219Free blocks: 72893Free inodes: 26060First block: 1Block size: 1024Fragment size: 1024Reserved GDT blocks: 256Blocks per group: 8192Fragments per group: 8192Inodes per group: 2008Inode blocks per group: 251Filesystem created: Fri Sep 17 14:05:57 2010Last mount time: Tue Sep 21 11:19:32 2010Last write time: Tue Sep 21 11:19:32 2010Mount count: 18Maximum mount count: -1Last checked: Fri Sep 17 14:05:57 2010Check interval: 0 (<none>)

Red Hat Certified Engineer

Page 17: RHCE - Apuntes del curso

Reserved blocks uid: 0 (user root)Reserved blocks gid: 0 (group root)First inode: 11Inode size: 128Journal inode: 8Default directory hash: teaDirectory Hash Seed: 76b62400-60eb-458b-b8ed-21ac69fa7e61Journal backup: inode blocks Para cambiar el tamaño de bloque hay que usar:[root@station2 ~]# mkfs.ext3 -b 4096 Sin embargo, una vez creado el FS no se puede cambiar el tamaño de bloque, es necesario recrear el FS otra vez.

6.1.- Memoria compartida La swap es un área de memoria en disco que la RAM puede usar en caso de necesidad. Para crear una nueva particion swap hay que seguir los siguientes pasos:[root@station2 ~]# cat /proc/partitions o fdisk -l[root@station2 ~]# fdisk /dev/sda (p,n,t=82,w)[root@station2 ~]# partprobe[root@station2 ~]# mkfswap /dev/sdaX[root@station2 ~]# vi /etc/fstab[root@station2 ~]# swapon -a[root@station2 ~]# mount -a

6.2.- RAID RAID o Redundant Array of Inexpensive disks hace referencia a un sistema de almacenamiento que usa múltiples discos duros o SSD entre los que distribuye o replica los datos. Dependiendo de su configuración (a la que suele llamarse «nivel»), los beneficios de un RAID respecto a un único disco son uno o varios de los siguientes: mayor integridad, mayor tolerancia a fallos, mayor throughput (rendimiento) y mayor capacidad. En sus implementaciones originales, su ventaja clave era la habilidad de combinar varios dispositivos de bajo coste y tecnología más antigua en un conjunto que ofrecía mayor capacidad, fiabilidad, velocidad o una combinación de éstas que un solo dispositivo de última generación y coste más alto. Los niveles RAID más comúnmente usados son:

● RAID 0: Conjunto dividido● RAID 1: Conjunto en espejo● RAID 5: Conjunto dividido con paridad distribuida

Red Hat Certified Engineer

Page 18: RHCE - Apuntes del curso

Para crear una nueva particion swap hay que seguir los siguientes pasos:[root@station2 ~]# cat /proc/partitions o fdisk -l[root@station2 ~]# fdisk /dev/sda /dev/sdb (siempre minimo 2 particiones) t=fd[root@station2 ~]# partprobe[root@station2 ~]# mdadm create[root@station2 ~]# mdadm -C /dev/md0 -a yes -L 5 -n 3 paticiones[root@station2 ~]# mkfs.ext3 /dev/md0

Para ver información sobre el array se puede consultar /proc/mdstat o también usar mdadm:[root@station2 ~]# mdadm --detail /dev/md0[root@station2 ~]# mdmonitor La configuración está en /etc/mdadm.conf. Para simular un fallo de disco:[root@station2 ~]# mdadm /dev/md0 -f /dev/sda1 Para quitar el disco físico (se supone en fallo):[root@station2 ~]# mdadm /dev/md0 -r /dev/sda1 Para recuperarse del fallo de disco (una vez reemplazado -este):[root@station2 ~]# mdadm /dev/md0 -a /dev/sda1 Para parar el array[root@station2 ~]# mdadm -S /dev/md0 Y una vez que esté parado y desensamblado, se puede reconstruir de la siguiente manera:[root@station2 ~]# mdadm --examine --scan >> /etc/mdadm.conf[root@station2 ~]# mdadm --assemble --scan Para ver cuántos discos hay en RAID configurados en el sistema:[root@station2 ~]# mdadm --examine -scan

6.3.- Logical Volume Manager La idea es poder añadir espacio en caliente a las particiones añadiendo discos reales. Primero se ha de crear un volúmen físico (PV) en el que estén los discos físicos y luego un grupo de volumenes (VG). Ambos son contenedores. dentro del VG se crean los volumenes lógicos, que es la estructura lógica con la que trabajaremos como si fuera una partición. Los pasos a seguir son[root@station2 ~]# pvcreate /dev/sda [/dev/sdb...][root@station2 ~]# vgcreate vg1 /dev/sda9

Red Hat Certified Engineer

Page 19: RHCE - Apuntes del curso

[root@station2 ~]# lvcreate -n research -L 1G vg1[root@station2 ~]# mkfs.ext3 /dev/vg1/research[root@station2 ~]# mount /dev/vg1/research /research Redimensionar un volumen:

● Agrandarlo:[root@station2 ~]# lvextend -s +100M /dev/vg1/research[root@station2 ~]# resize2fs -p /dev/vg1/research

● Encogerlo:[root@station2 ~]# umount /dev/vg1/research[root@station2 ~]# e2fsck /dev/vg1/research[root@station2 ~]# resize2fs -p /dev/vg1/research 200M[root@station2 ~]# lvreduce -L 200M /dev/vg1/research

También se pueden redimensionar los grupos de volúmenes (agrandarlos en caliente)[root@station2 ~]# vgextend vg1 /dev/sda9

Para reducirlo, sin parar, hay que quitar el disco físico del grupo:[root@station2 ~]# pmvove /dev/sda10[root@station2 ~]# vgreduce vg1 /dev/sda10 Removed “/dev/sda10” from volume group “vg1”

Ejercicios 1.- Crear una nueva partición primaria.[root@server2 ~]# fdisk -l Disk /dev/xvda: 5368 MB, 5368709120 bytes255 heads, 63 sectors/track, 652 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System/dev/xvda1 * 1 13 104391 83 Linux/dev/xvda2 14 469 3662820 8e Linux LVM[root@server2 ~]# fdisk /dev/xvda Command (m for help): nCommand action e extended p primary partition (1-4)pPartition number (1-4): 3First cylinder (470-652, default 470):Using default value 470Last cylinder or +size or +sizeM or +sizeK (470-652, default 652): +128M Command (m for help): w

Red Hat Certified Engineer

Page 20: RHCE - Apuntes del curso

The partition table has been altered! Calling ioctl() to re-read partition table. WARNING: Re-reading the partition table failed with error 16: Device or resource busy.The kernel still uses the old table.The new table will be used at the next reboot.Syncing disks.[root@server2 ~]# fdisk -l Disk /dev/xvda: 5368 MB, 5368709120 bytes255 heads, 63 sectors/track, 652 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System/dev/xvda1 * 1 13 104391 83 Linux/dev/xvda2 14 469 3662820 8e Linux LVM/dev/xvda3 470 486 136552+ 83 Linux[root@server2 ~]# grep xvda3 /proc/partitions[root@server2 ~]# partprobe /dev/xvda[root@server2 ~]# grep xvda3 /proc/partitions 202 3 136552 xvda3 2.- Etiquetar la particion y añadirla a /etc/fstab[root@server2 ~]# mkfs.ext3 -L newapp /dev/xvda3mke2fs 1.39 (29-May-2006)Filesystem label=newappOS type: LinuxBlock size=1024 (log=0)Fragment size=1024 (log=0)34272 inodes, 136552 blocks6827 blocks (5.00%) reserved for the super userFirst data block=1Maximum filesystem blocks=6737100817 block groups8192 blocks per group, 8192 fragments per group2016 inodes per groupSuperblock backups stored on blocks: 8193, 24577, 40961, 57345, 73729 Writing inode tables: done Creating journal (4096 blocks): doneWriting superblocks and filesystem accounting information: done This filesystem will be automatically checked every 32 mounts or180 days, whichever comes first. Use tune2fs -c or -i to override.[root@server2 ~]# mkdir -p /opt/newapp[root@server2 ~]# vi /etc/fstab

Red Hat Certified Engineer

Page 21: RHCE - Apuntes del curso

LABEL=newapp /opt/newapp ext3 defaults 1 2[root@server2 ~]# mount -a[root@server2 ~]# df -h /opt/newapp/Filesystem Size Used Avail Use% Mounted on/dev/xvda3 130M 5.6M 117M 5% /opt/newapp 3.- Crear un RAID software[root@server2 ~]# fdisk /dev/xvdaDisk /dev/xvda: 5368 MB, 5368709120 bytes255 heads, 63 sectors/track, 652 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System/dev/xvda1 * 1 13 104391 83 Linux/dev/xvda2 14 469 3662820 8e Linux LVM/dev/xvda3 470 486 136552+ 83 Linux/dev/xvda4 487 652 1333395 5 Extended/dev/xvda5 487 518 257008+ fd Linux raid autodetect/dev/xvda6 519 550 257008+ fd Linux raid autodetect[root@server2 ~]# partprobe[root@server2 ~]# mdadm -C /dev/md0 -a yes -l 1 -n 2 /dev/xvda5 /dev/xvda6mdadm: array /dev/md0 started.[root@server2 ~]# mkfs.ext3 /dev/md0[root@server2 ~]# mkdir /data[root@server2 ~]# mount /dev/md0 /data[root@server2 ~]# df -h /dataFilesystem Size Used Avail Use% Mounted on/dev/md0 243M 6.1M 225M 3% /data

4.- Ver la configuración actual del RAID, fallarlo y recuperarse[root@server2 ~]# mdadm --examine --scanARRAY /dev/md0 level=raid1 num-devices=2 UUID=bf52a9f6:f38d94b4:e546de2c:767da1fe[root@server2 ~]# mdadm --detail /dev/md0/dev/md0: Version : 0.90 Creation Time : Tue Sep 21 16:22:32 2010 Raid Level : raid1 Array Size : 256896 (250.92 MiB 263.06 MB) Used Dev Size : 256896 (250.92 MiB 263.06 MB) Raid Devices : 2 Total Devices : 2Preferred Minor : 0

Persistence : Superblock is persistent

Update Time : Tue Sep 21 16:25:16 2010 State : clean Active Devices : 2Working Devices : 2 Failed Devices : 0

Red Hat Certified Engineer

Page 22: RHCE - Apuntes del curso

Spare Devices : 0 UUID : bf52a9f6:f38d94b4:e546de2c:767da1fe Events : 0.2

Number Major Minor RaidDevice State 0 202 5 0 active sync /dev/xvda5 1 202 6 1 active sync /dev/xvda6 [root@server2 ~]# mdadm /dev/md0 --fail /dev/xvda6mdadm: set /dev/xvda6 faulty in /dev/md0[root@server2 ~]# mdadm --detail /dev/md0/dev/md0: Version : 0.90 Creation Time : Tue Sep 21 16:22:32 2010 Raid Level : raid1 Array Size : 256896 (250.92 MiB 263.06 MB) Used Dev Size : 256896 (250.92 MiB 263.06 MB) Raid Devices : 2 Total Devices : 2Preferred Minor : 0

Persistence : Superblock is persistent

Update Time : Tue Sep 21 16:43:10 2010 State : clean, degraded Active Devices : 1Working Devices : 1 Failed Devices : 1 Spare Devices : 0 UUID : bf52a9f6:f38d94b4:e546de2c:767da1fe Events : 0.4

Number Major Minor RaidDevice State 0 202 5 0 active sync /dev/xvda5 1 0 0 1 removed 2 202 6 - faulty spare /dev/xvda6[root@server2 ~]# mdadm /dev/md0 -r /dev/xvda6mdadm: hot removed /dev/xvda6[root@server2 ~]# mdadm /dev/md0 -a /dev/xvda6mdadm: re-added /dev/xvda6[root@server2 ~]# mdadm --detail /dev/md0/dev/md0: Version : 0.90 Creation Time : Tue Sep 21 16:22:32 2010 Raid Level : raid1 Array Size : 256896 (250.92 MiB 263.06 MB) Used Dev Size : 256896 (250.92 MiB 263.06 MB)

Red Hat Certified Engineer

Page 23: RHCE - Apuntes del curso

Raid Devices : 2 Total Devices : 2Preferred Minor : 0

Persistence : Superblock is persistent

Update Time : Tue Sep 21 16:46:02 2010 State : clean, degraded, recovering Active Devices : 1Working Devices : 2 Failed Devices : 0 Spare Devices : 1 Rebuild Status : 51% complete UUID : bf52a9f6:f38d94b4:e546de2c:767da1fe Events : 0.6

Number Major Minor RaidDevice State 0 202 5 0 active sync /dev/xvda5 1 202 6 1 spare rebuilding /dev/xvda6

5.- Crear volumenes lógicos. Designar el RAID como volumen físico y crear un volumen llamado volgroup y uno lógico llamado data[root@server2 ~]# pvcreate /dev/md0 Physical volume "/dev/md0" successfully created[root@server2 ~]# vgcreate volgroup /dev/md0 Volume group "volgroup" successfully created[root@server2 ~]# vgdisplay --- Volume group --- VG Name VolGroup00 System ID Format lvm2 Metadata Areas 1 Metadata Sequence No 4 VG Access read/write VG Status resizable MAX LV 0 Cur LV 3 Open LV 3 Max PV 0 Cur PV 1 Act PV 1 VG Size 3.47 GB PE Size 32.00 MB Total PE 111 Alloc PE / Size 99 / 3.09 GB Free PE / Size 12 / 384.00 MB VG UUID cPp86b-N7w2-G1eo-iYBp-2fdZ-FhOc-yPkqBq --- Volume group ---

Red Hat Certified Engineer

Page 24: RHCE - Apuntes del curso

VG Name volgroup System ID Format lvm2 Metadata Areas 1 Metadata Sequence No 1 VG Access read/write VG Status resizable MAX LV 0 Cur LV 0 Open LV 0 Max PV 0 Cur PV 1 Act PV 1 VG Size 248.00 MB PE Size 4.00 MB Total PE 62 Alloc PE / Size 0 / 0 Free PE / Size 62 / 248.00 MB VG UUID 0a6dym-E0Av-j1gb-rWjj-13aU-fQFw-S1Oa02[root@server2 ~]# lvcreate -n data -l 62 volgroup Logical volume "data" created[root@server2 ~]# mkfs.ext3 /dev/volgroup/data[root@server2 ~]# mount -a[root@server2 ~]# vi /etc/fstab/dev/volgroup/data /data ext3 defaults 1 2 6.- Crear un volumen físico y añadirlo a mi grupo de volumenes[root@server2 ~]# pvcreate /dev/xvda7 Physical volume "/dev/xvda7" successfully created[root@server2 ~]# vgextend volgroup /dev/xvda7 Volume group "volgroup" successfully extended[root@server2 ~]# lvextend -L +40M /dev/volgroup/data Extending logical volume data to 288.00 MB Logical volume data successfully resized[root@server2 ~]# resize2fs -p /dev/volgroup/dataresize2fs 1.39 (29-May-2006)Filesystem at /dev/volgroup/data is mounted on /data; on-line resizing requiredPerforming an on-line resize of /dev/volgroup/data to 294912 (1k) blocks.The filesystem on /dev/volgroup/data is now 294912 blocks long. [root@server2 ~]# df -hFilesystem Size Used Avail Use% Mounted on/dev/mapper/VolGroup00-LogVol00 2.3G 1.6G 585M 74% //dev/mapper/VolGroup00-LogVol02 248M 11M 226M 5% /home/dev/xvda1 99M 28M 67M 30% /boottmpfs 193M 0 193M 0% /dev/shm/dev/xvda3 130M 5.6M 117M 5% /opt/newapp

Red Hat Certified Engineer

Page 25: RHCE - Apuntes del curso

/dev/mapper/volgroup-data 279M 6.1M 259M 3% /data 7.- Reducir el tamaño del volumen data en 100Mb[root@server2 ~]# umount /data/[root@server2 ~]# e2fsck -f /dev/volgroup/datae2fsck 1.39 (29-May-2006)Pass 1: Checking inodes, blocks, and sizesPass 2: Checking directory structurePass 3: Checking directory connectivityPass 4: Checking reference countsPass 5: Checking group summary information/dev/volgroup/data: 11/73728 files (9.1% non-contiguous), 15481/294912 blocks[root@server2 ~]# resize2fs -p /dev/volgroup/data 179Mresize2fs 1.39 (29-May-2006)Resizing the filesystem on /dev/volgroup/data to 183296 (1k) blocks.Begin pass 3 (max = 36)Scanning inode table XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXThe filesystem on /dev/volgroup/data is now 183296 blocks long.[root@server2 ~]# lvreduce -L 179M /dev/volgroup/data

7.- Administración de usuarios Es necesario llevar un control de caducidad de contraseñas, grupos, accesos, etc. Todo esto se hace con los ficheros /etc/passwd y /etc/shadow, sin embargo para modificarlos es aconsejable usar el comando chage username. Los valores por defecto para los datos de caducidad se encuentran en /etc/login.defs, que aplica a los usuarios creados a partir de la modificación. vigr se usa para modificar un fichero de grupos o de contraseñas de manera controlada. Comprueba que el fichero no esté abierto para múltiples ediciones simultaneas. Con umask podemos cambiar la forma en que se crear los ficheros / directorios por defecto. Los grupos privados dificultan el intercambio de archivos entre usuarios, para lo que se suele crear un directorio colaborativo. Para ello se usan SUID, SGID, STICKY.

U G OSUID SGID STICKY RWX RWX RWX1 1 1 111 111 111 Poniendo SGID sobre un directorio, conseguimos crear un directorio propiedad del grupo, por tanto cada uno de los ficheros en él creados serán del grupo. Sin embargo, cualquier usuario

Red Hat Certified Engineer

Page 26: RHCE - Apuntes del curso

puede modificar / borrar dichos ficheros, puesto que para borrar ficheros, los permisos que aplican son los permisos sobre el directorio y no sobre el fichero. Para ello, se ha de activar el STICKY bit sobre el directorio. Sin embargo, para tener un control más fino sobre permisos a grupos y directorios, hay que usar las ACLS.

7.1.- Access Control Lists Primero hay que comprobar que nuestro FS está montado con soporte de acls: [root@station2 ~]# cat /etc/fstab/dev/vol0/root / ext3 defaults 1 1/dev/vol0/home /home ext3 defaults,acl 1 2 Y luego hay que activar las acls:[root@station2 ~]# getfacl fichero[root@station2 ~]# setfacl -m u:student:r f.txt[root@station2 ~]# setfacl -x u:student f.txt La última línea quita la entrada para student sobre f.txt de la ACL, no es quitar un permiso, es eliminarlo del ACL. Para directorios de colaboración, podemos usar ACLs por defecto:[root@station2 ~]# setfacl -m d:g:grupo:rw directorio

Hay que tener en cuenta que con este comando no damos ni quitamos permisos sobre el directorio, sino sobre los ficheros en él creados.

7.2.- Sistema de Quotas Con las quotas podemos tanto controlar el espacio en bloques (se mide en Kb) como el espacio en número de inodos (ficheros). Estos cuotas tiene 2 límites el soft (se le da un aviso) y el hard (se produce un error y no se permite continuar). Una vez más, hay que verificar que el FS está preparado para quotas:[root@station2 ~]# cat /etc/fstab/dev/vol0/root / ext3 defaults

1 1/dev/vol0/home /home ext3

defaults,acl,usrquota,grpquota 1 2 Luego, hay que habilitar las quotas (ésto sólo hay que hacerlo la primera vez):[root@station2 ~]# mount -o remount,rw /home

Red Hat Certified Engineer

Page 27: RHCE - Apuntes del curso

[root@station2 ~]# quotacheck -cugm /directorio[root@station2 ~]# quotaon /directorio Y finalmente, asignar las quotas deseadas (se puede hacer de varias maneras):[root@station2 ~]# edquota usernameDisk quotas for student (uid 500) Filesystem blocks soft hard inodes soft hard /dev/sda5 0 0 0 0 5 10

Así, el usuario student no puede crear más de 10 ficheros, avisándole cuando ha creado 5. También podemos usar el comando setquota, que es mucho mejor si lo que queremos es realizar un script donde se puedan automatizar las quotas.[root@station2 ~]# setquota username 4096 5120 40 50 /foo

Y además, se puede usar un usuario con cuotas ya existente como plantilla para crear otro:[root@station2 ~]# edquota -p user1 user2

Con repquota se pueden ver estadísticas sobre el estado de las cuotas.

Ejercicios. 1.- Crear 6 usuarios y hacer que su password expire cada 30 días.[root@server2 ~]# for USER in joshua alex dax bryan zak ed ; do useradd $USER ; passwd $USER ; done[root@server2 ~]# for USER in joshua alex dax bryan zak ed ; do chage -M 30 $USER ; done 2.- Modificar la política para que las passwords de todos los usuarios creados desde ahora expiren cada 30 días.[root@server2 ~]# cat /etc/login.defs# PASS_MAX_DAYS Maximum number of days a password may be used.PASS_MAX_DAYS 30 3.- Hacer que se pida cambio de contraseña para los usuarios cuando entren en el sistema.[root@server2 ~]# for USER in joshua alex dax bryan zak ed ; do chage -d 2010-08-21 $USER ; doneOJO: Poner un mes menos, pues queremos que la cambie siguiendo la política de 30 días después.[student@station2 ~]$ ssh -l alex server2alex@server2's password:You are required to change your password immediately (password aged)Last login: Wed Sep 22 10:09:15 2010 from station2.example.comWARNING: Your password has expired.You must change your password now and login again!Changing password for user alex.Changing password for alex

Red Hat Certified Engineer

Page 28: RHCE - Apuntes del curso

(current) UNIX password:New UNIX password: 4.- Añadir grupos al sistema, añadir a joshua y alex a sales, a dax y bryan a hr y a zak y edd a web. Student debe estar en todos los grupos.[root@server2 ~]# groupadd -g 201 sales[root@server2 ~]# groupadd -g 202 hr[root@server2 ~]# groupadd -g 203 web[root@server2 ~]# usermod -G sales joshua[root@server2 ~]# usermod -G sales alex[root@server2 ~]# usermod -G hr dax[root@server2 ~]# usermod -G hr bryan[root@server2 ~]# usermod -G web zak[root@server2 ~]# usermod -G web ed[root@server2 ~]# usermod -aG sales -aG hr -aG web student 5.- Comprobar que cada usuario pertenece a cada uno de los grupos secundarios.[root@server2 ~]# for USER in joshua alex dax bryan zak ed ; do id $USER ; doneuid=501(joshua) gid=501(joshua) groups=501(joshua),201(sales) context=root:system_r:unconfined_t:SystemLow-SystemHighuid=502(alex) gid=502(alex) groups=502(alex),201(sales) context=root:system_r:unconfined_t:SystemLow-SystemHighuid=503(dax) gid=503(dax) groups=503(dax),202(hr),203(web) context=root:system_r:unconfined_t:SystemLow-SystemHighuid=504(bryan) gid=504(bryan) groups=504(bryan),202(hr) context=root:system_r:unconfined_t:SystemLow-SystemHighuid=505(zak) gid=505(zak) groups=505(zak),203(web) context=root:system_r:unconfined_t:SystemLow-SystemHighuid=506(ed) gid=506(ed) groups=506(ed),203(web) context=root:system_r:unconfined_t:SystemLow-SystemHigh 6.- Crear el directorio /depts y los subdirectorios sales, hr y web, siendo el grupo correspondiente el propietario de cada uno. Los ficheros creados en cada subdirectorio han de pertenecer al grupo.[root@server2 depts]# for DIR in sales hr web ; do mkdir $DIR ; done[root@server2 depts]# for DIR in sales hr web ; do chgrp $DIR $DIR ; done[root@server2 depts]# ls -ld *drwxr-xr-x 2 root hr 4096 Sep 22 10:22 hrdrwxr-xr-x 2 root sales 4096 Sep 22 10:22 salesdrwxr-xr-x 2 root web 4096 Sep 22 10:22 web[root@server2 depts]# for DIR in sales hr web ; do chmod g+s $DIR ; done[root@server2 depts]# ls -ldh *drwxrws--- 2 root hr 4.0K Sep 22 10:22 hrdrwxrws--- 2 root sales 4.0K Sep 22 10:22 salesdrwxrws--- 2 root web 4.0K Sep 22 10:22 web[student@server2 sales]$ touch f.txt[student@server2 sales]$ ls -ltotal 12

Red Hat Certified Engineer

Page 29: RHCE - Apuntes del curso

-rw-rw-r-- 1 student sales0 Sep 22 10:27 f.txt 7.- Trabajar con ACLs. Crear usuarios y directorios cumpliendo: Como fred, asegurar que barney no podrá leer el fichero secretstuff, pero betty podrá leer y escribir; como barney, y luego como betty intentar leer el fichero.[root@server2 depts]# groupadd bedrock[root@server2 depts]# groupadd wbuffalo[root@server2 depts]# for USER in fred barney wilma betty ; do useradd $USER ; done[root@server2 /]# for USER in fred barney wilma betty ; do usermod -aG bedrock $USER ; done[root@server2 /]# for USER in fred barney ; do usermod -aG wbuffalo $USER ; done[root@server2 depts]# mkdir -p /shared/lodge[root@server2 /]# chgrp wbuffalo /shared/lodge/[root@server2 depts]# chmod 2775 /shared/lodge[fred@server2 lodge]$ touch secretstuff[fred@server2 lodge]$ setfacl -m u:barney:- secretstuff[fred@server2 lodge]$ setfacl -m u:betty:rw secretstuff[fred@server2 lodge]$ getfacl secretstuff# file: secretstuff# owner: fred# group: wbuffalouser::rw-user:barney:---user:betty:rw-group::rw-mask::rw-other::r--[barney@server2 ~]$ cat /shared/lodge/secretstuffcat: /shared/lodge/secretstuff: Permission denied[betty@server2 ~]$ cat /shared/lodge/secretstuffskdf sldkfh sdlkjfsdj lsk372 ñsla

8.- Establecer cuotas en /home, haciendo que zak tenga un límite soft de 512 bloques de 1k y uno hard de 1024 bloques de 1k[root@server2 /]# cat /etc/fstab/dev/VolGroup00/LogVol02 /home ext3 defaults,usrquota 1 2[root@server2 /]# mount -o remount,rw /home[root@server2 /]# quotacheck -cugm /home[root@server2 /]# quotaon /home[root@server2 /]# edquota zakDisk quotas for user zak (uid 505): Filesystem blocks soft hard inodes soft hard /dev/mapper/VolGroup00-LogVol02 14 512 1024 7 0

0[zak@server2 ~]$ dd if=/dev/zero of=bigfile bs=1k count=800dm-1: warning, user block quota exceeded.800+0 records in800+0 records out819200 bytes (819 kB) copied, 0.006009 seconds, 136 MB/s

Red Hat Certified Engineer

Page 30: RHCE - Apuntes del curso

[root@server2 /]# edquota -p zak ed[root@server2 /]# repquota /home*** Report for user quotas on device /dev/mapper/VolGroup00-LogVol02Block grace time: 7days; Inode grace time: 7days Block limits File limits User used soft

hard grace used soft hard grace---------------------------------------------------------------------- root -- 10289 0 0 4 0 0 student -- 24 0

0 12 0 0 joshua -- 14 0 0 7 0 0 alex -- 14 0 0 7 0 0 dax -- 14 0 0 7 0 0 bryan -- 14 0 0 7 0 0 zak +- 822 512 1024 6days 9 0 0 ed -- 14 512 1024 7 0 0 fred -- 18 0 0 9 0 0 barney-- 18 0 0 9 0 0 wilma -- 14 0 0 7 0 0 betty -- 18 0 0 9 0 0

8.- Gestión de cuentas avanzadas

8.1.- NIS NIS almacena en unas tablas locales la información de usuarios, así cuando un cliente quiera validar, obtiene toda la tabla NIS del servidor y posteriomente valida. Esto es muy inseguro, pues todo va en claro.El cliente necesita tener el paquete ypbind instalado. Para configurarlo, usamos la herramienta gráfica system-config-authentication (o la herramienta de texto authconfig). Con getent podemos ver la configuración actual sobre un item (obtenida del servidor NIS):[root@server2 /]# getent passwdroot:x:0:0:root:/root:/bin/bashbin:x:1:1:bin:/bin:/sbin/nologindaemon:x:2:2:daemon:/sbin:/sbin/nologinadm:x:3:4:adm:/var/adm:/sbin/nologin[...]

8.2.- Directorios Home centralizados Se exportan via NFS desde un servidor centralizado, y para montarlos bajo demanda, usamos autofs. Autofs usa varios mapas, el principal es /etc/auto.master. Para crear un nuevo montaje para /home/guest:[root@server2 /]# cat /etc/auto.master/home/guest /etc/auto.guests[root@server2 /]# cat /etc/auto.guestscd -fstype=iso9660,ro,nosuid,nodev:/dev/cdrom

Red Hat Certified Engineer

Page 31: RHCE - Apuntes del curso

linux -ro,soft,intrftp.example.org:/pub/linuxguest2018 -rw,soft,intrinstructor.example.com:/home/guests/guest2018 Por tanto, cuando en local vamos a /home/guest/guest2018 montaría el directorio /home/guests/guest2018 del servidor instructor.example.com. Para los directorios home, es mejor poner un patrón:* -rw,soft,intrinstructor.example.com:/home/guests/& Por tanto, el usuario ha de estar creado sólo en el servidor. Ésta es la configuración del cliente, el servidor simplemente ha de tener un export NFS normal (o cualquier otro tipo de exportación de ficheros, como SAMBA):[root@server2 /]# cat /etc/exports* (rw,soft,intr)

Ejercicios: 1.- Configurar la máquina para autenticarse con el servidor NIS 192.168.0.254 y el dominio notexample[root@server2 ~]# authconfig --enablenis --nisserver=192.168.0.254 --nisdomain=notexample --updateStopping portmap: [ OK ]Starting portmap: [ OK ]Turning on allow_ypbind SELinux booleanBinding to the NIS domain: [ OK ]Listening for an NIS domain server. 2.- Configurar un cliente autofs para el directorio /guests[root@server2 ~]# cat /etc/auto.master /home/guests /etc/auto.guests[root@server2 ~]# cat /etc/auto.guests* -rw,soft,intr 192.168.0.254:/home/guests/&[root@server2 ~]# service autofs restartStopping automount: [ OK ]Starting automount: [ OK ][root@server2 ~]# ssh guest2002@localhostguest2002@localhost's password:Last login: Wed Sep 22 11:31:45 2010 from localhost.localdomainEn el servidor sólo hay un export NFS:[root@server2 ~]# showmount -e 192.168.0.254Export list for 192.168.0.254:/kickstart 192.168.1.0/255.255.255.0,192.168.0.0/255.255.255.0/home/guests 192.168.0.0/255.255.255.0/var/ftp/pub 192.168.1.0/255.255.255.0,192.168.0.0/255.255.255.0[root@instructor ~]$ more exports/var/ftp/pub 192.168.0.0/255.255.255.0(ro,sync) 192.168.1.0/255.255.255.0(ro,sync)/kickstart 192.168.0.0/255.255.255.0(ro,sync) 192.168.1.0/255.255.255.0(ro,sync)

Red Hat Certified Engineer

Page 32: RHCE - Apuntes del curso

/home/guests 192.168.0.0/255.255.255.0(rw,sync)

9.- Segurización de datos y SELinux Es necesario encriptar el tráfico de los datos de nuestra red, protocolos como telnet y ftp son altamente inseguros, pues no cifran sus datos, y por tanto las contraseñas pueden ser obtenidas sólo con un sniffer. Un certificado digital es una clave pública firmada por una autorizad en quien confiamos. También existen los certificados autofirmados, no sirven nada más que para establecer una comunicación cifrada. En ciertas ocasiones necesitaremos un certificado digital o bien los pares de claves. Para generar certificados tenemos openssl, podemos generar CA o autofirmados:* Generar una peticion de firma (csr)* Enviarla al CA* Recibir la clave firmada por el CA

9.1.- OpenSSH Los ficheros de configuración están en /etc/sshd/sshd_config, /etc/ssh/*Se pueden controlar muchas cosas, las más interesantes en términos de seguridad son:* Protocol* ListenAddress* PermitRootLogin* Banner

9.2- SELinux Es una herramienta de control de acceso discrecional, el usuario puede decidir qué tipo de permisos puedo poner sobre cada fichero individual e independiente de los permisos de grupos/usuarios, ni siquiera root puede saltarse la seguridad de SELinux. SELinux trabaja con contextos de seguridad, se ve con la Z mayúscula de muchos comandos:[root@server2 ~]# ls -lZ-rw------- root root system_u:object_r:user_home_t anaconda-ks.cfg-rw-r--r-- root root root:object_r:user_home_t install.log-rw-r--r-- root root root:object_r:user_home_t install.log.syslog-rw-r--r-- root root system_u:object_r:user_home_dir_t post.log[root@server2 ~]# ps -ZLABEL PID TTY TIME CMD

Red Hat Certified Engineer

Page 33: RHCE - Apuntes del curso

root:system_r:unconfined_t:SystemLow-SystemHigh 5700 pts/0 00:00:00 bashroot:system_r:unconfined_t:SystemLow-SystemHigh 7439 pts/0 00:00:00 ps Cualquier cosa que la politica no diga explícitamente está prohibida, independientemente del proceso o del propietario que intenté acceder. Las políticas no se pueden modificar. La política más simple es target. Los procesos de usuarios no tienen restricción, pero los de sistema sí:[student@server2 sales]$ ps -Zuser_u:system_r:unconfined_t 6291 pts/1 00:00:00 bashuser_u:system_r:unconfined_t 7451 pts/1 00:00:00 ps[root@server2 ~]# ps -eZ | grep syslogsystem_u:system_r:syslogd_t 1333 ? 00:00:00 syslogd Los estados de SELinux son enforcing, permissive (sólo avisa) o disabled. Para que los cambios sean persistentes (modo y polítca) hay que editar /etc/sysconfig/selinux o con la herramienta system-config-securitylevel. También son parámetros que se le pueden pasar al kernel (selinux=0|1 o enforcing=0|1). En caliente sólo se puede pasar de permisivo a enforcing:[root@server2 ~]# getenforceEnforcing[root@server2 ~]# setenforce 0[root@server2 ~]# getenforcePermissive[root@server2 ~]# setenforce 1[root@server2 ~]# getenforceEnforcing Los contextos tienen varios elementos:usuario:rol:tipo:sensibilidad:categoríauser_u:object_r:tmp_t:s0:c0La política targeted usa principalmente el elemento “tipo”. Para cambiar los contextos, hay que usar chcon. También está restorecon, que vuelve a dejar los contextos originales.chcon -R -t public_content_t /mydata/htmlrestorecon -vvFR /mydata/html Para añadir un nuevo mapeo que sobreviva a un reetiquetado:semanage fcontext -a -t public_content_t ‘/mydata/html(/*)?’ La base de datos donde SELinux guarda los contextos está en /etc/selinux/politica/contexts. Las políticas de seguridad pueden incluír reglas condicionales que se pueden habilitar o deshabilitar basandose en los valores actuales de un grupo de políticas booleanas. Para ello tenemos getsebool y setsebool:[root@server2 ~]# getsebool -a |grep ftpallow_ftpd_anon_write --> off

Red Hat Certified Engineer

Page 34: RHCE - Apuntes del curso

allow_ftpd_full_access --> offallow_ftpd_use_cifs --> offallow_ftpd_use_nfs --> offallow_tftp_anon_write --> offftp_home_dir --> offftpd_connect_db --> offftpd_disable_trans --> offftpd_is_daemon --> onhttpd_enable_ftp_server --> offtftpd_disable_trans --> off[root@server2 ~]# setsebool httpd_enable_cgi off[root@server2 ~]# getsebool httpd_enable_cgihttpd_enable_cgi --> off Para que el cambio sea persistente, hay que usar -P:[root@server2 ~]# setsebool -P httpd_enable_cgi off También se puede usar la herramienta gráfica system-config-selinux. SELinux también controla los puertos, si queremos añadir un puerto para un nuevo servidor web (ej 81) habría que decirselo a SELinux.[root@server2 ~]# semanage port -l |grep httphttp_cache_port_t tcp 3128, 8080, 8118, 11211, 10001-10010http_cache_port_t udp 3130, 11211http_port_t tcp 80, 443, 488, 8008, 8009, 8443pegasus_http_port_t tcp 5988pegasus_https_port_t tcp 5989 Los logs que SELinux escribe se pueden ver en /var/log/audit/audit.log, sin embargo, son un poco crípticos, para lo que debemos instalar el setroubleshootd, quien procesará los mensajes calificándolos.

Ejercicios 1.- Ver si NTP está protegido por SELinux y romper su contexto.[root@station2 ~]# ntpq -c pe remote refid st t when poll reach delay offset jitter==============================================================================*instructor.exam LOCAL(0) 11 u 299 512 377 0.163 0.054 0.079[root@station2 ~]# ps -eZ |grep ntpdsystem_u:system_r:ntpd_t 2622 ? 00:00:00 ntpd[root@station2 ~]# cp /etc/ntp.conf ~[root@station2 ~]# rm /etc/ntp.conf[root@station2 ~]# mv ntp.conf /etc/[root@station2 ~]# service ntpd restart[root@station2 ~]# ntpq -c peNo association ID's returned

Red Hat Certified Engineer

Page 35: RHCE - Apuntes del curso

[root@station2 ~]# service setroubleshoot start[root@station2 ~]# setenforce 0[root@station2 ~]# getenforcePermissive[root@station2 ~]# service ntpd restart[root@station2 ~]# ntpq -c pe remote refid st t when poll reach delay offset jitter============================================================================== instructor.exam LOCAL(0) 11 u 5 64 1 0.150 -0.035 0.001[root@station2 ~]# setenforce 1[root@station2 ~]# service ntpd restart[root@station2 ~]# ntpq -c peNo association ID's returned[root@station2 ~]# getsebool -a |grep ntpntpd_disable_trans --> off[root@station2 ~]# setsebool -P ntpd_disable_trans on[root@station2 ~]# getsebool -a |grep ntpntpd_disable_trans --> on[root@station2 ~]# service ntpd restart[root@station2 ~]# ntpq -c pe remote refid st t when poll reach delay offset jitter============================================================================== instructor.exam LOCAL(0) 11 u 2 64 1 0.245 -0.058 0.001[root@station2 ~]# ps -ZC ntpdLABEL PID TTY TIME CMDuser_u:system_r:initrc_t 7118 ? 00:00:00 ntpd

2.- Pese a funcionar, el problema persiste, pues NTP está corriendo sin la protección de SELinux, hay que restaurarlo.[root@station2 ~]# setsebool -P ntpd_disable_trans off[root@station2 ~]# service ntpd restart[root@station2 ~]# tail /var/log/messagesSep 22 13:09:52 station2 ntpd[7309]: getconfig: Couldn't open </etc/ntp.conf>Sep 22 13:09:52 station2 setroubleshoot: SELinux is preventing the ntpd from using potentially mislabeled files (./ntp.conf). For complete SELinux messages. run sealert -l 16fdbbb2-8952-488f-92ec-d51eaa530809[root@station2 ~]# rpm -ql ntp |grep ntp.conf/etc/ntp.conf[root@station2 ~]# restorecon -v /etc/ntp.confrestorecon reset /etc/ntp.conf context user_u:object_r:user_home_t:s0->system_u:object_r:net_conf_t:s0[root@station2 ~]# service ntpd restartShutting down ntpd: [ OK ]ntpd: Synchronizing with time server: [ OK ]Starting ntpd: [ OK ][root@station2 ~]# ntpq -c pe remote refid st t when poll reach delay offset jitter============================================================================== instructor.exam LOCAL(0) 11 u 4 64 1 0.172 -0.079 0.001

Red Hat Certified Engineer

Page 36: RHCE - Apuntes del curso

10.- Control de Acceso a nivel de Red: Netfilter Con la herramienta gráfica system-config-securitylevel se puede hacer una configuración muy básica de los servicios de red internos de nuestra máquina. El fichero de configuración de iptables es /etc/sysconfig/iptables. Netfilter usa 3 tablas: filter, nat y mangle. Pero en este curso, sólo nos centraremos en la tabla de filter. Reglas:Las reglas se leen de arriba a abajo, por tanto hay que poner las más restrictivas siempre al final, se usa el criterio “first match wins”. Cada regla tiene uno o varios criterios de “matching” y un “target”. Finalmente, las cadenas tienen una política que se ejecuta cuando no se ha encontrado ninguna regla que encaje con el paquete. Targets:Para la cadena INPUT son 4:* ACCEPT : Paquete aceptado.* DROP : No avisa del motivo por el que se deniega el paquete.* REJECT : Avisa del motivo por el que se deniega el paquete.* LOG : Se loga la información del paquete / regla. Es el único que permite seguir ejecutando reglas. # iptables -t filter -A INPUT -s 192.168.0.1 -j DROP

10.1.- Opeaciones básiscas con Netfilter * Listar reglas de una cadena o tabla: -L o -vL* Añadir una regla a la cadena: -A* Insertar una regla al inicio -I (o en una posicion -I chain 3)* Borrar una regla indivudual: -D (-D chain 3 o -D chain rule)* Asignar una política a una cadena: -P (-P chain target)

- ACCEPT, por defecto- DROP, a un target- REJECT, no permitido, una extensión de un target

* Limpiar todas las reglas de una cadena: -F* Resetear los contadores de paquetes y bytes: -Z* Crear nuevas cadenas: -N, -X (-N micadena, para crear, -X micadena, para borrar) Ejemplos:

Red Hat Certified Engineer

Page 37: RHCE - Apuntes del curso

# iptables --append INPUT --protocol tcp 22 --dport 22 --jump ACCEPT# iptables --append INPUT --jump LOG# iptables --append INPUT --protocol icmp --icmp-type destination-unreachable -jump ACCEPT

10.2. Seguimiento de conexiones Se usan para mantener las conexiones con estado activas y por tanto que Netfilter sea capaz de permitir el paso a conexiones ya establecidas. Así el firewall trabaja a nivel de conexiones en lugar de a nivel IP. Los estados reconocidos son:* NEW : El paquete que crea la nueva conexión.* ESTABLISHED : Paquete que pertenece a una conexión ya establecida.* RELATED : Paquete que tiene que ver pero que no pertenece a una conexión existente (error ICMP, ftp-data, etc).* INVALID : Paquete sin definir, que normalmente será rechazado. iptables --insert INPUT 1 --match state --state ESTABLISHED,RELATED --jump ACCEPT Ejercicios: 1.- Configurar un servicio netfilter:[root@server2 ~]# iptables -N CLASS_RULES[root@server2 ~]# iptables -A INPUT -j CLASS_RULES[root@server2 ~]# vi /etc/sysconfig/iptables# Generated by iptables-save v1.3.5 on Wed Sep 22 15:42:06 2010*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [5:564]:CLASS_RULES - [0:0]-A INPUT -j CLASS_RULES-A CLASS_RULES -i lo -j ACCEPT-A CLASS_RULES -p icmp -j ACCEPT-A CLASS_RULES -p tcp --dport 631 -j ACCEPT-A CLASS_RULES -p udp --dport 631 -j ACCEPT-A CLASS_RULES -m state --state ESTABLISHED,RELATED -j ACCEPT-A CLASS_RULES -p tcp --dport 22 -j ACCEPT-A CLASS_RULES -p udp --dport 69 -j ACCEPT-A CLASS_RULES -j LOG-A CLASS_RULES -j REJECT --reject-with icmp-host-prohibitedCOMMIT 2.- Restringir el acceso al SSH por las máquinas de mi red unicamente.-A CLASS_RULES -p tcp --dport 22 --src 192.168.0.0/24 -j ACCEPT

Red Hat Certified Engineer

Page 38: RHCE - Apuntes del curso

[root@cracker2 ~]# ssh server2.example.comssh: connect to host server2.example.com port 22: No route to host

11.- TCP Wrappers Muchos demonios proveen su propio conjunto de mecanismos de seguridad. Estos mecanismos típicamente son mucho más avanzados que la seguridad que proven los tcp wrappers, sin embargo resulta mucho más fácil tener un punto centralizado para la seguirdad del sistema. Esta solución ha de intentar evitarse siempre que sea posible. TCP Wrappers utiliza la librería libwrap.so y los ficheros /etc/hosts.allow y /etc/hosts.deny, su funcionamiento es el siguiente cuando recibe una petición de conexión:1. Mira si hay alguna regla que encaje en /etc/hosts.allow y si la hay, acepta la conexión.2. Mira si hay alguna regla que encaje en /etc/hosts.deny y si la hay, deniega la conexión.3. Si no hay ninguna regla que encaje, acepta la conexión. Ejemplo[root@cracker2 ~]# cat /etc/hosts.allowsshd: 192.168.0.0/225.255.255.0[root@cracker2 ~]# cat /etc/hosts.allowALL: ALL Para ver los programas que usan TCP Wrappers tenemos que ver si el binario usa la librería libwrap.so:[root@cracker2 ~]# which vsftpd/usr/sbin/vsftpd[root@cracker2 ~]# ldd /usr/sbin/vsftpd | grep wrap libwrap.so.0 => /lib/libwrap.so.0 (0x0026a000) Si el anterior comando no devuelve nada, podemos ver si se usan los ficheros /etc/hosts.allow y /etc/hosts.deny por el binario en cuestion:[root@cracker2 ~]# strings /sbin/portmap | grep hostshosts_access_verbosehosts_allow_tablehosts_deny_table/etc/hosts.allow/etc/hosts.deny Ejercicios 1.- Configuar accesos con TCP Wrappers. Permitiendo explicitamente que ssh esté accesible a todos los hosts, que el resto de programas controlados por tcp wrappers sean accesibles desde localhost pero no desde fuera y que el tftp sea accesible a los hosts de la subred 192.168.0.0/24 únicamente.

Red Hat Certified Engineer

Page 39: RHCE - Apuntes del curso

[root@server2 ~]# cat /etc/hosts.allowsshd: ALLin.tftpd: 192.168.0.0/255.255.255.0ALL: 127.0.0.1[root@server2 ~]# cat /etc/hosts.denyALL: ALL[root@cracker2 ~]# tftp server2.example.com -c get getmeTransfer timed out.[root@cracker2 ~]# ssh [email protected]'s password:Last login: Wed Sep 22 16:40:52 2010 from cracker2.remote.test

12.- Servicios Web

12.1- Apache Es un servidor web sencillo y con una arquitectura modular. Se halla en el paquete httpd y su fichero de configuración principal es /etc/httpd/httpd.conf, pero hay más archivos en /etc/httpd/conf.d/* y /var/www, pero también se puede usar system-config-httpd (gráfica). Los parámetros están divididos en dos categorías global y main. En el fichero de configuración aparece una tercera categoría, virtual. Por defecto sólo se usan las dos primeras, virtual se usa si hay configurado un servidor virtual, heredando los parámetros de las categorías global y main. Los parámetros globales más típicos son:ServerRoot: La URL base de nuestro servidor Web.StartServers: Número de procesos httpd que va a lanzar Apache.MaxClients: Número simultáneo de peticiones.Include: Incluye otras configuraciones (conf.d) Los parámetros virtuales más típicos son:DocumentRoot: Dónde se hallan los ficheros.HostnameLookups: Resolver IPs a nombres para los logs. Suele ponerse en no por motivos de rendimiento.ErrorLog: Dónde se guardan los logs del servidor.CustomLog: Dónde guardar los logs de peticiones. El contenido del servidor por defecto se aloja en /var/www/html, si queremos ponerlo en otro sitio, tenemos que poner los contextos de SELinux correctamente (tipo httpd_sys_content_t), nomalmente le daremos permisos 2775 y apuntar al directorio con DocumentRoot.

12.1.1.- Virtual Hosts

Red Hat Certified Engineer

Page 40: RHCE - Apuntes del curso

Sirve para tener alojados distintos nombres de servidores en la misma máquina. Los pasos a seguir son:1. Activar los virtual hosts: NameVirtualHost IP:PUERTO2. Definir el virtual host:<VirtualHost 192.168.0.100:80>

ServerName virt1.comDocumentRoot /virt1

</VirtualHost>3. Reinciar el servidor: #service httpd restart Si el nombre con el que se llama al Virtual Host no es exactamente igual (ej uso redhat.com en vez de www.redhat.com) buscará uno a uno entre todos los servidores virtuales, y si no encuentra el match exacto, usará el primero de todos. Para eso se pueden crear alias con la directiva ServerAlias. Apache tiene sus propias directivas de control de acceso allow y deny (no usa tcpwrappers), se declaran dentro de cada una de las directivas Directory en las que se quiere especificar. Ésta es la ventaja frente a las reglas del FW, ya que se aplican por directorios.<Directory “/var/www/html/restricted”>

Order Allow,DenyAllow from .example.comDeny from station2.example.com station3.example.com

</Directory>En el caso de tener una petición que no encaja, siempre se toma en consideración la úlima de las 2 directivas especificada en Order.

12.2.- Squid Es un proxy sencillo que soporta los protocolos HTTP, HTTPS, FTP y otros. El paquete que lo contiene es squid y su fichero de configuración básico es /etc/squid/squid.conf, pero también tiene archivos en /etc/squid/*. Squid no soporta tcpwrappers pero tiene sus propios mecanismos de control de acceso. Los parámetros principales son:http_port PUERTOcache_mem MBhttp_access allow MAQUINA|SUBREDhttp_access deny MAQUINA|SUBREDacl all src 0.0.0.0/0.0.0.0 El control de acceso en squid está basada en ACLs, siendo su declaración del tipo “acl nombre_acl expresión”.

Red Hat Certified Engineer

Page 41: RHCE - Apuntes del curso

Squid irá comprobando las ACLs una a una de arriba a abajo, siguiendo la política “first match wins”.

Ejercicios 1.- Crear un servidor web sencillo.[root@server2 ~]# chkconfig httpd on[root@server2 ~]# service httpd start[root@server2 ~]# vi /etc/sysconfig/iptables-A CLASS_RULES -p tcp --dport 80 -j ACCEPT[root@server2 ~]# vi /etc/httpd/conf/httpd.confDocumentRoot "/var/www/html"[root@server2 ~]# echo "<H1> Prueba Apache Clase RH300 </H1>" > /var/www/html/index.html 2.- Crear un servidor web virtual, llamado www.amaya.com, al que sólo se pueda acceder desde la subred 192.168.0.0/24.[root@server2 ~]# vi /etc/sysconfig/iptables-A CLASS_RULES -p tcp --dport 80 --src 192.168.0.0/24 -j ACCEPT[root@server2 ~]# mkdir -p /var/www/virtual/www.amaya.com/html[root@server2 ~]# echo "<H1> Amayita's Virtual Web Server </H1>" > /var/www/virtual/www.amaya.com/html/index.html[root@server2 ~]# vi /etc/httpd/conf.d/www.amaya.com.conf<VirtualHost 192.168.0.102:80> ServerName www.amaya.com ServerAdmin [email protected] DocumentRoot /var/www/virtual/www.amaya.com/html ErrorLog logs/www.amaya.com-error_log CustomLog logs/www.amaya.com-access_log combined <Directory /var/www/virtual/www.amaya.com/html> Options Indexes Includes </Directory></VirtualHost>[root@server2 ~]# vi /etc/httpd/conf/httpd.confNameVirtualHost 192.168.1.102:80 3.- Configuración básica de un proxy caché con squid[root@server2 ~]# chkconfig squid on[root@server2 ~]# service squid start[root@server2 ~]# vi /etc/sysconfig/iptables-A CLASS_RULES -p tcp --dport 3128 --src 192.168.0.0/24 -j ACCEPT[root@server2 ~]# vi /etc/squid/squid.confacl example src 192.168.0.0/24acl otherguys dstdomain .yahoo.comacl otherguys dstdomain .hotmail.comhttp_access deny otherguys <<<<El orden es importante!!!!http_access allow example

Red Hat Certified Engineer

Page 42: RHCE - Apuntes del curso

13.- Infraestructura de servicios de Red.

13.1.- BIND Berkeley Internet Name Domain es el servidor de nombres (DNS) más comúnmente usado en Internet, especialmente en sistemas Unix. Es un servidor de nombres. El paquete que lo contiene es bind y bind-utils, pero el demonio es named. El principal archivo de configuración es /etc/named.conf, pero también tiene ficheros en /var/named/*. DNS usa los puertos 53 udp/tcp y 953 tcp. Para securizar un poco nuestro servidor DNS podemos instalar el paquete bind-chroot, que crea un árbol chroot bajo /var/named/chroot. El comando bind-chroot-admin -e activa el entorno chroot. Al igual que squid, BIND usa ACLs para restringir el acceso al mismo (bind tampoco usa tcpwrappers) y directivas allow y deny.

14.- Servicios de compartición de archivos

14.1.- vsftp Es un servidor ftp “seguro”. Su principal archivo de configuración es /etc/vsftpd/vsftpd.confvsftpd soporta tanto login de usuarios con usuarios anónimos, el directorio por defecto para exportar de forma anónima es /var/ftp, para cambiarlo, hay que cambiar el home del usuario.Los puertos que usa un servidor ftp son el 20 y 21 tcp, además vsftpd utiliza tcpwrappers:[root@station2 ~]# which vsftpd/usr/sbin/vsftpd[root@station2 ~]# ldd /usr/sbin/vsftpd |grep wrap libwrap.so.0 => /lib/libwrap.so.0 (0x00f16000)[root@station2 ~]# cat /etc/hosts.allowvsftpd: ALL En el firewall hay que usar los modos RELATED y ESTABLISHED para poder comunicarnos, dado que usa un puerto para conexiones y otro para datos. Además hay que cargar el módulo del kernel ip_conntrack_ftp y añadir el módulo a [root@station2 ~]# cat /etc/sysconfig/iptables-configIPTABLES_MODULES="ip_conntrack_ftp"[root@station2 ~]# modprobe ip_conntrack_ftp También se puede hacer con system-config-securitylevel, pues él al abrir el puerto del ftp ya

Red Hat Certified Engineer

Page 43: RHCE - Apuntes del curso

hace todo lo necesario. Para evitar que un usuario acceda al servidor ftp, hemos de escribir su nombre en el fichero /etc/vsftp/ftpusers. Además de lo anterior, hay que tener cuidado con SELinux, por ejemplo, SELinux se encargará de evitar que se accedan a los ficheros del home de un usuario, dado que el ftp es un protocolo inseguro.[root@station2 ~]# getsebool -a|grep ftpftp_home_dir --> off

14.2.- NFS Sirve para exportar de manera remota FS. Hay que instalar el paqute nfs-utils. Usa los siguientes demonios: rpc.nfsd, rpc.mountd, rpc.lock, rpc.statd, rpc.rqoutad (todos estan en /usr/sbin). Los puertos que usa son el 111 (udp / tcp) y el 2049, además de otros 4 aleatorios, lo mejor es fijar dichos puertos esto se hace en el fichero /etc/sysconfig/nfs.[root@station2 ~]# more /etc/sysconfig/nfsMOUNTD_PORT=4002STATD_PORT=4003LOCKD_TCPPORT=4004LOCKD_UDPPORT=4004RQUOTAD_PORT=4005 Para ver dónde está escuchando mi servidor NFS podemos usar rpcinfo -p servidor (rpcinfo siempre escucha en el 111):[root@station2 ~]# rpcinfo -p localhost program vers proto port

100000 2 tcp 111 portmapper100000 2 udp 111 portmapper100024 1 udp 834 status100024 1 tcp 837 status

El fichero donde se encuentran los FS exportados es /etc/exports, con el siguiente formato:/FS subred(opciones)[root@station2 ~]# cat /etc/exports/var/ftp/pub 192.168.0.0/255.255.255.0(ro,sync) 192.168.1.0/255.255.255.0(ro,sync)/kickstart 192.168.0.0/255.255.255.0(ro,sync) 192.168.1.0/255.255.255.0(ro,sync)/home/guests 192.168.0.0/255.255.255.0(rw,sync) Con showmount -e servidor podemos ver qué está exportando un servidor NFS.[root@station2 ~]# showmount -e instructor.example.comExport list for instructor.example.com:/kickstart 192.168.1.0/255.255.255.0,192.168.0.0/255.255.255.0/home/guests 192.168.0.0/255.255.255.0/var/ftp/pub 192.168.1.0/255.255.255.0,192.168.0.0/255.255.255.0

Red Hat Certified Engineer

Page 44: RHCE - Apuntes del curso

NFS también usa tcpwrappers:[root@station2 ~]# ldd /usr/sbin/rpc.mountd |grep wrap libwrap.so.0 => /lib/libwrap.so.0 (0x00aa9000)[root@station2 ~]# cat /etc/hosts.allowportmap, mountd: ALL

Posteriormente, para montar un FS exportado por NFS sólo hay que hacer:mount servidor:/FS_EXPORTADO /FS_LOCAL[root@station2 ~]# mount server20:/opt /mnt/opt

14.3.- SAMBA Implementa el mismo servicio de exportación de ficheros SMB/CIFS de Microsoft. Sirve para exportar FS con máquinas windows. Hay que instalar los paquetes samba, samba-common, samba-client. Usa los puertos 137 udp, 138 udp, 139 tcp y 445 tcp. Los ficheros de configuración son /etc/samba/smb.conf y /etc/samba/*. Hay herramientas de configuracion gráficas como system-config-samba y samba-swat (web). Samba no soporta tcpwrappers, pero sí que tiene las directovas hosts allows dentro de su propio fichero de configuración, esta directiva se puede poner directorio por directorio. En este fichero se configuran cada uno de los shares del servidor con sus opciones de accesibilidad.[root@station2 ~]# more /etc/samba/smb.conf[homes] comment = Home Directories browseable = no writable = yes; valid users = %S; valid users = MYDOMAIN\%S Los usuarios de samba han de ser del sistema, pero tienen que tener su propia contraseña samba, para ello se usa smbpasswd. Con testparm podemos ver si la sintaxis del /etc/samba/smb.conf es correcta. Para conectarnos a un servidor samba hay que usar smbclient:[root@station2 ~]# smbclient -L instructor.example.comPassword:Anonymous login successfulDomain=[EXAMPLE] OS=[Unix] Server=[Samba 3.0.33-3.14.el5] Sharename Type Comment --------- ---- ------- ftp Disk Instructor Public FTP IPC$ IPC IPC Service (Instructor Samba Server)Anonymous login successfulDomain=[EXAMPLE] OS=[Unix] Server=[Samba 3.0.33-3.14.el5]

Red Hat Certified Engineer

Page 45: RHCE - Apuntes del curso

Server Comment --------- ------- INSTRUCTOR Instructor Samba Server STATION12 Samba Server Version 3.0.33-3.14.el5 Workgroup Master --------- ------- EXAMPLE INSTRUCTOR MYGROUP SERVER9 O directamente especificando el share:[root@station2 ~]# smbclient '\\instructor.example.com\ftp'Password:Anonymous login successfulDomain=[EXAMPLE] OS=[Unix] Server=[Samba 3.0.33-3.14.el5]smb: \> SELinux por defecto no deja a un usuario acceder a su HOME a través de samba. Ejercicios: 1.- Configurar el servidor vsftpd para que puedan acceder usuarios anónimos pero no locales al sistema:[root@server2 ~]# cat /etc/sysconfig/iptables-A CLASS_RULES -m state --state ESTABLISHED,RELATED -p tcp --dport 21 -j ACCEPT[root@server2 ~]# cat /etc/hosts.allowin.tftpd: 192.168.0.0/255.255.255.0vsftpd: 192.168.0.0/255.255.255.0[root@server2 ~]# cat /etc/sysconfig/iptables-configIPTABLES_MODULES="ip_conntrack_ftp ip_nat_ftp"[root@server2 ~]# ftp localhostConnected to localhost.localdomain.220 (vsFTPd 2.0.5)530 Please login with USER and PASS.530 Please login with USER and PASS.KERBEROS_V4 rejected as an authentication typeName (localhost:root): amaya530 This FTP server is anonymous only.Login failed.ftp> 221 Goodbye.[root@server2 ~]# ftp localhostConnected to localhost.localdomain.220 (vsFTPd 2.0.5)530 Please login with USER and PASS.530 Please login with USER and PASS.KERBEROS_V4 rejected as an authentication typeName (localhost:root): anonymous

Red Hat Certified Engineer

Page 46: RHCE - Apuntes del curso

331 Please specify the password.Password:230 Login successful.Remote system type is UNIX.Using binary mode to transfer files. 2.- Crear un directorio compartido con SAMBA. Ojo con SELinux.[root@server2 ~]# mkdir -p /shared/smbfiles[root@server2 ~]# chown student /shared/smbfiles[root@server2 ~]# chcon -t samba_share_t /shared/[root@server2 ~]# chcon -t samba_share_t /shared/smbfiles[root@server2 ~]# echo "some data" > /shared/smbfiles/kk.txt[root@server2 ~]# smbpasswd student[root@server2 ~]# vi /etc/samba/smb.conf[smbfiles] comment = SMBFiles para la clase path = /shared/smbfiles public = no writable = yes printable = no write list = student[root@server2 ~]# cat /etc/sysconfig/iptables-A CLASS_RULES -p tcp --dport 445 -j ACCEPT 3.- Crear un servidor ftp con un directorio para subidas de ficheros anónimos. OJO con SELinux.[root@server2 ~]# mkdir /var/ftp/incoming[root@server2 ~]# chgrp ftp /var/ftp/incoming/[root@server2 ~]# chmod 2730[root@server2 ~]# chmod 2730 /var/ftp/incoming/[root@server2 ~]# ls -ldZ /var/ftp/incoming/drwx-ws--- root ftp root:object_r:public_content_t /var/ftp/incoming/[root@server2 ~]# chcon -t public_content_rw_t /var/ftp/incoming/[root@server2 ~]# ls -ldZ /var/ftp/incoming/drwx-ws--- root ftp root:object_r:public_content_rw_t /var/ftp/incoming/[root@server2 ~]# setsebool -P allow_ftpd_anon_write on[root@server2 ~]# cat /etc/sysconfig/iptables-A CLASS_RULES -m state --state NEW,ESTABLISHED,RELATED -p tcp --dport 21 --src 192.168.0.0/24 -j ACCEPT[root@server2 ~]# cat /etc/hosts.allowvsftpd: 192.168.0.0/255.255.255.0[root@server2 ~]# cat /etc/vsftpd/vsftpd.confanonymous_enable=YESanon_upload_enable=YESchown_uploads=YESchown_username=daemonanon_umask=077 4.- Configurar un servidor NFS. Ojo con los TCPWrappers.

Red Hat Certified Engineer

Page 47: RHCE - Apuntes del curso

[root@server2 ~]# service nfslock start[root@server2 ~]# chkconfig nfs on[root@server2 ~]# chkconfig nfslock on[root@server2 ~]# rpcinfo -p program vers proto port

100000 2 tcp 111 portmapper100000 2 udp 111 portmapper100024 1 udp 740 status

[...][root@server2 ~]# vi /etc/sysconfig/nfsMOUNTD_PORT=4002STATD_PORT=4003LOCKD_TCPPORT=4004LOCKD_UDPPORT=4004RQUOTAD_PORT=4005[root@server2 ~]# cat /etc/sysconfig/iptables-A CLASS_RULES -p tcp --dport 111 -j ACCEPT-A CLASS_RULES -p udp --dport 111 -j ACCEPT-A CLASS_RULES -p tcp --dport 631 -j ACCEPT-A CLASS_RULES -p udp --dport 631 -j ACCEPT-A CLASS_RULES -p tcp --dport 2049 -j ACCEPT-A CLASS_RULES -p udp --dport 2049 -j ACCEPT-A CLASS_RULES -p tcp --dport 4002:4005 -j ACCEPT-A CLASS_RULES -p udp --dport 4002:4005 -j ACCEPT[root@server2 ~]# useradd -u 1000 nfstest[root@server2 ~]# vi /etc/exports/home/nfstest *example.com(rw,sync,root_squash)[root@server2 ~]# showmount -e localhostExport list for localhost:/home/nfstest *example.com[root@server2 ~]# vi /etc/hosts.allowportmap, mountd: 192.168.0.0/255.255.255.0[root@station2 ~]# mkdir -p /mnt/remote[root@station2 ~]# mount server2:/home/nfstest /mnt/remote[root@station2 ~]# ls /mnt/remote/ls: /mnt/remote/: Permission denied[root@station2 ~]# su - nfstestsu: user nfstest does not exist[root@station2 ~]# useradd -u 1000 nfstest[root@station2 ~]# su - nfstest[nfstest@station2 ~]$ touch /mnt/remote/kk.txt 5.- Crear una carpeta exportada con SAMBA para el grupo legal. Ojo con SELinux.[root@server2 ~]# groupadd -g 3000 legal[root@server2 ~]# for USER in karl joe mary jen ; do adduser -G legal -s /sbin/nologin $USER ; done[root@server2 ~]# for USER in karl joe mary jen root student ; do echo passwd para $USER ; smbpasswd -a $USER ; done[root@server2 ~]# mkdir -p /shared/legal

Red Hat Certified Engineer

Page 48: RHCE - Apuntes del curso

[root@server2 ~]# chgrp legal /shared/legal[root@server2 ~]# chmod 3775 /shared/legal[root@server2 ~]# ls -ldZ /shared/legal/drwxrwsr-t root legal root:object_r:samba_share_t /shared/legal/[root@server2 ~]# chcon -t public_content_rw_t /shared/legal/[root@server2 ~]# setsebool -P allow_smbd_anon_write=1[root@server2 ~]# vi /etc/samba/smb.conf[legal] comment = SMBLegal para la clase path = /shared/legal write list = @legal read only = yes public = no create mask = 0664[student@station2 ~]$ smbclient -U jen '//server2/legal'Password:Domain=[SERVER2] OS=[Unix] Server=[Samba 3.0.33-3.14.el5]smb: \> put pruebaputting file prueba as \prueba (0.0 kb/s) (average 0.0 kb/s)smb: \> get pruebagetting file \prueba of size 0 as prueba (0.0 kb/s) (average nan kb/s)smb: \> quit[student@station2 ~]$ smbclient '//server2/legal'Password:Anonymous login successfulDomain=[MYGROUP] OS=[Unix] Server=[Samba 3.0.33-3.14.el5]tree connect failed: NT_STATUS_ACCESS_DENIED

15.- Servicios de Correo Electrónico

15.1.- Conceptos básicos MUA: Un Mail User Agent es un programa de ordenador usado para leer y enviar e-mails.MTA: Un Mail Transport Agent es uno de los programas que ejecutan los servidores de correo, y tiene como fin transferir un conjunto de datos (correo electronico) de una computadora a otra.MDA: El Mail Delivery Agent es un software que acepta correo entrante desde un Mail Transport Agent y los distribuye a los buzones de los destinatarios (si la cuenta de destino está en la máquina local), o lo reenvía a un servidor SMTP (si los destinatarios están en máquinas remotas).MAA: El Mail Access Agent es un servidor POP3/IMAP usado para que los MUAs puedan acceder al almacén de mensajes.

15.2.- Configuración básica

Red Hat Certified Engineer

Page 49: RHCE - Apuntes del curso

En CLI podemos definir cuál es nuestro MTA con el comando alternatives:[root@server2 ~]# alternatives --config mtaThere are 2 programs which provide 'mta'. Selection Command-----------------------------------------------*+ 1 /usr/sbin/sendmail.sendmail 2 /usr/sbin/sendmail.postfixEnter to keep the current selection[+], or type selection number: 2 Una vez instalado, el servidor de correo está sólo accesible dentro de nuestra máquina:[root@server2 ~]# netstat --listen --tcp --numeric --programActive Internet connections (only servers)Proto Recv-Q Send-Q Local Address Foreign Address State

PID/Program name tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN

1727/sendmail: acce

15.3.- Postfix Postfix usa el puerto 25 tcp para smtp, 465 tcp para smtps y 587 tcp para submission. El fichero de configuración es /etc/postfix/mail.cf y podemos configurarlo a mano o con postconf.Lo primero que hay que hacer es que postfix escuche en todas las interfaces para recibir peticiones:[root@server2 ~]# vi /etc/postfix/mail.cfinet_interfaces = all mydestination son los nombres para los que yo acepto correos electrónicos (hay que definirla en el mail.cf no las coge del entorno del sistema). En principio las cuentas de correo electrónico que voy a tener en mi sistema, son mis usuarios unix. Para controlar el relay (los correos que voy a enviar procedentes de mis redes de confianza) hay que usar mynetworks. Si queremos hacer masquerading (como por ejemplo marketing.redhat.com a redhat.com) hay que usar myorigin. Esto último no suele ser muy común hoy en día. Para revisar las colas podemos usar postqueue -pPara entregar automaticamente postqueue Para crear un alias hay que ir a /etc/aliases y luego hay que ejecutar newaliases (o reiniciar el servicio).

15.4.- Dovecot Es un servidor POP/IMAP sencillo, soporta imap, imaps, pop3, pop3s. Su fichero de configuración es /etc/dovecot.conf. Si usamos SSL tenemos que crear un certificado digital.1. Confirmar que la fecha y hora de mi servidor son correctos

Red Hat Certified Engineer

Page 50: RHCE - Apuntes del curso

2. Crear el fichero PEM que contenga tanto la clave como la firma.[root@server2 ~]# make -C /etc/pki/tls/certs dovecot.pem3. Añadirlo al fichero /etc/dovecot.conf en las directivas ssl_cert_file y ssl_key_file.[root@server2 ~]# vi /etc/dovecot.confssl_cert_file = /etc/pki/tls/certs/dovecot.pemssl_key_file = /etc/pki/tls/certs/dovecot.pem4.- Comprobar que dovecot está escuchando[root@server2 ~]# netstat -tulpn |grep dovecottcp 0 0 :::993 :::* LISTEN

11924/dovecot tcp 0 0 :::110 :::* LISTEN

11924/dovecot Ejercicios 1.- Crear un servidor dovecot seguro (pop3s e imaps)[root@server2 ~]# make -C /etc/pki/tls/certs dovecot.pem[root@server2 ~]# vi /etc/dovecot.confprotocols = imaps pop3sl_cert_file = /etc/pki/tls/certs/dovecot.pemssl_key_file = /etc/pki/tls/certs/dovecot.pem[root@server2 ~]# grep imaps pop3s /etc/servicesimaps 993/tcp # IMAP over SSLimaps 993/udp # IMAP over SSLpop3s 995/tcp # POP-3 over SSLpop3s 995/udp # POP-3 over SSL[root@server2 ~]# vi /etc/sysconfig/iptables-A CLASS_RULES -p tcp --dport 993 -j ACCEPT-A CLASS_RULES -p tcp --dport 993 -j ACCEPT-A CLASS_RULES -p tcp --dport 995 -j ACCEPT-A CLASS_RULES -p tcp --dport 995 -j ACCEPT[root@server2 ~]# echo 'correo de prueba a student' | mail -s prueba-dovecot-student student[student@station2 ~]$ mutt -f imaps://[email protected] 2.- Configurar un servidor postfix.[root@server2 ~]# alternatives --config mtaThere are 2 programs which provide 'mta'. Selection Command-----------------------------------------------* 1 /usr/sbin/sendmail.sendmail + 2 /usr/sbin/sendmail.postfixEnter to keep the current selection[+], or type selection number: 2[root@server2 ~]# vi /etc/aliasesroot: student[root@server2 ~]# chkconfig postfix on[root@server2 ~]# chkconfig sendmail off[root@server2 ~]# service postfix restart

Red Hat Certified Engineer

Page 51: RHCE - Apuntes del curso

[root@server2 ~]# service sendmail stop[root@server2 ~]# echo 'correo de prueba a root' | mail -s prueba-dovecot-root root[student@station2 ~]$ mutt -f imaps://[email protected] 3.- Configurar el MTA para recibir y reenviar email[root@server2 ~]# vi /etc/sysconfig/iptables-A CLASS_RULES -p tcp --dport 25 --src 192.168.0.1/24 -j ACCEPT-A CLASS_RULES -p tcp --dport 25 --src 192.168.1.0/24 -j ACCEPTinet_interfaces = all#inet_interfaces = localhostmynetworks = 127.0.0.1 192.168.0.0/24 192.168.1.0/24 (relay)[root@server2 ~]# netstat -tulpn |grep 25tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN

12893/master[root@station2 ~]# nc server2 25220 server2.example.com ESMTP Postfix

Red Hat Certified Engineer