/** {@inheritDoc} */
  @Override
  public IUtilisateur majMotDePasse(int idUtilisateur, String motDePasse) {
    IUtilisateur utilisateur = null;
    String sqlQuery =
        String.format(
            "UPDATE %s SET %s=? WHERE %s=?;",
            BaseDonneeEnum.UTILISATEUR,
            UtilisateurEnum.MOT_DE_PASSE_UTILISATEUR,
            UtilisateurEnum.ID_UTILISATEUR);
    PreparedStatement preparedStatement = this.getBd().openPrepared(sqlQuery);

    // Cryptage du mot de passe
    StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
    String motDePasseCrypt = passwordEncryptor.encryptPassword(motDePasse);

    try {
      int numeroParametre = 1;
      preparedStatement.setString(numeroParametre, motDePasseCrypt);
      preparedStatement.setInt(++numeroParametre, idUtilisateur);
      // On créé une instance Utilisateur avec les informations à notre disposition.
      utilisateur = new Utilisateur(idUtilisateur);
      utilisateur.setMotDePasseUtilisateur(motDePasseCrypt);
      preparedStatement.executeUpdate();
    } catch (SQLException e) {
      LOGGER.warn(e);
    }
    this.getBd().closePrepared(preparedStatement);

    return utilisateur;
  }
Esempio n. 2
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");
    HttpSession session = request.getSession(true);
    try (PrintWriter out = response.getWriter()) {

      String name = request.getParameter("Name");
      String username = request.getParameter("inputUsername");
      String password = request.getParameter("inputPassword");
      String status = null;

      StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
      String encryptedPassword = passwordEncryptor.encryptPassword(password);

      User user = new User(name, username, encryptedPassword, "user", "active");
      UserDAO userDAO = new UserDAO();
      User USER;
      USER = userDAO.getUser(username);

      if (USER != null) {

        session.setAttribute("errorRegister", "Username already taken");
        response.sendRedirect("user/register.jsp");

      } else {

        userDAO.addUser(user);
        response.sendRedirect("index.jsp");
      }
    }
  }
  /** {@inheritDoc} */
  @Override
  public IUtilisateur creerUtilisateur(
      String prenom,
      String nom,
      String identifiant,
      String motDePasse,
      int numeroEtudiant,
      int idEntite) {
    IUtilisateur utilisateur = null;
    String sqlQuery =
        String.format(
            "INSERT INTO %s (%s,%s,%s,%s,%s,%s) VALUES (?,?,?,?,?,?);",
            BaseDonneeEnum.UTILISATEUR,
            UtilisateurEnum.PRENOM_UTILISATEUR,
            UtilisateurEnum.NOM_UTILISATEUR,
            UtilisateurEnum.IDENTIFIANT_UTILISATEUR,
            UtilisateurEnum.MOT_DE_PASSE_UTILISATEUR,
            UtilisateurEnum.NUMERO_ETUDIANT,
            UtilisateurEnum.ID_ENTITE);
    PreparedStatement preparedStatement = this.getBd().openPrepared(sqlQuery);

    // Cryptage du mot de passe
    StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();
    String motDePasseCrypt = passwordEncryptor.encryptPassword(motDePasse);

    ResultSet resultSet = null;
    try {
      int numeroParametre = 1;
      preparedStatement.setString(numeroParametre, prenom);
      preparedStatement.setString(++numeroParametre, nom);
      preparedStatement.setString(++numeroParametre, identifiant);
      preparedStatement.setString(++numeroParametre, motDePasseCrypt);
      preparedStatement.setInt(++numeroParametre, numeroEtudiant);
      preparedStatement.setInt(++numeroParametre, idEntite);
      preparedStatement.executeUpdate();
      // On cherche à obtenir l'idUtilisateur généré.
      resultSet = preparedStatement.getGeneratedKeys();
    } catch (SQLException e) {
      LOGGER.warn(e);
    }

    if (resultSet != null) {
      try {
        // Si resusltSet n'est pas nul, on accède à la première ligne.
        resultSet.next();
        // On créé une instance Utilisateur avec les informations à notre disposition.
        utilisateur =
            new Utilisateur(
                resultSet.getInt(1), numeroEtudiant, nom, prenom, identifiant, motDePasseCrypt);
        utilisateur.setEntiteUtilisateur(new Entite(idEntite));
        resultSet.close();
      } catch (SQLException e) {
        LOGGER.warn(e);
      }
    }
    this.getBd().closePrepared(preparedStatement);

    return utilisateur;
  }
Esempio n. 4
0
  /** @param args */
  public static void main(String[] args) {
    BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();

    System.out.println(passwordEncryptor.encryptPassword("changeme"));

    StrongPasswordEncryptor strongPasswordEncryptor = new StrongPasswordEncryptor();

    System.out.println(strongPasswordEncryptor.encryptPassword("changeme"));
  }
Esempio n. 5
0
  /**
   * * Get User Name, session etc. and validate with database Respond with success or fail <argument
   * argName="sessionId" argValue="clients's nonce - post encryption with servers public key" />
   * <argument argName="secret" argValue="shared secret - hash value - with key as sessionId" />
   * <behavior>shared secret to be configured per device, sessionId should be pseudo random from
   * client</behavior> No encryption implemented yet Shared secret per device pending sessionId
   * implementation pending
   *
   * @param ctx
   * @param response
   * @throws IOException
   */
  private void login(ReqCtx ctx, HttpServletResponse response, HttpSession session)
      throws IOException {
    PreparedStatement stmt = null;
    ResultSet rs = null;
    String userId = ctx.getUserId();
    String sessionId = ctx.getArgVal(clntSessId_tag);
    String secret = ctx.getArgVal(secret_tag);
    String usrPass = ctx.getArgVal(Password_tag);
    StrongPasswordEncryptor passwordEncryptor = new StrongPasswordEncryptor();

    if (null == sessionId || null == secret) {
      errorResponse(ctx, response, "missingArgs:secret|sessionId");
      return; // working here
    }
    try {
      boolean status = false;
      stmt = con.prepareStatement("SELECT Password,Status FROM User WHERE MobileNumber = ?");
      stmt.setString(1, userId);
      rs = stmt.executeQuery();
      if (!rs.next()) {
        throw new Exception("No User"); // XXX TBD - should not let end client see this
      }

      String dbPass = rs.getString("Password");
      String dbStatus = rs.getString("Status");

      try {
        if (passwordEncryptor.checkPassword(usrPass, dbPass)) {
          status = true;
        }
      } catch (Exception e) {
        // do nothing - ignore StrongPasswordEncryptor checks in development : TBD XXX
      }

      if (!status) {
        if (dbPass.equals(usrPass) || secret.equals("testPass")) {
          status = true;
        }
      }
      if (status
          && dbStatus.equalsIgnoreCase(
              "operator")) { // 'active', 'suspended', 'deleted', 'operator'
        session.setAttribute(isOperator_tag, "true");
      }
      // XXX TBD - check that deviceId belongs to the User

      if (!status) throw new Exception("Unauthorized");

      // add ledger entry
      session.setAttribute(userId_tag, ctx.getUserId());
      session.setAttribute(DevId_tag, ctx.getDevId());
      session.setAttribute(clntSessId_tag, sessionId);
      session.setAttribute(Password_tag, usrPass);
      session.setMaxInactiveInterval(3600); // should be smaller in production TODO
      // session.setMaxInactiveInterval(5);
      // String message="Welcome " + userId + " from " + deviceId;
      Cookie loginCookie = new Cookie("USERNAME", userId);
      response.addCookie(loginCookie);

      log(Level.INFO, "Current session : " + session.getId());

      successResponse(ctx, response, "Added User : "******"processing error:" + e.getMessage()); // should not show user the actual error
      log(WARNING, "Error in login in Oprtr: " + e);
    } finally {
      if (stmt != null)
        try {
          stmt.close();
        } catch (SQLException logOrIgnore) {
        }
    }
  }
Esempio n. 6
0
  public static void main(String[] args) throws Exception {
    boolean isInteractive = false;
    classUrl = MynaInstaller.class.getResource("MynaInstaller.class").toString();
    isJar = (classUrl.indexOf("jar") == 0);
    if (!isJar) {
      System.err.println("Installer can only be run from inside a Myna distribution war file");
      System.exit(1);
    }

    Thread.sleep(1000);

    Console console = System.console();
    String response = null;
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption(
        "c", "context", true, "Webapp context. Must Start with \"/\" Default: " + webctx);
    options.addOption("h", "help", false, "Displays help.");
    options.addOption(
        "w",
        "webroot",
        true,
        "Webroot to use. Will be created if webroot/WEB-INF does not exist. Default: " + webroot);
    options.addOption(
        "l",
        "logfile",
        true,
        "Log file to use. Will be created if it does not exist. Default: ./<context>.log");
    options.addOption(
        "s",
        "servername",
        true,
        "Name of this instance. Will also be the name of the init script. Defaults to either \"myna\" or the value of <context> if defined");
    // options.addOption( "P", "purpose", true, "Purpose of the Server, such as DEV,PROD,TRAIN, etc.
    // Defaults to DEV" );

    options.addOption("p", "port", true, "HTTP port. Set to 0 to disable HTTP. Default: " + port);
    options.addOption(
        "sp", "ssl-port", true, "SSL (HTTPS) port. Set to 0 to disable SSL, Default: 0");

    options.addOption(
        "ks", "keystore", true, "keystore path. Default: <webroot>/WEB-INF/myna/myna_keystore");
    options.addOption("ksp", "ks-pass", true, "keystore password. Default: " + ksPass);
    options.addOption("ksa", "ks-alias", true, "certificate alias. Default: " + ksAlias);

    modeOptions.add("upgrade");
    modeOptions.add("install");
    options.addOption(
        "m",
        "mode",
        true,
        "Mode: one of "
            + modeOptions.toString()
            + ". \n"
            + "\"upgrade\": Upgrades myna installation in webroot and exits. "
            + "\"install\": Unpacks to webroot, and installs startup files");
    options.addOption(
        "u",
        "user",
        true,
        "User to own and run the Myna installation. Only applies to unix installs. Default: nobody");

    HelpFormatter formatter = new HelpFormatter();

    String cmdSyntax = "java -jar myna-X.war -m <mode> [options]";
    try {
      CommandLine line = parser.parse(options, args);
      Option option;
      if (args.length == 0) {
        formatter.printHelp(cmdSyntax, options);
        response = console.readLine("\nContinue with Interactive Install? (y/N)");
        if (response.toLowerCase().equals("y")) {
          isInteractive = true;

        } else System.exit(1);
      }
      // Help
      if (line.hasOption("help")) {
        formatter.printHelp(cmdSyntax, options);
        System.exit(1);
      }
      // mode
      if (line.hasOption("mode")) {
        mode = line.getOptionValue("mode");
        if (!modeOptions.contains(mode)) {
          System.err.println(
              "Invalid Arguments.  Reason: Mode must be in " + modeOptions.toString());
          formatter.printHelp(cmdSyntax, options);
          System.exit(1);
        }
      } else if (isInteractive) {
        option = options.getOption("mode");
        console.printf("\n" + option.getDescription());

        do {
          response = console.readLine("\nEnter " + option.getLongOpt() + "(" + mode + "): ");
          if (!response.isEmpty()) mode = response;
        } while (!modeOptions.contains(mode));
      }
      // webroot
      if (line.hasOption("webroot")) {
        webroot = line.getOptionValue("webroot");
      } else if (isInteractive) {
        option = options.getOption("webroot");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webroot + "): ");
        if (!response.isEmpty()) webroot = response;
      }
      // port
      if (line.hasOption("port")) {
        port = Integer.parseInt(line.getOptionValue("port"));
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("port");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + port + "): ");
        if (!response.isEmpty()) port = Integer.parseInt(response);
      }
      // context
      if (line.hasOption("context")) {
        webctx = line.getOptionValue("context");

      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("context");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webctx + "): ");
        if (!response.isEmpty()) webctx = response;
      }
      if (!webctx.startsWith("/")) {
        webctx = "/" + webctx;
      }
      // servername (depends on context)
      if (!webctx.equals("/")) {
        serverName = webctx.substring(1);
      }
      if (line.hasOption("servername")) {
        serverName = line.getOptionValue("servername");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("servername");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + serverName + "): ");
        if (!response.isEmpty()) serverName = response;
      }
      // user
      if (line.hasOption("user")) {
        user = line.getOptionValue("user");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("user");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + user + "): ");
        if (!response.isEmpty()) user = response;
      }
      // logfile
      logFile = "myna.log";
      if (!webctx.equals("/")) {
        logFile = webctx.substring(1) + ".log";
      }
      if (line.hasOption("logfile")) {
        logFile = line.getOptionValue("logfile");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("logfile");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "path(" + logFile + "): ");
        if (!response.isEmpty()) logFile = response;
      }

      // ssl-port
      if (line.hasOption("ssl-port")) {
        sslPort = Integer.parseInt(line.getOptionValue("ssl-port"));
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ssl-port");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + sslPort + "): ");
        if (!response.isEmpty()) sslPort = Integer.parseInt(response);
      }
      // ks-pass
      if (line.hasOption("ks-pass")) {
        ksPass = line.getOptionValue("ks-pass");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ks-pass");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksPass + "): ");
        if (!response.isEmpty()) ksPass = response;
      }
      // ks-alias
      if (line.hasOption("ks-alias")) {
        ksAlias = line.getOptionValue("ks-alias");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ks-alias");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksAlias + "): ");
        if (!response.isEmpty()) ksAlias = response;
      }
      // keystore
      String appBase = new File(webroot).getCanonicalPath();
      if (keystore == null) {
        keystore = appBase + "/WEB-INF/myna/myna_keystore";
      }
      if (line.hasOption("keystore")) {
        keystore = line.getOptionValue("keystore");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("keystore");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + keystore + "): ");
        if (!response.isEmpty()) keystore = response;
      }

      javaOpts = line.getArgList();
    } catch (ParseException exp) {
      System.err.println("Invalid Arguments.	Reason: " + exp.getMessage());

      formatter.printHelp(cmdSyntax, options);
      System.exit(1);
    }

    if (isInteractive) {
      System.out.println("\nProceeed with the following settings?:\n");
      System.out.println("mode        = " + mode);
      System.out.println("webroot     = " + webroot);
      if (mode.equals("install")) {
        System.out.println("port        = " + port);
        System.out.println("context     = " + webctx);
        System.out.println("servername  = " + serverName);
        System.out.println("user        = "******"logfile     = " + logFile);
        System.out.println("ssl-port    = " + sslPort);
        System.out.println("ks-pass     = "******"ks-alias    = " + ksAlias);
        System.out.println("keystore    = " + keystore);
      }
      response = console.readLine("Continue? (Y/n)");
      if (response.toLowerCase().equals("n")) System.exit(1);
    }
    File wrFile = new File(webroot);
    webroot = wrFile.toString();
    if (mode.equals("install")) {
      adminPassword = console.readLine("\nCreate an Admin password for this installation: ");
    }
    // unpack myna if necessary
    if (!wrFile.exists() || mode.equals("upgrade") || mode.equals("install")) {
      upgrade(wrFile);
    }

    if (mode.equals("install")) {
      File propertiesFile = new File(wrFile.toURI().resolve("WEB-INF/classes/general.properties"));
      FileInputStream propertiesFileIS = new FileInputStream(propertiesFile);
      Properties generalProperties = new Properties();
      generalProperties.load(propertiesFileIS);
      propertiesFileIS.close();
      if (!adminPassword.isEmpty()) {
        org.jasypt.util.password.StrongPasswordEncryptor cryptTool =
            new org.jasypt.util.password.StrongPasswordEncryptor();
        generalProperties.setProperty("admin_password", cryptTool.encryptPassword(adminPassword));
      }
      generalProperties.setProperty("instance_id", serverName);

      generalProperties.store(
          new java.io.FileOutputStream(propertiesFile), "Myna General Properties");

      String javaHome = System.getProperty("java.home");
      webroot = new File(webroot).getCanonicalPath();
      if (serverName.length() == 0) serverName = "myna";
      if (java.lang.System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
        if (!new File(logFile).isAbsolute()) {
          logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString();
        }
        File templateFile =
            new File(
                wrFile.toURI().resolve("WEB-INF/myna/install/windows/update_myna_service.cmd"));

        String initScript =
            FileUtils.readFileToString(templateFile)
                .replaceAll("\\{webctx\\}", webctx)
                .replaceAll("\\{server\\}", Matcher.quoteReplacement(serverName))
                .replaceAll("\\{webroot\\}", Matcher.quoteReplacement(webroot))
                .replaceAll("\\{logfile\\}", Matcher.quoteReplacement(logFile))
                .replaceAll("\\{javahome\\}", Matcher.quoteReplacement(javaHome))
                .replaceAll("\\{port\\}", new Integer(port).toString())
                .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString())
                .replaceAll("\\{keystore\\}", Matcher.quoteReplacement(keystore))
                .replaceAll("\\{ksPass\\}", Matcher.quoteReplacement(ksPass))
                .replaceAll("\\{ksAlias\\}", Matcher.quoteReplacement(ksAlias));

        File scriptFile =
            new File(wrFile.toURI().resolve("WEB-INF/myna/install/update_myna_service.cmd"));

        FileUtils.writeStringToFile(scriptFile, initScript);

        // Runtime.getRuntime().exec("cmd /c start " + scriptFile.toString()).waitFor();

        System.out.println(
            "\nInstalled Service 'Myna App Server " + serverName + "' the following settings:\n");
        System.out.println(
            "\nInit script '" + scriptFile + "' created with the following settings:\n");
        System.out.println("memory=256MB");
        System.out.println("serverName=" + serverName);
        System.out.println("javaHome=" + javaHome);
        System.out.println("context=" + webctx);
        System.out.println("port=" + port);
        System.out.println("myna_home=" + webroot);
        System.out.println("logfile=" + logFile);

        System.out.println("sslPort=" + sslPort);
        System.out.println("keyStore=" + keystore);
        System.out.println("ksPass="******"ksAlias=" + ksAlias);

        System.out.println(
            "\nEdit and and run the command file in " + scriptFile + " to update this service");

      } else {
        String curUser = java.lang.System.getProperty("user.name");
        if (!curUser.equals("root")) {
          System.out.println("Install mode must be run as root.");
          System.exit(1);
        }

        if (!new File(logFile).isAbsolute()) {
          logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString();
        }
        File templateFile =
            new File(wrFile.toURI().resolve("WEB-INF/myna/install/linux/init_script"));
        String initScript =
            FileUtils.readFileToString(templateFile)
                .replaceAll("\\{webctx\\}", webctx)
                .replaceAll("\\{server\\}", serverName)
                .replaceAll("\\{user\\}", user)
                .replaceAll("\\{webroot\\}", webroot)
                .replaceAll("\\{javahome\\}", javaHome)
                .replaceAll("\\{logfile\\}", logFile)
                .replaceAll("\\{port\\}", new Integer(port).toString())
                .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString())
                .replaceAll("\\{keystore\\}", keystore)
                .replaceAll("\\{ksPass\\}", ksPass)
                .replaceAll("\\{ksAlias\\}", ksAlias);

        File scriptFile = new File(wrFile.toURI().resolve("WEB-INF/myna/install/" + serverName));

        FileUtils.writeStringToFile(scriptFile, initScript);

        if (new File("/etc/init.d").exists()) {

          exec("chown  -R " + user + " " + webroot);
          exec("chown root " + scriptFile.toString());
          exec("chmod 700 " + scriptFile.toString());
          exec("cp " + scriptFile.toString() + " /etc/init.d/");

          System.out.println(
              "\nInit script '/etc/init.d/"
                  + serverName
                  + "' created with the following settings:\n");
        } else {
          System.out.println(
              "\nInit script '" + scriptFile + "' created with the following settings:\n");
        }

        System.out.println("user="******"memory=256MB");
        System.out.println("server=" + serverName);
        System.out.println("context=" + webctx);
        System.out.println("port=" + port);
        System.out.println("myna_home=" + webroot);
        System.out.println("logfile=" + logFile);

        System.out.println("sslPort=" + sslPort);
        System.out.println("keyStore=" + keystore);
        System.out.println("ksPass="******"ksAlias=" + ksAlias);

        System.out.println("\nEdit this file to customize startup behavior");
      }
    }
  }
Esempio n. 7
0
 public String encryptPassword(String plainText) {
   return encryptor.encryptPassword(plainText);
 }
Esempio n. 8
0
 public boolean isCorrectPassword(String plainText, String stored) {
   return encryptor.checkPassword(plainText, stored);
 }