Пример #1
0
  /**
   * 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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Statement stmt;
    ResultSet rs;
    Connection con = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
      String connectionUrl = "jdbc:mysql://localhost/myflickr?" + "user=root&password=123456";
      con = DriverManager.getConnection(connectionUrl);

      if (con != null) {
        System.out.println("connected to mysql");
      }
    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e.toString());
    } catch (ClassNotFoundException cE) {
      System.out.println("Class Not Found Exception: " + cE.toString());
    }

    try {
      stmt = con.createStatement();

      System.out.println("SELECT * FROM flickrusers WHERE name='" + username + "'");
      rs = stmt.executeQuery("SELECT * FROM flickrusers WHERE name='" + username + "'");

      while (rs.next()) {

        if (rs.getObject(1).toString().equals(username)) {

          out.println("<h1>To username pou epileksate uparxei hdh</h1>");
          out.println("<a href=\"project3.html\">parakalw dokimaste kapoio allo.</a>");

          stmt.close();
          rs.close();
          return;
        }
      }
      stmt.close();
      rs.close();

      stmt = con.createStatement();

      if (!stmt.execute("INSERT INTO flickrusers VALUES('" + username + "', '" + password + "')")) {
        out.println("<h1>Your registration is completed  " + username + "</h1>");
        out.println("<a href=\"index.jsp\">go to the login menu</a>");
        registerListener.Register(username);
      } else {
        out.println("<h1>To username pou epileksate uparxei hdh</h1>");
        out.println("<a href=\"project3.html\">Register</a>");
      }
    } catch (SQLException e) {
      throw new ServletException("Servlet Could not display records.", e);
    }
  }
  private void bad_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    String names[] = data.split("-");
    int iSuccess = 0;

    Logger log2 = Logger.getLogger("local-logger");

    Connection conn_tmp2 = null;
    Statement sqlstatement = null;

    try {
      conn_tmp2 = IO.getDBConnection();
      sqlstatement = conn_tmp2.createStatement();

      for (int i = 0; i < names.length; ++i) {
        /* POTENTIAL FLAW: take user input and place into dynamic sql query */
        sqlstatement.addBatch("update users set hitcount=hitcount+1 where name='" + names[i] + "'");
      }

      int dbResults[] = sqlstatement.executeBatch();

      for (int i = 0; i < names.length; ++i) {
        if (dbResults[i] > 0) {
          iSuccess++;
        }
      }

      IO.writeString("Succeeded in " + iSuccess + " out of " + names.length + " queries.");
    } catch (SQLException se) {
      log2.warning("Error getting database connection");
    } finally {
      try {
        if (sqlstatement != null) {
          sqlstatement.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing sqlstatement");
      } finally {
        try {
          if (conn_tmp2 != null) {
            conn_tmp2.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing conn_tmp2");
        }
      }
    }
  }
Пример #3
0
  public String checkValidLogin(String myUserName, String myPW) {

    try {
      Class.forName(javaSQLDriverPath);
      Connection conn =
          (Connection) DriverManager.getConnection(ConnectionPath, ConnectionUser, ConnectionPW);
      Statement st = conn.createStatement();
      String query = "Select * from User";

      ResultSet rs = st.executeQuery(query);
      while (rs.next()) {
        // return rs.getString("Username");
        if (myUserName.equals(rs.getString("Username"))) {
          if (myPW.equals(rs.getString("Password"))) {
            setUserVariables(myUserName);
            return "success";
          } else {
            return "wrongPassword";
          }
        }
      }

      rs.close();
      st.close();
      conn.close();

      return "userNotFound";
    } catch (Exception e) {

      return e.getMessage();
    }
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2BSink(String data) throws Throwable {

    Connection dbConnection = null;
    Statement sqlStatement = null;

    try {
      dbConnection = IO.getDBConnection();
      sqlStatement = dbConnection.createStatement();

      /* POTENTIAL FLAW: data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection */
      int rowCount =
          sqlStatement.executeUpdate(
              "insert into users (status) values ('updated') where name='" + data + "'");

      IO.writeLine("Updated " + rowCount + " rows successfully.");
    } catch (SQLException exceptSql) {
      IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
    } finally {
      try {
        if (sqlStatement != null) {
          sqlStatement.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
Пример #5
0
 protected collegeTable getCollege(String id, Connection con) throws SQLException {
   try {
     ResultSet rs = null;
     Statement statement = con.createStatement();
     rs =
         statement.executeQuery(
             "SELECT * FROM "
                 + TABLECOLLEGES
                 + " WHERE "
                 + collegeTable.ID
                 + " = "
                 + id
                 + " LIMIT 1");
     // if found
     if (rs.next()) {
       collegeTable table = new collegeTable();
       table.setID(id);
       table.setShort(rs.getString(collegeTable.SHORTNAME));
       table.setFull(rs.getString(collegeTable.FULLNAME));
       return table;
     } else {
       return null; // not found
     }
   } catch (Exception e) {
     log.writeException(e.getMessage());
     throw new SQLException(e.getMessage());
   }
 } // end getCollege
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B() throws Throwable {
    String data_copy;
    {
      String data;

      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded string */
      data = "foo";

      data_copy = data;
    }
    {
      String data = data_copy;

      Logger log2 = Logger.getLogger("local-logger");

      Connection conn_tmp2 = null;
      Statement sqlstatement = null;
      ResultSet sqlrs = null;

      try {
        conn_tmp2 = IO.getDBConnection();
        sqlstatement = conn_tmp2.createStatement();

        /* POTENTIAL FLAW: take user input and place into dynamic sql query */
        sqlrs = sqlstatement.executeQuery("select * from users where name='" + data + "'");

        IO.writeString(sqlrs.toString());
      } catch (SQLException se) {
        log2.warning("Error getting database connection");
      } finally {
        try {
          if (sqlrs != null) {
            sqlrs.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing sqlrs");
        } finally {
          try {
            if (sqlstatement != null) {
              sqlstatement.close();
            }
          } catch (SQLException e) {
            log2.warning("Error closing sqlstatement");
          } finally {
            try {
              if (conn_tmp2 != null) {
                conn_tmp2.close();
              }
            } catch (SQLException e) {
              log2.warning("Error closing conn_tmp2");
            }
          }
        }
      }
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (privateFive == 5) {
      data = ""; /* initialize data in case id is not in query string */
      /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
      {
        StringTokenizer tokenizer = new StringTokenizer(request.getQueryString(), "&");
        while (tokenizer.hasMoreTokens()) {
          String token = tokenizer.nextToken(); /* a token will be like "id=foo" */
          if (token.startsWith("id=")) /* check if we have the "id" parameter" */ {
            data = token.substring(3); /* set data to "foo" */
            break; /* exit while loop */
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (privateFive == 5) {
      Connection dbConnection = null;
      Statement sqlStatement = null;
      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();
        /* POTENTIAL FLAW: data concatenated into SQL statement used in execute(), which could result in SQL Injection */
        Boolean result =
            sqlStatement.execute(
                "insert into users (status) values ('updated') where name='" + data + "'");
        if (result) {
          IO.writeLine("Name, " + data + ", updated successfully");
        } else {
          IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql);
      } finally {
        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
 private void printOutLogs(Connection connection, PrintWriter out) throws SQLException {
   Statement select = connection.createStatement();
   ResultSet result = select.executeQuery("SELECT * FROM LOGGING ORDER BY DATE ASC");
   while (result.next()) {
     Timestamp date = result.getTimestamp("DATE");
     String ip = result.getString("IP");
     String url = result.getString("URL");
     out.println(date + "\t\t" + ip + "\t\t" + url);
   }
 }
  /* goodG2B1() - use goodsource and badsink by changing first IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */
  private void goodG2B1() throws Throwable {
    String data;
    if (IO.STATIC_FINAL_FIVE != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    if (IO.STATIC_FINAL_FIVE == 5) {
      if (data != null) {
        String names[] = data.split("-");
        int successCount = 0;
        Connection dbConnection = null;
        Statement sqlStatement = null;
        try {
          dbConnection = IO.getDBConnection();
          sqlStatement = dbConnection.createStatement();
          for (int i = 0; i < names.length; i++) {
            /* POTENTIAL FLAW: data concatenated into SQL statement used in executeBatch(), which could result in SQL Injection */
            sqlStatement.addBatch(
                "update users set hitcount=hitcount+1 where name='" + names[i] + "'");
          }
          int resultsArray[] = sqlStatement.executeBatch();
          for (int i = 0; i < names.length; i++) {
            if (resultsArray[i] > 0) {
              successCount++;
            }
          }
          IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries.");
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
        } finally {
          try {
            if (sqlStatement != null) {
              sqlStatement.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing Statament", exceptSql);
          }

          try {
            if (dbConnection != null) {
              dbConnection.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
          }
        }
      }
    }
  }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B() throws Throwable {
    String dataCopy;
    {
      String data;

      /* FIX: Use a hardcoded string */
      data = "foo";

      dataCopy = data;
    }
    {
      String data = dataCopy;

      if (data != null) {
        String names[] = data.split("-");
        int successCount = 0;
        Connection dbConnection = null;
        Statement sqlStatement = null;
        try {
          dbConnection = IO.getDBConnection();
          sqlStatement = dbConnection.createStatement();
          for (int i = 0; i < names.length; i++) {
            /* POTENTIAL FLAW: data concatenated into SQL statement used in executeBatch(), which could result in SQL Injection */
            sqlStatement.addBatch(
                "update users set hitcount=hitcount+1 where name='" + names[i] + "'");
          }
          int resultsArray[] = sqlStatement.executeBatch();
          for (int i = 0; i < names.length; i++) {
            if (resultsArray[i] > 0) {
              successCount++;
            }
          }
          IO.writeLine("Succeeded in " + successCount + " out of " + names.length + " queries.");
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
        } finally {
          try {
            if (sqlStatement != null) {
              sqlStatement.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing Statament", exceptSql);
          }

          try {
            if (dbConnection != null) {
              dbConnection.close();
            }
          } catch (SQLException exceptSql) {
            IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
          }
        }
      }
    }
  }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String dataCopy;
    {
      String data;

      /* FIX: Use a hardcoded string */
      data = "foo";

      dataCopy = data;
    }
    {
      String data = dataCopy;

      Connection dbConnection = null;
      Statement sqlStatement = null;
      ResultSet resultSet = null;

      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();

        /* POTENTIAL FLAW: data concatenated into SQL statement used in executeQuery(), which could result in SQL Injection */
        resultSet = sqlStatement.executeQuery("select * from users where name='" + data + "'");

        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  public void bad() throws Throwable {
    String data;
    if (IO.staticTrue) {
      /* get environment variable ADD */
      /* POTENTIAL FLAW: Read data from an environment variable */
      data = System.getenv("ADD");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (IO.staticTrue) {
      Connection dbConnection = null;
      Statement sqlStatement = null;
      ResultSet resultSet = null;
      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();
        /* POTENTIAL FLAW: data concatenated into SQL statement used in executeQuery(), which could result in SQL Injection */
        resultSet = sqlStatement.executeQuery("select * from users where name='" + data + "'");
        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  /* goodG2B1() - use goodsource and badsink by changing first IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */
  private void goodG2B1() throws Throwable {
    String data;
    if (IO.STATIC_FINAL_FIVE != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    if (IO.STATIC_FINAL_FIVE == 5) {
      Connection dbConnection = null;
      Statement sqlStatement = null;
      ResultSet resultSet = null;
      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();
        /* POTENTIAL FLAW: data concatenated into SQL statement used in executeQuery(), which could result in SQL Injection */
        resultSet = sqlStatement.executeQuery("select * from users where name='" + data + "'");
        IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
      } finally {
        try {
          if (resultSet != null) {
            resultSet.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
        }

        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
Пример #14
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter toClient = res.getWriter();
    toClient.println("<!DOCTYPE HTML>");
    toClient.println("<html>");
    toClient.println("<head><title>Books</title></head>");
    toClient.println("<body>");
    toClient.println("<a href=\"index.html\">Home</A>");
    toClient.println("<h2>List of books</h2>");

    HttpSession session = req.getSession(false);
    if (session != null) {
      String name = (String) session.getAttribute("name");
      if (name != null) {
        toClient.println("<h2>name: " + name + "</h2>");
      }
    }

    toClient.print("<form action=\"bookOpinion\" method=GET>");
    toClient.println("<table border='1'>");

    String sql = "Select code, title, author FROM books";
    System.out.println(sql);
    try {
      Statement statement = connection.createStatement();
      ResultSet result = statement.executeQuery(sql);
      while (result.next()) {
        toClient.println("<tr>");
        String codeStr = result.getString("code");
        toClient.println(
            "<td><input type=\"radio\" name=\"book" + "\" value=\"" + codeStr + "\"></td>");
        toClient.println("<td>" + codeStr + "</td>");
        toClient.println("<td>" + result.getString("title") + "</td>");
        toClient.println("<td>" + result.getString("author") + "</td>");
        toClient.println("</tr>");
      }
    } catch (SQLException e) {
      e.printStackTrace();
      System.out.println("Resulset: " + sql + " Exception: " + e);
    }
    toClient.println("</table>");
    toClient.println("<textarea rows=\"8\" cols=\"60\" name=\"comment\"></textarea><BR>");
    toClient.println("<input type=submit>");
    toClient.println("</form>");
    toClient.println("</body>");
    toClient.println("</html>");
    toClient.close();
  }
  public void bad() throws Throwable {
    String data;
    if (PRIVATE_STATIC_FINAL_TRUE) {
      /* get environment variable ADD */
      /* POTENTIAL FLAW: Read data from an environment variable */
      data = System.getenv("ADD");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (PRIVATE_STATIC_FINAL_TRUE) {
      Connection dbConnection = null;
      Statement sqlStatement = null;
      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();
        /* POTENTIAL FLAW: data concatenated into SQL statement used in execute(), which could result in SQL Injection */
        Boolean result =
            sqlStatement.execute(
                "insert into users (status) values ('updated') where name='" + data + "'");
        if (result) {
          IO.writeLine("Name, " + data + ", updated successfully");
        } else {
          IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql);
      } finally {
        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in first if */
  private void goodG2B2() throws Throwable {
    String data;

    if (IO.staticReturnsTrue()) {
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
       * but ensure data is inititialized before the Sink to avoid compiler errors */
      data = null;
    }

    if (IO.staticReturnsTrue()) {
      Connection dbConnection = null;
      Statement sqlStatement = null;
      try {
        dbConnection = IO.getDBConnection();
        sqlStatement = dbConnection.createStatement();
        /* POTENTIAL FLAW: data concatenated into SQL statement used in execute(), which could result in SQL Injection */
        Boolean result =
            sqlStatement.execute(
                "insert into users (status) values ('updated') where name='" + data + "'");
        if (result) {
          IO.writeLine("Name, " + data + ", updated successfully");
        } else {
          IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql);
      } finally {
        try {
          if (sqlStatement != null) {
            sqlStatement.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
        }

        try {
          if (dbConnection != null) {
            dbConnection.close();
          }
        } catch (SQLException exceptSql) {
          IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
        }
      }
    }
  }
Пример #17
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // get a connection
    ConnectionPool pool = ConnectionPool.getInstance();
    Connection connection = pool.getConnection();

    String sqlStatement = request.getParameter("sqlStatement");
    String sqlResult = "";
    try {
      // create a statement
      Statement statement = connection.createStatement();

      // parse the SQL string
      sqlStatement = sqlStatement.trim();
      if (sqlStatement.length() >= 6) {
        String sqlType = sqlStatement.substring(0, 6);
        if (sqlType.equalsIgnoreCase("select")) {
          // create the HTML for the result set
          ResultSet resultSet = statement.executeQuery(sqlStatement);
          sqlResult = SQLUtil.getHtmlTable(resultSet);
          resultSet.close();
        } else {
          int i = statement.executeUpdate(sqlStatement);
          if (i == 0) {
            sqlResult = "<p>The statement executed successfully.</p>";
          } else { // an INSERT, UPDATE, or DELETE statement
            sqlResult = "<p>The statement executed successfully.<br>" + i + " row(s) affected.</p>";
          }
        }
      }
      statement.close();
      connection.close();
    } catch (SQLException e) {
      sqlResult = "<p>Error executing the SQL statement: <br>" + e.getMessage() + "</p>";
    } finally {
      pool.freeConnection(connection);
    }

    HttpSession session = request.getSession();
    session.setAttribute("sqlResult", sqlResult);
    session.setAttribute("sqlStatement", sqlStatement);

    String url = "/index.jsp";
    getServletContext().getRequestDispatcher(url).forward(request, response);
  }
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {
      res.setContentType("text/html");
      pw = res.getWriter();
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:com", "o7it58", "yajiv32737");
      st = con.createStatement();
      pw.println("<html>");
      pw.println("<head><title>Welcome</title></head>");
      pw.println("<body>");

      s = req.getParameter("login");
      if (s.equals("Submit")) {
        uname = req.getParameter("firstname");
        pass = req.getParameter("pwd");
        PrintWriter out = new PrintWriter(new FileWriter("log.txt"), true);
        out.println(uname);
        rs =
            st.executeQuery(
                "select type from login where username='******' and password='******'");
        if (rs.next()) {
          type = rs.getString("type");
        } else {
          pw.println("<center>");
          pw.println("User does not exists");
          pw.println("</center>");
        }
        if (type.equals("admin")) {

          pw.println(
              "<a href=\"http://localhost:8080/servlet/AdminLogin\">Hello Admin.Please Click Here</a>");
        } else if (type.equals("staff")) {
          pw.println(
              "<a href=\"http://localhost:8080/servlet/StaffLogin\">Hello Staff.Please Click Here</a>");
        } else {
          pw.println(
              "<a href=\"http://localhost:8080/servlet/StudentLogin\">Hello Student.Please Click Here</a>");
        }
      }
      pw.println("</body></html>");
    } catch (Exception e) {
    }
  }
Пример #19
0
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    /* Get Session */
    HttpSession s = req.getSession(true);
    /* Make sure user is logged in */
    if (s.getAttribute("login") == null || (String) s.getAttribute("login") != "go") {
      req.getRequestDispatcher("login.jsp").forward(req, res);
    }

    try {
      String dbuser = this.getServletContext().getInitParameter("dbuser");
      String dbpassword = this.getServletContext().getInitParameter("dbpassword");

      Class.forName("com.mysql.jdbc.Driver");
      Connection conn =
          DriverManager.getConnection("jdbc:mysql://localhost/project", dbuser, dbpassword);

      Statement stmt = conn.createStatement();
      stmt.execute(
          "INSERT INTO songs VALUES(null, '"
              + req.getParameter("song_name")
              + "', '"
              + req.getParameter("artist")
              + "', '"
              + req.getParameter("album")
              + "', '"
              + req.getParameter("genre")
              + "', 0)");

      stmt.close();
      conn.close();

      // delete memcache since new song is now added
      MemcachedClient c = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
      c.delete("master");

      req.getRequestDispatcher("add_song_success.jsp").forward(req, res);

    } catch (Exception e) {
      out.println(e.getMessage());
    }
  }
Пример #20
0
 public void init(ServletConfig sc) throws ServletException {
   super.init(sc);
   try {
     Class.forName("com.mysql.jdbc.Driver");
     System.out.println("driver is loaded");
     con = DriverManager.getConnection(url, un, password);
     System.out.println("connected");
     stmt = con.createStatement();
     System.out.println("wrapper created");
   } catch (ClassNotFoundException cnfe) {
     System.out.println("driver Not Loaded" + cnfe.getMessage());
     return;
   } catch (SQLException sqle) {
     System.out.println("connection problem" + sqle.getMessage());
     return;
   }
 }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    Logger log2 = Logger.getLogger("local-logger");

    Connection conn_tmp2 = null;
    Statement sqlstatement = null;
    ResultSet sqlrs = null;

    try {
      conn_tmp2 = IO.getDBConnection();
      sqlstatement = conn_tmp2.createStatement();

      /* POTENTIAL FLAW: take user input and place into dynamic sql query */
      sqlrs = sqlstatement.executeQuery("select * from users where name='" + data + "'");

      IO.writeString(sqlrs.toString());
    } catch (SQLException se) {
      log2.warning("Error getting database connection");
    } finally {
      try {
        if (sqlrs != null) {
          sqlrs.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing sqlrs");
      } finally {
        try {
          if (sqlstatement != null) {
            sqlstatement.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing sqlstatement");
        } finally {
          try {
            if (conn_tmp2 != null) {
              conn_tmp2.close();
            }
          } catch (SQLException e) {
            log2.warning("Error closing conn_tmp2");
          }
        }
      }
    }
  }
  /* goodG2B() - use GoodSource and BadSink */
  public void goodG2BSink(HashMap<Integer, String> dataHashMap) throws Throwable {
    String data = dataHashMap.get(2);

    Connection dbConnection = null;
    Statement sqlStatement = null;
    ResultSet resultSet = null;

    try {
      dbConnection = IO.getDBConnection();
      sqlStatement = dbConnection.createStatement();

      /* POTENTIAL FLAW: data concatenated into SQL statement used in executeQuery(), which could result in SQL Injection */
      resultSet = sqlStatement.executeQuery("select * from users where name='" + data + "'");

      IO.writeLine(resultSet.getRow()); /* Use ResultSet in some way */
    } catch (SQLException exceptSql) {
      IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
    } finally {
      try {
        if (resultSet != null) {
          resultSet.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing ResultSet", exceptSql);
      }

      try {
        if (sqlStatement != null) {
          sqlStatement.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
Пример #23
0
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   Statement question;
   String query;
   ResultSet answer;
   connect();
   try {
     query = "SELECT * FROM PILOT WHERE Address ='" + request.getParameter("city") + "'";
     question = link.createStatement();
     answer = question.executeQuery(query);
     PrintWriter pen;
     response.setContentType("text/html");
     pen = response.getWriter();
     pen.println("<HTML>");
     pen.println("<HEAD> <TITLE> Answer </TITLE> </HEAD>");
     pen.println("<BODY>");
     while (answer.next()) {
       String pN = answer.getString("PilotNumber");
       String lN = answer.getString("LastName");
       String fN = answer.getString("FirstName");
       String ad = answer.getString("Address");
       float sa = answer.getFloat("Salary");
       float pr = answer.getFloat("Premium");
       Date hD = answer.getDate("HiringDate");
       if (answer.wasNull() == false) {
         pen.println("<P><B> Pilot : </B>" + lN + " " + fN);
         pen.println("<P><B> ---Reference : </B>" + pN);
         pen.println("<P><B> ---Address : </B>" + ad);
         pen.println("<P><B> ---Salary : </B>" + sa);
         pen.println("<P><B> ---since : </B>" + hD);
         if (pr > 0) pen.println("<P><B> ---Premium : </B>" + pr);
         else pen.println("<P><B> ---No premium </B>");
       }
     }
     pen.println("</BODY>");
     pen.println("</HTML>");
     answer.close();
     question.close();
     link.close();
   } catch (SQLException e) {
     System.out.println("Connection error: " + e.getMessage());
   }
 }
  public void bad() throws Throwable {
    String data = bad_source();

    Logger log2 = Logger.getLogger("local-logger");

    Connection conn_tmp2 = null;
    Statement sqlstatement = null;

    try {
      conn_tmp2 = IO.getDBConnection();
      sqlstatement = conn_tmp2.createStatement();

      /* POTENTIAL FLAW: value of "name" taken directly from an untrusted source and inserted into a command string executed against a SQL interpreter */
      Boolean bResult =
          sqlstatement.execute(
              "insert into users (status) values ('updated') where name='" + data + "'");

      if (bResult) {
        IO.writeString("Name, " + data + ", updated successfully");
      } else {
        IO.writeString("Unable to update records for user: "******"Error getting database connection");
    } finally {
      try {
        if (sqlstatement != null) {
          sqlstatement.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing sqlstatement");
      } finally {
        try {
          if (conn_tmp2 != null) {
            conn_tmp2.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing conn_tmp2");
        }
      }
    }
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2BSink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    Connection dbConnection = null;
    Statement sqlStatement = null;

    try {
      dbConnection = IO.getDBConnection();
      sqlStatement = dbConnection.createStatement();

      /* POTENTIAL FLAW: data concatenated into SQL statement used in execute(), which could result in SQL Injection */
      Boolean result =
          sqlStatement.execute(
              "insert into users (status) values ('updated') where name='" + data + "'");

      if (result) {
        IO.writeLine("Name, " + data + ", updated successfully");
      } else {
        IO.writeLine("Unable to update records for user: "******"Error getting database connection", exceptSql);
    } finally {
      try {
        if (sqlStatement != null) {
          sqlStatement.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
 public void doGet(HttpServletRequest request, HttpServletResponse response) {
   try {
     String comment = request.getParameter("comment");
     int answerId = Integer.parseInt(request.getParameter("answer_id"));
     Connection connection = GlobalResources.getConnection();
     Statement s;
     s = connection.createStatement();
     PreparedStatement preparedStatement;
     PreparedStatement preparedStatement1;
     preparedStatement =
         connection.prepareStatement("insert into comment(comment,answer_id) values(?,?)");
     preparedStatement.setString(1, comment);
     preparedStatement.setInt(2, answerId);
     preparedStatement.executeUpdate();
     preparedStatement.close();
     connection.close();
     RequestDispatcher requestDispatcher;
     requestDispatcher = request.getRequestDispatcher("/studenthome.jsp");
     requestDispatcher.forward(request, response);
   } catch (Exception e) {
   }
 }
  /* goodG2B() - use goodsource and badsink */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data =
        (new CWE89_SQL_Injection__getQueryString_Servlet_executeUpdate_61b())
            .goodG2BSource(request, response);

    Connection dbConnection = null;
    Statement sqlStatement = null;

    try {
      dbConnection = IO.getDBConnection();
      sqlStatement = dbConnection.createStatement();

      /* POTENTIAL FLAW: data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection */
      int rowCount =
          sqlStatement.executeUpdate(
              "insert into users (status) values ('updated') where name='" + data + "'");

      IO.writeLine("Updated " + rowCount + " rows successfully.");
    } catch (SQLException exceptSql) {
      IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
    } finally {
      try {
        if (sqlStatement != null) {
          sqlStatement.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
      }

      try {
        if (dbConnection != null) {
          dbConnection.close();
        }
      } catch (SQLException exceptSql) {
        IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
      }
    }
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(Object data_obj) throws Throwable {
    String data = (String) data_obj;

    Logger log2 = Logger.getLogger("local-logger");

    Connection conn_tmp2 = null;
    Statement sqlstatement = null;

    try {
      conn_tmp2 = IO.getDBConnection();
      sqlstatement = conn_tmp2.createStatement();

      /* POTENTIAL FLAW: place user input into dynamic sql query */
      int iResult =
          sqlstatement.executeUpdate(
              "insert into users (status) values ('updated') where name='" + data + "'");

      IO.writeString("Updated " + iResult + " rows successfully.");
    } catch (SQLException se) {
      log2.warning("Error getting database connection");
    } finally {
      try {
        if (sqlstatement != null) {
          sqlstatement.close();
        }
      } catch (SQLException e) {
        log2.warning("Error closing sqlstatement");
      } finally {
        try {
          if (conn_tmp2 != null) {
            conn_tmp2.close();
          }
        } catch (SQLException e) {
          log2.warning("Error closing conn_tmp2");
        }
      }
    }
  }
Пример #29
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String dbUser = "******"; // enter your username here
    String dbPassword = "******"; // enter your password here

    try {
      OracleDataSource ods = new oracle.jdbc.pool.OracleDataSource();
      ods.setURL("jdbc:oracle:thin:@//w4111b.cs.columbia.edu:1521/ADB");
      ods.setUser(dbUser);
      ods.setPassword(dbPassword);

      Connection conn = ods.getConnection();

      String query = new String();
      Statement s = conn.createStatement();

      query = "select * from events";

      ResultSet r = s.executeQuery(query);
      while (r.next()) {
        out.println("Today's Date: " + r.getString(1) + " ");
      }
      r.close();
      s.close();

      conn.close();

    } catch (Exception e) {
      out.println("The database could not be accessed.<br>");
      out.println("More information is available as follows:<br>");
      e.printStackTrace(out);
    }
  } // end doGet method
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(true);

    try {
      Object accountObject = session.getValue(ACCOUNT);

      // If no account object was put in the session, or
      // if one exists but it is not a hashtable, then
      // redirect the user to the original login page

      if (accountObject == null)
        throw new RuntimeException("You need to log in to use this service!");

      if (!(accountObject instanceof Hashtable))
        throw new RuntimeException("You need to log in to use this service!");

      Hashtable account = (Hashtable) accountObject;

      String userName = (String) account.get("name");

      //////////////////////////////////////////////
      // Display Messages for the user who logged in
      //////////////////////////////////////////////
      out.println("<HTML>");
      out.println("<HEAD>");
      out.println("<TITLE>Contacts for " + userName + "</TITLE>");
      out.println("</HEAD>");
      out.println("<BODY BGCOLOR='#EFEFEF'>");
      out.println("<H3>Welcome " + userName + "</H3>");

      out.println("<CENTER>");

      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;
      try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con =
            DriverManager.getConnection(
                "jdbc:mysql://localhost/contacts?user=kareena&password=kapoor");

        stmt = con.createStatement();
        rs =
            stmt.executeQuery(
                "SELECT * FROM contacts WHERE userName='******' ORDER BY contactID");

        out.println("<form name='deleteContactsForm' method='post' action='deleteContact'>");

        out.println("<TABLE BGCOLOR='#EFEFFF' CELLPADDING='2' CELLSPACING='4' BORDER='1'>");
        out.println("<TR BGCOLOR='#D6DFFF'>");
        out.println("<TD ALIGN='center'><B>Contact ID</B></TD>");
        out.println("<TD ALIGN='center'><B>Contact Name</B></TD>");
        out.println("<TD ALIGN='center'><B>Comment</B></TD>");
        out.println("<TD ALIGN='center'><B>Date</B></TD>");
        out.println("<TD ALIGN='center'><B>Delete Contacts</B></TD>");
        out.println("</TR>");

        int nRows = 0;
        while (rs.next()) {
          nRows++;
          String messageID = rs.getString("contactID");
          String fromUser = rs.getString("contactName");
          String message = rs.getString("comments");
          String messageDate = rs.getString("dateAdded");

          out.println("<TR>");
          out.println("<TD>" + messageID + "</TD>");
          out.println("<TD>" + fromUser + "</TD>");
          out.println("<TD>" + message + "</TD>");
          out.println("<TD>" + messageDate + "</TD>");
          out.println(
              "<TD><input type='checkbox' name='msgList' value='" + messageID + "'> Delete</TD>");
          out.println("</TR>");
        }

        out.println("<TR>");
        out.println(
            "<TD COLSPAN='6' ALIGN='center'><input type='submit' value='Delete Selected Contacts'></TD>");
        out.println("</TR>");

        out.println("</TABLE>");
        out.println("</FORM>");
      } catch (Exception e) {
        out.println("Could not connect to the users database.<P>");
        out.println("The error message was");
        out.println("<PRE>");
        out.println(e.getMessage());
        out.println("</PRE>");
      } finally {
        if (rs != null) {
          try {
            rs.close();
          } catch (SQLException ignore) {
          }
        }
        if (stmt != null) {
          try {
            stmt.close();
          } catch (SQLException ignore) {
          }
        }
        if (con != null) {
          try {
            con.close();
          } catch (SQLException ignore) {
          }
        }
      }

      out.println("</CENTER>");
      out.println("</BODY>");
      out.println("</HTML>");

    } catch (RuntimeException e) {
      out.println("<script language=\"javascript\">");
      out.println("alert(\"You need to log in to use this service!\");");
      out.println("</script>");

      out.println("<a href='index.html'>Click Here</a> to go to the main page.<br><br>");

      out.println(
          "Or Click on the button to exit<FORM><INPUT onClick=\"javascipt:window.close()\" TYPE=\"BUTTON\" VALUE=\"Close Browser\" TITLE=\"Click here to close window\" NAME=\"CloseWindow\" STYLE=\"font-family:Verdana, Arial, Helvetica; font-size:smaller; font-weight:bold\"></FORM>");

      log(e.getMessage());
      return;
    }
  }