public boolean login() throws LoginException {
    // prompt for a user name and password
    if (callbackHandler == null)
      throw new LoginException(
          "Error: no CallbackHandler available "
              + "to garner authentication information from the user");

    Callback[] callbacks = new Callback[1];
    callbacks[0] = new CMCCArtifactIDCallback();

    try {
      this.callbackHandler.handle(callbacks);
      this.artifactID = ((CMCCArtifactIDCallback) callbacks[0]).getArtifactID();
      this.artifactDomain = ((CMCCArtifactIDCallback) callbacks[0]).getArtifactDomain();
      if (StringUtils.isEmpty(artifactID)) {
        succeeded = false;
        artifactID = null;
        return false;
      }
      Helper.validateArtifactID(artifactID);
    } catch (java.io.IOException e) {
      log.error(e.getMessage(), e);
      throw new LoginException(e.toString());
    } catch (UnsupportedCallbackException e) {
      log.error(e.getMessage(), e);
      throw new LoginException(
          "Error: "
              + e.getCallback().toString()
              + " not available to garner authentication information "
              + "from the user");
    }

    // print debugging information
    if (debug) {
      log.info("Resolv artifactId from cookie: " + artifactID);
    }

    // verify the artifactID/password
    boolean correct;
    try {
      correct = authenticate(artifactID, artifactDomain);
    } catch (Exception e) {
      log.error("Failure to check artifactID.", e);
      throw new LoginException(e.getMessage());
    }
    if (correct) {
      // authentication succeeded!!!
      if (debug) log.info("Success to verify artifactID: [" + artifactID + "]");
      succeeded = true;
      return true;
    } else {

      // authentication failed -- clean out state
      if (debug) log.info("Invalidate artifactID: [" + artifactID + "]");
      succeeded = false;
      artifactID = null;
      artifactDomain = null;
      return false;
    }
  }
 @Override
 public boolean login() throws LoginException {
   Callback[] callbacks = new Callback[2];
   callbacks[0] = new NameCallback(Messages.PROMPT_USERNAME.getText());
   callbacks[1] = new PasswordCallback(Messages.PROMPT_PASSWORD.getText(), false);
   try {
     mCallback.handle(callbacks);
   } catch (UnsupportedCallbackException e) {
     final LoginException ex = new FailedLoginException(e.getMessage());
     ex.initCause(e);
     throw ex;
   } catch (IOException e) {
     final LoginException ex = new FailedLoginException(e.getMessage());
     ex.initCause(e);
     throw ex;
   }
   mUsername = ((NameCallback) callbacks[0]).getName();
   if (mUsername == null || mUsername.trim().length() == 0) {
     throw new AccountNotFoundException(Messages.EMPTY_USERNAME.getText());
   }
   char[] password = ((PasswordCallback) callbacks[1]).getPassword();
   try {
     if (!ClientLoginHelper.isValidCredentials(mUsername, password)) {
       Messages.USER_LOGIN_ERROR_LOG.warn(this, mUsername);
       throw new FailedLoginException(Messages.USER_LOGIN_FAIL.getText(mUsername));
     }
   } catch (ClientInitException e) {
     Messages.USER_LOGIN_ERROR_LOG.warn(this, e, mUsername);
     LoginException exception = new FailedLoginException(Messages.USER_LOGIN_ERROR.getText());
     exception.initCause(e);
     throw exception;
   }
   SLF4JLoggerProxy.debug(this, "login done for user {}", mUsername); // $NON-NLS-1$
   return true;
 }
 public boolean login() throws LoginException {
   Callback[] callbacks = new Callback[2];
   callbacks[0] = new NameCallback("Username: "******"Password: "******" not available to obtain information from user");
   }
   String user = ((NameCallback) callbacks[0]).getName();
   char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
   return user.equals(new String(tmpPassword));
 }
예제 #4
0
  /**
   * Retrieves the user name by querying the property of {@link Constants#SECURITY_LOGIN_USERNAME}
   * through {@link AppCallbackHandler}.
   *
   * @return true if user name provided by application is set and not empty
   * @throws LoginException when the login fails
   */
  @Override
  public boolean login() throws LoginException {
    Callback[] callbacks = new Callback[1];
    callbacks[0] = new NameCallback("user name: ");
    try {
      mCallbackHandler.handle(callbacks);
    } catch (IOException e) {
      throw new LoginException(e.getMessage());
    } catch (UnsupportedCallbackException e) {
      throw new LoginException(e.getMessage());
    }

    String userName = ((NameCallback) callbacks[0]).getName();
    if (!userName.isEmpty()) {
      mUser = new User(userName);
      return true;
    }
    return false;
  }
  @Override
  public boolean login() throws LoginException {
    Callback[] callbacks = new Callback[2];

    callbacks[0] = new NameCallback("Username: "******"Password: "******" not available to obtain information from user");
    }
    user = ((NameCallback) callbacks[0]).getName();
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    if (tmpPassword == null) {
      tmpPassword = new char[0];
    }
    if (user == null) {
      if (configuration.getDefaultUser() == null) {
        throw new FailedLoginException("Both username and defaultUser are null");
      } else {
        user = configuration.getDefaultUser();
      }
    } else {
      String password =
          configuration.getUser(user) == null ? null : configuration.getUser(user).getPassword();

      if (password == null) {
        throw new FailedLoginException("User does not exist");
      }
      if (!password.equals(new String(tmpPassword))) {
        throw new FailedLoginException("Password does not match");
      }
    }
    loginSucceeded = true;

    logger.debug("login " + user);

    return loginSucceeded;
  }
 @Test
 public void testHandler() {
   DefaultCallbackHandler handler = new DefaultCallbackHandler();
   SecurityContext context = new SecurityContext();
   handler.setup(context);
   Callback[] callbacks = new Callback[3];
   callbacks[0] = new NameCallback("UserName:"******"Password:"******"Realm:");
   try {
     handler.handle(callbacks);
     Assert.assertEquals("Username", "user1", ((NameCallback) callbacks[0]).getName());
     Assert.assertEquals(
         "Password", "pass", new String(((PasswordCallback) callbacks[1]).getPassword()));
     Assert.assertEquals("Realm", "default", ((RealmCallback) callbacks[2]).getText());
   } catch (IOException e) {
     Assert.fail(e.getMessage());
   } catch (UnsupportedCallbackException e) {
     Assert.fail(e.getMessage());
   }
 }
예제 #7
0
  @Override
  public AuthStatus validateRequest(
      MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
    HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
    String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());

    try {
      boolean stale = false;
      // TODO extract from request
      long timestamp = System.currentTimeMillis();
      if (credentials != null) {
        if (LOG.isDebugEnabled()) LOG.debug("Credentials: " + credentials);
        QuotedStringTokenizer tokenizer =
            new QuotedStringTokenizer(credentials, "=, ", true, false);
        final Digest digest = new Digest(request.getMethod());
        String last = null;
        String name = null;

        while (tokenizer.hasMoreTokens()) {
          String tok = tokenizer.nextToken();
          char c = (tok.length() == 1) ? tok.charAt(0) : '\0';

          switch (c) {
            case '=':
              name = last;
              last = tok;
              break;
            case ',':
              name = null;
            case ' ':
              break;

            default:
              last = tok;
              if (name != null) {
                if ("username".equalsIgnoreCase(name)) digest.username = tok;
                else if ("realm".equalsIgnoreCase(name)) digest.realm = tok;
                else if ("nonce".equalsIgnoreCase(name)) digest.nonce = tok;
                else if ("nc".equalsIgnoreCase(name)) digest.nc = tok;
                else if ("cnonce".equalsIgnoreCase(name)) digest.cnonce = tok;
                else if ("qop".equalsIgnoreCase(name)) digest.qop = tok;
                else if ("uri".equalsIgnoreCase(name)) digest.uri = tok;
                else if ("response".equalsIgnoreCase(name)) digest.response = tok;
                break;
              }
          }
        }

        int n = checkNonce(digest.nonce, timestamp);

        if (n > 0) {
          if (login(
              clientSubject, digest.username, digest, Constraint.__DIGEST_AUTH, messageInfo)) {
            return AuthStatus.SUCCESS;
          }
        } else if (n == 0) stale = true;
      }

      if (!isMandatory(messageInfo)) {
        return AuthStatus.SUCCESS;
      }
      String domain = request.getContextPath();
      if (domain == null) domain = "/";
      response.setHeader(
          HttpHeader.WWW_AUTHENTICATE.asString(),
          "Digest realm=\""
              + realmName
              + "\", domain=\""
              + domain
              + "\", nonce=\""
              + newNonce(timestamp)
              + "\", algorithm=MD5, qop=\"auth\""
              + (useStale ? (" stale=" + stale) : ""));
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return AuthStatus.SEND_CONTINUE;
    } catch (IOException e) {
      throw new AuthException(e.getMessage());
    } catch (UnsupportedCallbackException e) {
      throw new AuthException(e.getMessage());
    }
  }
예제 #8
0
  public PrivateKey getPrivateKey(String alias) {
    RandomAccessFile raf = null;
    try {
      if (key == null && keyfile != null) // If keyfile is null, we do not load the key
      { // The private key must be loaded
        if (cert == null) { // We need the certificate for the algorithm
          if (getCertificateChain("user") == null) return null; // getCertificateChain failed...
        }

        try {
          raf = new RandomAccessFile(new File(keyfile), "r");
        } catch (FileNotFoundException ex) {
          if (!defaultfile) { // It is not an error if there is no file at the default location
            throw ex;
          }
          return null;
        }
        byte[] keydata = new byte[(int) raf.length()];
        raf.readFully(keydata);
        raf.close();
        raf = null;

        KeyFactory kf = KeyFactory.getInstance(cert[0].getPublicKey().getAlgorithm());
        try {
          KeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keydata);
          key = kf.generatePrivate(pkcs8KeySpec);
        } catch (InvalidKeySpecException ex) // The key might be password protected
        {
          EncryptedPrivateKeyInfo ePKInfo = new EncryptedPrivateKeyInfo(keydata);
          Cipher cipher;
          try {
            cipher = Cipher.getInstance(ePKInfo.getAlgName());
          } catch (
              NoSuchPaddingException
                  npex) { // Why is it not a subclass of NoSuchAlgorithmException?
            throw new NoSuchAlgorithmException(npex.getMessage(), npex);
          }
          // We call back for the password
          PasswordCallback pwdcb = new PasswordCallback(GT.tr("Enter SSL password: "******"Console is not available".equals(ucex.getMessage()))) {
              error =
                  new PSQLException(
                      GT.tr(
                          "Could not read password for SSL key file, console is not available.",
                          null),
                      PSQLState.CONNECTION_FAILURE,
                      ucex);
            } else {
              error =
                  new PSQLException(
                      GT.tr(
                          "Could not read password for SSL key file by callbackhandler {0}.",
                          new Object[] {cbh.getClass().getName()}),
                      PSQLState.CONNECTION_FAILURE,
                      ucex);
            }
            return null;
          }
          try {
            PBEKeySpec pbeKeySpec = new PBEKeySpec(pwdcb.getPassword());
            // Now create the Key from the PBEKeySpec
            SecretKeyFactory skFac = SecretKeyFactory.getInstance(ePKInfo.getAlgName());
            Key pbeKey = skFac.generateSecret(pbeKeySpec);
            // Extract the iteration count and the salt
            AlgorithmParameters algParams = ePKInfo.getAlgParameters();
            cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
            // Decrypt the encryped private key into a PKCS8EncodedKeySpec
            KeySpec pkcs8KeySpec = ePKInfo.getKeySpec(cipher);
            key = kf.generatePrivate(pkcs8KeySpec);
          } catch (GeneralSecurityException ikex) {
            error =
                new PSQLException(
                    GT.tr("Could not decrypt SSL key file {0}.", new Object[] {keyfile}),
                    PSQLState.CONNECTION_FAILURE,
                    ikex);
            return null;
          }
        }
      }
    } catch (IOException ioex) {
      if (raf != null) {
        try {
          raf.close();
        } catch (IOException ex) {
        }
        ;
      }

      error =
          new PSQLException(
              GT.tr("Could not read SSL key file {0}.", new Object[] {keyfile}),
              PSQLState.CONNECTION_FAILURE,
              ioex);
    } catch (NoSuchAlgorithmException ex) {
      error =
          new PSQLException(
              GT.tr(
                  "Could not find a java cryptographic algorithm: {0}.",
                  new Object[] {ex.getMessage()}),
              PSQLState.CONNECTION_FAILURE,
              ex);
      return null;
    }

    return key;
  }
예제 #9
0
  public boolean login() throws LoginException {
    File f = new File(usersFile);
    Properties users;
    try {
      users = new Properties(f);
    } catch (IOException ioe) {
      throw new LoginException("Unable to load user properties file " + f);
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: "******" not available to obtain information from user");
    }
    String user = ((NameCallback) callbacks[0]).getName();
    if (user == null) {
      throw new FailedLoginException("Unable to retrieve user name");
    }
    PublicKey key = ((PublickeyCallback) callbacks[1]).getPublicKey();
    if (key == null) {
      throw new FailedLoginException("Unable to retrieve public key");
    }

    // user infos container read from the users properties file
    String userInfos = null;

    try {
      userInfos = (String) users.get(user);
    } catch (NullPointerException e) {
      // error handled in the next statement
    }
    if (userInfos == null) {
      if (!this.detailedLoginExcepion) {
        throw new FailedLoginException("login failed");
      } else {
        throw new FailedLoginException("User " + user + " does not exist");
      }
    }

    // the password is in the first position
    String[] infos = userInfos.split(",");
    String storedKey = infos[0];

    // check if the stored password is flagged as encrypted
    String encryptedKey = getEncryptedPassword(storedKey);
    if (!storedKey.equals(encryptedKey)) {
      if (debug) {
        LOG.debug("The key isn't flagged as encrypted, encrypt it.");
      }
      if (debug) {
        LOG.debug("Rebuild the user informations string.");
      }
      userInfos = encryptedKey + ",";
      for (int i = 2; i < infos.length; i++) {
        if (i == (infos.length - 1)) {
          userInfos = userInfos + infos[i];
        } else {
          userInfos = userInfos + infos[i] + ",";
        }
      }
      if (debug) {
        LOG.debug("Push back the user informations in the users properties.");
      }
      users.put(user, userInfos);
      try {
        if (debug) {
          LOG.debug("Store the users properties file.");
        }
        users.save();
      } catch (IOException ioe) {
        LOG.warn("Unable to write user properties file " + f, ioe);
      }
      storedKey = encryptedKey;
    }

    // check the provided password
    if (!checkPassword(getString(key), storedKey)) {
      if (!this.detailedLoginExcepion) {
        throw new FailedLoginException("login failed");
      } else {
        throw new FailedLoginException("Public key for " + user + " does not match");
      }
    }

    principals = new HashSet<Principal>();
    principals.add(new UserPrincipal(user));
    for (int i = 1; i < infos.length; i++) {
      principals.add(new RolePrincipal(infos[i]));
    }

    users.clear();

    if (debug) {
      LOG.debug("Successfully logged in " + user);
    }
    return true;
  }