protected String[] authenticate() throws IOException, UnsupportedCallbackException {

    NameCallback nameCallback = new NameCallback("name: ");
    PasswordCallback passwordCallback = new PasswordCallback("password: ", false);

    _callbackHandler.handle(new Callback[] {nameCallback, passwordCallback});

    String name = nameCallback.getName();

    String password = null;
    char[] passwordChar = passwordCallback.getPassword();

    if (passwordChar != null) {
      password = new String(passwordChar);
    }

    if (name == null) {
      return new String[] {StringPool.BLANK, StringPool.BLANK};
    }

    try {
      long userId = GetterUtil.getLong(name);

      if (UserLocalServiceUtil.authenticateForJAAS(userId, password)) {
        return new String[] {name, password};
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    return null;
  }
  @Override
  public boolean login() throws LoginException {
    if (callbackHandler == null) {
      throw new LoginException("Pas de callbackHandler");
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Login :"******"Mot de passe :", false);

    try {
      callbackHandler.handle(callbacks);
    } catch (IOException e) {
      throw new LoginException("IOException");
    } catch (UnsupportedCallbackException e) {
      throw new LoginException("UnsupportedCallbackException");
    }

    NameCallback nameCallback = (NameCallback) callbacks[0];
    PasswordCallback passwordCallback = (PasswordCallback) callbacks[1];

    String name = nameCallback.getName();
    String password = new String(passwordCallback.getPassword());

    return true;
  }
  private List<KeyStore> initDnieJava(
      final PasswordCallback pssCallBack, final Object parentComponent)
      throws AOKeyStoreManagerException, IOException {
    final Provider p;
    if (Security.getProvider(AOKeyStore.DNIEJAVA.getProviderName()) == null) {
      try {
        p =
            (Provider)
                Class.forName("es.gob.jmulticard.jse.provider.DnieProvider")
                    .newInstance(); //$NON-NLS-1$
        Security.addProvider(p);
      } catch (final Exception e) {
        throw new AOKeyStoreManagerException(
            "No se ha podido instanciar e instalar el proveedor 100% Java para DNIe de Afirma: "
                + e, //$NON-NLS-1$
            e);
      }
    }

    try {
      final Class<?> managerClass =
          Class.forName(
              "es.gob.jmulticard.ui.passwordcallback.PasswordCallbackManager"); //$NON-NLS-1$
      final Method setDialogOwnerFrameMethod =
          managerClass.getMethod("setDialogOwner", Component.class); // $NON-NLS-1$
      setDialogOwnerFrameMethod.invoke(null, parentComponent);
    } catch (final Exception e) {
      LOGGER.warning(
          "No se ha podido establecer el componente padre para los dialogos del almacen: "
              + e); //$NON-NLS-1$
    }

    // Inicializamos
    try {
      this.ks = KeyStore.getInstance(this.ksType.getProviderName());
    } catch (final Exception e) {
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen DNIe 100% Java: " + e, e); // $NON-NLS-1$
    }

    LOGGER.info("Cargando KeyStore DNIe 100% Java"); // $NON-NLS-1$
    try {
      this.ks.load(null, pssCallBack == null ? null : pssCallBack.getPassword());
    } catch (final NoSuchAlgorithmException e) {
      throw new AOKeyStoreManagerException(
          "Error de algoritmo al obtener el almacen DNIe 100% Java: " + e, e); // $NON-NLS-1$
    } catch (final CertificateException e) {
      throw new AOKeyStoreManagerException(
          "Error de certificado al obtener el almacen DNIe 100% Java: " + e, e); // $NON-NLS-1$
    }

    final List<KeyStore> ret = new ArrayList<KeyStore>(1);
    ret.add(this.ks);
    return ret;
  }
  private List<KeyStore> initSingle(final InputStream store, final PasswordCallback pssCallBack)
      throws AOKeyStoreManagerException, IOException {
    if (store == null) {
      throw new AOKeyStoreManagerException(
          "Es necesario proporcionar el fichero X.509 o PKCS#7"); //$NON-NLS-1$
    }

    final Provider pkcs7Provider;
    try {
      pkcs7Provider =
          (Provider)
              Class.forName("es.gob.afirma.keystores.single.SingleCertKeyStoreProvider")
                  .newInstance(); //$NON-NLS-1$
    } catch (final Exception e) {
      throw new MissingLibraryException(
          "No se ha podido instanciar el proveedor SingleCertKeyStoreProvider: " + e,
          e); //$NON-NLS-1$
    }
    Security.addProvider(pkcs7Provider);

    try {
      this.ks = KeyStore.getInstance(this.ksType.getProviderName(), pkcs7Provider);
    } catch (final Exception e) {
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen PKCS#7 / X.509", e); // $NON-NLS-1$
    }

    try {
      this.ks.load(store, pssCallBack != null ? pssCallBack.getPassword() : null);
    } catch (final IOException e) {
      if (e.getCause() instanceof UnrecoverableKeyException
          || e.getCause() instanceof BadPaddingException) {
        throw new IOException("Contrasena invalida: " + e, e); // $NON-NLS-1$
      }
      throw new AOKeyStoreManagerException(
          "No se ha podido abrir el almacen PKCS#7 / X.509 solicitado", e); // $NON-NLS-1$
    } catch (final CertificateException e) {
      throw new AOKeyStoreManagerException(
          "No se han podido cargar los certificados del almacen PKCS#7 / X.509 solicitado",
          e); //$NON-NLS-1$
    } catch (final NoSuchAlgorithmException e) {
      throw new AOKeyStoreManagerException(
          "No se ha podido verificar la integridad del almacen PKCS#7 / X.509 solicitado",
          e); //$NON-NLS-1$
    }
    final List<KeyStore> ret = new ArrayList<KeyStore>(1);
    ret.add(this.ks);
    try {
      store.close();
    } catch (final Exception e) {
      // Ignoramos errores en el cierre
    }
    return ret;
  }
示例#5
0
    public void setPassword(Principal principal, PasswordCallback callback)
        throws IOException, AccountNotFoundException {
      // Let the read DB set the password
      _realPricipalDatabase.setPassword(principal, callback);

      // Retrieve the setpassword
      char[] plainPassword = callback.getPassword();

      char[] hexPassword = toHex(plainPassword);

      callback.setPassword(hexPassword);
    }
 /**
  * Obtiene la clave privada de un certificado.
  *
  * @param alias Alias del certificado
  * @param pssCallback <i>CallBback</i> para obtener la contrase&ntilde;a del certificado que
  *     contiene la clave
  * @return Clave privada del certificado correspondiente al alias
  * @throws KeyStoreException Cuando ocurren errores en el tratamiento del almac&eacute;n de claves
  * @throws NoSuchAlgorithmException Cuando no se puede identificar el algoritmo para la
  *     recuperaci&oacute;n de la clave.
  * @throws UnrecoverableEntryException Si la contrase&ntilde;a proporcionada no es v&aacute;lida
  *     para obtener la clave privada
  * @throws es.gob.afirma.core.AOCancelledOperationException Cuando el usuario cancela el proceso
  *     antes de que finalice
  */
 public KeyStore.PrivateKeyEntry getKeyEntry(
     final String alias, final PasswordCallback pssCallback)
     throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
   if (this.ks == null) {
     throw new IllegalStateException(
         "Se han pedido claves a un almacen no inicializado"); //$NON-NLS-1$
   }
   return (KeyStore.PrivateKeyEntry)
       this.ks.getEntry(
           alias,
           pssCallback != null
               ? new KeyStore.PasswordProtection(pssCallback.getPassword())
               : null);
 }
    private Object[] getUserPass() throws LoginException {
      NameCallback nameCB = new NameCallback("username");
      PasswordCallback passwordCB = new PasswordCallback("password", false);

      try {
        callbackHandler.handle(new Callback[] {nameCB, passwordCB});
      } catch (IOException | UnsupportedCallbackException e) {
        throw new LoginException(e.toString());
      }

      String username = nameCB.getName();
      char[] password = passwordCB.getPassword();
      passwordCB.clearPassword();
      return new Object[] {username, password};
    }
  public void initialize(
      Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
    this.subject = subject;

    try {
      TextInputCallback textCallback = new TextInputCallback("prompt");
      NameCallback nameCallback = new NameCallback("prompt");
      PasswordCallback passwordCallback = new PasswordCallback("prompt", false);

      callbackHandler.handle(new Callback[] {textCallback, nameCallback, passwordCallback});

      passwordFromLoginPage = new String(passwordCallback.getPassword());
      userFromLoginPage = nameCallback.getName();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  private List<KeyStore> initJava(final InputStream store, final PasswordCallback pssCallBack)
      throws AOKeyStoreManagerException, IOException {
    // Suponemos que el proveedor SunJSSE esta instalado. Hay que tener
    // cuidado con esto
    // si alguna vez se usa JSS, que a veces lo retira
    if (store == null) {
      throw new IOException("Es necesario proporcionar el fichero KeyStore"); // $NON-NLS-1$
    }

    try {
      this.ks = KeyStore.getInstance(this.ksType.getProviderName());
    } catch (final Exception e) {
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen JavaKeyStore", e); // $NON-NLS-1$
    }

    // TODO: Revisar si el KeyStore de Java requiere contrasena
    try {
      this.ks.load(store, pssCallBack != null ? pssCallBack.getPassword() : null);
    } catch (final IOException e) {
      if (e.getCause() instanceof UnrecoverableKeyException
          || e.getCause() instanceof BadPaddingException) {
        throw new IOException("Contrasena invalida: " + e, e); // $NON-NLS-1$
      }
    } catch (final CertificateException e) {
      throw new AOKeyStoreManagerException(
          "No se han podido cargar los certificados del almacen JavaKeyStore solicitado",
          e); //$NON-NLS-1$
    } catch (final NoSuchAlgorithmException e) {
      throw new AOKeyStoreManagerException(
          "No se ha podido verificar la integridad del almacen JavaKeyStore solicitado",
          e); //$NON-NLS-1$
    }
    final List<KeyStore> ret = new ArrayList<KeyStore>(1);
    ret.add(this.ks);
    try {
      store.close();
    } catch (final Exception e) {
      // Ignoramos errores en el cierre
    }
    return ret;
  }
示例#10
0
  public ConnectionProxy connect(Properties info) throws SQLException {
    this.properties = info;

    PasswordCallback passwordCallback = this.config.getPasswordCallback();

    if (passwordCallback != null) {
      char[] chars = passwordCallback.getPassword();
      String password = new String(chars);
      info.put("password", password);
    }

    NameCallback userCallback = this.config.getUserCallback();
    if (userCallback != null) {
      String user = userCallback.getName();
      info.put("user", user);
    }

    FilterChain chain = new FilterChainImpl(this);
    return chain.connection_connect(info);
  }
示例#11
0
  private void getSaltedPasswordFromPasswordCallback(NameCallback nameCallback, ByteStringBuilder b)
      throws SaslException {
    final PasswordCallback passwordCallback = new PasswordCallback("User password", false);
    try {
      tryHandleCallbacks(nameCallback, passwordCallback);
    } catch (UnsupportedCallbackException e) {
      final Callback callback = e.getCallback();
      if (callback == nameCallback) {
        throw log.saslCallbackHandlerDoesNotSupportUserName(getMechanismName(), e);
      } else if (callback == passwordCallback) {
        return; // PasswordCallback not supported
      } else {
        throw log.saslCallbackHandlerFailedForUnknownReason(getMechanismName(), e);
      }
    }

    salt = ScramUtil.generateSalt(16, getRandom());
    algorithmSpec = new IteratedSaltedPasswordAlgorithmSpec(minimumIterationCount, salt);

    char[] passwordChars = passwordCallback.getPassword();
    passwordCallback.clearPassword();
    getSaltedPasswordFromPasswordChars(passwordChars, b);
  }
示例#12
0
  /**
   * Loads the keystore using the given <code>KeyStore.LoadStoreParameter</code>.
   *
   * <p>Note that if this KeyStore has already been loaded, it is reinitialized and loaded again
   * from the given parameter.
   *
   * @param param the <code>KeyStore.LoadStoreParameter</code> that specifies how to load the
   *     keystore, which may be <code>null</code>
   * @exception IllegalArgumentException if the given <code>KeyStore.LoadStoreParameter</code> input
   *     is not recognized
   * @exception IOException if there is an I/O or format problem with the keystore data. If the
   *     error is due to an incorrect <code>ProtectionParameter</code> (e.g. wrong password) the
   *     {@link Throwable#getCause cause} of the <code>IOException</code> should be an <code>
   *     UnrecoverableKeyException</code>
   * @exception NoSuchAlgorithmException if the algorithm used to check the integrity of the
   *     keystore cannot be found
   * @exception CertificateException if any of the certificates in the keystore could not be loaded
   * @since 1.5
   */
  public void engineLoad(KeyStore.LoadStoreParameter param)
      throws IOException, NoSuchAlgorithmException, CertificateException {

    if (param == null) {
      engineLoad((InputStream) null, (char[]) null);
      return;
    }

    if (param instanceof KeyStore.SimpleLoadStoreParameter) {
      ProtectionParameter protection = param.getProtectionParameter();
      char[] password;
      if (protection instanceof PasswordProtection) {
        password = ((PasswordProtection) protection).getPassword();
      } else if (protection instanceof CallbackHandlerProtection) {
        CallbackHandler handler = ((CallbackHandlerProtection) protection).getCallbackHandler();
        PasswordCallback callback = new PasswordCallback("Password: "******"Could not obtain password", e);
        }
        password = callback.getPassword();
        callback.clearPassword();
        if (password == null) {
          throw new NoSuchAlgorithmException("No password provided");
        }
      } else {
        throw new NoSuchAlgorithmException(
            "ProtectionParameter must" + " be PasswordProtection or CallbackHandlerProtection");
      }
      engineLoad(null, password);
      return;
    }

    throw new UnsupportedOperationException();
  }
  /** {@inheritDoc} */
  public boolean login() throws LoginException {
    try {
      final NameCallback nameCb = new NameCallback("Enter user: "******"Enter user password: "******"Authentication failed", authEx);
        }
        throw new LoginException(authEx != null ? authEx.getMessage() : "Authentication failed");
      } else {
        if (this.setLdapPrincipal) {
          final LdapPrincipal lp = new LdapPrincipal(nameCb.getName());
          if (attrs != null) {
            lp.getLdapAttributes().addAttributes(attrs);
          }
          this.principals.add(lp);
        }

        final String loginDn = this.auth.getDn(nameCb.getName());
        if (loginDn != null && this.setLdapDnPrincipal) {
          final LdapDnPrincipal lp = new LdapDnPrincipal(loginDn);
          if (attrs != null) {
            lp.getLdapAttributes().addAttributes(attrs);
          }
          this.principals.add(lp);
        }
        if (this.setLdapCredential) {
          this.credentials.add(new LdapCredential(passCb.getPassword()));
        }
        this.storeCredentials(nameCb, passCb, loginDn);
      }
    } catch (NamingException e) {
      if (this.logger.isDebugEnabled()) {
        this.logger.debug("Error occured attempting authentication", e);
      }
      this.loginSuccess = false;
      throw new LoginException(e != null ? e.getMessage() : "Authentication Error");
    } finally {
      this.auth.close();
    }
    return true;
  }
  public byte[] evaluateChallenge(final byte[] challenge) throws SaslException {
    if (challenge == null) {
      throw new SaslException("null challenge");
    }
    try {
      final String username;
      final char[] password;
      Callback[] callbacks;

      if ((!properties.containsKey(Registry.SASL_USERNAME))
          && (!properties.containsKey(Registry.SASL_PASSWORD))) {
        callbacks = new Callback[2];

        final NameCallback nameCB;
        final String defaultName = System.getProperty("user.name");
        if (defaultName == null) {
          nameCB = new NameCallback("username: "******"username: "******"password: "******"user.name");
          if (defaultName == null) {
            nameCB = new NameCallback("username: "******"username: "******"password: "******"null password supplied");
      }
      final byte[] digest;
      try {
        digest = CramMD5Util.createHMac(password, challenge);
      } catch (InvalidKeyException x) {
        throw new AuthenticationException("evaluateChallenge()", x);
      }
      final String response = username + " " + Util.toString(digest).toLowerCase();
      this.complete = true;

      return response.getBytes("UTF-8");
    } catch (UnsupportedCallbackException x) {
      throw new AuthenticationException("evaluateChallenge()", x);
    } catch (IOException x) {
      throw new AuthenticationException("evaluateChallenge()", x);
    }
  }
  /**
   * Inicializa un almac&eacute;n PKCS#11.
   *
   * @param pssCallBack Callback para la recuperaci&oacute;n de la contrase&ntilde;a del
   *     almac&eacute;n.
   * @param params Parametros adicionales para la configuraci&oacute;n del almac&eacute;n.
   * @return Array con los almacenes configurados.
   * @throws AOKeyStoreManagerException Cuando ocurre un error durante la inicializaci&oacute;n.
   * @throws IOException Cuando se indique una contrase&ntilde;a incorrecta para la apertura del
   *     almac&eacute;n.
   * @throws es.gob.afirma.keystores.main.common.MissingSunPKCS11Exception Si no se encuentra la
   *     biblioteca SunPKCS11
   */
  private List<KeyStore> initPKCS11(final PasswordCallback pssCallBack, final Object[] params)
      throws AOKeyStoreManagerException, IOException {
    // En el "params" debemos traer los parametros:
    // [0] -p11lib: Biblioteca PKCS#11, debe estar en el Path (Windows) o en el LD_LIBRARY_PATH
    // (UNIX, Linux, Mac OS X)
    // [1] -desc: Descripcion del token PKCS#11 (opcional)
    // [2] -slot: Numero de lector de tarjeta (Sistema Operativo) [OPCIONAL]

    // Anadimos el proveedor PKCS11 de Sun
    if (params == null || params.length < 2) {
      throw new IOException(
          "No se puede acceder al KeyStore PKCS#11 si no se especifica la biblioteca"); //$NON-NLS-1$
    }
    final String p11lib;
    if (params[0] != null) {
      p11lib = params[0].toString();
    } else {
      throw new IllegalArgumentException(
          "No se puede acceder al KeyStore PKCS#11 si se especifica una biblioteca nula"); //$NON-NLS-1$
    }

    // Numero de lector
    Integer slot = null;
    if (params.length >= 3 && params[2] instanceof Integer) {
      slot = (Integer) params[2];
    }

    // Agregamos un nombre a cada PKCS#11 para asegurarnos de no se
    // agregan mas de una vez como provider.
    // Si ya se cargo el PKCS#11 anteriormente, se volvera a instanciar.
    final String p11ProviderName = new File(p11lib).getName().replace('.', '_').replace(' ', '_');
    Provider p11Provider = Security.getProvider("SunPKCS11-" + p11ProviderName); // $NON-NLS-1$

    if (p11Provider == null) {

      Constructor<?> sunPKCS11Contructor;
      try {
        sunPKCS11Contructor =
            Class.forName("sun.security.pkcs11.SunPKCS11")
                .getConstructor(InputStream.class); // $NON-NLS-1$
      } catch (final Exception e) {
        throw new MissingSunPKCS11Exception(e);
      }

      final byte[] config =
          KeyStoreUtilities.createPKCS11ConfigFile(p11lib, p11ProviderName, slot).getBytes();
      try {
        p11Provider = (Provider) sunPKCS11Contructor.newInstance(new ByteArrayInputStream(config));
      } catch (final Exception e) {
        // El PKCS#11 del DNIe a veces falla a la primera pero va
        // correctamente a la segunda
        // asi que reintentamos una vez mas
        try {
          p11Provider =
              (Provider) sunPKCS11Contructor.newInstance(new ByteArrayInputStream(config));
        } catch (final Exception ex) {
          throw new AOKeyStoreManagerException(
              "No se ha podido instanciar el proveedor SunPKCS11 para la la biblioteca " + p11lib,
              ex); //$NON-NLS-1$
        }
      }
      Security.addProvider(p11Provider);
    } else {
      LOGGER.info(
          "El proveedor SunPKCS11 solicitado ya estaba instanciado, se reutilizara esa instancia: "
              + p11Provider.getName()); // $NON-NLS-1$
    }

    try {
      this.ks = KeyStore.getInstance(this.ksType.getProviderName(), p11Provider);
    } catch (final Exception e) {
      Security.removeProvider(p11Provider.getName());
      p11Provider = null;
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen PKCS#11", e); // $NON-NLS-1$
    }

    try {
      this.ks.load(null, pssCallBack != null ? pssCallBack.getPassword() : null);
    } catch (final IOException e) {
      if (e.getCause() instanceof UnrecoverableKeyException
          || e.getCause() instanceof BadPaddingException) {
        throw new IOException("Contrasena invalida: " + e, e); // $NON-NLS-1$
      }
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen PKCS#11 solicitado", e); // $NON-NLS-1$
    } catch (final CertificateException e) {
      Security.removeProvider(p11Provider.getName());
      p11Provider = null;
      throw new AOKeyStoreManagerException(
          "No se han podido cargar los certificados del almacen PKCS#11 solicitado",
          e); //$NON-NLS-1$
    } catch (final NoSuchAlgorithmException e) {
      Security.removeProvider(p11Provider.getName());
      p11Provider = null;
      throw new AOKeyStoreManagerException(
          "No se ha podido verificar la integridad del almacen PKCS#11 solicitado",
          e); //$NON-NLS-1$
    }
    final List<KeyStore> ret = new ArrayList<KeyStore>(1);
    ret.add(this.ks);
    return ret;
  }
示例#16
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;
  }
示例#17
0
  @Override
  protected boolean login(final NameCallback nameCb, final PasswordCallback passCb)
      throws LoginException {
    try {
      getCredentials(nameCb, passCb, false);
      authRequest.setUser(new User(nameCb.getName()));
      authRequest.setCredential(new Credential(passCb.getPassword()));

      AuthenticationResponse response = auth.authenticate(authRequest);
      LdapEntry entry = null;
      if (response.getResult()) {
        entry = response.getLdapEntry();
        if (entry != null) {
          roles.addAll(LdapRole.toRoles(entry));
          if (defaultRole != null && !defaultRole.isEmpty()) {
            roles.addAll(defaultRole);
          }
        }
        loginSuccess = true;
      } else {
        if (tryFirstPass) {
          getCredentials(nameCb, passCb, true);
          response = auth.authenticate(authRequest);
          if (response.getResult()) {
            entry = response.getLdapEntry();
            if (entry != null) {
              roles.addAll(LdapRole.toRoles(entry));
            }
            if (defaultRole != null && !defaultRole.isEmpty()) {
              roles.addAll(defaultRole);
            }
            loginSuccess = true;
          } else {
            loginSuccess = false;
          }
        } else {
          loginSuccess = false;
        }
      }

      if (!loginSuccess) {
        logger.debug("Authentication failed: " + response);
        throw new LoginException("Authentication failed: " + response);
      } else {
        if (setLdapPrincipal) {
          principals.add(new LdapPrincipal(nameCb.getName(), entry));
        }

        final String loginDn = response.getResolvedDn();
        if (loginDn != null && setLdapDnPrincipal) {
          principals.add(new LdapDnPrincipal(loginDn, entry));
        }

        if (setLdapCredential) {
          credentials.add(new LdapCredential(passCb.getPassword()));
        }
        storeCredentials(nameCb, passCb, loginDn);
      }
    } catch (LdapException e) {
      logger.debug("Error occurred attempting authentication", e);
      loginSuccess = false;
      throw new LoginException(e != null ? e.getMessage() : "Authentication Error");
    }
    return true;
  }
  public boolean login() throws LoginException {
    System.out.println("Login Module - login called");
    if (callbackHandler == null) {
      throw new LoginException("Oops, callbackHandler is null");
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("name:");
    callbacks[1] = new PasswordCallback("password:"******"Oops, IOException calling handle on callbackHandler");
    } catch (UnsupportedCallbackException e) {
      throw new LoginException(
          "Oops, UnsupportedCallbackException calling handle on callbackHandler");
    }

    NameCallback nameCallback = (NameCallback) callbacks[0];
    PasswordCallback passwordCallback = (PasswordCallback) callbacks[1];
    loggedUser = new User();
    loggedUser.setUsername(nameCallback.getName());
    loggedUser.setPassword(String.valueOf(passwordCallback.getPassword()));

    MyDatabase database = null;
    try {
      database = new MyDatabase(options);
      database.createDatabaseConnection();
      if (database.loginUser(loggedUser.getUsername(), loggedUser.getPassword())) {

        loggedUser.setRole(database.getUserRole(loggedUser));
        System.out.println("Il database ha tornato il valore");
        succeeded = true;
      } else {
        System.out.println("Il database non ha tornato il valore");

        succeeded = false;
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return succeeded;
  }
  @Override
  public boolean login() throws LoginException {
    NameCallback nameCallback = new NameCallback("Username");
    PasswordCallback passwordCallback = new PasswordCallback("Password", false);

    Callback callbacks[] = new Callback[] {nameCallback, passwordCallback};

    try {
      callbackHandler.handle(callbacks);
    } catch (java.io.IOException e) {
      throw new LoginException(e.toString());
    } catch (UnsupportedCallbackException e) {
      throw new LoginException("Error: " + e.getCallback().toString());
    }

    boolean success;
    ParticipantId id = null;

    String address = nameCallback.getName();
    if (!address.contains(ParticipantId.DOMAIN_PREFIX)) {
      address = address + ParticipantId.DOMAIN_PREFIX + AccountStoreHolder.getDefaultDomain();
    }

    try {
      id = ParticipantId.of(address);
      AccountData account = accountStore.getAccount(id);
      char[] password = passwordCallback.getPassword();

      if (account == null) {
        // The user doesn't exist. Auth failed.
        success = false;
      } else if (!account.isHuman()) {
        // The account is owned by a robot. Auth failed.
        success = false;
      } else if (password == null) {
        // Null password provided by callback. We require a password (even an empty one).
        success = false;
      } else if (!account.asHuman().getPasswordDigest().verify(password)) {
        // The supplied password doesn't match. Auth failed.
        success = false;
      } else {
        success = true;
      }
    } catch (InvalidParticipantAddress e) {
      // The supplied user address is invalid. Auth failed.
      success = false;
    } catch (PersistenceException e) {
      LOG.severe("Failed to retreive account data for " + id, e);
      throw new LoginException(
          "An unexpected error occured while trying to retrieve account information!");
    }

    // The password is zeroed before it gets GC'ed for memory security.
    passwordCallback.clearPassword();

    if (success) {
      principal = new ParticipantPrincipal(id);
      status = Status.OK;
      return true;
    } else {
      return false;
    }
  }