Нет описания
hroman9 044838386c initial commit 7 лет назад
templates initial commit 7 лет назад
README.md initial commit 7 лет назад
sql.py initial commit 7 лет назад
sqlgen1.py initial commit 7 лет назад
sqlgen2.py initial commit 7 лет назад

README.md

SQL Injection: Rompiendo Autenticación

Introducción

En esta experiencia de laboratorio estaremos estudiando la inyección de SQL. La inyección de SQL es un método por el cual la data de una base de datos es alterada, borrada o robada con intenciones maliciosas por medio de la inserción de código SQL en una aplicación insegura. Cuando escucha en las noticias que la data de alguna compañía fue comprometida por un ataque cibernético, lo más probable significa que una o más de sus bases de datos fueron comprometidas por medio de una inyección de SQL. Cada vez se hace más difícil llevar a cabo este tipo de ataque dado que las librerías de programación que se usan para conectar con las bases de datos, cada vez implementan mejores métodos de seguridad para llevar a cabo transacciones con bases de datos. De todas maneras cuando se diseña una aplicación que hace uso de una base de datos, es necesario hacer validación de la entrada, como también asegurarse que se hace uso de la librería de conneción a la base de datos de la manera más segura posible, lo que significa desabilitar el uso de múltiples queries y usar queries parametrizados (queries preparados). En esta experiencia de laboratorio se va a demostrar como una aplicación de web insegura puede ser explotada usando inyección de SQL. Se utiliza Flask para servir las páginas web en este laboratorio . La base de datos que se utiliza es MySQL server.

Setup Pre Laboratorio

  1. Necesita tener el interpretador de Python instalado en su computadora.

  2. Flask necesita ser instalado. Refiérase a estas instrucciones.

  3. Un servidor de MySQL necesita estar corriendo en su computadora. Necesita correr el servidor como el usuario root, la contraseña para el usuario root debe ser python1234, también necesita crear una base de datos llamada sqlinjection . Refiérase a estas instrucciones para la instalación.

  4. Descarge el código fuente de este laboratorio.

Parte I

En esta parte estaremos demostrando algunas inyecciones utilizando una simple aplicación web que sirve para hacer búsqueda en una guía de teléfono.(con los nombre de algunos científicos de cómputos famosos)

  1. Localice el lugar donde almaceno el código fuente. Luego de asegurarse de tener Flask instalado al igual que el servidor de MySL con los parámetros requeridos, localice archivo de python sqlgen1.py y ejecute este script. El script preparará la base de datos para la primera parte de este laboratorio.

  2. Ahora localice el archivo de python sql.py y ejecute este script. Este es el script que ejecuta la aplicación web para este laboratorio. Este script debe mantenerse corriendo por el resto de este laboratorio.

  3. Vaya a su browser e ingrese localhost:5000/phone en la barra de URL. Esta es la aplicación de la guía de teléfono. Localhost significa que este pidiendo un documento que esta siendo servido en la misma computadora donde corre el browser y 5000 es el puerto default donde Flask sirve los documentos html.

  4. Ingrese Ada en la caja de texto y presione Search para verificar como funciona la búsqueda.

  5. En el paso anterior vio como pudo encontrar entradas que fueran igual al string ingresado en la caja de texto. En este paso utilizará una inyección de SQL para poder desplegar todas las entradas en la guía a la vez. El query que utiliza la aplicación web para buscar en la base de datos se contruye de la siguiente forma:

    query = "select * from phonebook where name = '"  
    query += name  
    query += "';"
    

    La variable name que la aplicación añade al string del query, corresponde a la entrada del usuario de la caja de texto. Como esta es una aplicación insegura donde no se hace validación de la entrada del usuario, el string del query se enviaba con cualquier inyección para interpretación en la base de datos. Ahora usara una inyección para mostrar todas las entradas de la base de datos a la a vez. Ingrese el string que sigue y pulse Search:

    randomText' or 1=1; --
    

    IMPORTANTE: Debe incluir un espacio después del doble guión.

    Note que el string que se construye es select * from phonebook where name = ‘randomText’ or 1=1; -- Note que esta añadiendo la condición 1=1 que hará que el query sea válido para cualquier fila en la tabla, por lo tanto todas las entradas se desplegarán en la página. Tome un screenshot con todas las entradas.

  6. En este paso utilizará una inyección para borrar una entrada de la guía.(la entrada que usted quiera). Luego de borrar la entrada, muestre la guía completa de nuevo como hizo en el paso anterior y tome un screenshot. El string para la inyección debe lucir así:

    randomText'; DELETE FROM phonebook where name = "chosenName"; --
    
  7. En este paso usted hará una inyección para borrar el contenido completo de la guía. Luego de borrar la guía usará una inyección para insertar dos estradas de su preferencia a la guía. Luego de hacer las inserciones tome un screenshot. Aquí están los strings de inyección que debe usar:

    randomText'; DELETE FROM phonebook; --
    randomText'; INSERT INTO phonebook (name, phone) VALUES ("someName", "123-456-7890"); --
    

Parte 2

En esta parte romperá la autenticación de una muy simple e insegura aplicación web. El simple método de autenticación consiste en verificar si la combinación de nombre de usuario y contraseña está en la tabla de autenticación de la base de datos.

  1. En al código fuente, ejecute el script de python sqlgen2.py para preparar la base de datos para este ejercicio.

  2. Navegue en su browser a localhost:5000/auth

  3. En la primera parte del laboratorio se le proveyó el nombre de las tablas y las columnas que iba a alterar. En la vida real esta información es desconocida para un potencial atacante. Su tarea es determianr el nombre de la tabla de autenticacion en la base de datos por medio de verificar los mensajes de error en la aplicación al tratar de hacer una inyección con un nombre potencial para la tabla. Utilize la siguiente inyección, cambiando la palabra tableName por una de las siguientes: (authtentication , login) tome screenshot de ambos intentos y determine el nombre de la tabla.

    randomText' select * from tableName; --
    
  4. En el siguiente paso su tarea es determinar los nombres de las columnas en la tabla de autenticación de la cual usted determinó el nombre en el paso anterior. Utilizará las siguientes 4 palabras (userid , password, username, passphrase) con la siguiente inyección para determinar los nombres correctos de las columnas. Permita que los errores le dejen saber los nombres correctos de las columnas y tome a screenshot de sus intentos.

    randomText'; INSERT INTO tableNameStep2 (guessColumnName, guessColumnName) VALUES ("someValue", "someValue"); --
    
  5. Los aplicaciones web almacenan las contraseñas como hashes en las bases de datos. En el caso de este laboratorio, la contraseña se almacena como un hash de md5. Esta será su tarea final. Su meta debe ser poder autenticarse como el usuario dbadmin de la base de datos. Para lograr esto necesita hacer lo siguiente:

    • Computar el md5 hash de algun string.
    • Usar una inyección para modificar el hash en la base de datos de este usuario por el que usted computó.
    • Autentíquese usando como username dbadmin y como contraseña el string al que le computó el hash usted. (La aplicación web hace hash al string que se ingrese en el campo de la contraseña)
    • Luego de autenticar como dbadmin tome un screenshot de la página web y anote la inyección que utilizó.

Entregables

Entregue un documento PDF que inluya los screenshots que tomó y todas las inyecciones de codigo que utilizó.

SQL Injection: Breaking Authentication

Introduction

In this lab experience we will be studying SQL injection. SQL injection is a method by which data from a database is deleted, stolen, or altered with malicious intentions by inserting SQL code in an unsececure application. Whenever you hear that data from some company was compromised in the news, it most probably means that one or more of their databases were breached by some type of SQL injection. It is getting more difficult everytime to make these attacks since the programming languages libraries used to connect to databases implement methods to secure database transactions. Nevertheless when an application is designed that makes use of a database, input validation is very important, as well as making sure of using the database connection libraries in the most secure manner, which means disabling multiple queries and using parameterized statements(prepared statements). In this lab experience it will be shown how an unsecured web application can be exploited using SQL injection. Flask is used to serve the web pages for the lab. Also, MySQL is the database that is used.

Pre Lab Setup

  1. You should have the Python interpreter installed in your computer.

  2. Flask needs to be installed. Refer to these instructions.

  3. A MySQL server needs to be running in your computer. You need to be running the server as the user root, the password for the root user should be python1234, you also need to create a database called sqlinjection . Refer to these instructions for installation.

  4. Download the source code for the lab.

Part I

In this part we will be demonstrating some injections using a simple phone book search web application. (with the first names of some famous computer scientists)

  1. Navigate to the location where you stored the source code. After making sure that you have Flask installed as well as the MySQL server running with the required parameters locate the python file sqlgen1.py and execute the script. This script will set up the database for Part 1 of the lab.

  2. Now locate the python file sql.py and execute the script. This will be the script that will run the web application for the lab. This script should be running for the remainder of the lab experience.

  3. Go to your browser and enter localhost:5000/phone in the address bar. This is the phonebook app. Localhost means we are retrieving a web document in our same computer and 5000 is the default port on which Flask serves html documents.

  4. Type Ada in the textbox and click Search to check how the phonebook works.

  5. In the previous step you saw that you were able to find entries that matched the string you typed in the text box. In this step you will use an injection to show all entries in the phonebook. The query the web app is using to search the database is constructed like this:

    query = "select * from phonebook where name = '"
    query += name
    query += "';"  
    

    The variable name that the app is appending to the query string, corresponds to the user input from the textbox. Since this is an unsecure application no input validation is done and the query string is sent directly to the database for interpretation. You will now use an injection to show all entries from the phonebook at once. Enter the following string in the textbox and click Search

    randomText' or 1=1; --
    

    IMPORTANT: You need to include a space after the double hyphens.

    Notice that the string that is created is select * from phonebook where name = ‘randomText’ or 1=1; -- You are adding the condition 1=1 that will make the query valid for any row in the table and all entries will be shown in the webapage. Take a screenshot with all the entries.

  6. For the next step you will use an injection to delete an entry from the phonebook (any name you like or don’t like). After you delete an entry show the complete phonebook with the same injection used in the previous step and take a screenshot. The string for the injection should be like this:

    randomText'; DELETE FROM phonebook where name = "chosenName"; --
    
  7. In this step you will make an injection to delete the whole contents of the phonebook. After you delete the phonebook you will use another injection to insert two entries of your choice into the phonebook. After you make the insertions take a screenshot. Here are the injection strings you should use:

    randomText'; DELETE FROM phonebook; --
    randomText'; INSERT INTO phonebook (name, phone) VALUES ("someName", "123-456-7890"); --  
    

Part 2

In this part you will break the authentication of a very simple and unsecure web application. The simple method of authentication consists of checking if the username and the password combination is in the database authentication table.

  1. In the source folder, execute the python script sqlgen2.py to set up the database for this exercise.

  2. Go to the address localhost:5000/auth in your browser.

  3. In the first part of the lab you were given the name of the table and columns you wanted to alter. In real life this information is unknown to a potential attacker. Your job is to determine the name of the authentication table in the database by checking the error messages in the web page after doing an injection with a potential table name. Use the following code injection, exchanging the word tableName for each of the following: (authtentication , login) take a screenshot of both tries and determine the name of the table.

    randomText' select * from tableName; --
    
  4. For the next step your job is determine what are the names of the columns in the table whose name you determined in the previous step. You will use the following 4 words (userid , password, username, passphrase) with the following injection to determine the correct column names. Let the errors help you determine the column names and take a screenshot of all your tries.

    randomText'; INSERT INTO tableNameStep2 (guessColumnName, guessColumnName) VALUES ("someValue", "someValue"); --
    
  5. Web applications store user passwords as hashes in a database. In the case of the lab, the password is stored as an md5 hash. This will be your final task. Your goal is to be able to authenticate as the user in the database whose id is dbadmin. To accomplish this task you will need to do the following:

    • Compute the md5 hash of some string.
    • Use an injection to modify the stored hash for the user dbadmin with the hash you computed.
    • Authenticate in the web app using as id dbadmin and as password the string whose hash you just computed. (The web app hashes all the input in the password field.)
    • After you authenticate as dbadmin take a screenshot of the web page and write down the injection that you used to modify the hash in the db.

Deliverables

Hand in a PDF document with the screenshots you took and with all the injections you used.