Java Web desde cero en Netbeans ☁️[25.- Consultas preparadas para evitar inyección sql?]

En este tutorial vamos a evitar la inyección de SQL con consultas preparadas que nos ofrece java.

? 05.-Firewall y Access en CloudFlare☁️. Tutorial en español (2019): https://www.youtube.com/watch?v=eOe589EUJhQ
?Tutorial de cloudflare: https://www.youtube.com/playlist?list=PLCTD_CpMeEKTipTlrB5em9K9wwtUdLmO6
? Rate Limiting to protect: https://support.cloudflare.com/hc/en-us/articles/115001993248-How-do-I-use-Rate-Limiting-to-protect-against-brute-force-attacks-
Codigo: https://github.com/programadornovato/javaWeb/commit/4b7c7e06babf35c956bbc9b7f040c69f8f16b6dc

package Servelets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import com.mysql.jdbc.Driver;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author eugenio
 */
@WebServlet(name = "Empleados", urlPatterns = {"/Empleados"})
public class Empleados extends HttpServlet {

    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */

            try {

                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost/jsp?user=eugenio&password=123456");
                st = con.createStatement();
                String query="SELECT * FROM `empledos` ";
                String where=" where 1=1 ";
                String nombre=request.getParameter("nombre");
                if(nombre!=null){
                    //nombre=nombre.replaceAll("'", "\\\\'");
                    nombre=this.mysql_real_scape_string(nombre);
                    where=where+" and nombre=? "; 
                }
                query=query+where;
                //out.println(query);
                PreparedStatement preparar=con.prepareStatement(query);
                if(nombre!=null){
                    preparar.setString(1, nombre);
                }
                rs=preparar.executeQuery();
                while (rs.next()) {

                    out.print("<tr>"
                            + "<th scope=\"row\">" + rs.getString(1) + "</th>"
                            + "<td>" + rs.getString(2) + "</td>"
                            + "<td>" + rs.getString(3) + "</td>"
                            + "<td>" + rs.getString(4) + "</td>"
                            + "<td>"
                            + "  <a href=\"editar.jsp?id=" + rs.getString(1) + "&nombre=" + rs.getString(2) + "&direccion=" + rs.getString(3) + "&telefono=" + rs.getString(4) + "\"><i class=\"fa fa-pencil\" aria-hidden=\"true\"></i></a>"
                            + "  <a href=\"borrar.jsp?id=" + rs.getString(1) + "\" class=\"ml-1\"><i class=\"fa fa-trash\" aria-hidden=\"true\"></i></a>"
                            + "</td>"
                            + "</tr>"
                    );

                }
            } catch (Exception e) {
                out.print("error mysql " + e);
            }finally{
                try {
                    con.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Empleados.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
    }
    public String mysql_real_scape_string(String texto){
        texto=texto.replaceAll("\\\\", "\\\\\\\\'");
        texto=texto.replaceAll("\\n", "\\\\n'");
        texto=texto.replaceAll("\\r", "\\\\r'");
        texto=texto.replaceAll("\\t", "\\\\t'");
        texto=texto.replaceAll("\\n", "\\\\n'");
        texto=texto.replaceAll("'", "\\\\'");
        return texto;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

? Pagina de sqlmap: http://sqlmap.org/

Descubrir la BD
sqlmap -u http://192.168.8.103/cat.php?id=2 –dbs

Aumentar el nivel y riesgo
sqlmap -u http://192.168.8.103/cat.php?id=2 –dbs –level=5 –risk=3

?Sqlmap en Kali Linux: https://www.youtube.com/watch?v=TRR5TWr-HFI
?Instalar kali linux en una usb desde windows 10: https://youtu.be/6POGcKizDts
?Blog con vulnerabilidades para hacer pentatesting con kali linux ?:https://www.youtube.com/watch?v=EuYJSXqngTY

Curso de Java de 0 a 100: https://www.youtube.com/playlist?list=PLCTD_CpMeEKTT-qEHGqZH3fkBgXH4GOTF

? Esta lista de reproducción: https://www.youtube.com/playlist?list=PLCTD_CpMeEKRAgcBmPee0Wjx5HsJ0nb0L
Codigos en gdrive: https://drive.google.com/file/d/10uLG9o2oDV-qB32G4kMIpzXgLCiUYaYz/view?usp=sharing

Gracias por apoyar este canal: https://www.patreon.com/programadornovato?fan_landing=true

? Facebook: https://facebook.com/ProgramadorNovatoOficial
? Twitter: https://twitter.com/programadornova
? Linkedin: https://www.linkedin.com/in/programadornovato/
? Instagram: https://www.instagram.com/programadornovato/

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *