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

domingo, 5 de julio de 2026

AI Coding Agents Vulnerable to Bash Exploits

A critical security vulnerability has emerged in the world of AI-assisted software development, exposing a worrying gap in the protective measures of popular coding agents. Security researchers have identified a flaw called GuardFall that demonstrates how decades-old Bash shell techniques can be weaponised to circumvent the safety mechanisms built into most open source AI coding assistants.

AI Coding Agents Vulnerable to Bash Exploits

The vulnerability centres on fundamental Bash shell behaviours that have existed for years, including quote removal and variable expansion. Malicious actors can exploit these seemingly innocuous features to conceal harmful commands within commonly accessed development resources such as repositories, README files, and Makefiles. When AI coding agents process these materials—particularly in automated approval workflows or continuous integration environments—they can inadvertently execute the hidden commands, potentially leading to severe security breaches.

The implications of such attacks are far-reaching and alarming. Successful exploitation could result in the theft of sensitive credentials, complete compromise of developer systems, or facilitate sophisticated software supply chain attacks that could affect countless downstream users. This type of vulnerability is particularly dangerous because it targets the increasingly popular AI tools that developers trust to streamline their workflows and improve productivity.

Research conducted by the team at Adversa AI revealed the extent of this security gap across the ecosystem. In their comprehensive testing of 11 widely used open source AI coding agents, the results were sobering: only a single agent successfully defended against all the Bash trick techniques employed in the tests. This means that the vast majority of these tools remain vulnerable to exploitation, leaving developers and organisations potentially exposed to attack vectors they may not even be aware of.

This discovery underscores the urgent need for enhanced security measures in AI-assisted development tools and highlights the importance of maintaining vigilance even with established, trusted technologies. As AI coding agents become more prevalent in software development workflows, addressing these fundamental security weaknesses must become a priority for both tool developers and the wider security community.

Fuente Original: https://linux.slashdot.org/story/26/07/04/0325244/decades-old-bash-tricks-expose-ai-coding-agents-to-supply-chain-attacks?utm_source=rss1.0mainlinkanon&utm_medium=feed

Artículos relacionados de LaRebelión:

Artículo generado mediante LaRebelionBOT

sábado, 7 de marzo de 2026

10 Ejercicios Resueltos de Bash Scripting en Linux: Guía para Universidad

Bienvenidos de nuevo a larebelion.com. Si estás cursando Sistemas Operativos o Administración de Sistemas, sabrás que la interfaz gráfica es para cobardes. Un verdadero Ingeniero Informático se mueve por la terminal de Linux como pez en el agua.

Para ayudarte a superar tus exámenes prácticos, hemos recopilado 10 ejercicios esenciales de Bash Scripting de distintas universidades españolas. Desde condicionales básicos hasta automatización de copias de seguridad. ¡Abre tu terminal y empecemos!




1. Comprobación de Archivos (UPM)

Enunciado: Crea un script que reciba el nombre de un archivo por parámetro y compruebe si existe y si tiene permisos de lectura.

#!/bin/bash
ARCHIVO=$1

if [ -r "$ARCHIVO" ]; then
    echo "El archivo existe y se puede leer."
else
    echo "El archivo no existe o no hay permisos."
fi

2. Bucle For: Renombrado Masivo (UPC)

Enunciado: Escribe un script que busque todos los archivos con extensión .txt en el directorio actual y les añada la extensión .bak al final.

#!/bin/bash
for archivo in *.txt; do
    if [ -e "$archivo" ]; then
        mv "$archivo" "$archivo.bak"
        echo "Renombrado: $archivo a $archivo.bak"
    fi
done

3. Bucle While: Leer un Fichero Línea a Línea (UGR)

Enunciado: Lee el contenido del archivo /etc/passwd e imprime solo los nombres de los usuarios (la primera palabra antes de los dos puntos).

#!/bin/bash
while IFS=: read -r usuario resto; do
    echo "Usuario encontrado: $usuario"
done < /etc/passwd

4. Operaciones Aritméticas Básicas (UCM)

Enunciado: Crea un script que pida al usuario dos números por teclado y muestre la suma, resta y multiplicación de ambos.

#!/bin/bash
read -p "Introduce el primer número: " num1
read -p "Introduce el segundo número: " num2

suma=$((num1 + num2))
resta=$((num1 - num2))
multi=$((num1 * num2))

echo "Suma: $suma | Resta: $resta | Multiplicación: $multi"

5. Estructura Case: Menú Interactivo (UV)

Enunciado: Implementa un menú sencillo usando case que permita elegir entre ver la fecha actual, ver el espacio en disco o salir del script.

#!/bin/bash
echo "1. Ver Fecha 2. Espacio Disco 3. Salir"
read -p "Elige una opción: " opcion

case $opcion in
    1)
        date ;;
    2)
        df -h ;;
    3)
        echo "Saliendo..."; exit 0 ;;
    *)
        echo "Opción no válida." ;;
esac

6. Funciones en Bash: Factorial (UC3M)

Enunciado: Crea una función recursiva o iterativa en Bash que calcule el factorial de un número pasado como argumento.

#!/bin/bash
factorial() {
    n=$1
    if [ $n -le 1 ]; then
        echo 1
    else
        prev=$(factorial $((n - 1)))
        echo $((n * prev))
    fi
}

echo "Factorial de 5 es: $(factorial 5)"

7. Uso de AWK: Filtrar Procesos (US)

Enunciado: Ejecuta el comando ps aux y usa awk para imprimir solo el PID (columna 2) y el comando (columna 11) de los procesos que pertenecen al usuario 'root'.

#!/bin/bash
# Filtramos por root y usamos awk para formatear la salida
ps aux | awk '$1 == "root" {print "PID: " $2 " -> CMD: " $11}' | head -n 10

8. Automatización: Copia de Seguridad Simple (UAM)

Enunciado: Crea un script que comprima la carpeta /var/log en un archivo tar.gz. El nombre del archivo debe contener la fecha actual (ej. backup_2024-05-20.tar.gz).

#!/bin/bash
FECHA=$(date +%Y-%m-%d)
ARCHIVO="backup_log_$FECHA.tar.gz"

tar -czf /tmp/$ARCHIVO /var/log 2>/dev/null
echo "Backup guardado en /tmp/$ARCHIVO"

9. Alerta de Espacio en Disco (UNED)

Enunciado: Script que comprueba si la partición principal (/) supera el 85% de uso. Si es así, muestra una advertencia en la terminal.

#!/bin/bash
PORCENTAJE=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')

if [ "$PORCENTAJE" -gt 85 ]; then
    echo "¡PELIGRO! El disco está al $PORCENTAJE% de capacidad."
else
    echo "Disco en estado óptimo ($PORCENTAJE%)."
fi

10. Creación Masiva de Usuarios (UMA)

Enunciado: Escribe un script que lea un archivo llamado usuarios.txt (un nombre por línea) y cree automáticamente una cuenta en el sistema para cada uno usando useradd.

#!/bin/bash
ARCHIVO="usuarios.txt"

if [ ! -f "$ARCHIVO" ]; then
    echo "No se encuentra el archivo $ARCHIVO"
    exit 1
fi

while IFS= read -r user; do
    sudo useradd -m "$user"
    echo "Usuario $user creado exitosamente."
done < "$ARCHIVO"

lunes, 11 de agosto de 2025

Creación de un script Bash para detectar y bloquear intrusiones en SSH

 ¡Hola a todos! En el mundo de la ciberseguridad, proteger nuestros servidores es una prioridad. Los intentos de intrusión a través de SSH son comunes, y detectarlos y bloquearlos de forma automatizada puede ahorrarnos muchos dolores de cabeza. En este artículo, vamos a ver cómo crear un script en Bash que analice el log de SSH, identifique intentos de acceso fallidos y, si se repiten, aplique una regla de iptables para bloquear al atacante durante 15 días.


1. El análisis de los logs

Lo primero es saber dónde buscar. El log de SSH se encuentra típicamente en /var/log/auth.log en sistemas basados en Debian (como Ubuntu) o en /var/log/secure en sistemas basados en Red Hat (como CentOS). Usaremos grep para buscar líneas que indiquen intentos de conexión fallidos. La clave es identificar patrones. Por ejemplo, en un log de Ubuntu, un intento fallido se ve así:

Aug 11 20:53:14 servername sshd[12345]: Failed password for invalid user admin from 192.168.1.100 port 54321 ssh2

De esta línea, nos interesa la dirección IP (192.168.1.100). Podemos usar expresiones regulares y herramientas como awk o sed para extraerla.


2. El script paso a paso

Vamos a desglosar la lógica del script. El objetivo es:

  1. Leer las últimas líneas del log.

  2. Extraer las direcciones IP que han intentado iniciar sesión sin éxito.

  3. Contar cuántas veces cada IP ha fallado.

  4. Si una IP supera un umbral (en nuestro caso, 2 veces), la bloqueamos.

Aquí tienes el script completo. Puedes guardarlo como ssh_protector.sh.

Bash
#!/bin/bash

# Definimos la ruta del log y el número de intentos fallidos permitidos
LOGFILE="/var/log/auth.log"  # Cambiar a "/var/log/secure" si usas RHEL/CentOS
MAX_ATTEMPTS=2
# Duración del bloqueo en segundos (15 días = 15 * 24 * 60 * 60)
BLOCK_DURATION=1296000

# Usamos tail para leer las últimas líneas del log y grep para filtrar
# los intentos fallidos. awk se usa para extraer la IP.
# Sort y uniq -c se encargan de contar las repeticiones.
FAILED_IPS=$(tail -n 200 $LOGFILE | grep "Failed password" | awk '{print $11}' | sort | uniq -c | awk '{if ($1 > '$MAX_ATTEMPTS') print $2}')

# Verificamos si la variable FAILED_IPS contiene alguna IP
if [ -n "$FAILED_IPS" ]; then
    # Recorremos cada IP que ha superado el umbral
    for ip in $FAILED_IPS; do
        # Verificamos si la IP ya está bloqueada para evitar duplicados
        if ! iptables -L INPUT -n | grep -q "$ip"; then
            echo "Detectada IP maliciosa: $ip con más de $MAX_ATTEMPTS intentos fallidos. Bloqueando..."
            
            # Bloqueamos la IP con iptables.
            # -A INPUT: Añade la regla a la cadena INPUT.
            # -s $ip: Origen de la IP a bloquear.
            # -j DROP: La acción a tomar es "descartar" todo el tráfico.
            iptables -A INPUT -s $ip -j DROP
            
            echo "IP $ip bloqueada por $BLOCK_DURATION segundos."
            
            # Programamos una tarea para eliminar la regla después de 15 días
            # "at" es una herramienta que ejecuta comandos en un momento determinado.
            echo "iptables -D INPUT -s $ip -j DROP" | at now + $BLOCK_DURATION seconds
        fi
    done
else
    echo "No se encontraron IPs con más de $MAX_ATTEMPTS intentos fallidos."
fi

3. Explicación del código

  • LOGFILE: Es la variable que almacena la ruta a tu archivo de log.

  • MAX_ATTEMPTS: Define el número máximo de intentos fallidos antes de bloquear una IP.

  • BLOCK_DURATION: La duración del bloqueo en segundos.

  • FAILED_IPS: Esta es la línea más importante.

    • tail -n 200 $LOGFILE: Leemos las últimas 200 líneas del log, ya que es más eficiente que leer todo el archivo.

    • grep "Failed password": Filtra solo las líneas que contienen "Failed password" o "Failed password for invalid user".

    • awk '{print $11}': Extrae el undécimo campo, que en este formato de log es la dirección IP.

    • sort | uniq -c: Ordena las IPs y las cuenta, mostrando cuántas veces ha aparecido cada una.

    • awk '{if ($1 > '$MAX_ATTEMPTS') print $2}': Filtra las IPs que tienen un conteo mayor a MAX_ATTEMPTS.

  • iptables: La herramienta que utilizamos para gestionar las reglas del firewall en Linux.

    • iptables -A INPUT -s $ip -j DROP: Añade una regla a la cadena INPUT para descartar todo el tráfico (-j DROP) proveniente de la IP (-s $ip).

  • at: El comando at nos permite programar la ejecución de un comando en el futuro.

    • echo "iptables -D INPUT -s $ip -j DROP" | at now + $BLOCK_DURATION seconds: Esto programa la eliminación de la regla de iptables (-D de delete) después de 15 días.

4. Automatización del script

Para que este script sea realmente útil, debe ejecutarse periódicamente. La mejor manera de hacerlo es usando cron.

  1. Dale permisos de ejecución al script:

    Bash
    chmod +x ssh_protector.sh
    
  2. Edita la tabla de cron de root para que se ejecute con los permisos necesarios:

    Bash
    sudo crontab -e
    
  3. Añade la siguiente línea para que se ejecute cada 5 minutos:

    */5 * * * * /ruta/al/script/ssh_protector.sh
    

    Cambia /ruta/al/script/ por la ruta real donde guardaste tu script.


Consideraciones de seguridad y mejoras

  • Rendimiento: Si tu log es muy grande, leer las últimas 200 líneas puede no ser suficiente. Puedes ajustar el valor en tail -n.

  • Persistencia: Las reglas de iptables se pierden al reiniciar el sistema. Para hacerlas persistentes, puedes usar herramientas como iptables-persistent o scripts de inicio.

  • Notificaciones: Puedes añadir una función para que te envíe un correo electrónico o un mensaje a Slack cada vez que se bloquea una IP.

  • Reversibilidad: Si accidentalmente bloqueas una IP legítima, puedes eliminar la regla manualmente con:

    Bash
    sudo iptables -D INPUT -s la.ip.bloqueada -j DROP
    

Con este script y su automatización, tu servidor estará mucho más protegido contra los ataques de fuerza bruta por SSH. ¡Mantén tus sistemas seguros! 🔒

sábado, 25 de noviembre de 2023

What is the tech stack for the shortern future?

Predicting the exact technology stack for the future can be challenging because technology evolves rapidly, and new innovations constantly emerge. However, there are some trends and technologies that have been gaining traction and are likely to play a significant role in the tech stacks of the future. Keep in mind that the specific stack you choose will depend on your project's requirements and goals. Here are some key trends and technologies to consider:


  • Cloud Computing: Cloud platforms like Amazon Web Services (AWS), Microsoft Azure, and Google Cloud are expected to continue dominating the cloud computing landscape. Serverless computing and containerization (using technologies like Docker and Kubernetes) will likely become even more important for scalability and efficiency.

  • Edge Computing: As IoT devices become more prevalent, edge computing will grow in importance. This involves processing data closer to the source (i.e., the "edge" of the network) to reduce latency and improve real-time decision-making.

  • Artificial Intelligence (AI) and Machine Learning (ML): AI and ML will continue to be integrated into various applications and services. Frameworks like TensorFlow and PyTorch will remain important, and AI/ML models will be increasingly deployed at the edge for faster processing.

  • Blockchain: While blockchain technology is primarily associated with cryptocurrencies like Bitcoin, it has applications beyond finance, such as supply chain management, voting systems, and more. Blockchain platforms like Ethereum and Hyperledger are likely to see continued development and adoption.

  • Quantum Computing: Quantum computing is still in its infancy, but it holds great promise for solving complex problems that are currently beyond the capabilities of classical computers. Companies like IBM and Google are actively working on quantum computing research.

  • 5G Technology: The rollout of 5G networks will enable faster and more reliable wireless connectivity. This will impact various industries, including IoT, autonomous vehicles, augmented reality, and virtual reality.

  • Cybersecurity: With the increasing importance of digital data and connectivity, cybersecurity will remain a top concern. Technologies like AI-driven threat detection, zero-trust security models, and encryption will continue to evolve.

  • Web Technologies: JavaScript, HTML, and CSS will remain fundamental for web development, but frameworks like React, Angular, and Vue.js are likely to continue their popularity. Progressive Web Apps (PWAs) and WebAssembly are also promising technologies.

  • DevOps and Automation: DevOps practices, along with tools like Jenkins, Docker, and Ansible, will continue to streamline development, deployment, and operations processes. Automation will be critical for efficiency and reliability.

  • Sustainability: Sustainability considerations will play a larger role in tech stacks. Energy-efficient hardware, green data centers, and eco-friendly software development practices will become more important.

  • AR/VR: Augmented reality (AR) and virtual reality (VR) technologies will continue to advance, with applications in gaming, education, healthcare, and more.

  • Natural Language Processing (NLP): NLP technologies like GPT-4 and beyond will enable more sophisticated conversational AI, language translation, and content generation.

  • Container Orchestration: Technologies like Kubernetes and Docker Swarm will remain crucial for managing and scaling containerized applications.



It's essential to stay up-to-date with emerging technologies and adapt your tech stack based on your project's specific needs and the evolving industry trends. Flexibility and a willingness to learn and experiment will be valuable skills for technology professionals in the future. 

martes, 14 de julio de 2020

Installing, hardening, mod-security and fail2ban for Apache server

The following post is related to computer security, one of my passions as a hobby and what has fed me for several years being my profession a few years ago. The aim of the article is none other than to install and secure a web server, I have chosen Apache.

  1. Installing

If you need something help in order to compiling and installing you apache web server, please find more information in the official documentation.

    2. Hardening


Relatively recently, I found this public project called "Apache Hardening" and was completely delighted. It's not even worth transcribing, the best thing you can do is go to the original link and marvel at it by following the instructions.

    3. Mod-Security

Another important topic related you webserver Apache, is apply the mod-security. Mod-Security is one of the most popular security module for Apache and due MS more than the 85% of the automatics vulnerabilities and exploits are stopped.


On Intenet, normally you can find a lot of valid websites where explain how you need to install the tool but in my opinion one of the best is this.

    4. Fail2ban

Ok, we are very close to conclude this mini tutorial, imagine that all the above fails, what we have left, well, many things, we should be sure that we have secured our operating system, that we do not have unnecessary services published on the Internet and a long etcetera, but ... what if we apply firewall rules dynamically before events recorded in the log? Welcome to Fail2ban.

Let’s assume that you already installed fail2ban, you can check here how to do that: – https://www.ionos.com/community/server-cloud-infrastructure/linux-server/use-fail2ban-on-a-cloud-server-with-linux/

We need to copy this to a file called jail.local for Fail2Ban to find it.

cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Configure defaults in jail.local
Open up the new Fail2Ban configuration file:
You can see the default section below:
[DEFAULT]

# "ignoreip" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not
# ban a host which matches an address in this list. Several addresses can be
# defined using space separator.
ignoreip = 127.0.0.1

# Override /etc/fail2ban/jail.d/00-firewalld.conf:
banaction = iptables-multiport

# "bantime" is the number of seconds that a host is banned.
bantime  = 600

# A host is banned if it has generated "maxretry" during the last "findtime"
# seconds.
findtime  = 600

# "maxretry" is the number of failures before a host get banned.
maxretry = 5

Configure Fail2ban For ssh

Although you can add this parameters in the global jail.local file, it is a good practice to create seperate jail files for each of the services we want to protect with Fail2Ban.
So lets create a new jail for SSH with the vi editor.
vi /etc/fail2ban/jail.d/sshd.local
In the above file, add the following lines of code:
[sshd]
enabled = true
port = ssh
action = iptables-multiport
logpath = /var/log/secure
maxretry = 5
bantime = 600
Restart Fail2Ban
After making any changes to the Fail2Ban config, always be sure to restart Fail2Ban.
systemctl restart fail2ban
You can see the rules that fail2ban puts in effect within the IP table:
iptables -L -n
Check Fail2Ban Status
Use fail2ban-client command to query the overall status of the Fail2Ban jails.
fail2ban-client status
You can also query a specific jail status using the following command:
fail2ban-client status sshd

Configure Fail2ban For Apache

Edit this file:
sudo nano /etc/fail2ban/jail.local
Add the following content. Note: Substitute your own static IP address for the sample address (127.0.0.1) in this example:
# detect password authentication failures
[apache]
enabled  = true
filter   = apache-auth
action   = iptables-multiport[name=auth, port="http,https"]
logpath  = /var/log/httpd/fail2ban_log
bantime  = 3600
maxretry = 3
ignoreip = 127.0.0.1

# detect spammer robots crawling email addresses
[apache-badbots]
enabled  = true
filter   = apache-badbots
action   = iptables-multiport[name=badbots, port="http,https"]
logpath  = /var/log/httpd/fail2ban_log
bantime  = 3600
maxretry = 1
ignoreip = 127.0.0.1

# detect potential search for exploits
[apache-noscript]
enabled  = true
filter   = apache-noscript
action   = iptables-multiport[name=noscript, port="http,https"]
logpath  = /var/log/httpd/fail2ban_log
bantime  = 3600
maxretry = 6
ignoreip = 127.0.0.1

# detect Apache overflow attempts
[apache-overflows]
enabled  = true
filter   = apache-overflows
action   = iptables-multiport[name=overflows, port="http,https"]
logpath  = /var/log/httpd/fail2ban_log
bantime  = 3600
maxretry = 2
ignoreip = 127.0.0.1
Save and close the file, then restart Fail2ban for the changes to take effect:
sudo systemctl restart fail2ban
Now, configure the Fail2ban service to start on boot with the command:
sudo systemctl enable fail2ban
To verify the rules that were added to iptables by Fail2ban, use the following command:
sudo iptables -L



martes, 14 de abril de 2020

Backup de seguridad de tu máquina Linux

En estos días de confinamiento, me he decidido a ordenar un poco mis máquinas, en mi caso, cuento con tres raspberry en casa con diferentes distribuciones de Linux que utilizo para montar labs de sistemas, de programación, bases de datos como MariaDB o PostgreSQL e incluso cosas de seguridad o hardening.

Las raspberry, por la experiencia que tengo ya con ellas de varios años pueden sufrir problemas con la tarjeta SD y dejarte tirado. Como me ha pasado ya varias veces, me he decidido por escribir un script en shell para salvaguardar la información. Hasta aquí, todo más o menos sencillo, el problema es... ¿donde lo almaceno?.

Gracias a mi hermano, he descubierto http://mega.nz, se trata de una nueva startup del reputado empresario Kim_Dotcom, el creador de Megaupload. Lo primero que recomiendo hacer es crearte una cuenta gratuita de Meganz (50GB gratis).



Una vez la crees, descargate el componente para utilizar via json la integración con el API de meganz, el componente se llama Megacmd


Una vez que ya tengas todo esto instalado en tu máquina, ya puedes personalizar este pequeño shell script y almacenar tus backups en la nube.



#!/bin/bash

NAME=`hostname`
LIMITSIZE=5485760 # 5G = 10*1024*1024k   # limit size in GB   (FLOOR QUOTA)
MAILCMD=mail
R=/home/xxxx/src
LOG=$R/log/log-$(basename ${0}).log
EMAILIDS="user@domain.net"
MAILMESSAGE=$R/log/tmp-$(basename ${0})

if [ -d /media/4TB ]
then
        ROOTPATH=/media/4TB/servers/$NAME  # in case we've mount volume
        MOUNTP=/media/4TB
else
        ROOTPATH=/opt/$NAME  # in case no
        MOUNTP=/
fi

BKDIR=$ROOTPATH/bkdir # simple text file for to list your directories for backup, normally /etc /home/user /root /var/www/html ...
BKPATH=$ROOTPATH/backup
FREE=$(df -k --output=avail "$MOUNTP" | tail -n1) # df -k not df -h because is more exact

if [ ! -d $BKPATH ]
then
        mkdir -p $BKPATH
fi

if [ ! -d $R/log ]
then
        mkdir -p $R/log
fi

email_on_failure () # functions for launch email alert
{

          sMess="$1"
          echo "" >$MAILMESSAGE
          echo "Hostname: $(hostname)" >>$MAILMESSAGE
          echo "Date & Time: $(date)" >>$MAILMESSAGE

          # Email letter formation here:
          echo -e "\n[ $(date +%Y%m%d_%H%M%S%Z) ] Current Status:\n\n" >>$MAILMESSAGE
          cat $sMess >>$MAILMESSAGE

          echo "" >>$MAILMESSAGE
          echo "*** This email generated by $(basename $0) shell script ***" >>$MAILMESSAGE
          echo "*** Please don't reply this email, this is just notification email ***" >>$MAILMESSAGE

          # sending email (need to have an email client set up or sendmail)
          $MAILCMD -s "Urgent MAIL Alert For $(hostname) Server" "$EMAILIDS" < $MAILMESSAGE

          [ -f $MAILMESSAGE ] && rm -f $MAILMESSAGE
}

if [ "$FREE" -lt "$LIMITSIZE" ]
then
          echo "Writing to $LOG"
          echo "MAIL ERROR: Less than $((($FREE/1000))) MB free (QUOTA) on $MOUNTP!" | tee ${LOG}
          echo -e "\nPotential Files To Delete:" | tee -a ${LOG}
          find $MOUNTP -xdev -type f -size +500M -exec du -sh {} ';' | sort -rh | head -n20 | tee -a ${LOG}
          email_on_failure ${LOG}
else
   echo "Currently $((($FREE-$LIMITSIZE)/1000))) MB of QUOTA available of on $MOUNTP. " 
fi

if [ ! -f $BKDIR ]
then
        echo "Doesn't exist bkdir file. Aborting!" 
        exit 1
else
        filename=$NAME"_daily_backup_""$(date +'%Y_%m_%d')".tar.gz
        logfile="$R/"log/backup_log_"$(date +'%Y_%m')".log

        # Packages installed on Linux

        dpkg-query -W -f='${Installed-Size} ${Package}\n' | sort -n > $BKPATH/packages_installed.txt

        # Compressing my directories

        tar czf $BKPATH/$filename -T $BKDIR
        echo "dumping source code finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"

        # Changing permission

        chown root -R "$BKPATH"
        chown root "$logfile"
        chmod 644 $BKDIR
        chmod 600 $ROOTPATH

        echo "file permission changed" >> "$logfile"

        # removing old files and temporary files

        find "$BKPATH" -name "*daily_backup*" -mtime +3 -exec rm {} \;
        echo "old files deleted" >> "$logfile"
        echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"

        # pushing mega.nz

        mega-login user@domain.net password
        mega-sync $BKPATH $NAME
        echo "pushing backup to mega.nz $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
        echo "*****************" >> "$logfile"
        exit 0
fi