#netfilter-persistent
Explore tagged Tumblr posts
timothemauzet · 8 years ago
Photo
Tumblr media
Iptables est une interface qui permet de configurer le firewall interne de votre Debian. Celui-ci permet de protéger votre serveur de plusieurs type d'attaque.
0 notes
sololinuxes · 5 years ago
Text
Script to block countries in iptables - Bloquear países
Tumblr media
Script to block countries in Iptables - Bloquear países. Todos los propietarios de Servidores o VPS, padecemos de la gran lacra  de los sitios web... evidentemente hablamos de los intentos de intrusión, dDOS, ataques constantes, rastreo de puertos, spammers, etc... etc... La gran mayoría de este tipo de situaciones que nos pueden generar auténticos dolores de cabeza, provienen de los mismos países, China, Rusia, India, etc... Entonces yo me pregunto... realmente es necesario admitir a un país como China?, la respuesta es no, no es necesario, pues no te reportara ningún beneficio (salvo casos muy puntuales), solo problemas. Soy consciente que mi afirmación puede ser discutida, incluso criticada, pero vamos a ver... seamos sinceros, acaso piensas que un chino está interesado en tu tienda de zapatos, tu periódico en castellano, tus servicios en la red, etc..., pues no, no les interesas para nada, su único interés es hacerse con tu servicio, por ejemplo tu SMTP para enviar su mier** de spam que lo único que hará sera perjudicar la reputación de tu IP o dominio. No te lo pienses más y no dudes, si tienes este problema bloquea el país al completo.
Tumblr media
Script to block countries - Bloquear países   Hace ya un tiempo publicamos un script "bash", que descargaba el listado de IP's de un país y las aplicaba en Iptables. Lamentablemente aquel script ya está obsoleto... y por ello te presento la nueva versión del script bash "block-countries.sh", que viene con muchas mejoras. Principales novedades: Programación mejorada Definir puertos permitidos (por defecto 80 y 443) Reducción del proceso de las reglas Solo busca la coincidencia en el primer octeto del rango IP Se permite al acceso desde un puerto a definir del país bloqueado Carga el listado de país con iptables-restore etc... En la antigua versión cargar y aplicar el listado de IP's, de un país como China, podía tomar más de una hora. En esta nueva versión, menos de 30 segundos y todo gracias a el uso de "iptables-restore", para que me entiendas mejor... restaura tablas IP a partir de datos especificados en STDIN. AVISO: Este script es para Centos, si utilizas Debian o Ubuntu debes realizar unas modificaciones. Instrucciones al final del artículo. Sin más preámbulos vemos el script.  
Script block countries en Iptables
Desde consola / terminal y como root creamos el archivo "block-countries.sh" (países predeterminados, Rusia y China). nano block-countries.sh Copia y pega el script. #!/bin/bash #Use ISO code countries ### ### Block all traffic from RUSIA (ru) and CHINA (cn) ISO="ru cn" ### codigo de país a bloquear ### Set PATH ### IPT=/sbin/iptables WGET=/usr/bin/wget EGREP=/bin/egrep ### No editing below ### CBLIST="countrydrop" ZONEROOT="/var/iptables" IPTCBRESTORE="/etc/sysconfig/iptables.cb" IPTCBDEVICE=eth0 ALLOWPORTS=80,443 ALLOWSUBNET=192.168.0.0/255.255.0.0 MAXZONEAGE=7 DLROOT="http://www.ipdeny.com/ipblocks/data/countries" cleanOldRules(){ $IPT -L $CBLIST > /dev/null 2>&1 if ; then $IPT -D INPUT ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST $IPT -D OUTPUT ${IPTCBDEVICE:+-o }${IPTCBDEVICE} -j $CBLIST $IPT -D FORWARD ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST fi $IPT -F $CBLIST $IPT -X $CBLIST for i in `$IPT -L -n | grep Chain | cut -f 2 -d ' ' | grep '\-$CBLIST'` do $IPT -F ${i} $IPT -X ${i} done } updateZoneFiles() { ZONEARCH=${ZONEROOT}/arch mkdir -p ${ZONEARCH} find ${ZONEROOT} -maxdepth 1 -mindepth 1 -ctime +${MAXZONEAGE} -exec mv {} ${ZONEARCH} \; for c in $ISO do # local zone file tDB=$ZONEROOT/$c.zone if ; then printf "Zone file %s is new enough - no update required.\n" $tDB else # get fresh zone file if it is newer than MAXZONEAGE days $WGET -O $tDB $DLROOT/$c.zone fi done oldzones=`find ${ZONEROOT} -mindepth 1 -maxdepth 1 -type f -exec basename {} \; | cut -f 1 -d '.'` # Archive old zones no longer blocked for z in $oldzones ; do archme=${c} for c in $ISO ; do if ; then archme="X"; fi done if ; then mv ${archme} ${ZONEARCH} else printf "Working from previous zone file for %s\n" ${z} fi done } createIPTLoadFile() { printf "# Generated by %s on" $0 > ${IPTCBRESTORE} printf "%s " `date` >> ${IPTCBRESTORE} printf "\n*filter\n" >> ${IPTCBRESTORE} # Create CBLIST chain printf ":$CBLIST - \n" >> ${IPTCBRESTORE} printf "%s INPUT ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST\n" "-I" > ${IPTCBRESTORE}.tmp printf "%s OUTPUT ${IPTCBDEVICE:+-o }${IPTCBDEVICE} -j $CBLIST\n" "-I" >> ${IPTCBRESTORE}.tmp printf "%s FORWARD ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST\n" "-I" >> ${IPTCBRESTORE}.tmp if ; then printf "Blocking all traffic from country - no ports allowed\n" else printf "%s $CBLIST -p tcp -m multiport --dports ${ALLOWPORTS} -j RETURN\n" "-I">> ${IPTCBRESTORE}.tmp fi if ; then printf "Blocking all traffic from country - no subnets excluded\n" else printf "%s $CBLIST -s ${ALLOWSUBNET} -j RETURN\n" "-I">> ${IPTCBRESTORE}.tmp fi for c in $ISO do # local zone file tDB=$ZONEROOT/$c.zone # country specific log message SPAMDROPMSG="iptables: ${c}-Country-Drop: " # Create drop chain for identified packets CBLISTDROP=${c}-${CBLIST}-DROP printf ":${CBLISTDROP} - \n" >> ${IPTCBRESTORE} printf "%s ${CBLISTDROP} -j LOG --log-prefix \"$SPAMDROPMSG\"\n" "-A" >> ${IPTCBRESTORE}.tmp printf "%s ${CBLISTDROP} -j DROP\n" "-A" >> ${IPTCBRESTORE}.tmp # Load IP ranges into chains correlating to first octet BADIPS=$(egrep -v "^#|^$" $tDB) for ipblock in $BADIPS do topip=`echo $ipblock | cut -f 1 -d '.'` chainExists=`grep -c :${topip}-${CBLIST} ${IPTCBRESTORE}` if ; then printf "Creating chain for octet %s\n" ${topip} printf ":$topip-$CBLIST - \n" >> ${IPTCBRESTORE} sip=${topip}.0.0.0/8 printf "%s $CBLIST -s ${sip} -j $topip-$CBLIST\n" "-A" >> ${IPTCBRESTORE}.tmp fi printf " Adding rule for %s to chain for octet %s\n" ${ipblock} ${topip} printf "%s $topip-$CBLIST -s $ipblock -j ${CBLISTDROP}\n" "-A" >> ${IPTCBRESTORE}.tmp done done cat ${IPTCBRESTORE}.tmp >> ${IPTCBRESTORE} && rm -f ${IPTCBRESTORE}.tmp printf "COMMIT\n# Completed on " >> ${IPTCBRESTORE} printf "%s " `date` >> ${IPTCBRESTORE} printf "\n" >> ${IPTCBRESTORE} } directLoadTables() { # Create CBLIST chain $IPT -N $CBLIST $IPT -I INPUT ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST $IPT -I OUTPUT ${IPTCBDEVICE:+-o }${IPTCBDEVICE} -j $CBLIST $IPT -I FORWARD ${IPTCBDEVICE:+-i }${IPTCBDEVICE} -j $CBLIST if ; then printf "Blocking all traffic from country - no ports allowed\n" else $IPT -I $CBLIST -p tcp -m multiport --dports ${ALLOWPORTS} -j RETURN fi if ; then printf "Blocking all traffic from country - no subnets allowed\n" else $IPT -I $CBLIST -s ${ALLOWSUBNET} -j RETURN fi for c in $ISO do # local zone file tDB=$ZONEROOT/$c.zone # country specific log message SPAMDROPMSG="$c Country Drop" # Create drop chain for identified packets CBLISTDROP=${c}-${CBLIST}-DROP $IPT -N ${CBLISTDROP} $IPT -A ${CBLISTDROP} -j LOG --log-prefix "$SPAMDROPMSG" $IPT -A ${CBLISTDROP} -j DROP # Load IP ranges into chains correlating to first octet BADIPS=$(egrep -v "^#|^$" $tDB) for ipblock in $BADIPS do topip=`echo $ipblock | cut -f 1 -d '.'` $IPT -L $topip-$CBLIST > /dev/null 2>&1 if ; then printf "Creating chain for octet %s\n" ${topip} $IPT -N $topip-$CBLIST sip=${topip}.0.0.0/8 $IPT -A $CBLIST -s ${sip} -j $topip-$CBLIST fi printf " Adding rule for %s to chain for octet %s\n" ${ipblock} ${topip} $IPT -A $topip-$CBLIST -s $ipblock -j ${CBLISTDROP} done done } loadTables() { createIPTLoadFile ${IPT}-restore -n ${IPTCBRESTORE} #directLoadTables printf "Country block instituted for: %s\n" "$ISO" } # create a dir && /bin/mkdir -p $ZONEROOT # clean old rules cleanOldRules # update zone files as needed updateZoneFiles # create a new iptables list loadTables exit 0 Guarda y cierra el editor.
Tumblr media
  Ejecuta el script: bash block-countries.sh Como te comente anteriormente, este script es muy rápido. Ejemplo de salida: --2018-02-07 06:37:55-- http://www.ipdeny.com/ipblocks/data/countries/cn.zone Resolviendo www.ipdeny.com (www.ipdeny.com)... 192.241.240.22 Conectando con www.ipdeny.com (www.ipdeny.com):80... conectado. Petición HTTP enviada, esperando respuesta... 200 OK Longitud: 125774 (123K) Grabando a: “/var/iptables/cn.zone” 100% 125.774 324KB/s en 0,4s 2018-02-07 06:37:56 (324 KB/s) - “/var/iptables/cn.zone” guardado Working from previous zone file for cn Creating chain for octet 1 Adding rule for 1.0.1.0/24 to chain for octet 1 Adding rule for 1.0.2.0/23 to chain for octet 1 Adding rule for 1.0.8.0/21 to chain for octet 1 Adding rule for 1.0.32.0/19 to chain for octet 1 Adding rule for 1.1.0.0/24 to chain for octet 1 Adding rule for 1.1.2.0/23 to chain for octet 1 Adding rule for 1.1.4.0/22 to chain for octet 1 ............................................. .............................................. Ya lo tenemos instalado y ejecutándose Script to block countries, te recomiendo que crees una tarea cron para que se actualice el listado de ip's. Por ejemplo: @weekly /path/to/block-countries.sh y lo ejecutamos. /path/to/block-countries.sh Si prefieres descargar el script "block countries"directamente, lo encontraras a continuación.
Tumblr media
  Uso del Script to block countries en Debian, Ubuntu y derivados Este Script to block countries fue creado para CentOS. En Ubuntu o Debian se deben utilizar otras rutas que pasamos a detallar. Primero ejecuta el siguiente comando, para realizar una instalacion completa. sudo apt install iptables-persistent netfilter-persistent Te solicitara que aceptes la persistencia en V4 y V6. Responde YES.
Tumblr media
Script to block countries Al terminar reiniciamos iptables. sudo service iptables restart En el script to block countries buscas la siguiente sección. ### No editing below ### CBLIST="countrydrop" ZONEROOT="/var/iptables" IPTCBRESTORE="/etc/sysconfig/iptables.cb" IPTCBDEVICE=eth0 ALLOWPORTS=80,443 ALLOWSUBNET=192.168.0.0/255.255.0.0 MAXZONEAGE=7 DLROOT="http://www.ipdeny.com/ipblocks/data/countries" y la cambias por... ### No editing below ### CBLIST="countrydrop" ZONEROOT="/var/iptables" IPTCBRESTORE="/etc/iptables/rules.v4" IPTCBDEVICE=eth0 ALLOWPORTS=80,443 ALLOWSUBNET=192.168.0.0/255.255.0.0 MAXZONEAGE=7 DLROOT="http://www.ipdeny.com/ipblocks/data/countries" Ahora, ya puedes ejecutar el script anterior con las modificaciones para Debian o Ubuntu. El resto de pasos son los mismos. Que disfrutes el script.   Recursos Listas de países y sus ip. Nota Final Asegurate que estas utilizando la interfaz... IPTCBDEVICE=eth0 Si no es así, modificas el nombre.   Canales de Telegram: Canal SoloLinux – Canal SoloWordpress Espero que este articulo te sea de utilidad, puedes ayudarnos a mantener el servidor con una donación (paypal), o también colaborar con el simple gesto de compartir nuestros artículos en tu sitio web, blog, foro o redes sociales. Script to block countries in iptables - Bloquear países.   Read the full article
0 notes
open-vault · 6 years ago
Text
VPNFILTER
VPNFILTER
On May 25th of 2018, the FBI issued a PSA recommending that “any owner of small office and home office routers” reboot those devices. The reason was because VPNFilter, a sophisticated piece of malware developed by a nation-state, had infected about 500,000 router and NAS devices world-wide. This network of compromised devices created by VPNFilter posed a serious threat to global cyber security, but appeared to be focused primarily on Ukraine.
VPNFilter is an advanced, multi-stage modular malware.
Stage 1 - Once a device is compromised, it reaches out to a domain hosting images with the ip address of the stage-2 command and control (C&C or C2) servers embedded in the EXIF metadata. This stage’s purpose is to gain a persistent foothold on the compromised device.
Stage 2 - After connecting to the C&C servers, stage-2 malware is pushed to the device. Although it does not persist through a reboot, it possesses a number of capabilities such as file collection, command execution, data exfiltration and device management, as well as “self-destruct” capability that renders a device unusable.
Stage 3 - Additional modules act as plugins for the stage-2 malware, providing extra functionality:
1. Additional capabilities that could be leveraged to map networks and exploit endpoint systems that are connected to devices compromised by VPNFilter.
2. Multiple ways for the threat actor to obfuscate and/or encrypt malicious traffic, including communications used for C2 and data exfiltration.
3. Multiple tools that could be utilized to identify additional victims accessible from the actor's foothold on devices compromised by VPNFilter for both lateral movement within a network, as well as to identify new edge devices in other networks of interest to the actor.
4. The capacity to build a distributed network of proxies that could be leveraged in future unrelated attacks to provide a means of obfuscating the true source of attack traffic by making it appear as if the attacks originated from devices previously compromised by VPNFilter.
List of Modules
• packetsniffer - collects all traffic passing through the device
• torify - uses Tor to communicate with Stage 2 Command and Control servers
• ssler - intercepts network traffic and inject malicious code into it without the user's knowledge.
• dstr - Destroys the device when activated
• htpx - Allows for the injection of malicious code into windows executable files during download
• ndbr - Functions as an Secure Shell (SSH) server and network scanner
• netfilter - Denial of Service Module that can block access to sites
• portforwarding - Victims can be redirected to attacker controlled servers
• socks5proxy - Activates a SOCKS5 proxy on compromised devices to obfuscate traffic
• tcpvpn - Establishes a secure Reverse-TCP VPN backdoor on compromised devices
Sources:
https://www.ic3.gov/media/2018/180525.aspx
https://blog.talosintelligence.com/2019/05/one-year-later-vpnfilter-catastrophe.html#more
https://blog.talosintelligence.com/2018/05/VPNFilter.html
https://blog.talosintelligence.com/2018/06/vpnfilter-update.html
https://blog.talosintelligence.com/2018/09/vpnfilter-part-3.html
0 notes
maartenmostert · 8 years ago
Text
Postgres listening on multiple ports
If you need to have Postgres listening on multiple ports you can do so using the iptables
In our case, we want to have Postgres listing on both 80 and 443 on top of its standard 5432 port.
To do so you type the following in terminal
iptables -t nat -A PREROUTING -p tcp -s 0/0 -d 37.58.106.56 --match multiport --dport 80,443 -j DNAT --to 37.58.106.56:5432
In this case, our IP is 37.58.106.56
In order to make the IP tables persistent first install the tool
sudo apt-get install iptables-persistent
For Ubuntu 14.04 you will need to do:
sudo /etc/init.d/iptables-persistent save sudo /etc/init.d/iptables-persistent reload
On Ubuntu 16.04 the commands changed to:
 sudo netfilter-persistent save  sudo netfilter-persistent reload
Also see the following external resources
http://www.cyberciti.biz/faq/linux-port-redirection-with-iptables/ http://www.debiantutorials.com/port-forwarding-with-iptables/ http://askubuntu.com/questions/119393/how-to-save-rules-of-the-iptables
0 notes