Información blog

Linux, tutoriales, noticias, sistemas, redes y seguridad informática, entre otras cosas.

lunes, 12 de enero de 2015

Sencillo cortafuegos linux escrito en bash

He aquí un sencillo, pero funcional script de iptables llamado que permite que se pueda crear y modificar reglas de filtrado de iptables. Las variables que aparecen en el inicio serían las que almacenarían los puertos que se quieren abrir, ya que la política por defecto es que todo que sea INPUT se bloquee. En caso de que a uno le de miedo modificar a mano el script, puede ver/modificar las reglas de entrada/salida mediante "nombre_script.sh" change. Este script está preparado para funcionar en distribuciones basadas en Debian (Ubuntu, Elementary OS...), con lo que en caso de querer usarlo para distribuciones Red Hat habría que modificarlo un poco.

Espero que les sea útil. Por supuesto son libres de copiar, compartir y modificar el código.

  1. #!/bin/bash
  2. ### BEGIN INIT INFO
  3. # Provides:          iptables.sh
  4. # Required-Start:    $local_fs $remote_fs $network $syslog $named
  5. # Required-Stop:     $local_fs $remote_fs $network $syslog $named
  6. # Default-Start:     2 3 4 5
  7. # Default-Stop:      0 1 6
  8. ### END INIT INFO
  9. ###REGLAS APLICADAS AL KERNEL /etc/sysctl.conf###
  10. #net.ipv6.conf.all.disable_ipv6=1#
  11. #net.ipv4.ip_forward=1#
  12. #net.ipv4.tcp_syncookies=1#
  13. #net.ipv4.icmp_echo_ignore_broadcasts=1#
  14. #net.ipv4.conf.all.rp_filter=1#
  15. #net.ipv4.conf.all.accept_redirects=0#
  16. #net.ipv4.conf.all.log_martians=1#
  17. ######################################VARIABLES###################################
  18. ##VARIABLES MENU##
  19. OUTPUT=/tmp/output.tx$$
  20. INPUT=/tmp/input.sh$$
  21. >$OUTPUT
  22. trap "rm $INPUT; rm $OUTPUT; exit" SIGHUP SIGINT SIGTERM
  23. ##BLOQUEOS INPUT##
  24. #PUERTOS TCP DESTINO INPUT
  25. INTCPPORTD=(  )
  26. #PUERTOS TCP ORIGEN INPUT
  27. INTCPPORTS=( 20 21 22 80 443 )
  28. #PUERTOS UDP DESTINO INPUT
  29. INUDPPORTD=( 123 )
  30. #PUERTOS UDP ORIGEN INPUT
  31. INUDPPORTS=( 53 123 )
  32. ##BLOQUEOS OUTPUT##
  33. #PUERTOS TCP ORIGEN OUTPUT
  34. OTCPPORTS=( 31337 31338 31339 31340 )
  35. #PUERTOS UDP ORIGEN OUTPUT
  36. OUDPPORTS=(31337 31338 31339 31340)
  37. ##VARIABLES EXTRA
  38. #CONTADOR INTERFACES
  39. INTERFACES=$(ifconfig |grep eth |wc -l)
  40. #INTEFAZ
  41. I=0
  42. ##DATOS RED
  43. IP=0
  44. MASCARA=0
  45. ################################START############################
  46. Arrancar_cortafuegos()
  47. {
  48. ###POLITICAS GENERALES###
  49. iptables -F
  50. iptables -t nat -F
  51. iptables -t mangle -F
  52. iptables -P INPUT DROP
  53. iptables -P FORWARD DROP
  54. iptables -P OUTPUT ACCEPT
  55. #############################FILTER#########################
  56. INTERFACES=$((INTERFACES-1))
  57. while [ ${I} -le ${INTERFACES} ]
  58. do
  59. if [ $(cat /etc/issue |awk '{print $1}') == "Debian" ];
  60. then
  61.         IP=$(ifconfig eth${I} |grep "inet " |awk {'print $2'} |cut -d ":" -f 2)
  62.         MASCARA=$(ifconfig eth${I} |grep "inet " |awk {'print $4'} |cut -d ":" -f 2)
  63. else
  64.         IP=$(ifconfig eth${I} |grep "inet:" |awk {'print $2'} |cut -d ":" -f 2)
  65.         MASCARA=$(ifconfig eth${I} |grep "inet " |awk {'print $4'} |cut -d ":" -f 2)
  66. fi
  67. ###INPUT ACCEPT INTERNAL###
  68. iptables -A INPUT -p icmp --icmp-type echo-reply -m state --state ESTABLISHED -j ACCEPT
  69. #TCP INPUT
  70. if [ -n "${INTCPPORTD}" ];
  71. then
  72.         for i in "${INTCPPORTD[@]}"
  73.         do
  74.                 iptables -A INPUT -s ${IP}/${MASCARA} -p tcp --dport $i -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
  75.         done
  76. fi
  77. if [ -n "${INTCPPORTS}" ];
  78. then
  79.         for i in "${INTCPPORTS[@]}"
  80.         do
  81.                 iptables -A INPUT -p tcp --sport $i -m state --state ESTABLISHED,RELATED -j ACCEPT
  82.         done
  83. fi
  84. #UDP INPUT
  85. if [ -n "${INUDPPORTD}" ];
  86. then
  87.         for i in "${INUDPPORTD[@]}"
  88.         do
  89.                 iptables -A INPUT -s ${IP}/${MASCARA} -p udp --dport $i -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
  90.         done
  91. fi
  92. if [ -n "${INUDPPORTS}" ];
  93. then
  94.         for i in "${INUDPPORTS[@]}"
  95.         do
  96.                 iptables -A INPUT -p udp --sport $i -m state --state ESTABLISHED,RELATED -j ACCEPT
  97.         done
  98. fi
  99. ###OUTPUT BLOCK###
  100. #TCP OUTPUT
  101. if [ -n "${OTCPPORTS}" ];
  102. then
  103.         for i in "${OTCPPORTS[@]}"
  104.         do
  105.                 iptables -A OUTPUT -p tcp --sport $i -m state --state ESTABLISHED,RELATED -j DROP
  106.         done
  107. fi
  108. #UDP OUTPUT
  109. if [ -n "${OUDPPORTS}" ];
  110. then
  111.         for i in "${OUDPPORTS[@]}"
  112.         do
  113.                 iptables -A OUTPUT -p udp --sport $i -m state --state ESTABLISHED,RELATED -j DROP
  114.         done
  115. fi
  116. I=$((I+1))
  117. done
  118. ###REGLAS EXTRA###
  119. #DNS
  120. cat /etc/resolv.conf |awk {'print $2'} > /tmp/dns.txt
  121. while read LINEA
  122. do
  123.         iptables -A INPUT -s ${LINEA} -m state --state NEW,ESTABLISHED,RELATED -p udp --sport 53 -j ACCEPT
  124. done < /tmp/dns.txt
  125. rm /tmp/dns.txt
  126. #LOOPBACK
  127. iptables -A INPUT -i lo -j ACCEPT
  128. }
  129. ################################STOP############################
  130. Parar_cortafuegos()
  131. {
  132. #POLITICAS GENERALES ABIERTAS
  133. iptables -F
  134. iptables -t nat -F
  135. iptables -t mangle -F
  136. iptables -P INPUT ACCEPT
  137. iptables -P FORWARD ACCEPT
  138. iptables -P OUTPUT ACCEPT
  139. }
  140. Modificacion_puertos()
  141. {
  142. FINAL=n
  143. clear
  144. echo "Los puertos actuales seran eliminados y sustituidos por los introducidos ahora:"
  145. while [ ${FINAL} !'y' ];
  146. do
  147.         echo "Introduce un puerto:"
  148.         read PUERTO
  149.         if [ ${PUERTO} -gt 0 ];
  150.         then
  151.                 echo ${PUERTO} >> /tmp/puertos.txt
  152.         else
  153.                 echo "NO ES UN VALOR VALIDO!"
  154.         fi
  155.         echo "Quiere añadir otro puerto?[s/n]"
  156.         read RESPUESTA
  157.         if [ ${RESPUESTA} !'s' ];
  158.         then
  159.                 FINAL='y'
  160.         fi
  161. done
  162. }
  163. ENTRANTES_TCP_DESTINO()
  164. {
  165. dialog --clear \
  166. --title "Puertos TCP de destino ENTRANTES abiertos" \
  167. --menu "" 15 50 4 \
  168. LEER "Consultar puertos configurados" \
  169. MODIFICAR "Modificacion de puertos" \
  170. ATRAS "Volver al menu principal" \
  171. SALIDA "Salir"  2>"${INPUT}"
  172. menuitem=$(<"${INPUT}")
  173. case $menuitem in
  174. LEER)
  175. if [ -n "${INTCPPORTD}" ];
  176. then
  177.         echo "                     LISTADO DE PUERTOS" >> /tmp/temporal.txt
  178.         for i in "${INTCPPORTD[@]}"
  179.         do
  180.         echo "                          PUERTO:${i}" >> /tmp/temporal.txt
  181.         done
  182.         clear
  183.         cat /tmp/temporal.txt
  184.         rm /tmp/temporal.txt
  185.         echo " Pulse cualquier tecla para continuar"
  186.         read
  187. else
  188.         dialog --clear \
  189.         --title "Vacio" \
  190.         --msgbox "No hay puertos configurados" 5 50
  191. fi
  192. ENTRANTES_TCP_DESTINO
  193. ;;
  194. MODIFICAR)
  195. Modificacion_puertos
  196. SENTENCIA="INTCPPORTD=("
  197. while read LINEA
  198. do
  199.         SENTENCIA="${SENTENCIA} ${LINEA}"
  200. done < /tmp/puertos.txt
  201. SENTENCIA="${SENTENCIA} )"
  202. LINEAORIG=$(head -n 30 /etc/init.d/iptables.sh |grep INTCPPORTD)
  203. sed -i "s/${LINEAORIG}/${SENTENCIA}/g" /etc/init.d/iptables.sh
  204. rm /tmp/puertos.txt
  205. dialog --clear \
  206.  --title "Cambios realizados" \
  207.  --msgbox "Cambios implantados, reiniciar cortafuegos para aplicar la nueva config" 5 80
  208. ENTRANTES_TCP_DESTINO
  209. ;;
  210. ATRAS) Cambiar_parametros;;
  211. SALIDA) exit 0;;
  212. esac
  213. }
  214. ENTRANTES_TCP_ORIGEN()
  215. {
  216. dialog --clear \
  217. --title "Puertos TCP de origen ENTRANTES abiertos" \
  218. --menu "" 15 50 4 \
  219. LEER "Consultar puertos configurados" \
  220. MODIFICAR "Modificacion de puertos" \
  221. ATRAS "Volver al menu principal" \
  222. SALIDA "Salir"  2>"${INPUT}"
  223. menuitem=$(<"${INPUT}")
  224. case $menuitem in
  225. LEER)
  226. if [ -n "${INTCPPORTS}" ];
  227. then
  228.         echo "                     LISTADO DE PUERTOS" >> /tmp/temporal.txt
  229.         for i in "${INTCPPORTS[@]}"
  230.         do
  231.         echo "                          PUERTO:${i}" >> /tmp/temporal.txt
  232.         done
  233.         clear
  234.         cat /tmp/temporal.txt
  235.         rm /tmp/temporal.txt
  236.         echo " Pulse cualquier tecla para continuar"
  237.         read
  238. else
  239.         dialog --clear \
  240.         --title "Vacio" \
  241.         --msgbox "No hay puertos configurados" 5 50
  242. fi
  243. ENTRANTES_TCP_ORIGEN
  244. ;;
  245. MODIFICAR)
  246. Modificacion_puertos
  247. SENTENCIA="INTCPPORTS=("
  248. while read LINEA
  249. do
  250.         SENTENCIA="${SENTENCIA} ${LINEA}"
  251. done < /tmp/puertos.txt
  252. SENTENCIA="${SENTENCIA} )"
  253. LINEAORIG=$(head -n 32 /etc/init.d/iptables.sh |grep INTCPPORTS)
  254. sed -i "s/${LINEAORIG}/${SENTENCIA}/g" /etc/init.d/iptables.sh
  255. rm /tmp/puertos.txt
  256. dialog --clear \
  257.  --title "Cambios realizados" \
  258.  --msgbox "Cambios implantados, reiniciar cortafuegos para aplicar la nueva config" 5 80
  259. ENTRANTES_TCP_ORIGEN
  260. ;;
  261. ATRAS) Cambiar_parametros;;
  262. SALIDA) exit 0;;
  263. esac
  264. }
  265. ENTRANTES_UDP_DESTINO()
  266. {
  267. dialog --clear \
  268. --title "Puertos UDP de destino ENTRANTES abiertos" \
  269. --menu "" 15 50 4 \
  270. LEER "Consultar puertos configurados" \
  271. MODIFICAR "Modificacion de puertos" \
  272. ATRAS "Volver al menu principal" \
  273. SALIDA "Salir"  2>"${INPUT}"
  274. menuitem=$(<"${INPUT}")
  275. case $menuitem in
  276. LEER)
  277. if [ -n "${INUDPPORTD}" ];
  278. then
  279.         echo "                     LISTADO DE PUERTOS" >> /tmp/temporal.txt
  280.         for i in "${INUDPPORTD[@]}"
  281.         do
  282.         echo "                          PUERTO:${i}" >> /tmp/temporal.txt
  283.         done
  284.         clear
  285.         cat /tmp/temporal.txt
  286.         rm /tmp/temporal.txt
  287.         echo " Pulse cualquier tecla para continuar"
  288.         read
  289. else
  290.         dialog --clear \
  291.         --title "Vacio" \
  292.         --msgbox "No hay puertos configurados" 5 50
  293. fi
  294. ENTRANTES_UDP_DESTINO
  295. ;;
  296. MODIFICAR)
  297. Modificacion_puertos
  298. SENTENCIA="INUDPPORTD=("
  299. while read LINEA
  300. do
  301.         SENTENCIA="${SENTENCIA} ${LINEA}"
  302. done < /tmp/puertos.txt
  303. SENTENCIA="${SENTENCIA} )"
  304. LINEAORIG=$(head -n 34 /etc/init.d/iptables.sh |grep INUDPPORTD)
  305. sed -i "s/${LINEAORIG}/${SENTENCIA}/g" /etc/init.d/iptables.sh
  306. rm /tmp/puertos.txt
  307. dialog --clear \
  308.  --title "Cambios realizados" \
  309.  --msgbox "Cambios implantados, reiniciar cortafuegos para aplicar la nueva config" 5 80
  310. ENTRANTES_UDP_DESTINO
  311. ;;
  312. ATRAS) Cambiar_parametros;;
  313. SALIDA) exit 0;;
  314. esac
  315. }
  316. ENTRANTES_UDP_ORIGEN()
  317. {
  318. dialog --clear \
  319. --title "Puertos UDP de origen ENTRANTES abiertos" \
  320. --menu "" 15 50 4 \
  321. LEER "Consultar puertos configurados" \
  322. MODIFICAR "Modificacion de puertos" \
  323. ATRAS "Volver al menu principal" \
  324. SALIDA "Salir"  2>"${INPUT}"
  325. menuitem=$(<"${INPUT}")
  326. case $menuitem in
  327. LEER)
  328. if [ -n "${INUDPPORTS}" ];
  329. then
  330.         echo "                     LISTADO DE PUERTOS" >> /tmp/temporal.txt
  331.         for i in "${INUDPPORTS[@]}"
  332.         do
  333.         echo "                          PUERTO:${i}" >> /tmp/temporal.txt
  334.         done
  335.         clear
  336.         cat /tmp/temporal.txt
  337.         rm /tmp/temporal.txt
  338.         echo " Pulse cualquier tecla para continuar"
  339.         read
  340. else
  341.         dialog --clear \
  342.         --title "Vacio" \
  343.         --msgbox "No hay puertos configurados" 5 50
  344. fi
  345. ENTRANTES_UDP_ORIGEN
  346. ;;
  347. MODIFICAR)
  348. Modificacion_puertos
  349. SENTENCIA="INUDPPORTS=("
  350. while read LINEA
  351. do
  352.         SENTENCIA="${SENTENCIA} ${LINEA}"
  353. done < /tmp/puertos.txt
  354. SENTENCIA="${SENTENCIA} )"
  355. LINEAORIG=$(head -n 36 /etc/init.d/iptables.sh |grep INUDPPORTS)
  356. sed -i "s/${LINEAORIG}/${SENTENCIA}/g" /etc/init.d/iptables.sh
  357. rm /tmp/puertos.txt
  358. dialog --clear \
  359.  --title "Cambios realizados" \
  360.  --msgbox "Cambios implantados, reiniciar cortafuegos para aplicar la nueva config" 5 80
  361. ENTRANTES_UDP_ORIGEN
  362. ;;
  363. ATRAS) Cambiar_parametros;;
  364. SALIDA) exit 0;;
  365. esac
  366. }
  367. SALIENTES_TCP_ORIGEN()
  368. {
  369. dialog --clear \
  370. --title "Puertos TCP de origen SALIENTES abiertos" \
  371. --menu "" 15 50 4 \
  372. LEER "Consultar puertos configurados" \
  373. MODIFICAR "Modificacion de puertos" \
  374. ATRAS "Volver al menu principal" \
  375. SALIDA "Salir"  2>"${INPUT}"
  376. menuitem=$(<"${INPUT}")
  377. case $menuitem in
  378. LEER)
  379. if [ -n "${OTCPPORTS}" ];
  380. then
  381.         echo "                     LISTADO DE PUERTOS" >> /tmp/temporal.txt
  382.         for i in "${OTCPPORTS[@]}"
  383.         do
  384.         echo "                          PUERTO:${i}" >> /tmp/temporal.txt
  385.         done
  386.         clear
  387.         cat /tmp/temporal.txt
  388.         rm /tmp/temporal.txt
  389.         echo " Pulse cualquier tecla para continuar"
  390.         read
  391. else
  392.         dialog --clear \
  393.         --title "Vacio" \
  394.         --msgbox "No hay puertos configurados" 5 50
  395. fi
  396. SALIENTES_TCP_ORIGEN
  397. ;;
  398. MODIFICAR)
  399. Modificacion_puertos
  400. SENTENCIA="OTCPPORTS=("
  401. while read LINEA
  402. do
  403.         SENTENCIA="${SENTENCIA} ${LINEA}"
  404. done < /tmp/puertos.txt
  405. SENTENCIA="${SENTENCIA} )"
  406. LINEAORIG=$(head -n 40 /etc/init.d/iptables.sh |grep OTCPPORTS)
  407. sed -i "s/${LINEAORIG}/${SENTENCIA}/g" /etc/init.d/iptables.sh
  408. rm /tmp/puertos.txt
  409. dialog --clear \
  410.  --title "Cambios realizados" \
  411.  --msgbox "Cambios implantados, reiniciar cortafuegos para aplicar la nueva config" 5 80
  412. SALIENTES_TCP_ORIGEN
  413. ;;
  414. ATRAS) Cambiar_parametros;;
  415. SALIDA) exit 0;;
  416. esac
  417. }
  418. SALIENTES_UDP_ORIGEN()
  419. {
  420. dialog --clear \
  421. --title "Puertos UDP de origen SALIENTES abiertos" \
  422. --menu "" 15 50 4 \
  423. LEER "Consultar puertos configurados" \
  424. MODIFICAR "Modificacion de puertos" \
  425. ATRAS "Volver al menu principal" \
  426. SALIDA "Salir"  2>"${INPUT}"
  427. menuitem=$(<"${INPUT}")
  428. case $menuitem in
  429. LEER)
  430. if [ -n "${OUDPPORTS}" ];
  431. then
  432.         echo "                     LISTADO DE PUERTOS" >> /tmp/temporal.txt
  433.         for i in "${OUDPPORTS[@]}"
  434.         do
  435.         echo "                          PUERTO:${i}" >> /tmp/temporal.txt
  436.         done
  437.         clear
  438.         cat /tmp/temporal.txt
  439.         rm /tmp/temporal.txt
  440.         echo " Pulse cualquier tecla para continuar"
  441.         read
  442. else
  443.         dialog --clear \
  444.         --title "Vacio" \
  445.         --msgbox "No hay puertos configurados" 5 50
  446. fi
  447. SALIENTES_UDP_ORIGEN
  448. ;;
  449. MODIFICAR)
  450. Modificacion_puertos
  451. SENTENCIA="OUDPPORTS=("
  452. while read LINEA
  453. do
  454.         SENTENCIA="${SENTENCIA} ${LINEA}"
  455. done < /tmp/puertos.txt
  456. SENTENCIA="${SENTENCIA} )"
  457. LINEAORIG=$(head -n 42 /etc/init.d/iptables.sh |grep OUDPPORTS)
  458. sed -i "s/${LINEAORIG}/${SENTENCIA}/g" /etc/init.d/iptables.sh
  459. rm /tmp/puertos.txt
  460. dialog --clear \
  461.  --title "Cambios realizados" \
  462.  --msgbox "Cambios implantados, reiniciar cortafuegos para aplicar la nueva config" 5 80
  463. SALIENTES_UDP_ORIGEN
  464. ;;
  465. ATRAS) Cambiar_parametros;;
  466. SALIDA) exit 0;;
  467. esac
  468. }
  469. Cambiar_parametros()
  470. {
  471. dialog --clear \
  472. --title "Parametros cortafuegos" \
  473. --menu "" 15 100 7 \
  474. TCPDESTENT "Puertos TCP de destino ENTRANTES" \
  475. TCPORIGENT "Puertos TCP de origen ENTRANTES" \
  476. UDPDESTENT "Puertos UDP de destino ENTRANTES" \
  477. UDPORIGENT "Puertos UDP de origen ENTRANTES" \
  478. TCPORIGSAL "Puertos TCP de origen SALIENTES" \
  479. UDPORIGSAL "Puertos UDP de origen SALIENTES" \
  480. SALIDA "Salir" 2>"${INPUT}"
  481. menuitem=$(<"${INPUT}")
  482. case $menuitem in
  483.         TCPDESTENT) ENTRANTES_TCP_DESTINO;;
  484.         TCPORIGENT) ENTRANTES_TCP_ORIGEN;;
  485.         UDPDESTENT) ENTRANTES_UDP_DESTINO;;
  486.         UDPORIGENT) ENTRANTES_UDP_ORIGEN;;
  487.         TCPORIGSAL) SALIENTES_TCP_ORIGEN;;
  488.         UDPORIGSAL) SALIENTES_UDP_ORIGEN;;
  489.         SALIDA) exit 0;;
  490. esac
  491. }
  492. #SECUENCIA
  493. case $1 in
  494. start)
  495. Arrancar_cortafuegos
  496. ;;
  497. stop)
  498. Parar_cortafuegos
  499. ;;
  500. restart)
  501. $0 stop
  502. $0 start
  503. ;;
  504. change)
  505. Cambiar_parametros
  506. ;;
  507. *)
  508. echo "Usage /etc/init.d/iptables.sh start|stop|restart|change"
  509. ;;
  510. esac
  511. exit 0

2 comentarios :

  1. Me ha encantado tu post, lo tendre en cuenta para probarlo

    ResponderEliminar
    Respuestas
    1. Me alegro que te haya sido útil. Espero que le puedas sacar mucho partido.

      Un saludo.

      Eliminar