jueves, 15 de mayo de 2014

cerrar o bloquear acceso a root por ssh y a otros usuarios por ssh

hola, en mi diario trabajo me encontré con la necesidad de asegurar ciertos accesos, restringir a los usuarios principales o de mayores privilegios y dejar solo a un usuario con pocos privilegios con acceso ssh para evitar accesos no deseados, por lo anterior me vi en la obligacion de bloquear acceso ssh a root y a otros usuarios que estan en el sistema y dejar acceso  a un unico usuario para poder asi saltar de usuario en usuario de manera interna en el servidor.

despues del largo intro viene el instructivo asi:

1. editar el archivo:
vi /etc/ssh/sshd_config

2. al final del archivo agregar:
PermitRootLogin no
AllowUsers unicoUsuarioIngresar
MaxAuthTries 3

en donde:
PermitRootLogin no
significa que no se desea que el usuario root ingrese de manera remota "ssh".

AllowUsers unicoUsuarioIngresar

significa que el unico usuario que puede ingresar por ssh es unicoUsuarioIngresar, por lo cual ningun usuario mas podrá ingresar de manera remota si no se registra en esta linea, la manera de separar a los usuarios en caso de ser varios es un espacio " " así:
AllowUsers unicoUsuarioIngresar OTROUsuarioIngresar

y MaxAuthTries 3 es para la máxima cantidad de intentos fallidos que se pueden dar antes de cortar la conexión, es de aclarar que el 3 indica cuantos intentos se desean, pueden ser mas o menos segun se cambie el numero.


luego se cierra el archivo guardando los cambios.

y finalmente se reinicia el servicio de ssh así:

/sbin/service ssh restart



y listo solo han quedado con acceso remoto los usuarios que se hayan incluido en la lista de permitidos "AllowUsers", espero haber sido de utilidad y hasta pronto!






modificar o cambiar hora a servidor Linux CENTOS o RHEL

Hola, bueno, lo primero es dar los créditos respectivos, copio la información de este sitio es por la disponibilidad, bueno, los comandos son los siguientes:

primero borrar el fichero en donde se tiene el registro de la hora, sino se borra, al reiniciar el sistema la hora quedará igual como está actualmente "sin modificaciones":

rm /etc/adjtime

luego se establece la fecha y hora del SO así:

date --set "2014-05-15 16:26"

posteriormente se actualiza la hora de la BIOS con la deseada "generalmente se usa la misma digitada en el comando date"

hwclock --set --date="2014-05-15 16:27"

es mejor mantener la fecha y hora actualizada del sistema desde un servidor de internet, para esto se usa el comando:

ntpdate -u ntp.ubuntu.com

pero mejor para sincronizar ahora la hora de la BIOS con la que se ha dejado sincronizada con el servidor de internet se usa:

hwclock --set --date="`date '+%D %H:%M:%S'`"


espero que haya sido de utilidad, hasta pronto!


miércoles, 5 de febrero de 2014

script de bash para reiniciar tomcat

Hola amigos, en las tareas del dia a dia me encontré con el tema de tener que reiniciar un servidor tomcat de manera automatica, la solicion fue buscar un script de bash que  realizara la tarea.

me he encontrado este script muy interesante y con bastantes validaciones les dejo la url:

http://java360.blogspot.com/2012/03/restart-tomcat-via-shell-script-using.html

por si acaso copio el contenido porque puede que despues no se encuentre disponible...


#!/bin/bash
#Important!! Script Must be run as root(you can ignore this if your tomcat does not need root
PATH=$PATH:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/ant/bin:/opt/java/
export PATH
NOW=$(date +"%Y%m-%dT%H%M")

if [ "$(id -u)" != "0" ];
then
echo "This script must be run as root" 1>&2
exit 1
fi

echo `date` ":=================================" >> /tmp/tomcat-restart.log
echo `date` ":Tomcat restart script initiated!!" >> /tmp/tomcat-restart.log
echo `date` ":=================================" >> /tmp/tomcat-restart.log

if [ `ps -ef | egrep 'tomcat6' | egrep -v egrep | wc -l` -gt 0 ];
then
echo `date` ":Tomcat is running" >> /tmp/tomcat-restart.log

kill -3 `ps ax | grep tomcat6 | grep -v grep | awk '{print $1}'`
/opt/tomcat/bin/catalina.sh stop
echo `date` ":Tomcat has shutdown" >> /tmp/tomcat-restart.log

if [ `ps -ef | egrep 'tomcat6' | egrep -v egrep | wc -l` -gt 0 ];
then
kill -9 `ps ax | grep tomcat6 | grep -v grep | awk '{print $1}'`
fi

#echo "Restarting tomcat !!!!!" >> /tmp/tomcat-restart.log
#/opt/tomcat/bin/catalina.sh start
#else
#echo "Tomcat not found running" >> /tmp/tomcat-restart.log
#echo "Restarting tomcat !!!!!" >> /tmp/tomcat-restart.log
#/opt/tomcat/bin/catalina.sh start
fi

echo `date` "Sleep started" >> /tmp/tomcat-restart.log
sleep 30
echo `date` "Sleep End" >> /tmp/tomcat-restart.log

if [ `ps -ef | egrep 'tomcat6' | egrep -v egrep | wc -l` -eq 0 ];
then
/opt/tomcat/bin/catalina.sh start
echo `date` "Tomcat restarted." >> /tmp/tomcat-restart.log
fi


bendito error generico ORA-00600

copio la informacion que seguí paso a paso de esta URL: http://oraclemamukutti.blogspot.com/2011/06/ora-00600-13013-5001.html

por si acaso se llegan a encontrar con el tema que no saben donde ubicar los archivos de log que tienen el error, se puede usar:
select value from v$parameter where name = 'USER_DUMP_DEST'
por otro lado si desean una ubicacion en donde se puede localizar, les dejo esta ruta:

/app/oracle/diag/rdbms/prod/prod/trace/prod_ora_4303.trc

y dentro de ese archivo se debe buscar la cadena: mismatch



Ora - 00600 [13013], [5001]

I experience an Ora-00600 error. Let's look what is the error and the way to resolve it.

Error received
--------------

ORA-00600: internal error code, arguments: [13013], [5001], [4722], [29361923], [9], [29361923], [17], []

Let's look into details of how to solve this issue.

Section 1> What information needs to be Collected
ORA-600 [13013] [a] [b] [c] [d] [e] [f]

This format relates to Oracle Server 8.0.3 to 10.1

Arg [a] Passcount
Arg [b] Data Object number
Arg [c] Tablespace Relative DBA of block containing the row to be updated
Arg [d] Row Slot number
Arg [e] Relative DBA of block being updated (should be same as [c])
Arg [f] Code

The Second argument would give the information about the data object id.
This would give information about the object involved.

SQL> Select object_name,object_type,owner from dba_objects where data_object_id=;

Once the Object is identified run the following :
The below command check if the table has corruption or not .

SQL> Analzye table . validate structure online;

If this goes fine table doesnot have corruption. For next command.
If the above command fails with ORA-1498 go to Section 3

The below command check if table/index has corruption or not

SQL> Analzye table . validate structure cascade online;

If the above command errors out with ora-1499 it indicates a corruption in index.
Go to section 2 for resolution

Run dbverify on the datafile reported in the error
Arg [c] in the ora-0600[13011] would give the Relative DBA

For example
ORA-00600: internal error code, arguments: [13013], [5001], [57353], [155254965], [261], [151062605], [17], []

Arg [c] --> rdba-->155254965
Use this value and find the file and block number for this dba(data block address)

SQL> select dbms_utility.data_block_address_file(155254965) Rfile# ,dbms_utility.data_block_address_block(155254965) "Block#" from dual;

RFILE# Block#
---------- ----------
37 65717

You can run dbveirfy on datafile with rfile#=37

SQL> Select name from v$datafile where rfile#=37;

$ dbv file= blocksize=

Section 2 > How to resolve if an Index is corrupted.

You would need to drop and recreate the index
Ensure before dropping the Index 

SQL> Spool /tmp/createindex.sql
SQL> Set long 100000000
SQL> Select dbms_metadata.get_ddl('INDEX','',<'user name>') from dual; 
SQL> Spool off

To Identify the index please do the following

Analyze table with "validate structure cascade" fails with ORA-1499 and the trace file contains message "Table/Index row count mismatch". Example:

SQL> analyze table test validate structure cascade;
analyze table test validate structure cascade
*
ERROR at line 1:
ORA-01499: table/index cross reference failure - see trace file
 

The associated trace file contains:
Table/Index row count mismatch 
table 6559 : index 10000, 0 
Index root = tsn: 6 rdba: 0x01400091

It means: A table scan returned 6559 rows and an index scan returned 10000 rows. 
"Index root" is the segment header information for the index: 
rdba: 0x01400091 is the Index segment header relative data block address. It is decimal 20971665 which is Rfile#=5 Block#=145 :

SQL> select dbms_utility.data_block_address_file(20971665)  "Rfile#"   
2          ,dbms_utility.data_block_address_block(20971665) "Block#"   
from dual;   

Rfile#     Block#   
---------- ----------   
5          145  

Running the next query can identify the associated index:
QUERY 1:  

SQL> select owner, segment_name, segment_type  
2    from  dba_segments  
3    where header_file = 5  
4      and header_block = 145;  

OWNER    SEGMENT_NAME    SEGMENT_TYPE  
-------- --------------- ------------------  
SCOTT    I_TEST          INDEX 


Section 3> How to resolve if table is corrupted

Option a> Backup is available

Ora-1498 would be reported on the table.

The trace file from Ora-1498 would contain following information

Example

Block Checking: DBA = 1066265208, Block Type = KTB-managed data block ---> 
file 254,block 911992 
data header at 0xc00000010118e07c 
kdbchk: avsp(816) > tosp(812) 
Block header dump: 0x3f8dea78 
Object id on Block? Y 
seg/obj: 0x155b452 csc: 0x05.7b2b4ee6 itc: 3 flg: E typ: 1 - DATA 
brn: 0 bdba: 0x3f8dde0c ver: 0x01 
inc: 0 exflg: 0 

Note the DBA value reported in the trace file DBA = 1066265208
Convert this to find the file number and block number having issue

Sql> Select dbms_utility.data_block_address_file('1066265208') from dual;

DBMS_UTILITY.DATA_BLOCK_ADDRESS_FILE('1066265208') 
-------------------------------------------------- 
254

Sql> Select dbms_utility.data_block_address_block('1066265208') from dual;

DBMS_UTILITY.DATA_BLOCK_ADDRESS_BLOCK('1066265208') 
--------------------------------------------------- 
911992


Run dbverify on the datafile containing the table

$ dbv file= blocksize=

Corruption would be reported on the block.

If you have an Rman backup do a Rman block recovery (Take the file number and block number affected from the trace file)

Rman> Blockrecover datafile block ;

Or

If you have a user managed backup you can do an restore and recovery from good copy of the problematic datafile
Option b> Backup is not available

If no backups are available then use event 10231 at session level to create a salvage table

SQL> Alter session set events '10231 trace name context forever, level 10'; 
SQL> Create table .salvage_table as select * from ;

Rename the Original table to old.

Rename salvage table to Original table name

How to resolve when Smon terminates the instance due to Ora-00600[13013]

If Smon is terminating the instance then.

Set event 10513 and startup the database
event="10513 trace name context forever, level 2" 

SQL> Startup mount;
SQL> Show parameter event
SQL> Alter datatabase open;

Identify the object involved using information from Section 1.

How to resolve the issue if the object involved belongs to system tablespace

System objects are very important.
Please open a Service request with Oracle support if system tables are involved.

lunes, 13 de enero de 2014

problema al subir archivos con vsftp o vsftpd


Hola amigos, en este día deseo compartir una experiencia que me ha ocurrido en el trabajo al configurar un servidor FTP para que el diseñador de aplicaciones tuviera acceso a una herramienta. Bueno, entrando en materia les cuento que la instalacion del servidor vsftp es muy sencillapara ello usamos:

yum -y install vsftpd

luego editamos el archivo en donde tenemos la configuración del servidor asi:
vi /etc/vsftpd/vsftpd.conf
adicionar las siguientes lineas al final del archivo para evitar inconvenientes:

pam_service_name=vsftpd
userlist_enable=YES
tcp_wrappers=YES
local_root=/opt/tomcat/webapps
use_localtime=YES
xferlog_enable=YES
idle_session_timeout=600
data_connection_timeout=120
local_max_rate=102400
max_clients=50
max_per_ip=20
syslog_enable=YES
pasv_enable=YES
write_enable=YES

y descomentar las siguientes:

chroot_local_user=YES
chroot_list_enable=YES

ascii_upload_enable=YES
ascii_download_enable=YES
connect_from_port_20=YES

se crea un nuevo usuario para el grupo ftp así:
useradd -g ftp usuario

se cambia el password del usuario:

passwd

mejor modificamos el usuario con el grupo tomcat y el grupo ftp así:

usermod -G ftp,tomcat sergio

luego se edita el archivo para adicionar los usuarios del servidor así:
vi /etc/vsftpd/chroot_list

y se copia el nombre del usuario que se creó.

se debe modificar las reglas del firewall en el fichero /etc/sysconfig/iptables

y se agregan las reglas necesarias, en este caso se debe abrir el puerto 21 y estoy en investigacion de que otro puerto debo abrir para poder lograr total funcionamiento del servidor.

por ultimo se reinicia con la siguiente instruccion:

/etc/init.d/vsftpd restart


si llega a poner algun inconveniente con el usuario porque no puede acceder al directorio se debe modificar el usuario para que inicie en el directorio que deseamos y que tenga permisos para hacerlo, eso se hace así:

vi /etc/passwd

se busca el usuario y se cambia el directorio por defecto.

ahora se deben proporcionar las instrucciones para poder permitir el libre trabajo con SELinux, así:

setsebool -P allow_ftpd_full_access 1
setsebool -P allow_ftpd_use_cifs 1
setsebool -P httpd_enable_ftp_server 1
setsebool -P allow_ftpd_use_nfs 1
/*no es necesaria pero si se desea se puede*/
setsebool -P ftpd_connect_db 1
setsebool -P allow_ftpd_full_access 1
setsebool -P allow_ftpd_use_cifs 1
setsebool -P httpd_enable_ftp_server 1
setsebool -P allow_ftpd_use_nfs 1
setsebool -P ftpd_use_passive_mode 1
setsebool -P ftp_home_dir 1
setsebool -P tftp_anon_write 1
setsebool -P allow_ftpd_anon_write 1




se puede seguir el siguiente vinculo para establecer las reglas en el SELinux que es el causante de no poder subir los archivos "cuestiones de seguridad".

http://linux.die.net/man/8/ftpd_selinux

ahora para permitir que se cargue un modulo con sin problemas para administracion de archivos es:
editar el archivo de configuración de iptables para cargar el modulo ftp así:

vi /etc/sysconfig/iptables-config

y agregar el contenido ip_conntrack_ftp en IPTABLES_MODULES, de manera que quede así:

IPTABLES_MODULES="ip_conntrack_ftp"

http://balajitheone.blogspot.com/2011/09/opening-iptables-for-vsftpd.html