Exemplo n.º 1
0
  public Message startAuthentication(AuthenticationMessage msg)
      throws AuthenticationException, GeneralSecurityException {
    if (msg instanceof RequestLoginMessage) {
      RequestLoginMessage rlm = (RequestLoginMessage) msg;
      username = rlm.getLogin();

      if (!allowRoot && username.equals("root")) {
        throw new AuthenticationException("Must authenticate as a regular user first.");
      }

      // generate challange
      byte[] passhash = UserManager.v().getPassHash(username);
      if (passhash == null) {
        throw new AuthenticationException("User has no password");
      }

      ChallangeMessage cm = new ChallangeMessage();
      SecureRandom rand = new SecureRandom();
      rand.nextBytes(randNumber);
      cm.setChallange(randNumber, passhash);
      state = CL_CHALLANGE_SENT;

      // send the challange
      return cm;
    } else if (msg instanceof ChallangeCheckStatusMessage) {
      // After authentication is complete the client sends this message
      //  It can be safely ignored. We don't care that the client has
      //  actually authenticated us.
      return null;
    }

    throw new AuthenticationException("State Error");
  }
Exemplo n.º 2
0
  private void handleSignupPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    String userId = request.getParameter(PARAM_USER_ID);
    String userName = request.getParameter(PARAM_USER_NAME);
    String email = request.getParameter(PARAM_EMAIL);
    String stringPassword = request.getParameter(PARAM_PASSWORD);
    String stringPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM);

    if (!stringPassword.equals(stringPasswordConfirm)) {
      WebUtils.redirectToError(
          "Mismatch between password and password confirmation", request, httpServletResponse);
      return;
    }

    SecureRandom secureRandom = new SecureRandom();
    String salt = "" + secureRandom.nextLong();
    byte[] password = User.computeHashedPassword(stringPassword, salt);
    User user = userDb.get(userId);
    if (user != null) {
      WebUtils.redirectToError(
          "There already exists a user with the ID " + userId, request, httpServletResponse);
      return;
    }

    user =
        new User(
            userId,
            userName,
            password,
            salt,
            email,
            new ArrayList<String>(),
            Config.getConfig().activateAccountsAtCreation,
            false);
    // ttt2 add confirmation by email, captcha, ...
    List<String> fieldErrors = user.checkFields();
    if (!fieldErrors.isEmpty()) {
      StringBuilder bld =
          new StringBuilder("Invalid values when trying to create user with ID ")
              .append(userId)
              .append("<br/>");
      for (String s : fieldErrors) {
        bld.append(s).append("<br/>");
      }
      WebUtils.redirectToError(bld.toString(), request, httpServletResponse);
      return;
    }

    // ttt2 2 clients can add the same userId simultaneously
    userDb.add(user);

    httpServletResponse.sendRedirect("/");
  }
Exemplo n.º 3
0
  private void handleChangePasswordPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {

    LoginInfo loginInfo = userHelpers.getLoginInfo(request);
    if (loginInfo == null) {
      WebUtils.redirectToError("Couldn't determine the current user", request, httpServletResponse);
      return;
    }

    String userId = loginInfo.userId;
    String stringCrtPassword = request.getParameter(PARAM_CURRENT_PASSWORD);
    String stringNewPassword = request.getParameter(PARAM_PASSWORD);
    String stringNewPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM);

    if (!stringNewPassword.equals(stringNewPasswordConfirm)) {
      showResult(
          "Mismatch between password and password confirmation",
          PATH_SETTINGS,
          request,
          httpServletResponse);
      return;
    }

    User user =
        userDb.get(
            userId); // ttt1 crashes for wrong ID; 2013.07.20 - no longer have an idea what this is
                     // about
    if (user == null) {
      WebUtils.redirectToError("Couldn't find the current user", request, httpServletResponse);
      return;
    }

    if (!user.checkPassword(stringCrtPassword)) {
      showResult("Incorrect current password", PATH_SETTINGS, request, httpServletResponse);
      return;
    }

    SecureRandom secureRandom = new SecureRandom();
    String salt = "" + secureRandom.nextLong();
    byte[] password = User.computeHashedPassword(stringNewPassword, salt);
    user.salt = salt;
    user.password = password;

    // ttt3 2 clients can change the password simultaneously
    userDb.add(user);

    // httpServletResponse.sendRedirect(PATH_SETTINGS);
    showResult("Password changed", PATH_SETTINGS, request, httpServletResponse);
  }
Exemplo n.º 4
0
 {
   try {
     rng = SecureRandom.getInstance("SHA1PRNG");
   } catch (NoSuchAlgorithmException e) {
     throw (new Error(e));
   }
 }
Exemplo n.º 5
0
  // Generate Random Key
  static Key makeKey(int keyBit) throws NoSuchAlgorithmException {

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    SecureRandom rd = SecureRandom.getInstance("SHA1PRNG");
    kg.init(keyBit, rd);
    Key key = kg.generateKey();
    return key;
  } // makeKey
Exemplo n.º 6
0
 /*
  * Generate random salt
  */
 private byte[] getSalt() {
   // Generate a random salt.
   byte[] salt = new byte[SALT_LEN];
   if (random == null) {
     random = new SecureRandom();
   }
   salt = random.generateSeed(SALT_LEN);
   return salt;
 }
Exemplo n.º 7
0
  public static void main(String[] args) {
    try {
      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
      SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
      keyGen.initialize(1024, random);

      KeyPair pair = keyGen.generateKeyPair();
      PrivateKey priv = pair.getPrivate();
      PublicKey pub = pair.getPublic();

      byte[] encPriv = priv.getEncoded();
      FileOutputStream privfos = new FileOutputStream("DSAPrivateKey.key");
      privfos.write(encPriv);
      privfos.close();

      byte[] encPub = pub.getEncoded();
      FileOutputStream pubfos = new FileOutputStream("DSAPublicKey.key");
      pubfos.write(encPub);
      pubfos.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 8
0
  /**
   * Installs a Linux PRNG-backed {@code SecureRandom} implementation as the default. Does nothing
   * if the implementation is already the default or if there is not need to install the
   * implementation.
   *
   * @throws SecurityException if the fix is needed but could not be applied.
   */
  private static void installLinuxPRNGSecureRandom() throws SecurityException {
    if (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2) {
      // No need to apply the fix
      return;
    }

    // Install a Linux PRNG-based SecureRandom implementation as the
    // default, if not yet installed.
    Provider[] secureRandomProviders = Security.getProviders("SecureRandom.SHA1PRNG");
    if ((secureRandomProviders == null)
        || (secureRandomProviders.length < 1)
        || (!LinuxPRNGSecureRandomProvider.class.equals(secureRandomProviders[0].getClass()))) {
      Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1);
    }

    // Assert that new SecureRandom() and
    // SecureRandom.getInstance("SHA1PRNG") return a SecureRandom backed
    // by the Linux PRNG-based SecureRandom implementation.
    SecureRandom rng1 = new SecureRandom();
    if (!LinuxPRNGSecureRandomProvider.class.equals(rng1.getProvider().getClass())) {
      throw new SecurityException(
          "new SecureRandom() backed by wrong Provider: " + rng1.getProvider().getClass());
    }

    SecureRandom rng2;
    try {
      rng2 = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
      throw new SecurityException("SHA1PRNG not available", e);
    }
    if (!LinuxPRNGSecureRandomProvider.class.equals(rng2.getProvider().getClass())) {
      throw new SecurityException(
          "SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong"
              + " Provider: "
              + rng2.getProvider().getClass());
    }
  }
Exemplo n.º 9
0
  public static void load(Properties properties)
      throws NoSuchAlgorithmException, InstantiationException, IllegalAccessException,
          ClassNotFoundException, IOException, NoSuchProviderException {
    CsrfGuard csrfGuard = SingletonHolder.instance;

    /** load simple properties * */
    csrfGuard.setLogger(
        (ILogger)
            Class.forName(
                    properties.getProperty(
                        "org.owasp.csrfguard.Logger", "org.owasp.csrfguard.log.ConsoleLogger"))
                .newInstance());
    csrfGuard.setTokenName(
        properties.getProperty("org.owasp.csrfguard.TokenName", "OWASP_CSRFGUARD"));
    csrfGuard.setTokenLength(
        Integer.parseInt(properties.getProperty("org.owasp.csrfguard.TokenLength", "32")));
    csrfGuard.setRotate(
        Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Rotate", "false")));
    csrfGuard.setTokenPerPage(
        Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.TokenPerPage", "false")));
    csrfGuard.setTokenPerPagePrecreate(
        Boolean.valueOf(
            properties.getProperty("org.owasp.csrfguard.TokenPerPagePrecreate", "false")));
    csrfGuard.setPrng(
        SecureRandom.getInstance(
            properties.getProperty("org.owasp.csrfguard.PRNG", "SHA1PRNG"),
            properties.getProperty("org.owasp.csrfguard.PRNG.Provider", "SUN")));
    csrfGuard.setNewTokenLandingPage(
        properties.getProperty("org.owasp.csrfguard.NewTokenLandingPage"));

    // default to false if newTokenLandingPage is not set; default to true if set.
    if (csrfGuard.getNewTokenLandingPage() == null) {
      csrfGuard.setUseNewTokenLandingPage(
          Boolean.valueOf(
              properties.getProperty("org.owasp.csrfguard.UseNewTokenLandingPage", "false")));
    } else {
      csrfGuard.setUseNewTokenLandingPage(
          Boolean.valueOf(
              properties.getProperty("org.owasp.csrfguard.UseNewTokenLandingPage", "true")));
    }
    csrfGuard.setSessionKey(
        properties.getProperty("org.owasp.csrfguard.SessionKey", "OWASP_CSRFGUARD_KEY"));
    csrfGuard.setAjax(Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Ajax", "false")));
    csrfGuard.setProtect(
        Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Protect", "false")));

    /** first pass: instantiate actions * */
    Map<String, IAction> actionsMap = new HashMap<String, IAction>();

    for (Object obj : properties.keySet()) {
      String key = (String) obj;

      if (key.startsWith(ACTION_PREFIX)) {
        String directive = key.substring(ACTION_PREFIX.length());
        int index = directive.indexOf('.');

        /** action name/class * */
        if (index < 0) {
          String actionClass = properties.getProperty(key);
          IAction action = (IAction) Class.forName(actionClass).newInstance();

          action.setName(directive);
          actionsMap.put(action.getName(), action);
          csrfGuard.getActions().add(action);
        }
      }
    }

    /** second pass: initialize action parameters * */
    for (Object obj : properties.keySet()) {
      String key = (String) obj;

      if (key.startsWith(ACTION_PREFIX)) {
        String directive = key.substring(ACTION_PREFIX.length());
        int index = directive.indexOf('.');

        /** action name/class * */
        if (index >= 0) {
          String actionName = directive.substring(0, index);
          IAction action = actionsMap.get(actionName);

          if (action == null) {
            throw new IOException(
                String.format("action class %s has not yet been specified", actionName));
          }

          String parameterName = directive.substring(index + 1);
          String parameterValue = properties.getProperty(key);

          action.setParameter(parameterName, parameterValue);
        }
      }
    }

    /** ensure at least one action was defined * */
    if (csrfGuard.getActions().size() <= 0) {
      throw new IOException("failure to define at least one action");
    }

    /** initialize protected, unprotected pages * */
    for (Object obj : properties.keySet()) {
      String key = (String) obj;

      if (key.startsWith(PROTECTED_PAGE_PREFIX)) {
        String directive = key.substring(PROTECTED_PAGE_PREFIX.length());
        int index = directive.indexOf('.');

        /** page name/class * */
        if (index < 0) {
          String pageUri = properties.getProperty(key);

          csrfGuard.getProtectedPages().add(Pattern.compile(pageUri));
        }
      }

      if (key.startsWith(UNPROTECTED_PAGE_PREFIX)) {
        String directive = key.substring(UNPROTECTED_PAGE_PREFIX.length());
        int index = directive.indexOf('.');

        /** page name/class * */
        if (index < 0) {
          String pageUri = properties.getProperty(key);

          csrfGuard.getUnprotectedPages().add(Pattern.compile(pageUri));
        }
      }
    }

    /** initialize protected methods * */
    String methodList = properties.getProperty("org.owasp.csrfguard.ProtectedMethods");
    if (methodList != null && methodList.trim().length() != 0) {
      for (String method : methodList.split(",")) {
        csrfGuard.getProtectedMethods().add(method.trim());
      }
    }
  }
  public static void main(String[] args) throws Exception {
    // prompt user to enter a port number

    System.out.print("Enter the port number: ");
    Scanner scan = new Scanner(System.in);
    int port = scan.nextInt();
    scan.nextLine();
    System.out.print("Enter the host name: ");
    String hostName = scan.nextLine();

    // Initialize a key pair generator with the SKIP parameters we sepcified, and genrating a pair
    // This will take a while: 5...15 seconrds

    System.out.println("Generating a Diffie-Hellman keypair: ");
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
    kpg.initialize(PARAMETER_SPEC);
    KeyPair keyPair = kpg.genKeyPair();
    System.out.println("key pair has been made...");

    // one the key pair has been generated, we want to listen on
    // a given port for a connection to come in
    // once we get a connection, we will get two streams, One for input
    // and one for output
    // open a port and wait for a connection

    ServerSocket ss = new ServerSocket(port);
    System.out.println("Listeining on port " + port + " ...");
    Socket socket = ss.accept();

    // use to output and input primitive data type

    DataOutputStream out = new DataOutputStream(socket.getOutputStream());

    // next thing to do is send our public key and receive client's
    // this corresponds to server step 3 and step 4 in the diagram

    System.out.println("Sending my public key...");
    byte[] keyBytes = keyPair.getPublic().getEncoded();
    out.writeInt(keyBytes.length);
    out.write(keyBytes);
    System.out.println("Server public key bytes: " + CryptoUtils.toHex(keyBytes));

    // receive the client's public key

    System.out.println("Receiving client's public key...");
    DataInputStream in = new DataInputStream(socket.getInputStream());
    keyBytes = new byte[in.readInt()];
    in.readFully(keyBytes);

    // create client's public key

    KeyFactory kf = KeyFactory.getInstance("DH");
    X509EncodedKeySpec x509Spec = new X509EncodedKeySpec(keyBytes);
    PublicKey clientPublicKey = kf.generatePublic(x509Spec);

    // print out client's public key bytes

    System.out.println(
        "Client public key bytes: " + CryptoUtils.toHex(clientPublicKey.getEncoded()));

    // we can now use the client's public key and
    // our own private key to perform the key agreement

    System.out.println("Performing the key agreement ... ");
    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(keyPair.getPrivate());
    ka.doPhase(clientPublicKey, true);

    // in a chat application, each character is sendt over the wire, separetly encrypted,
    // Instead of using ECB, we are goin to use CFB, with a block size of 8 bits(1byte)
    // to send each character. We will encrypt the same character in a different way
    // each time. But in order to use CFB8, we need an IVof 8 bytes. We will create
    // that IV randomly and and send it to the client. It doesn't matter if somoene
    // eavesdrops on the IV when it is sent over the wire. it's not sensitive info

    // creating the IV and sending it corresponds to step 6 and 7

    byte[] iv = new byte[8];
    SecureRandom sr = new SecureRandom();
    sr.nextBytes(iv);
    out.write(iv);

    // we generate the secret byte array we share with the client and use it
    // to create the session key (Step 8)

    byte[] sessionKeyBytes = ka.generateSecret();

    // create the session key

    SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
    DESedeKeySpec DESedeSpec = new DESedeKeySpec(sessionKeyBytes);
    SecretKey sessionKey = skf.generateSecret(DESedeSpec);

    // printout session key bytes

    System.out.println("Session key bytes: " + CryptoUtils.toHex(sessionKey.getEncoded()));

    // now use tha that session key and IV to create a CipherInputStream. We will use them to read
    // all character
    // that are sent to us by the client

    System.out.println("Creating the cipher stream ...");
    Cipher decrypter = Cipher.getInstance("DESede/CFB8/NoPadding");
    IvParameterSpec spec = new IvParameterSpec(iv);
    decrypter.init(Cipher.DECRYPT_MODE, sessionKey, spec);
    CipherInputStream cipherIn = new CipherInputStream(socket.getInputStream(), decrypter);

    // we just keep reading the input and print int to the screen, until -1 sent over

    int theCharacter = 0;
    theCharacter = cipherIn.read();
    while (theCharacter != -1) {
      System.out.print((char) theCharacter);
      theCharacter = cipherIn.read();
    }
    // once -1 is received we want to close up our stream and exit

    cipherIn.close();
    in.close();
    out.close();
    socket.close();
  }
Exemplo n.º 11
0
 private void writeNewSecret() {
   long secretValue = secureRandom.nextLong();
   secret = new Long(secretValue).toString();
   StringUtilities.writeFile(secretFile, secret);
 }
Exemplo n.º 12
0
 private String getRandomId() {
   SecureRandom secureRandom = new SecureRandom();
   return "" + secureRandom.nextLong();
 }
Exemplo n.º 13
0
  public double runTest(String exec, String seed) {
    try {
      this.exec = exec;
      readFiles();
      Random r;
      try {
        r = SecureRandom.getInstance("SHA1PRNG");
        r.setSeed(Long.parseLong(seed));
      } catch (Exception e) {
        return -1;
      }
      P = r.nextDouble() * 0.04 + 0.01;
      C = r.nextDouble() * 1e-3;
      String[] medkit = getMedkit(availableResources, requiredResources, missions, P, C);
      if (medkit == null) {
        System.err.println("Got null");
        return 0;
      }
      double[] mk = new double[10000];
      for (int i = 0; i < medkit.length; i++) {
        String[] sp = medkit[i].split(" ");
        if (sp.length != 2) {
          System.err.println("Invalid return.  Element not formatted correctly: " + medkit[i]);
          return 0;
        }
        try {
          int rid = Integer.parseInt(sp[0].substring(1));
          double cnt = Double.parseDouble(sp[1]);
          if (cnt < 0 || Double.isNaN(cnt) || Double.isInfinite(cnt)) {
            System.err.println("Your return contained an invalid double");
            return 0;
          }
          mk[rid] += cnt;
        } catch (Exception e) {
          System.err.println("Invalid return.  Element not formatted correctly: " + medkit[i]);
          return 0;
        }
      }
      String[] sample = missions;
      int[] used = new int[100000];
      ArrayList<String[]> al[] = new ArrayList[10000];
      Arrays.fill(used, -1);
      for (int i = 0; i < 10000; i++) {
        al[i] = new ArrayList();
        int j = r.nextInt(used.length);
        while (used[j] != -1) {
          j = r.nextInt(used.length);
        }
        used[j] = i;
      }
      for (int i = 0; i < sample.length; i++) {
        String[] sp = sample[i].split(" ");
        int mid = Integer.parseInt(sp[0]);
        if (used[mid - 1] != -1) {
          al[used[mid - 1]].add(sp);
        }
      }
      int evac = 0;
      for (int i = 0; i < 10000; i++) {
        double[] m = (double[]) mk.clone();
        evac += eval(m, al[i]);
      }
      System.err.println("Total evacuations: " + evac + "\n");
      if (evac <= P * 10000) {
        double score = 0;
        double m = 0, v = 0;
        for (int i = 0; i < mk.length; i++) {
          m += mass[i] * mk[i];
          v += vol[i] * mk[i];
        }
        score = C * v + m;
        System.out.println("Total mass: " + m + "\n");
        System.out.println("Total volume: " + v + "\n");
        return 1000 / score;
      } else {
        System.out.println("Evacutions exceeded allowed rate");
        return 0;
      }

    } catch (Exception e) {
      System.err.println(e.toString() + "\n");
      StackTraceElement[] ste = e.getStackTrace();
      for (int i = 0; i < ste.length; i++) System.err.println(ste[i] + "\n");
      return -1;
    }
  }