Mostrando entradas con la etiqueta Monitoreo. Mostrar todas las entradas
Mostrando entradas con la etiqueta Monitoreo. Mostrar todas las entradas

apache_access_stats.sh

d
Nombre: apache_access_stats.sh
Autor: @linuxitux
Tomado de Linuxito
#!/bin/bash

# apache_access_stats.sh
#
#     Muestra un gráfico de accesos por hora a un servidor Apache a partir de un archivo
#     de log de accesos
#

mensaje="Muestra un gráfico de accesos por hora a un servidor Apache a partir de un archivo de log de
accesos."

# Variables
ancho=50

if [ $# -lt 1 ]
then
        printf "Uso: $0 ARCHIVO\n$mensaje\n"
        exit 1
fi

# Defino un arreglo de horas desde 0 a 23
hs=(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)

# Contabilizo la cantidad de accesos por cada hora
for h in $(cat $* | cut -d '[' -f2 | cut -d "]" -f1 | cut -d ' ' -f1 | cut -d ':' -f2 | sed 's/^0//')
do
        (( hs[$h]++ ))
done

# Calculo la máxima cantidad de accesos
max=0
for h2 in ${hs[@]}
do
        if [ "$h2" -gt "$max" ]
        then
                max=$h2
        fi
done

# Calculo la longitud de caracteres del máximo
longitud=${#max}

# Imprimo el gráfico
echo "HORA (ACCESOS)"
hora="0"
for h3 in ${hs[@]}
do
        # Para cada hora
        # Calculo la cantidad de numerales a imprimir
        c=$(( h3 * ancho / max ))

        # Imprimo la hora con formato "HH:MM"
        if [ $hora == "0" ]
        then
                printf " 0"
        else
                printf "%2.i" "$hora"
        fi
        printf ":00"

        # Imprimo la cantidad de accesos
        printf " (%$longitud.i) " "$h3"

        # Imprimo los numerales
        for (( i=0; i<$c; i++ ))
        do
                printf "#"
        done
        echo

        # Siguiente hora
        (( hora++ ))
done
Leer más...

Monitoreo de Espacio en Disco

d
Muy útil si no se tiene instalado el plugin en Nagios.
Autor: nixcraft
Visto en: nixcraft
#!/bin/sh
# Shell script to monitor or watch the disk space
# It will send an email to $ADMIN, if the (free avilable) percentage 
# of space is >= 90% 
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project 
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# ----------------------------------------------------------------------
# Linux shell script to watch disk space (should work on other UNIX oses )
# SEE URL: http://www.cyberciti.biz/tips/shell-script-to-watch-the-disk-space.html
# set admin email so that you can get email
ADMIN="me@somewher.com"
# set alert level 90% is default
ALERT=90
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
  #echo $output
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1  )
  partition=$(echo $output | awk '{ print $2 }' )
  if [ $usep -ge $ALERT ]; then
    echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" | 
     mail -s "Alert: Almost out of disk space $usep" $ADMIN
  fi
done
Leer más...

Mem.bash

d
Nombre: Mem.bash
Autor: SASIKALA
Descripción: Script que muestra la memoria usada,memoria libre y memoria total.
Visto en The Geek Stuff
#! /bin/bash

# Total memory space details

echo "Memory Space Details"
free -t -m | grep "Total" | awk '{ print "Total Memory space : "$2 " MB";
print "Used Memory Space : "$3" MB";
print "Free Memory : "$4" MB";
}'

echo "Swap memory Details"
free -t -m | grep "Swap" | awk '{ print "Total Swap space : "$2 " MB";
print "Used Swap Space : "$3" MB";
print "Free Swap : "$4" MB";
}'
Permisos: chmod 700 Mem.bash 
Ejecución: ./Mem.bash
Leer más...

Loggedin.bash

d
Nombre: Loggedin.sh
Autor: SASIKALA
Descripción: Script que muestra los usuarios conectados, el porcentaje de CPU que están usando y lo que están haciendo.
Visto en The Geek Stuff
#! /bin/bash

w > /tmp/a

echo "Total number of unique users logged in currently"
cat /tmp/a|  sed '1,2d' | awk '{print $1}' | uniq | wc -l
echo ""

echo "List of unique users logged in currently"
cat /tmp/a | sed '1,2d'|  awk '{print $1}' | uniq
echo ""

echo "The user who is using high %cpu"
cat /tmp/a | sed '1,2d' | awk   '$7 > maxuid { maxuid=$7; maxline=$0 }; END { print maxuid, maxline }' 

echo ""
echo "List of users logged in and what they are doing"
cat /tmp/a
Permisos: chmod 700 Loggedin.bash 
Ejecución: ./Loggedin.bash
Leer más...

Processes.bash

d
Nombre: Processes.bash
Autor: SASIKALA
Descripción: Script que muestra los procesos basados en el procentaje de uso de CPU y de la memoria
Visto en The Geek Stuff
#! /bin/bash
#List processes based on %cpu and memory usage

echo "Start Time" `date`
# By default, it display the list of processes based on the cpu and memory usage #
if [ $# -eq 0 ]
then

 echo "List of processes based on the %cpu Usage"
 ps -e -o pcpu,cpu,nice,state,cputime,args --sort pcpu  # sorted based on %cpu
 echo "List of processes based on the memory Usage"
 ps -e -orss=,args= | sort -b -k1,1n # sorted bases rss value

# If arguements are given (mem/cpu)
else
 case "$1" in
 mem)
  echo "List of processes based on the memory Usage"
   ps -e -orss=,args= | sort -b -k1,1n
  ;;
  cpu)
  echo "List of processes based on the %cpu Usage"
  ps -e -o pcpu,cpu,nice,state,cputime,args --sort pcpu
  ;;
  *)
  echo "Invalid Argument Given \n"
  echo "Usage : $0 mem/cpu"
  exit 1
  esac 

fi
echo "End Time" `date`
exit 0
Permisos: chmod 700 Processes.bash 
Ejecución:
./Processes.bash
./Processes.bash cpu
./Processes.bash mem
Leer más...

Shell Script para analizar Access.log

d
Nombre: webaccess.bash
Autor: Desconocido
Descripción: Script que genera una serie de estadísticas útiles, habida cuenta de un archivo de registro de formato de Apache access_log.
Visto en Linux Party
#!/bin/bash

# webaccess - analyze an Apache-format access_log file, extracting
# useful and interesting statistics

bytes_in_gb=1048576
scriptbc="$HOME/bin/scriptbc"
nicenumber="$HOME/bin/nicenumber"
host="intuitive.com"

if [ $# -eq 0 -o ! -f "$1" ] ; then
echo "Usage: $(basename $0) logfile" >&2
exit 1
fi

firstdate="$(head -1 "$1" | awk '{print $4}' | sed 's/[//')"
lastdate="$(tail -1 "$1" | awk '{print $4}' | sed 's/[//')"

echo "Results of analyzing log file $1"
echo ""
echo " Start date: $(echo $firstdate|sed 's/:/ at /')"
echo " End date: $(echo $lastdate|sed 's/:/ at /')"

hits="$(wc -l < "$1" | sed 's/[^[:digit:]]//g')"

echo " Hits: $($nicenumber $hits) (total accesses)"

pages="$(grep -ivE '(.txt|.gif|.jpg|.png)' "$1" | wc -l | sed 's/[^[:digit:]]//g')"

echo " Pageviews: $($nicenumber $pages) (hits minus graphics)"

totalbytes="$(awk '{sum+=$10} END {print sum}' "$1")"

echo -n " Transferred: $($nicenumber $totalbytes) bytes "

if [ $totalbytes -gt $bytes_in_gb ] ; then
echo "($($scriptbc $totalbytes / $bytes_in_gb) GB)"
elif [ $totalbytes -gt 1024 ] ; then
echo "($($scriptbc $totalbytes / 1024) MB)"
else
echo ""
fi

# now let's scrape the log file for some useful data:

echo ""
echo "The ten most popular pages were:"

awk '{print $7}' "$1" | grep -ivE '(.gif|.jpg|.png)' | 
sed 's//$//g' | sort | 
uniq -c | sort -rn | head -10

echo ""

echo "The ten most common referrer URLs were:"

awk '{print $11}' "$1" | 
grep -vE "(^"-"$|/www.$host|/$host)" | 
sort | uniq -c | sort -rn | head -10

echo ""
exit 0

Permisos: chmod 700 webaccess.bash 
Ejecución: ./webaccess.bash [ log ]
Leer más...

email-alertfs.bash

d
Nombre: email-alertfs.bash
Autor: @_tty0
Descripción: Script que monitorea el uso de disco.
Visto en tty0
#!/bin/bash
# -------------------------------------------------------------------------------------------------------
# set -x
# Shell script to monitor or watch the disk space
# It will send an email to $ADMIN, if the (free available) percentage of space is >= 90%.
# -------------------------------------------------------------------------------------------------------
# Set admin email so that you can get email.
ADMIN="somebody@foo.bar"
# set alert level 90% is default
ALERT=90
# Exclude list of unwanted monitoring, if several partions then use "|" to separate the partitions.
# An example: EXCLUDE_LIST="/dev/sdb1|/dev/sdc5"
EXCLUDE_LIST=""
#
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#

date=$(date "+%D %H:%m:%S")
function main_prog() 
{
 while read output;
 do
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1)
  partition=$(echo $output | awk '{print $2}')
  if [[ $usep -ge $ALERT ]] ; then
   echo -e "ALERT: $date \n\t Running out of space $partition ($usep%) on server: $(hostname)" | \
   mail -s "AACREA Alert: $(hostname) Almost out of disk space $usep%" $ADMIN
   logger -p local7.warn "Running out of space $partition ($usep) - Email sent to $ADMIN"  
  fi
 done
}

if [ "$EXCLUDE_LIST" != "" ] ; then
 df -H | grep -vE "^Filesystem|tmpfs|cdrom|${EXCLUDE_LIST}" | awk '{print $5 " " $6}' | main_prog
else
 df -H | grep -vE "^Filesystem|tmpfs|cdrom" | awk '{print $5 " " $6}' | main_prog
fi
Permisos: chmod 700 email-alertfs.bash 
Ejecución: ./email-alertfs.bash
Leer más...

Show.bash

d
Nombre: Show.bash
Autor: @Tonejito
Descripción: Script que te muestra la IP privada
Visto en Tonejito
#!/bin/sh

IP=/bin/ip
SED=/bin/sed
CUT=/usr/bin/cut

IF=en0

if [ ! -z ${1} ]
then
  IF=${1}
fi

$IP addr show dev $IF | $SED -n 3p | $SED -e 's/\ \+/\ /g' -e 's/\/.*$//g' | $CUT -d ' ' -f 3
Permisos: chmod 700 show.bash 
Ejecución: ./show.bash
Leer más...

CheckSec.sh

d
Nombre: checksec.sh
Autor: Tobias Klein.
Visto en tty0
Descripción: Script diseñado para probar las características de seguridad "estándar" que están siendo utilizadas en un Sistema Operativo Linux y Pax (http://pax.grsecurity.net/)
#!/bin/bash
#
# The BSD License (http://www.opensource.org/licenses/bsd-license.php) 
# specifies the terms and conditions of use for checksec.sh:
#
# Copyright (c) 2009-2011, Tobias Klein.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without 
# modification, are permitted provided that the following conditions 
# are met:
# 
# * Redistributions of source code must retain the above copyright 
#   notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright 
#   notice, this list of conditions and the following disclaimer in 
#   the documentation and/or other materials provided with the 
#   distribution.
# * Neither the name of Tobias Klein nor the name of trapkit.de may be 
#   used to endorse or promote products derived from this software 
#   without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
# DAMAGE.
#
# Name    : checksec.sh
# Version : 1.5
# Author  : Tobias Klein
# Date    : November 2011
# Download: http://www.trapkit.de/tools/checksec.html
# Changes : http://www.trapkit.de/tools/checksec_changes.txt
#
# Description:
#
# Modern Linux distributions offer some mitigation techniques to make it 
# harder to exploit software vulnerabilities reliably. Mitigations such 
# as RELRO, NoExecute (NX), Stack Canaries, Address Space Layout 
# Randomization (ASLR) and Position Independent Executables (PIE) have 
# made reliably exploiting any vulnerabilities that do exist far more 
# challenging. The checksec.sh script is designed to test what *standard* 
# Linux OS and PaX (http://pax.grsecurity.net/) security features are being 
# used.
#
# As of version 1.3 the script also lists the status of various Linux kernel 
# protection mechanisms.
#
# Credits:
#
# Thanks to Brad Spengler (grsecurity.net) for the PaX support.
# Thanks to Jon Oberheide (jon.oberheide.org) for the kernel support.
# Thanks to Ollie Whitehouse (Research In Motion) for rpath/runpath support.
# 
# Others that contributed to checksec.sh (in no particular order):
#
# Simon Ruderich, Denis Scherbakov, Stefan Kuttler, Radoslaw Madej,
# Anthony G. Basile, Martin Vaeth and Brian Davis. 
#

# global vars
have_readelf=1
verbose=false

# SELinux prefix
# Set where the script must search for the SELinux bin files.
se_prefix='/usr/sbin'

# FORTIFY_SOURCE vars
FS_end=_chk
FS_cnt_total=0x
FS_cnt_checked=0
FS_cnt_unchecked=0
FS_chk_func_libc=0
FS_functions=0
FS_libc=0
 
# version information
version() {
  echo "checksec v1.5, Tobias Klein, www.trapkit.de, November 2011"
  echo 
}

# help
help() {
  echo "Usage: checksec [OPTION]"
  echo
  echo "Options:"
  echo
  echo "  --file "
  echo "  --dir  [-v]"
  echo "  --proc "
  echo "  --proc-all"
  echo "  --proc-libs "
  echo "  --kernel"
  echo "  --fortify-file "
  echo "  --fortify-proc "
  echo "  --version"
  echo "  --help"
  echo
  echo "For more information, see:"
  echo "  http://www.trapkit.de/tools/checksec.html"
  echo
}

# check if command exists
command_exists () {
  type $1  > /dev/null 2>&1;
}

# check if directory exists
dir_exists () {
  [ -d $1 ] || return 1
}

# check user privileges
root_privs () {
  [ $UID -eq 0 ] || return 1
}

# check if input is numeric
isNumeric () {
  echo "$@" | grep -q -v "[^0-9]" && return 0
}

# check if input is a string
isString () {
  echo "$@" | grep -q -v "[^A-Za-z]" && return 0
}

# check file(s)
filecheck() {
  # check for RELRO support
  if readelf -l $1 2>/dev/null | grep -q 'GNU_RELRO'; then
    if readelf -d $1 2>/dev/null | grep -q 'BIND_NOW'; then
      echo -n -e '\033[32mFull RELRO   \033[m   '
    else
      echo -n -e '\033[33mPartial RELRO\033[m   '
    fi
  else
    echo -n -e '\033[31mNo RELRO     \033[m   '
  fi

  # check for stack canary support
  if readelf -s $1 2>/dev/null | grep -q '__stack_chk_fail'; then
    echo -n -e '\033[32mCanary found   \033[m   '
  else
    echo -n -e '\033[31mNo canary found\033[m   '
  fi

  # check for NX support
  if readelf -W -l $1 2>/dev/null | grep 'GNU_STACK' | grep -q 'RWE'; then
    echo -n -e '\033[31mNX disabled\033[m   '
  else
    echo -n -e '\033[32mNX enabled \033[m   '
  fi 

  # check for PIE support
  if readelf -h $1 2>/dev/null | grep -q 'Type:[[:space:]]*EXEC'; then
    echo -n -e '\033[31mNo PIE       \033[m   '
  elif readelf -h $1 2>/dev/null | grep -q 'Type:[[:space:]]*DYN'; then
    if readelf -d $1 2>/dev/null | grep -q '(DEBUG)'; then
      echo -n -e '\033[32mPIE enabled  \033[m   '
    else   
      echo -n -e '\033[33mDSO          \033[m   '
    fi
  else
    echo -n -e '\033[33mNot an ELF file\033[m   '
  fi 

  # check for rpath / run path
  if readelf -d $1 2>/dev/null | grep -q 'rpath'; then
   echo -n -e '\033[31mRPATH    \033[m  '
  else
   echo -n -e '\033[32mNo RPATH \033[m  '
  fi

  if readelf -d $1 2>/dev/null | grep -q 'runpath'; then
   echo -n -e '\033[31mRUNPATH    \033[m  '
  else
   echo -n -e '\033[32mNo RUNPATH \033[m  '
  fi
}

# check process(es)
proccheck() {
  # check for RELRO support
  if readelf -l $1/exe 2>/dev/null | grep -q 'Program Headers'; then
    if readelf -l $1/exe 2>/dev/null | grep -q 'GNU_RELRO'; then
      if readelf -d $1/exe 2>/dev/null | grep -q 'BIND_NOW'; then
        echo -n -e '\033[32mFull RELRO       \033[m '
      else
        echo -n -e '\033[33mPartial RELRO    \033[m '
      fi
    else
      echo -n -e '\033[31mNo RELRO         \033[m '
    fi
  else
    echo -n -e '\033[31mPermission denied (please run as root)\033[m\n'
    exit 1
  fi

  # check for stack canary support
  if readelf -s $1/exe 2>/dev/null | grep -q 'Symbol table'; then
    if readelf -s $1/exe 2>/dev/null | grep -q '__stack_chk_fail'; then
      echo -n -e '\033[32mCanary found         \033[m  '
    else
      echo -n -e '\033[31mNo canary found      \033[m  '
    fi
  else
    if [ "$1" != "1" ] ; then
      echo -n -e '\033[33mPermission denied    \033[m  '
    else
      echo -n -e '\033[33mNo symbol table found\033[m  '
    fi
  fi

  # first check for PaX support
  if cat $1/status 2> /dev/null | grep -q 'PaX:'; then
    pageexec=( $(cat $1/status 2> /dev/null | grep 'PaX:' | cut -b6) )
    segmexec=( $(cat $1/status 2> /dev/null | grep 'PaX:' | cut -b10) )
    mprotect=( $(cat $1/status 2> /dev/null | grep 'PaX:' | cut -b8) )
    randmmap=( $(cat $1/status 2> /dev/null | grep 'PaX:' | cut -b9) )
    if [[ "$pageexec" = "P" || "$segmexec" = "S" ]] && [[ "$mprotect" = "M" && "$randmmap" = "R" ]] ; then
      echo -n -e '\033[32mPaX enabled\033[m   '
    elif [[ "$pageexec" = "p" && "$segmexec" = "s" && "$randmmap" = "R" ]] ; then
      echo -n -e '\033[33mPaX ASLR only\033[m '
    elif [[ "$pageexec" = "P" || "$segmexec" = "S" ]] && [[ "$mprotect" = "m" && "$randmmap" = "R" ]] ; then
      echo -n -e '\033[33mPaX mprot off \033[m'
    elif [[ "$pageexec" = "P" || "$segmexec" = "S" ]] && [[ "$mprotect" = "M" && "$randmmap" = "r" ]] ; then
      echo -n -e '\033[33mPaX ASLR off\033[m  '
    elif [[ "$pageexec" = "P" || "$segmexec" = "S" ]] && [[ "$mprotect" = "m" && "$randmmap" = "r" ]] ; then
      echo -n -e '\033[33mPaX NX only\033[m   '
    else
      echo -n -e '\033[31mPaX disabled\033[m  '
    fi
  # fallback check for NX support
  elif readelf -W -l $1/exe 2>/dev/null | grep 'GNU_STACK' | grep -q 'RWE'; then
    echo -n -e '\033[31mNX disabled\033[m   '
  else
    echo -n -e '\033[32mNX enabled \033[m   '
  fi 

  # check for PIE support
  if readelf -h $1/exe 2>/dev/null | grep -q 'Type:[[:space:]]*EXEC'; then
    echo -n -e '\033[31mNo PIE               \033[m   '
  elif readelf -h $1/exe 2>/dev/null | grep -q 'Type:[[:space:]]*DYN'; then
    if readelf -d $1/exe 2>/dev/null | grep -q '(DEBUG)'; then
      echo -n -e '\033[32mPIE enabled          \033[m   '
    else   
      echo -n -e '\033[33mDynamic Shared Object\033[m   '
    fi
  else
    echo -n -e '\033[33mNot an ELF file      \033[m   '
  fi
}

# check mapped libraries
libcheck() {
  libs=( $(awk '{ print $6 }' /proc/$1/maps | grep '/' | sort -u | xargs file | grep ELF | awk '{ print $1 }' | sed 's/:/ /') )
 
  printf "\n* Loaded libraries (file information, # of mapped files: ${#libs[@]}):\n\n"
  
  for element in $(seq 0 $((${#libs[@]} - 1)))
  do
    echo "  ${libs[$element]}:"
    echo -n "    "
    filecheck ${libs[$element]}
    printf "\n\n"
  done
}

# check for system-wide ASLR support
aslrcheck() {
  # PaX ASLR support
  if !(cat /proc/1/status 2> /dev/null | grep -q 'Name:') ; then
    echo -n -e ':\033[33m insufficient privileges for PaX ASLR checks\033[m\n'
    echo -n -e '  Fallback to standard Linux ASLR check'
  fi
  
  if cat /proc/1/status 2> /dev/null | grep -q 'PaX:'; then
    printf ": "
    if cat /proc/1/status 2> /dev/null | grep 'PaX:' | grep -q 'R'; then
      echo -n -e '\033[32mPaX ASLR enabled\033[m\n\n'
    else
      echo -n -e '\033[31mPaX ASLR disabled\033[m\n\n'
    fi
  else
    # standard Linux 'kernel.randomize_va_space' ASLR support
    # (see the kernel file 'Documentation/sysctl/kernel.txt' for a detailed description)
    ASLR=$(/sbin/sysctl -n kernel.randomize_va_space 2> /dev/null)
    printf " (Address Space Layout Randomization): " 
    if [ ! -z $ASLR ] ; then
      if [ $ASLR -ge 2 ]; then
        echo -n -e '\033[32mOn (Setting: 2)\033[m\n\n'
        printf "  Description - Make the addresses of mmap base, heap, stack and VDSO page randomized.\n"
        printf "  This, among other things, implies that shared libraries will be loaded to random \n"
        printf "  addresses. Also for PIE-linked binaries, the location of code start is randomized.\n\n"
      elif [ $ASLR -eq 1 ]; then 
        echo -n -e '\033[33mOn (Setting: 1)\033[m\n\n'
        printf "  Description - Make the addresses of mmap base, stack and VDSO page randomized.\n"
        printf "  This, among other things, implies that shared libraries will be loaded to \n"
        printf "  random addresses. Also for PIE-linked binaries, the location of code start\n"
        printf "  is randomized. Heap addresses are *not* randomized.\n\n"
      elif [ $ASLR -eq 0 ]; then
        echo -n -e '\033[31mOff (Setting:0)\033[m\n'
      fi
    else
      echo -n -e '\033[31mNot kernel support\033[m\n'
    fi
    printf "  See the kernel file 'Documentation/sysctl/kernel.txt' for more details.\n\n"
  fi 
}

# check cpu nx flag
nxcheck() {
  if grep -q nx /proc/cpuinfo; then
    echo -n -e '\033[32mYes\033[m\n\n'
  else
    echo -n -e '\033[31mNo\033[m\n\n'
  fi
}

# check for kernel protection mechanisms
kernelcheck() {
  printf "  Description - List the status of kernel protection mechanisms. Rather than\n"
  printf "  inspect kernel mechanisms that may aid in the prevention of exploitation of\n"
  printf "  userspace processes, this option lists the status of kernel configuration\n"
  printf "  options that harden the kernel itself against attack.\n\n"
  printf "  Kernel version: \033[33m%s\033[m - OS architecture: \033[33m%s\033[m\n" $(/bin/uname -r) $(/bin/uname -m)
  printf "  Kernel config : "
 
  if [ -f /proc/config.gz ] ; then
    kconfig="zcat /proc/config.gz"
    printf "\033[32m/proc/config.gz\033[m\n\n"
  elif [ -f /boot/config-`uname -r` ] ; then
    kconfig="cat /boot/config-`uname -r`"
    printf "\033[33m/boot/config-`uname -r`\033[m\n\n"
    printf "  Warning: The config on disk may not represent running kernel config!\n\n";
  elif [ -f "${KBUILD_OUTPUT:-/usr/src/linux}"/.config ] ; then
    kconfig="cat ${KBUILD_OUTPUT:-/usr/src/linux}/.config"
    printf "\033[33m%s\033[m\n\n" "${KBUILD_OUTPUT:-/usr/src/linux}/.config"
    printf "  Warning: The config on disk may not represent running kernel config!\n\n";
  else
    printf "\033[31mNOT FOUND\033[m\n\n"
    exit 0
  fi

  printf "  GCC stack protector support:            "
  if $kconfig | grep -qi 'CONFIG_CC_STACKPROTECTOR=y'; then
    printf "\033[32mEnabled\033[m\n"
  else
    printf "\033[31mDisabled\033[m\n"
  fi

  printf "  Strict user copy checks:                "
  if $kconfig | grep -qi 'CONFIG_DEBUG_STRICT_USER_COPY_CHECKS=y'; then
    printf "\033[32mEnabled\033[m\n"
  else
    printf "\033[31mDisabled\033[m\n"
  fi

  printf "  Enforce read-only kernel data:          "
  if $kconfig | grep -qi 'CONFIG_DEBUG_RODATA=y'; then
    printf "\033[32mEnabled\033[m\n"
  else
    printf "\033[31mDisabled\033[m\n"
  fi
  printf "  Restrict /dev/mem access:               "
  if $kconfig | grep -qi 'CONFIG_STRICT_DEVMEM=y'; then
    printf "\033[32mEnabled\033[m\n"
  else
    printf "\033[31mDisabled\033[m\n"
  fi

  printf "  Restrict /dev/kmem access:              "
  if $kconfig | grep -qi 'CONFIG_DEVKMEM=y'; then
    printf "\033[31mDisabled\033[m\n"
  else
    printf "\033[32mEnabled\033[m\n"
  fi

  printf "\n"
  printf "* grsecurity / PaX: "

  if $kconfig | grep -qi 'CONFIG_GRKERNSEC=y'; then
    if $kconfig | grep -qi 'CONFIG_GRKERNSEC_HIGH=y'; then
      printf "\033[32mHigh GRKERNSEC\033[m\n\n"
    elif $kconfig | grep -qi 'CONFIG_GRKERNSEC_MEDIUM=y'; then
      printf "\033[33mMedium GRKERNSEC\033[m\n\n"
    elif $kconfig | grep -qi 'CONFIG_GRKERNSEC_LOW=y'; then
      printf "\033[31mLow GRKERNSEC\033[m\n\n"
    else
      printf "\033[33mCustom GRKERNSEC\033[m\n\n"
    fi

    printf "  Non-executable kernel pages:            "
    if $kconfig | grep -qi 'CONFIG_PAX_KERNEXEC=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Prevent userspace pointer deref:        "
    if $kconfig | grep -qi 'CONFIG_PAX_MEMORY_UDEREF=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Prevent kobject refcount overflow:      "
    if $kconfig | grep -qi 'CONFIG_PAX_REFCOUNT=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Bounds check heap object copies:        "
    if $kconfig | grep -qi 'CONFIG_PAX_USERCOPY=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Disable writing to kmem/mem/port:       "
    if $kconfig | grep -qi 'CONFIG_GRKERNSEC_KMEM=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Disable privileged I/O:                 "
    if $kconfig | grep -qi 'CONFIG_GRKERNSEC_IO=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Harden module auto-loading:             "
    if $kconfig | grep -qi 'CONFIG_GRKERNSEC_MODHARDEN=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi

    printf "  Hide kernel symbols:                    "
    if $kconfig | grep -qi 'CONFIG_GRKERNSEC_HIDESYM=y'; then
      printf "\033[32mEnabled\033[m\n"
    else
      printf "\033[31mDisabled\033[m\n"
    fi
  else
    printf "\033[31mNo GRKERNSEC\033[m\n\n"
    printf "  The grsecurity / PaX patchset is available here:\n"
    printf "    http://grsecurity.net/\n"
  fi

  printf "\n"
  printf "* Kernel Heap Hardening: "

  if $kconfig | grep -qi 'CONFIG_KERNHEAP=y'; then
    if $kconfig | grep -qi 'CONFIG_KERNHEAP_FULLPOISON=y'; then
      printf "\033[32mFull KERNHEAP\033[m\n\n"
    else
      printf "\033[33mPartial KERNHEAP\033[m\n\n"
    fi
  else
    printf "\033[31mNo KERNHEAP\033[m\n\n"
    printf "  The KERNHEAP hardening patchset is available here:\n"
    printf "    https://www.subreption.com/kernheap/\n\n"
  fi

  # Check SELinux support, status and configuration. 
  printf "  SELinux support:" 

  if $kconfig | grep -qi 'CONFIG_SECURITY_SELINUX=y'; then
    if [ ! -e ${se_prefix}/sestatus ] || [ ! -e ${se_prefix}/getenforce ]; then 
      printf "\033[31m SELinux kernel support but no utils installed\033[m\n\n"
      exit 
    else
      printf "\033[32m SELinux kernel support\033[m\n" 
    fi

    if ( $kconfig 1> /dev/null ); then
      printf "  SELinux mode:  "
      se_status=$($se_prefix/getenforce)
      [ $se_status = 'Enforcing'  ] && printf "\033[32m  Enforcing\033[m\n"
      [ $se_status = 'Permissive' ] && printf "\033[33m  Permissive\033[m\n"
      [ $se_status = 'Disabled'   ] && printf "\033[31m  Disabled\033[m\n"

      printf "  SELinux policy:"
      se_policy=$($se_prefix/sestatus | grep "Policy from config file" | awk -F: {'print $2'})
      [ $se_policy = 'targeted'  ] && printf "\033[33m  Targeted \033[m\n\n"
      [ $se_policy = 'stric'     ] && printf "\033[32m  Stric\033[m\n\n"
    fi
      printf "  Warning: The config may represent the running SELinux config!\n\n"
  else
    printf "\033[31m  No Kernel SELinux support\033[m\n\n"
  fi
  

}

# --- FORTIFY_SOURCE subfunctions (start) ---

# is FORTIFY_SOURCE supported by libc?
FS_libc_check() {
  printf "* FORTIFY_SOURCE support available (libc)    : "

  if [ "${#FS_chk_func_libc[@]}" != "0" ] ; then
    printf "\033[32mYes\033[m\n"
  else
    printf "\033[31mNo\033[m\n"
    exit 1
  fi
}

# was the binary compiled with FORTIFY_SOURCE?
FS_binary_check() {
  printf "* Binary compiled with FORTIFY_SOURCE support: "

  for FS_elem_functions in $(seq 0 $((${#FS_functions[@]} - 1)))
  do
    if [[ ${FS_functions[$FS_elem_functions]} =~ _chk ]] ; then
      printf "\033[32mYes\033[m\n"
      return
    fi
  done
  printf "\033[31mNo\033[m\n"
  exit 1
}

FS_comparison() {
  echo
  printf " ------ EXECUTABLE-FILE ------- . -------- LIBC --------\n"
  printf " FORTIFY-able library functions | Checked function names\n"
  printf " -------------------------------------------------------\n"

  for FS_elem_libc in $(seq 0 $((${#FS_chk_func_libc[@]} - 1)))
  do
    for FS_elem_functions in $(seq 0 $((${#FS_functions[@]} - 1)))
    do
      FS_tmp_func=${FS_functions[$FS_elem_functions]}
      FS_tmp_libc=${FS_chk_func_libc[$FS_elem_libc]}

      if [[ $FS_tmp_func =~ ^$FS_tmp_libc$ ]] ; then
        printf " \033[31m%-30s\033[m | __%s%s\n" $FS_tmp_func $FS_tmp_libc $FS_end
        let FS_cnt_total++
        let FS_cnt_unchecked++
      elif [[ $FS_tmp_func =~ ^$FS_tmp_libc(_chk) ]] ; then
        printf " \033[32m%-30s\033[m | __%s%s\n" $FS_tmp_func $FS_tmp_libc $FS_end
        let FS_cnt_total++
        let FS_cnt_checked++
      fi

    done
  done
}

FS_summary() {
  echo
  printf "SUMMARY:\n\n"
  printf "* Number of checked functions in libc                : ${#FS_chk_func_libc[@]}\n"
  printf "* Total number of library functions in the executable: ${#FS_functions[@]}\n"
  printf "* Number of FORTIFY-able functions in the executable : %s\n" $FS_cnt_total
  printf "* Number of checked functions in the executable      : \033[32m%s\033[m\n" $FS_cnt_checked
  printf "* Number of unchecked functions in the executable    : \033[31m%s\033[m\n" $FS_cnt_unchecked
  echo
}

# --- FORTIFY_SOURCE subfunctions (end) ---

if !(command_exists readelf) ; then
  printf "\033[31mWarning: 'readelf' not found! It's required for most checks.\033[m\n\n"
  have_readelf=0
fi


# parse command-line arguments
case "$1" in

 --version)
  version
  exit 0
  ;;

 --help)
  help
  exit 0
  ;;

 --dir)
  if [ "$3" = "-v" ] ; then
    verbose=true
  fi
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid directory.\033[m\n\n"
    exit 1
  fi
  # remove trailing slashes
  tempdir=`echo $2 | sed -e "s/\/*$//"`
  if [ ! -d $tempdir ] ; then
    printf "\033[31mError: The directory '$tempdir' does not exist.\033[m\n\n"
    exit 1
  fi
  cd $tempdir
  printf "RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH      FILE\n"
  for N in [A-Za-z]*; do
    if [ "$N" != "[A-Za-z]*" ]; then
      # read permissions?
      if [ ! -r $N ]; then
        printf "\033[31mError: No read permissions for '$tempdir/$N' (run as root).\033[m\n"
      else
        # ELF executable?
        out=`file $N`
        if [[ ! $out =~ ELF ]] ; then
           if [ "$verbose" = "true" ] ; then
             printf "\033[34m*** Not an ELF file: $tempdir/"
             file $N
             printf "\033[m"
           fi
        else 
          filecheck $N
          if [ `find $tempdir/$N \( -perm -004000 -o -perm -002000 \) -type f -print` ]; then
            printf "\033[37;41m%s%s\033[m" $2 $N
          else
            printf "%s%s" $tempdir/ $N
          fi
          echo
        fi
      fi
    fi
  done
  exit 0
  ;;

 --file)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid file.\033[m\n\n"
   exit 1
  fi
  # does the file exist?
  if [ ! -e $2 ] ; then
    printf "\033[31mError: The file '$2' does not exist.\033[m\n\n"
    exit 1
  fi
  # read permissions?
  if [ ! -r $2 ] ; then
    printf "\033[31mError: No read permissions for '$2' (run as root).\033[m\n\n"
    exit 1
  fi
  # ELF executable?
  out=`file $2`
  if [[ ! $out =~ ELF ]] ; then
    printf "\033[31mError: Not an ELF file: "
    file $2
    printf "\033[m\n"
    exit 1
  fi
  printf "RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH      FILE\n"
  filecheck $2
  if [ `find $2 \( -perm -004000 -o -perm -002000 \) -type f -print` ] ; then
    printf "\033[37;41m%s%s\033[m" $2 $N
  else
    printf "%s" $2
  fi
  echo
  exit 0
  ;;

 --proc-all)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  cd /proc
  printf "* System-wide ASLR"
  aslrcheck
  printf "* Does the CPU support NX: "
  nxcheck 
  printf "         COMMAND    PID RELRO             STACK CANARY           NX/PaX        PIE\n"
  for N in [1-9]*; do
    if [ $N != $$ ] && readlink -q $N/exe > /dev/null; then
      printf "%16s" `head -1 $N/status | cut -b 7-`
      printf "%7d " $N
      proccheck $N
      echo
    fi
  done
  if [ ! -e /usr/bin/id ] ; then
    printf "\n\033[33mNote: If you are running 'checksec.sh' as an unprivileged user, you\n"
    printf "      will not see all processes. Please run the script as root.\033[m\n\n"
  else 
    if !(root_privs) ; then
      printf "\n\033[33mNote: You are running 'checksec.sh' as an unprivileged user.\n" 
      printf "      Too see all processes, please run the script as root.\033[m\n\n"
    fi
  fi
  exit 0
  ;;

 --proc)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid process name.\033[m\n\n"
    exit 1
  fi
  cd /proc
  printf "* System-wide ASLR"
  aslrcheck
  printf "* Does the CPU support NX: "
  nxcheck
  printf "         COMMAND    PID RELRO             STACK CANARY           NX/PaX        PIE\n"
  for N in `ps -Ao pid,comm | grep $2 | cut -b1-6`; do
    if [ -d $N ] ; then
      printf "%16s" `head -1 $N/status | cut -b 7-`
      printf "%7d " $N
      # read permissions?
      if [ ! -r $N/exe ] ; then
        if !(root_privs) ; then
          printf "\033[31mNo read permissions for '/proc/$N/exe' (run as root).\033[m\n\n"
          exit 1
        fi
        if [ ! `readlink $N/exe` ] ; then
          printf "\033[31mPermission denied. Requested process ID belongs to a kernel thread.\033[m\n\n"
          exit 1
        fi
        exit 1
      fi
      proccheck $N
      echo
    fi
  done
  exit 0
  ;;

 --proc-libs)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid process ID.\033[m\n\n"
    exit 1
  fi
  if !(isNumeric "$2") ; then
     printf "\033[31mError: Please provide a valid process ID.\033[m\n\n"
     exit 1
  fi
  cd /proc
  printf "* System-wide ASLR"
  aslrcheck
  printf "* Does the CPU support NX: "
  nxcheck
  printf "* Process information:\n\n"
  printf "         COMMAND    PID RELRO             STACK CANARY           NX/PaX        PIE\n"
  N=$2
  if [ -d $N ] ; then
    printf "%16s" `head -1 $N/status | cut -b 7-`
    printf "%7d " $N
    # read permissions?
    if [ ! -r $N/exe ] ; then
      if !(root_privs) ; then
        printf "\033[31mNo read permissions for '/proc/$N/exe' (run as root).\033[m\n\n"
        exit 1
      fi
      if [ ! `readlink $N/exe` ] ; then
        printf "\033[31mPermission denied. Requested process ID belongs to a kernel thread.\033[m\n\n"
        exit 1
      fi
      exit 1
    fi
    proccheck $N
    echo
    libcheck $N
  fi
  exit 0
  ;;

 --kernel)
  cd /proc
  printf "* Kernel protection information:\n\n"
  kernelcheck
  exit 0
  ;;

 --fortify-file)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid file.\033[m\n\n"
   exit 1
  fi
  # does the file exist?
  if [ ! -e $2 ] ; then
    printf "\033[31mError: The file '$2' does not exist.\033[m\n\n"
    exit 1
  fi
  # read permissions?
  if [ ! -r $2 ] ; then
    printf "\033[31mError: No read permissions for '$2' (run as root).\033[m\n\n"
    exit 1
  fi
  # ELF executable?
  out=`file $2`
  if [[ ! $out =~ ELF ]] ; then
    printf "\033[31mError: Not an ELF file: "
    file $2
    printf "\033[m\n"
    exit 1
  fi
  if [ -e /lib/libc.so.6 ] ; then
    FS_libc=/lib/libc.so.6
  elif [ -e /lib64/libc.so.6 ] ; then
    FS_libc=/lib64/libc.so.6
  elif [ -e /lib/i386-linux-gnu/libc.so.6 ] ; then
    FS_libc=/lib/i386-linux-gnu/libc.so.6
  elif [ -e /lib/x86_64-linux-gnu/libc.so.6 ] ; then
    FS_libc=/lib/x86_64-linux-gnu/libc.so.6
  else
    printf "\033[31mError: libc not found.\033[m\n\n"
    exit 1
  fi

  FS_chk_func_libc=( $(readelf -s $FS_libc | grep _chk@@ | awk '{ print $8 }' | cut -c 3- | sed -e 's/_chk@.*//') )
  FS_functions=( $(readelf -s $2 | awk '{ print $8 }' | sed 's/_*//' | sed -e 's/@.*//') )

  FS_libc_check
  FS_binary_check
  FS_comparison
  FS_summary

  exit 0
  ;;

 --fortify-proc)
  if [ $have_readelf -eq 0 ] ; then
    exit 1
  fi
  if [ -z "$2" ] ; then
    printf "\033[31mError: Please provide a valid process ID.\033[m\n\n"
    exit 1
  fi
  if !(isNumeric "$2") ; then
     printf "\033[31mError: Please provide a valid process ID.\033[m\n\n"
     exit 1
  fi
  cd /proc
  N=$2
  if [ -d $N ] ; then
    # read permissions?
    if [ ! -r $N/exe ] ; then
      if !(root_privs) ; then
        printf "\033[31mNo read permissions for '/proc/$N/exe' (run as root).\033[m\n\n"
        exit 1
      fi
      if [ ! `readlink $N/exe` ] ; then
        printf "\033[31mPermission denied. Requested process ID belongs to a kernel thread.\033[m\n\n"
        exit 1
      fi
      exit 1
    fi
    if [ -e /lib/libc.so.6 ] ; then
      FS_libc=/lib/libc.so.6
    elif [ -e /lib64/libc.so.6 ] ; then
      FS_libc=/lib64/libc.so.6
    elif [ -e /lib/i386-linux-gnu/libc.so.6 ] ; then
      FS_libc=/lib/i386-linux-gnu/libc.so.6
    elif [ -e /lib/x86_64-linux-gnu/libc.so.6 ] ; then
      FS_libc=/lib/x86_64-linux-gnu/libc.so.6
    else
      printf "\033[31mError: libc not found.\033[m\n\n"
      exit 1
    fi
    printf "* Process name (PID)                         : %s (%d)\n" `head -1 $N/status | cut -b 7-` $N
    FS_chk_func_libc=( $(readelf -s $FS_libc | grep _chk@@ | awk '{ print $8 }' | cut -c 3- | sed -e 's/_chk@.*//') )
    FS_functions=( $(readelf -s $2/exe | awk '{ print $8 }' | sed 's/_*//' | sed -e 's/@.*//') )

    FS_libc_check
    FS_binary_check
    FS_comparison
    FS_summary
  fi
  exit 0
  ;;

 *)
  if [ "$#" != "0" ] ; then
    printf "\033[31mError: Unknown option '$1'.\033[m\n\n"
  fi
  help
  exit 1
  ;;
esac
Establecemos permisos de ejecución:
chmod +x checksec.sh
Ejecutamos el script de acuerdo a los parámetros que tiene (ver función "help").
Leer más...

Mandar mail al iniciar el equipo y al apagarlo

d
Autor: Linuxaria
Descripción: Init Script que manda un correo electrónico al iniciar o apagar el sistema
Visto en Linuxaria
#!/bin/sh
# chkconfig: 2345 99 01
# Description: Sends an email at system start and shutdown
 
#############################################
#                                           #
# Send an email on system start/stop to     #
# a user.                                   #
#                                           #
#############################################
 
EMAIL="example@example.com"
RESTARTSUBJECT="["`hostname`"] - System Startup"
SHUTDOWNSUBJECT="["`hostname`"] - System Shutdown"
RESTARTBODY="This is an automated message to notify you that "`hostname`" started successfully.
 
Start up Date and Time: "`date`
SHUTDOWNBODY="This is an automated message to notify you that "`hostname`" is shutting down.
Shutdown Date and Time: "`date`
LOCKFILE=/var/lock/subsys/SystemEmail
RETVAL=0
 
# Source function library.
. /etc/init.d/functions
 
stop()
{
echo -n $"Sending Shutdown Email: "
echo "${SHUTDOWNBODY}" | mail -s "${SHUTDOWNSUBJECT}" ${EMAIL}
RETVAL=$?
 
if [ ${RETVAL} -eq 0 ]; then
rm -f ${LOCKFILE}
success
else
failure
fi
echo
return ${RETVAL}
}
 
start()
{
echo -n $"Sending Startup Email: "
echo "${RESTARTBODY}" | mail -s "${RESTARTSUBJECT}" ${EMAIL}
RETVAL=$?
 
if [ ${RETVAL} -eq 0 ]; then
touch ${LOCKFILE}
success
else
failure
fi
echo
return ${RETVAL}
}
 
case $1 in
stop)
stop
;;
 
start)
start
;;
 
*)
 
esac
exit ${RETVAL}
Damos los permisos necesarios 
chmod u+x /etc/init.d/mailme
Para probarlo podemos ejecutar:
/etc/init.d/mailme start
/etc/init.d/mailme stop
Configuramos con chkconfig para que corra en un nivel determinado del sistema
chkconfig --levels 3 mailme on
Leer más...

Detectar Man In the Middle

d
Autor: flu project
Visto en: Flu Project
Descripción: Script que permite detectar ataques man in the middle y dar de baja la interface de red.
(Para mas información sobre éste tipo de ataques consultar el siguiente link )

#!/bin/bash

if [ $# -ne 1 ]
then
echo "Uso ./mitm.sh  [ dirección mac ]"
exit
fi

mac=$1
while true
do
entradaRouter=$( arp -a | grep 192.168.1.1 | cut -d' ' -f4 )
if [ $mac != $entradaRouter ]
then
echo “Atento la Mac ha cambiado”
ifconfig  [ dispositivo red, ejemplo eth0 ] down
fi
sleep 2
done

Damos permisos de ejecución: chmod +x mitm.sh 
Ejecutamos el script: ./mitm.sh [ dirección mac ]
Ejemplo: ./mitm.sh 00:02:cf:ce:c6:1a
Leer más...

Netstat Conexiones Activas

d
Autor: Desconocido
Descripción: Script que muestra las conexiones activas del host.


sudo ls &>/dev/null
if [ $? -ne 0 ]; then
echo "El usuario no tiene permisos de administrador"
exit 1
fi

parse_num()
{
x=$(echo $1 | sed -n 's/0*//p')
if [ $(echo $x | wc -c) -eq 1 ]
then
x=0
fi
echo $x
}


hex_to_ip()
{
index=7
output=''
while [ $index -gt 0 ]
do
end=$(expr $index + 1)
value=$(printf "%d" "0x$(parse_num $(echo $1 | cut -b $index-$end))")
output="$output.$value"
index=$(expr $index - 2)
done
echo $(echo $output | cut -b 2-)
}
printf " Src IP Src port Dst IP Dst port\n"

cat /proc/net/tcp | while read line; do
srcip=$(hex_to_ip $(echo $line | sed -n 's/^[0-9]*: //p' | sed 's/:.*//p'))
srcport=$(printf "%d" 0x$(parse_num $(echo $line | sed -n 's/^ *[0-9]*: [0-9,A-F]*://p' | cut "-d " -f 1)))
dstip=$(hex_to_ip $(echo $line | sed -n 's/^[0-9]*: [0-9,A-F]*:[0-9,A-F]* //p' | sed -n 's/:.*//p'))
dstport=$(printf "%d" 0x$(parse_num $(echo $line | sed -n 's/^ *[0-9]*: [0-9,A-F]*:[0-9,A-F]* [0-9,A-F]*://p' | cut "-d " -f1)))

printf "%15s %9s %15s %9s\n" $srcip $srcport $dstip $dstport
done

netstat -ant | awk '{print $NF}' | grep -v '[a-z]' | sort | uniq -c

exit 0
Leer más...

Bash IDS

d
Autor: Jonathan Cox
Función: IDS Básico.

 #!/bin/bash
# Interupt and Exit Function
control_c()
{
clear
echo -e "Would you like to block connections with a client?\n"
echo -e "Enter y or n: "
read yn

if [ "$yn" == "y" ]; then

echo -e "\nEnter Ip Address to Block: \n"
read ip

if [ -n $ip ]; then

echo -e "\nNow retrieving mac address to block...\n"
ping -c 1 $ip > /dev/null
mac=`arp $ip | grep ether | awk '{ print $3 }'`

if [ -z $mac ]; then
clear
echo -e "\n***Client does not exist or is no longer\
on this network***"
echo -e "\nSkipping action and resuming monitoring.\n\n"
sleep 2
bash leecher.sh
exit 0

else
iptables -A INPUT -m mac --mac-source $mac -j DROP
clear
echo -e "\nClient with mac address $mac is now\
blocked.\n"
echo -e "We will continue monitoring for changes\
in clients\n\n"
sleep 2
bash leecher.sh
exit 0
fi
fi


else
clear
echo -e "\n\nLeecher has exited\n\n"
setterm -cursor on
rm -f $pid
exit 0
fi
}

# Print the scan from the engine()
twice(){
g=0
len=${#second[@]}
for (( g = 0; g < $len; g++ ));
do
echo -e "${second[$g]}\n"
done
}

# If there's a change in the network, ask to block ips.
interupt(){
clear
echo -e "\nList of Clients has Changed!\n"
twice
echo -e '\a'
echo -e "Would you like to block connections with a client?\n"
echo -e "Enter y or n: "
read yn

if [ "$yn" == "y" ]; then

echo -e "\nEnter Ip Address to Block: \n"
read ip
if [ -n $ip ]; then
ping -c 1 $ip > /dev/null
mac=`arp $ip | grep ether | awk '{ print $3 }'`

if [ -z $mac ]; then
clear
echo -e "\n***Client does not exist or is no longer on\
this network***"
echo -e "\nSkipping action and resuming monitoring.\n\n"
else
iptables -A INPUT -m mac --mac-source $mac -j DROP
clear
echo -e "\nClient with mac address $mac is now blocked.\n"
echo -e "We will continue monitoring for changes\
in clients\n\n"
echo -e "Current clients are: \n"
twice
echo -e "\nResuming monitoring..."
fi
fi
else
clear
echo -e "Current clients are: \n"
twice
echo -e "Resuming monitoring..."
fi
}

# Function to keep monitoring for any changes
engine()
{
# Scan networks again for comparison of changes.
for subnet in $(/sbin/ifconfig | awk '/inet addr/ && !/127.0.0.1/ && !a[$2]++\
{print substr($2,6)}')
do
second+=( "$(nmap -sP ${subnet%.*}.0/24 | awk 'index($0,t)\
{ print $i }' t="$t" i="$i" )" )
sleep 1
done
}

# Make sure user is logged in as root
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root" 1>&2
exit 1
fi

# Check if nmap is installed
ifnmap=`type -p nmap`
if [ -z $ifnmap ]; then

echo -e "\n\nNmap must be installed for this program to work\n"
echo -e "Only Nmap 5.00 and 5.21 are supported at this time\n"
echo -e "Please install and try again"
exit 0
fi

clear
echo -e "\nNow finding clients on your local network(s)"
echo -e "Press Control-C at any time to block additional clients or exit\n"


# Remove temp files on exit and allow Control-C to exit.
trap control_c SIGINT

# Turn off cursor
setterm -cursor off

# Make some arrays and variables
declare -a first
declare -a second
sid=5.21

# Check for which version of nmap
if [ 5.21 = $(nmap --version | awk '/Nmap/ { print $3 }') ]; then
i=5 t=report
else
i=2 t=Host
fi

# Get ip's from interfaces and run the first scan
for subnet in $(/sbin/ifconfig | awk '/inet addr/ && !/127.0.0.1/ && !a[$2]++ {print \
substr($2,6)}')
do
first+=( "$(nmap -sP ${subnet%.*}.0/24 | awk 'index($0,t) { print $i }' \
t="$t" i="$i" )" )
sleep 1
done

echo -e "Current clients are: \n"

#Display array elements and add new lines
e=0
len=${#first[@]}
for (( e = 0; e < $len; e++ ));
do
echo -e "${first[$e]}\n"
done

echo -e "Leecher is now monitoring for new clients."
echo -e "\nAny changes with clients will be reported by the system bell."
echo -e "If bell is not enabled details will log to this console."

# Forever loop to keep monitoring constant
for (( ; ; ))
do
engine

if [[ ${first[@]} == ${second[@]} ]]; then

second=( )
else
interupt
sleep 1
first=( )
first=("${second[@]}")
second=( )
fi

done
Leer más...

Monitor-Traffic

d
Autor: @Tonejito
http://tonejito.blogspot.com/2011/12/monitoring-my-network-traffic.html
Función: Script que monitorea el tráfico de la red excluyendo las peticiones más comunes.

 #!/bin/bash
TCPDUMP=/usr/sbin/tcpdump
IP=/sbin/ip
DEV=en1
ADDR=`$IP addr show dev $DEV | grep 'inet ' | cut -d ' ' -f 6 | cut -d '/' -f 1`

$TCPDUMP -ni $DEV "host $ADDR and port not (67 or 68 or 80 or 443 or 1863 or 5222 or 587 or 993 or 995)"
Leer más...