/* goodG2B1() - use goodsource and badsink by changing first 5==5 to 5!=5 */
  private void goodG2B1(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    /* INCIDENTAL: CWE 570 Statement is Always False */
    if (5 != 5) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      Logger log_bad = Logger.getLogger("local-logger");
      /* read parameter from cookie */
      Cookie cookieSources[] = request.getCookies();
      if (cookieSources != null) {
        data = cookieSources[0].getValue();
      } else {
        data = null;
      }
    } else {

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

      /* FIX: Use a hardcoded string */
      data = "foo";
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (5 == 5) {
      Cookie cookieSink = new Cookie("lang", data);
      /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */
      response.addCookie(cookieSink);
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-16"));
      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      response.addCookie(cookieSink);
    }
  }
  /* goodG2B() - use goodsource and badsink by changing the conditions on the first and second while statements */
  private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    boolean local_f = false;

    while (true) {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
      /* FIX: Use a hardcoded string */
      data = "foo";
      break;
    }

    while (local_f) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      Logger log_bad = Logger.getLogger("local-logger");
      /* get environment variable ADD */
      data = System.getenv("ADD");
      break;
    }

    while (true) {
      Cookie cookieSink = new Cookie("lang", data);
      /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */
      response.addCookie(cookieSink);
      break;
    }

    while (local_f) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-16"));
      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      response.addCookie(cookieSink);
      break;
    }
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in first if */
  private void goodG2B2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_t) {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

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

      data = ""; /* init data */

      /* read user input from console with readLine*/
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        instrread = new InputStreamReader(System.in);
        buffread = new BufferedReader(instrread);
        data = buffread.readLine();
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (instrread != null) {
              instrread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing instrread");
          }
        }
      }
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_t) {
      Cookie cookieSink = new Cookie("lang", data);
      /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */
      response.addCookie(cookieSink);
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-16"));
      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      response.addCookie(cookieSink);
    }
  }
Esempio n. 4
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    HttpSession session = req.getSession();
    String exitParam = req.getParameter("exit");
    String deleteParam = req.getParameter("delete");
    String settingsParam = req.getParameter("settings");

    if ("settings".equals(settingsParam)) {
      resp.sendRedirect("/profileSettings");
      return;
    }

    if ("exit".equals(exitParam)) {
      // обнуляем куку
      Cookie[] cookies = req.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember")) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            break;
          }
        }
      }
      session.setAttribute("user_a", null);
      resp.sendRedirect("/login");
    }

    if ("delete".equals(deleteParam)) {
      // обнуляем куку
      Cookie[] cookies = req.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember")) {
            cookie.setMaxAge(0);
            cookie.setValue(null);
            resp.addCookie(cookie);
            break;
          }
        }
      }
      try {
        UserRepository.deleteUser((User) session.getAttribute("user_a"));
      } catch (SQLException e) {
        req.setAttribute("message", "Some problems with server");
        resp.sendRedirect("/profile");

        e.printStackTrace();
      }
      session.setAttribute("user_a", null);
      resp.sendRedirect("/welcome");
    }
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    Cookie cookieSink = new Cookie("lang", data);
    /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */
    response.addCookie(cookieSink);
  }
  /* goodB2G() - use badsource and goodsink */
  public void goodB2G_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-16"));
    /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
    response.addCookie(cookieSink);
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    if (request.getParameter("setcookie") != null) {
      Cookie cookie = new Cookie("Learningjava", "Cookies!");
      cookie.setMaxAge(3600);
      response.addCookie(cookie);
      out.println("<html><body><h1>Cookie Set...</h1>");
    } else {
      out.println("<html><body>");
      Cookie[] cookies = request.getCookies();
      if (cookies.length == 0) {
        out.println("<h1>No cookies found...</h1>");
      } else {
        for (int i = 0; i < cookies.length; i++)
          out.print(
              "<h1>Name: "
                  + cookies[i].getName()
                  + "<br>"
                  + "Value: "
                  + cookies[i].getValue()
                  + "</h1>");
      }
      out.println(
          "<p><a href=\""
              + request.getRequestURI()
              + "?setcookie=true\">"
              + "Reset the Learning Java cookie.</a>");
    }
    out.println("</body></html>");
  }
Esempio n. 8
0
 private void processSessionCookie(HttpSession session) {
   if (null == response || null == session) {
     // No response or session object attached, skip the pre processing
     return;
   }
   // cookieOverWritten - Flag to filter multiple "Set-Cookie" headers
   Object cookieOverWritten = getAttribute("COOKIE_OVERWRITTEN_FLAG");
   if (null == cookieOverWritten && isSecure() && isRequestedSessionIdFromCookie()) {
     // Might have created the cookie in SSL protocol and tomcat will
     // loose the session
     // if there is change in protocol from HTTPS to HTTP. To avoid this,
     // trick the browser
     // using the HTTP and HTTPS session cookie.
     Cookie cookie =
         new Cookie("JSESSIONID", RequestUtil.getSessionWithoutSuffix(session.getId()));
     cookie.setMaxAge(-1); // Life of the browser or timeout
     String contextPath = getContextPath();
     if ((contextPath != null) && (contextPath.length() > 0)) {
       cookie.setPath(contextPath);
     } else {
       cookie.setPath("/");
     }
     response.addCookie(cookie); // Adding an "Set-Cookie" header to the
     // response
     setAttribute("COOKIE_OVERWRITTEN_FLAG", "true"); // To avoid multiple
     // "Set-Cookie"
     // header
   }
 }
Esempio n. 9
0
 private void invalidateCookies(HttpServletRequest request, HttpServletResponse response) {
   Cookie[] c = request.getCookies();
   for (Cookie cookie : c) {
     cookie.setMaxAge(0);
     LOGGER.info(TextUtils.merge("Invalidate cookie: {0}", cookie.getName()));
     response.addCookie(cookie);
   }
 }
Esempio n. 10
0
 private void refreshCookie(Cookie cookie, HttpServletResponse response) {
   cookie.setValue(values[index++]);
   if (index == 8) {
     index = 0;
   }
   int minutes = 10;
   cookie.setMaxAge(60 * minutes);
   response.addCookie(cookie);
 }
  /* goodB2G() - use badsource and goodsink */
  public void goodB2G_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    String prefix = "Tru3ly 0b$scUre";
    MessageDigest hash = MessageDigest.getInstance("SHA512");

    /* FIX: credentials hashed prior to setting in cookie */
    byte[] hashv = hash.digest((prefix + data).getBytes());

    response.addCookie(new Cookie("auth", IO.toHex(hashv)));
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(
      CWE113_HTTP_Response_Splitting__listen_tcp_addCookieServlet_67a.Container data_container,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Throwable {
    String data = data_container.a;

    Cookie cookieSink = new Cookie("lang", data);
    /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */
    response.addCookie(cookieSink);
  }
  /* goodB2G() - use badsource and goodsink */
  public void goodB2G_sink(
      CWE113_HTTP_Response_Splitting__listen_tcp_addCookieServlet_67a.Container data_container,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Throwable {
    String data = data_container.a;

    Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-16"));
    /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
    response.addCookie(cookieSink);
  }
  /* goodB2G1() - use badsource and goodsink by changing second PRIVATE_STATIC_FINAL_TRUE to PRIVATE_STATIC_FINAL_FALSE */
  private void goodB2G1(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (PRIVATE_STATIC_FINAL_TRUE) {
      data = ""; /* Initialize data */
      {
        InputStreamReader readerInputStream = null;
        BufferedReader readerBuffered = null;
        /* read user input from console with readLine */
        try {
          readerInputStream = new InputStreamReader(System.in, "UTF-8");
          readerBuffered = new BufferedReader(readerInputStream);
          /* POTENTIAL FLAW: Read data from the console using readLine */
          data = readerBuffered.readLine();
        } catch (IOException exceptIO) {
          IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
        } finally {
          try {
            if (readerBuffered != null) {
              readerBuffered.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
          }

          try {
            if (readerInputStream != null) {
              readerInputStream.close();
            }
          } catch (IOException exceptIO) {
            IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
          }
        }
      }
      /* NOTE: Tools may report a flaw here because buffread and isr are not closed.  Unfortunately, closing those will close System.in, which will cause any future attempts to read from the console to fail and throw an exception */
    } 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_FALSE) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      IO.writeLine("Benign, fixed string");
    } else {

      if (data != null) {
        Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-8"));
        /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
        response.addCookie(cookieSink);
      }
    }
  }
  /* goodG2B() - use GoodSource and BadSink */
  public void goodG2BSink(
      HashMap<Integer, String> dataHashMap,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Throwable {
    String data = dataHashMap.get(2);

    if (data != null) {
      Cookie cookieSink = new Cookie("lang", data);
      /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */
      response.addCookie(cookieSink);
    }
  }
  /* goodB2G() - use BadSource and GoodSink */
  public void goodB2GSink(
      HashMap<Integer, String> dataHashMap,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Throwable {
    String data = dataHashMap.get(2);

    if (data != null) {
      Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-8"));
      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      response.addCookie(cookieSink);
    }
  }
Esempio n. 17
0
  /**
   * Аутентификация пользователя по паролю.
   *
   * @param answer ссылка на JSONObject ответа для клиента
   * @param user логин
   * @param pass пароль
   * @throws Exception
   */
  private void authenticationByPassword(
      HttpServletRequest request,
      HttpServletResponse response,
      JSONObject answer,
      String user,
      String pass)
      throws Exception {
    Mongo myMongoServ = new Mongo();
    myMongoServ.initMongoConnect();
    if (user.length() > 0) {
      try {
        List<UsersEntity> users =
            (List<UsersEntity>) myMongoServ.find(new UsersEntity(), "username", user);
        if (users.size() > 0) {
          if (users.get(0).getPassword().equals(pass)) {
            String session = UUID.randomUUID().toString();
            // System.out.println("session = "+session);
            myMongoServ.update(users.get(0), "session", session);
            myMongoServ.update(users.get(0), "last_login", new Date().getTime() + "");
            Cookie cuk = new Cookie("JSESSIONID", session);
            cuk.setPath("/phonebk");
            cuk.setHttpOnly(true);
            cuk.setMaxAge(UpdateCookie.COOKIE_MAX_AGE);
            response.addCookie(cuk);

            answer.put("answer", "Auth by pass is correct!");
            answer.put("code", 200);
          } else {
            answer.put("answer", "Password is invalid!");
            answer.put("code", 401);
          }
        } else {
          answer.put("answer", "Username or password is invalid!");
          answer.put("code", 401);
        }
      } catch (MongoSocketOpenException e) {
        System.out.println("Mongo ex");
        System.out.println(e.getMessage());
      } catch (ConnectException e) {
        System.out.println("Connect ex");
        System.out.println(e.getMessage());
      } catch (MongoTimeoutException e) {
        answer.put("answer", "Server is unavailable!");
        answer.put("code", 503);
      }

    } else {
      answer.put("answer", "Username is empty!");
      answer.put("code", 401);
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    boolean local_f = false; /* This local variable is used becuase the
		  Java compiler will generate an error on while(false) and similar
		  constructs that evaluate to false.  This is the simplest construct
		  that will always be false and still compile. */

    while (local_f) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
      /* FIX: Use a hardcoded string */
      data = "foo";
      break;
    }

    while (true) {
      Logger log_bad = Logger.getLogger("local-logger");
      /* get environment variable ADD */
      data = System.getenv("ADD");
      break;
    }

    while (true) {
      Cookie cookieSink = new Cookie("lang", data);
      /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */
      response.addCookie(cookieSink);
      break;
    }

    while (local_f) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      Cookie cookieSink = new Cookie("lang", URLEncoder.encode(data, "UTF-16"));
      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      response.addCookie(cookieSink);
      break;
    }
  }
  /* goodG2B() - use goodsource and badsink */
  public void goodG2B_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    /* NOTE: potential incidental issues with not setting secure or HttpOnly flag */
    String fp = "../common/config.properties";

    /* simple pre-set key makes the stored password recoverable */
    String sharedKey = "0000000000000000";
    byte[] input = data.getBytes();
    SecretKeySpec key = new SecretKeySpec(sharedKey.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");

    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] cipherText = cipher.doFinal(input);

    /* FLAW: writing a recoverable password to a cookie */
    response.addCookie(new Cookie("auth", new String(cipherText)));
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in first if */
  private void goodG2B2(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (PRIVATE_STATIC_FINAL_TRUE) {
      /* 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 (PRIVATE_STATIC_FINAL_TRUE) {
      if (data != null) {
        Cookie cookieSink = new Cookie("lang", data);
        /* POTENTIAL FLAW: Input not verified before inclusion in the cookie */
        response.addCookie(cookieSink);
      }
    }
  }
Esempio n. 21
0
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   final String button = request.getParameter("button");
   if (button.equals("create")) {
     Cookie cookie = new Cookie("carlos-cookie-test", "");
     refreshCookie(cookie, response);
     response.sendRedirect("cookie");
   } else if (button.equals("no-pass")) {
     response.sendRedirect("cookie");
   } else if (button.equals("delete")) {
     Cookie cookie = getCookie("carlos-cookie-test", request);
     if (cookie != null) {
       cookie.setMaxAge(0);
       response.addCookie(cookie);
     }
     response.sendRedirect("cookie");
   } else {
     throw new RuntimeException("unknown action: " + button);
   }
 }
Esempio n. 22
0
  /**
   * Аутентификация пользователя по сессии.
   *
   * @param response ссылка на response клиенту для записи кук
   * @param answer ссылка на JSONObject ответа для клиента
   * @param session сессия из кук
   * @throws Exception
   */
  private void authenticationBySession(
      HttpServletResponse response, JSONObject answer, String session) throws Exception {
    Mongo myMongoServ = new Mongo();
    myMongoServ.initMongoConnect();

    List<UsersEntity> users =
        (List<UsersEntity>) myMongoServ.find(new UsersEntity(), "session", session);
    if (users.size() > 0) {
      myMongoServ.update(users.get(0), "last_login", new Date().getTime() + "");
      Cookie cuk = new Cookie("session", session);
      cuk.setPath("/pb/");
      cuk.setHttpOnly(true);
      cuk.setMaxAge(UpdateCookie.COOKIE_MAX_AGE);
      response.addCookie(cuk);
      answer.put("answer", "Auth by session is correct!");
      answer.put("code", 200);
    } else {
      answer.put("answer", "User session incorrect!");
      answer.put("code", 401);
    }
  }
Esempio n. 23
0
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    HttpSession session = req.getSession();

    if ((session.getAttribute("user_a") == null)) {

      Cookie cookie = ServletUtilities.getCookie(req, "remember");

      if (cookie != null) {
        // достаем user'а из БД с таким же cookie
        try {
          User user = UserRepository.getUserByCookie(cookie);
          if (user != null) {
            // меняем значение cookie для безопасности
            Cookie newCookie = new Cookie("remember", SecurityService.genRndHash(12));
            newCookie.setMaxAge(60 * 60 * 48);
            UserRepository.updateUserCookie(user, newCookie);
            resp.addCookie(newCookie);
            session.setAttribute("user_a", user);
            resp.sendRedirect("/profile");
            return;
          }

        } catch (SQLException e) {
          e.printStackTrace();
        }
      }

      resp.sendRedirect("/login");
    } else {
      req.setAttribute("user", session.getAttribute("user_a"));
      getServletContext().getRequestDispatcher("/WEB-INF/views/profile.jsp").forward(req, resp);
    }
  }
Esempio n. 24
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    // UserService userService = UserServiceFactory.getUserService();
    // User user = userService.getCurrentUser();

    // este try se usa por posibles problemas del server de google
    try {

      String texto = req.getParameter("texto");
      String latitud = req.getParameter("latitud");
      String longitud = req.getParameter("longitud");

      PersistenceManager pm = PMF.get().getPersistenceManager();

      String usuario = "";
      int i = 0;
      Cookie[] cookies = req.getCookies();
      // se recorren las cookies en busca del nombre de usuario para buscar en la tabla
      for (i = 0; i < cookies.length; i++) {

        if (cookies[i].getName().equalsIgnoreCase("username")) {
          usuario = cookies[i].getValue();
        }
      }

      Query query = pm.newQuery(Usuarios.class, "name == '" + usuario + "'");

      try {
        List<Usuarios> results = (List<Usuarios>) query.execute();
        if (!results.isEmpty()) {
          for (Usuarios u : results) {

            float x = Float.parseFloat(latitud);
            float y = Float.parseFloat(longitud);

            u.addPendX(x);
            u.addPendY(y);
            u.setTexto(texto);
            // codigo html para ver que todo ha ido bien
            /*
            resp.setContentType("text/html");
            PrintWriter pw = resp.getWriter();
            pw.println("<HTML><HEAD><TITLE>Coordenadas almacenadas correctamente</TITLE></HEAD>");
            pw.println("<BODY>");
            pw.println("<H2>Leyendo parámetros desde un formulario html</H2>");

            pw.println("<H3>X: "+x+"</H3>");
            pw.println("<H3>Y: "+y+"</H3>");
            pw.println("<H3>TEXTO: "+texto+"</H3>");
            pw.println("</BODY></HTML>");


                  pw.close();*/

            // creo cookie con las coordenadas recuperadas
            Cookie coordenadas = new Cookie("coordPend", u.getCoordPend().toString());
            coordenadas.setValue(u.getCoordPend().toString());
            coordenadas.setComment("coordenadas pendientes del usuario");
            coordenadas.setPath("/");
            resp.addCookie(coordenadas);

            resp.sendRedirect("/php/quieroIr.php");
          }
        } else {
          // no persistent object found
          resp.sendRedirect("/mensajesFallo/coordInvalid.html");
        }

      } catch (Exception e) {
        resp.sendRedirect("/mensajesFallo/coordInvalid.html");
      } finally {
        query.closeAll();
        pm.close();
      }

    } catch (Exception e) {
      resp.sendRedirect("/mensajesFallo/falloBaseDatos.html");
    }
  }
Esempio n. 25
0
  /**
   * Redirects the HTTP request to the Authentication module. It gets the authentication url from
   * <code>SystemProperties</code>.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception IOException If an input or output exception occurs
   */
  private void redirectForAuthentication(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.redirectForAuthentication: " + "requestURL=" + request.getRequestURL());
    }
    StringBuffer redirectURL = new StringBuffer(100);
    StringBuffer gotoURL = new StringBuffer(100);

    // Check if user has authenticated to another OpenSSO
    // instance
    String authURL = null;
    Cookie authCookie = CookieUtils.getCookieFromReq(request, authURLCookieName);
    if (authCookie != null) {
      authURL = CookieUtils.getCookieValue(authCookie);
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication: "
                + "got an authenticated URL= "
                + authURL);
      }
    }
    try {
      if (authURL == null
          || authURL.length() == 0
          || !authURL.toLowerCase().startsWith("http")
          || policyAdviceList != null) {
        String finalURL = request.getParameter(GOTO_PARAMETER);

        if (finalURL == null || finalURL.equals("")) {
          finalURL = request.getParameter(TARGET_PARAMETER);
        }

        if (finalURL == null || finalURL.equals("")) {
          showError(response, "GOTO or TARGET parameter is missing" + " in the request");
          return;
        }

        gotoURL
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(TARGET_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(finalURL))
            .append(AMPERSAND)
            .append(requestParams);

        // Construct the login URL
        String cdcurl = SystemProperties.get(Constants.CDCSERVLET_LOGIN_URL);
        if (cdcurl != null && cdcurl.length() > 0) {
          if (cdcurl.indexOf("?") == -1) {
            redirectURLStr = cdcurl + QUESTION_MARK;
          } else {
            redirectURLStr = cdcurl + AMPERSAND;
          }
        } else {
          redirectURLStr = AUTHURI + QUESTION_MARK;
        }
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet init redirect URL is" + "set to= " + redirectURLStr);
        }

        redirectURL.append(redirectURLStr);
        if (policyAdviceList != null) {
          redirectURL.append(policyAdviceList).append(AMPERSAND);
        }
        redirectURL
            .append(GOTO_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(gotoURL.toString()));

        // Check for policy advices
        if (policyAdviceList != null) {
          redirectURL.append(AMPERSAND).append(policyAdviceList);
        }
        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication"
                  + ":redirectURL before dispatching is="
                  + redirectURL);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(redirectURL.toString());
        dispatcher.forward(request, response);
      } else {
        // Redirect the user to the authenticated URL
        redirectURL
            .append(authURL)
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(request.getQueryString());
        // Reset the cookie value to null, to avoid continous loop
        // when a load balancer is used
        if (authCookie != null) {
          authCookie.setValue("");
          response.addCookie(authCookie);
        }
        response.sendRedirect(redirectURL.toString());
      }

      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication:"
                + "Forwarding for authentication to= "
                + redirectURL);
      }
    } catch (IOException ex) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication: Failed "
              + "in forwarding to Authentication service. IOException",
          ex);
      showError(response, "Could for forward to authentication service:" + ex.getMessage());
    } catch (ServletException se) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. ServletException",
          se);
      showError(response, "Could for forward to authentication service:" + se.getMessage());
    } catch (IllegalStateException ie) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. Illegal state",
          ie);
      showError(response, "Could for forward to authentication service:" + ie.getMessage());
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_five == 5) {
      Logger log_bad = Logger.getLogger("local-logger");
      data = ""; /* init data */
      Connection conn = null;
      PreparedStatement statement = null;
      ResultSet rs = null;
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        /* setup the connection */
        conn = IO.getDBConnection();
        /* prepare the query */
        statement = conn.prepareStatement("select name from users where id=?");
        /* get user input for the userid */
        IO.writeLine("Enter a userid to login as (number): ");
        instrread = new InputStreamReader(System.in);
        buffread = new BufferedReader(instrread);
        int num = Integer.parseInt(buffread.readLine());
        statement.setInt(1, num);
        rs = statement.executeQuery();
        data = rs.getString(1);
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (instrread != null) {
              instrread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing instrread");
          }
        }

        /* clean up database objects */
        try {
          if (rs != null) {
            rs.close();
          }
        } catch (SQLException se) {
          log_bad.warning("Error closing rs");
        } finally {
          try {
            if (statement != null) {
              statement.close();
            }
          } catch (SQLException se) {
            log_bad.warning("Error closing statement");
          } finally {
            try {
              if (conn != null) {
                conn.close();
              }
            } catch (SQLException se) {
              log_bad.warning("Error closing conn");
            }
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

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

      /* FIX: Use a hardcoded string */
      data = "foo";
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_five == 5) {
      /* NOTE: potential incidental issues with not setting secure or HttpOnly flag */
      String fp = "../common/config.properties";
      /* simple pre-set key makes the stored password recoverable */
      String sharedKey = "0000000000000000";
      byte[] input = data.getBytes();
      SecretKeySpec key = new SecretKeySpec(sharedKey.getBytes(), "AES");
      Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
      cipher.init(Cipher.ENCRYPT_MODE, key);
      byte[] cipherText = cipher.doFinal(input);
      /* FLAW: writing a recoverable password to a cookie */
      response.addCookie(new Cookie("auth", new String(cipherText)));
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      String prefix = "Tru3ly 0b$scUre";
      MessageDigest hash = MessageDigest.getInstance("SHA512");

      /* FIX: credentials hashed prior to setting in cookie */
      byte[] hashv = hash.digest((prefix + data).getBytes());

      response.addCookie(new Cookie("auth", IO.toHex(hashv)));
    }
  }
Esempio n. 27
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String email = request.getParameter("email");
    String password = request.getParameter("password");
    String verifypassword = request.getParameter("verifypassword");
    Map<String, String> myResponse = new HashMap<String, String>();
    PrintWriter out = response.getWriter();
    if (email.matches(
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")) // make sure email is properly
    // formatted
    {
      try {

        MongoURI mongoURI = new MongoURI(System.getenv("MONGOHQ_URL"));
        DB db = mongoURI.connectDB(); // instance of databse
        db.authenticate(mongoURI.getUsername(), mongoURI.getPassword()); // authenticates d
        // Set<string> accounts = db.getCollectionName("accounts");
        // Mongo mongo = new Mongo("localhost", 27017); //creates new instance of mongo
        // DB db = mongo.getDB("fourup"); //gets fourup database
        DBCollection accounts = db.getCollection("accounts"); // creates collection for accounts	
        BasicDBObject query = new BasicDBObject(); // creates a basic object named query
        query.put("email", email); // sets email to email
        DBCursor cursor = accounts.find(query);
        if (cursor.size() > 0) // check if email has already been registered
        {
          myResponse.put("Status", "Error");
          myResponse.put("Error", "Account already exists using this email address.");
        } else // since email doesn't currently exist in DB, go ahead and register user
        {
          if (password.equals(
              verifypassword)) // check that both of the passwords entered match each other
          {
            BasicDBObject document = new BasicDBObject();
            int salt = getSalt();
            String hpass = passwrdHash(password, salt);
            document.put("email", email);
            document.put("salt", salt);
            document.put("password", hpass); // this is where we need to hash the password
            accounts.insert(document);
            myResponse.put("Status", "Sucess");
            myResponse.put("Sucess", "Account has been Created");
            AccountObject user = new AccountObject(email, hpass);
            // set session
            HttpSession session = request.getSession();
            session.setAttribute("currentUser", email);
            // return cookie
            Cookie cookie = new Cookie("fourupCookie", email); // add the login information here
            response.addCookie(cookie);
            // redirect to homepage
            String message = "this is a test";
            myResponse.put("html", "<html></html>");
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            // response.sendRedirect("index.html"); //should add check to index page for cookie with
            // login information
          } else {
            myResponse.put("Status", "Failed");
            myResponse.put("Failed", "Passwords do not match.");
          }
        }

      } catch (MongoException e) {

        out.write(e.getMessage());
      }
    } else {
      myResponse.put("Status", "Invalid");
      myResponse.put(
          "Invalid", "The email address has not been entered correctly."); // should output error
    }

    String strResponse = new Gson().toJson(myResponse);
    response.getWriter().write(strResponse);
    response.getWriter().close();
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (5 == 5) {
      Logger log_bad = Logger.getLogger("local-logger");
      data = ""; /* init data */
      /* read user input from console with readLine*/
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        instrread = new InputStreamReader(System.in);
        buffread = new BufferedReader(instrread);
        data = buffread.readLine();
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (instrread != null) {
              instrread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing instrread");
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

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

      /* FIX: Use a hardcoded string */
      data = "foo";
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (5 == 5) {
      /* NOTE: potential incidental issues with not setting secure or HttpOnly flag */
      String fp = "../common/config.properties";
      /* simple pre-set key makes the stored password recoverable */
      String sharedKey = "0000000000000000";
      byte[] input = data.getBytes();
      SecretKeySpec key = new SecretKeySpec(sharedKey.getBytes(), "AES");
      Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
      cipher.init(Cipher.ENCRYPT_MODE, key);
      byte[] cipherText = cipher.doFinal(input);
      /* FLAW: writing a recoverable password to a cookie */
      response.addCookie(new Cookie("auth", new String(cipherText)));
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      String prefix = "Tru3ly 0b$scUre";
      MessageDigest hash = MessageDigest.getInstance("SHA512");

      /* FIX: credentials hashed prior to setting in cookie */
      byte[] hashv = hash.digest((prefix + data).getBytes());

      response.addCookie(new Cookie("auth", IO.toHex(hashv)));
    }
  }
Esempio n. 29
0
  /**
   * Redirects the HTTP request to the Authentication module. It gets the authentication url from
   * <code>SystemProperties</code>.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception IOException If an input or output exception occurs
   */
  private void redirectForAuthentication(
      HttpServletRequest request,
      HttpServletResponse response,
      String policyAdviceList,
      String requestParams)
      throws IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.redirectForAuthentication: " + "requestURL=" + request.getRequestURL());
    }
    StringBuilder redirectURL = new StringBuilder(100);
    StringBuilder gotoURL = new StringBuilder(100);

    // Check if user has authenticated to another OpenAM
    // instance
    String authURL = null;
    Cookie authCookie = CookieUtils.getCookieFromReq(request, authURLCookieName);
    if (authCookie != null) {
      authURL = CookieUtils.getCookieValue(authCookie);
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication: "
                + "got an authenticated URL= "
                + authURL);
      }
    }
    try {
      if (authURL == null
          || authURL.length() == 0
          || !authURL.toLowerCase().startsWith("http")
          || policyAdviceList != null) {
        String finalURL = request.getParameter(GOTO_PARAMETER);

        if (finalURL == null || finalURL.equals("")) {
          finalURL = request.getParameter(TARGET_PARAMETER);
        }

        if (finalURL == null || finalURL.equals("")) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication: "
                    + "goto or target parameter is missing in the request.");
          }

          showError(response, SERVER_ERROR_STR_MATCH);
          return;
        }

        gotoURL
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(TARGET_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(finalURL))
            .append(AMPERSAND)
            .append(requestParams);

        // Construct the login URL
        String loginURI = request.getParameter(LOGIN_URI);
        String cdcUri;

        if (loginURI != null && !loginURI.isEmpty() && isValidCDCURI(loginURI)) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication:found " + LOGIN_URI + "=" + loginURI);
          }

          cdcUri = loginURI;
        } else {
          cdcUri = cdcAuthURI;
        }

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication: Login URI is set to = " + cdcUri);
        }

        if (cdcUri.indexOf(QUESTION_MARK) == -1) {
          redirectURL.append(cdcUri).append(QUESTION_MARK);
        } else {
          redirectURL.append(cdcUri).append(AMPERSAND);
        }

        if (policyAdviceList != null) {
          redirectURL.append(policyAdviceList).append(AMPERSAND);
        }
        redirectURL
            .append(GOTO_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(gotoURL.toString()));

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication"
                  + ":redirectURL before dispatching is="
                  + redirectURL);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(redirectURL.toString());
        dispatcher.forward(request, response);
      } else {
        // Redirect the user to the authenticated URL
        redirectURL
            .append(authURL)
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(request.getQueryString());
        // Reset the cookie value to null, to avoid continuous loop
        // when a load balancer is used
        if (authCookie != null) {
          authCookie.setValue("");
          response.addCookie(authCookie);
        }
        response.sendRedirect(redirectURL.toString());
      }

      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication:"
                + "Forwarding for authentication to= "
                + redirectURL);
      }
    } catch (IOException ex) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication: Failed "
              + "in forwarding to Authentication service. IOException",
          ex);
      showError(response, "Could for forward to authentication service:" + ex.getMessage());
    } catch (ServletException se) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. ServletException",
          se);
      showError(response, "Could for forward to authentication service:" + se.getMessage());
    } catch (IllegalStateException ie) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. Illegal state",
          ie);
      showError(response, "Could for forward to authentication service:" + ie.getMessage());
    }
  }