private void authenticateToKDC(
      GSSAPICallbackHandler callbackHandler, UserDomainInfo userDomainInfo)
      throws EngineDirectoryServiceException {

    try {
      loginContext = new LoginContext(LOGIN_MODULE_POLICY_NAME, callbackHandler);
      loginContext.login();
      userDomainInfo.setLoginContext(loginContext);
      if (log.isDebugEnabled()) {
        log.debug("Successful login for user " + userName);
      }
    } catch (LoginException ex) {

      // JAAS throws login exception due to various reasons.
      // We check if the login exception matches a case where the user
      // provided wrong authentication details, or
      // if there was another error - in case the user provided wrong
      // authentication details, we will abort the kdc search
      loginContext = null;
      KerberosReturnCodeParser parser = new KerberosReturnCodeParser();
      AuthenticationResult result = parser.parse(ex.getMessage());
      if (result == AuthenticationResult.OTHER || result == null) {
        // An error our error parser does not recognize
        log.error("Error from Kerberos: " + ex.getMessage());
      } else {
        StringBuilder error = new StringBuilder();
        error.append(result.getDetailedMessage());
        log.error(error.toString());
      }
      throw new EngineDirectoryServiceException(result);
    }
  }
  /**
   * Returns true if user with given username exists in kerberos database
   *
   * @param username username without Kerberos realm attached or with correct realm attached
   * @return true if user available
   */
  public boolean isUserAvailable(String username) {
    logger.debug("Checking existence of user: "******"does-not-matter",
              null,
              createJaasCallbackHandler(principal, "fake-password-which-nobody-has"),
              createJaasConfiguration());

      loginContext.login();

      throw new IllegalStateException("Didn't expect to end here");
    } catch (LoginException le) {
      String message = le.getMessage();
      logger.debug("Message from kerberos: " + message);

      checkKerberosServerAvailable(le);

      // Bit cumbersome, but seems to work with tested kerberos servers
      boolean exists = (!message.contains("Client not found"));
      return exists;
    }
  }
Exemplo n.º 3
0
	public void authenticate() throws FailedLoginException {
	    mappedGroups=null;
	    contextLoop : for (Iterator it=this.mappedLoginContextNames.keySet().iterator(); it.hasNext();) {
	        loginContextKey = it.next();
		    try {	    		        
		    	lc = new LoginContext(mappedLoginContextNames.get(loginContextKey).toString(), new CallbackHandler() {		        	
					public void handle(Callback[] callbacks) throws IOException,
							UnsupportedCallbackException {
						
						Callback[] mono=new Callback[1];
						for (int i = 0; i < callbacks.length; i++) {
							mono[0]=callbacks[i];
						    if (mono[0] instanceof NameCallback) {
						    	((NameCallback)mono[0]).setName(getUsername());
					 		} else if (mono[0] instanceof PasswordCallback) {
					 			((PasswordCallback)mono[0]).setPassword(getPassword());
					 		
					 	    } else {
					 	    	getCallbackHandler().handle(mono);
					 	    }
						}
					}
		        });		        
		        lc.login();		
		        break contextLoop;
		    } catch (LoginException e) {
		        if (!it.hasNext())
		            throw new FailedLoginException("mapped LoginContext exception : "+e.getMessage());
		    }
	    }
	    
	}
  private Subject login() throws AuthenticationException {
    try {
      LoginContext lc =
          new LoginContext(
              KerberosLdapContextSource.class.getSimpleName(), null, null, this.loginConfig);

      lc.login();

      return lc.getSubject();
    } catch (LoginException e) {
      AuthenticationException ae = new AuthenticationException(e.getMessage());
      ae.initCause(e);
      throw ae;
    }
  }
Exemplo n.º 5
0
  /**
   * Log a user into the site and create the user's session.
   *
   * @param username User's login name.
   * @param password User's unencrypted password.
   * @param request HttpServletRequest for this action.
   * @param response HttpServletResponse for this action.
   * @return Any action error messages that may have occurred.
   */
  private User loginUser(
      String username,
      String password,
      HttpServletRequest request,
      HttpServletResponse response,
      ActionErrors e) {

    User user = null;

    try {
      user = UserManager.loginUser(username, password);
    } catch (LoginException ex) {
      e.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(ex.getMessage()));
    }

    return user;
  }
Exemplo n.º 6
0
 public void shutdown() {
   for (ClientEndpoint endpoint : endpoints.values()) {
     try {
       endpoint.destroy();
     } catch (LoginException e) {
       logger.finest(e.getMessage());
     }
     try {
       final Connection conn = endpoint.getConnection();
       if (conn.live()) {
         conn.close();
       }
     } catch (Exception e) {
       logger.finest(e);
     }
   }
   endpoints.clear();
 }
Exemplo n.º 7
0
 /** Call the login method on the Jaas Login Module */
 public boolean login() {
   try {
     context.login();
     // load the user profile and save it in a User object and keep this object in the session
     usuarioLogged = loadUserProfile();
     return true;
   } catch (FailedLoginException fle) {
     error(fle.getMessage());
     return false;
   } catch (LoginException le) {
     error(le.getMessage());
     return false;
   } catch (Exception e) {
     log("SessionBean1::Exception occured while logging in" + e.getMessage());
     error("Error Loggin In");
     return false;
   }
 }
Exemplo n.º 8
0
  public boolean initLoginContext(String username, String password) {
    try {
      // Create a new instace of the callback handler to be passed to the context
      CallbackHandler cbh = new SipCallbackHandler(username, password);
      context = new LoginContext(login_config, cbh);
      log("SessionBean1::Login context created successfully");
      return true;
    } catch (LoginException le) {
      error("LoginException: " + le.getMessage());
      return false;

    } catch (Exception e) {
      error(
          "Error Creating LoginContext, \n Please make sure your application has been configured properly.");
      log("SessionBean1::Exception Occured:" + e.getMessage());
      return false;
    }
  }
Exemplo n.º 9
0
 @Override
 public void shutdown(boolean terminate) {
   for (ClientEndpoint ce : endpointManager.getEndpoints()) {
     ClientEndpointImpl endpoint = (ClientEndpointImpl) ce;
     try {
       endpoint.destroy();
     } catch (LoginException e) {
       logger.finest(e.getMessage());
     }
     try {
       final Connection conn = endpoint.getConnection();
       if (conn.isAlive()) {
         conn.close("Shutdown of ClientEngine", null);
       }
     } catch (Exception e) {
       logger.finest(e);
     }
   }
   endpointManager.clear();
   ownershipMappings.clear();
 }
Exemplo n.º 10
0
  @Override
  protected List<ConnectorError> validateValues() {
    final List<ConnectorError> errors = new ArrayList<ConnectorError>();

    testEmptyVar(sugarSoapPort, "sugarSoapPort", errors);
    testEmptyVar(applicationName, "applicationName", errors);
    testEmptyVar(user, "user", errors);
    testEmptyVar(module, "module", errors);

    try {
      this.initSugarCrmSoapClient(sugarSoapPort, user, password, applicationName);
    } catch (MalformedURLException e) {
      errors.add(
          new ConnectorError(
              "sugarSoapPort", new MalformedURLException("URL not valid! " + e.getMessage())));
    } catch (LoginException e) {
      errors.add(
          new ConnectorError(
              "user", new LoginException("Wrong user or password! " + e.getMessage())));
    } catch (RemoteException e) {
      errors.add(
          new ConnectorError(
              "sugarSoapPort",
              new RemoteException("Error accessing Sugar services! " + e.getMessage())));
    } catch (ServiceException e) {
      errors.add(
          new ConnectorError(
              "sugarSoapPort",
              new ServiceException("Error accessing Sugar services! " + e.getMessage())));
    } catch (Exception e) {
      errors.add(
          new ConnectorError(
              "sugarSoapPort", new Exception("Exception occurred! " + e.getMessage())));
    }

    return errors;
  }
  /**
   * Perform the JAAS login and run the command within a privileged scope.
   *
   * @param privilegedSendMessage the PrivilegedSendMessage
   * @return The result Document
   */
  private Document runPrivileged(final PrivilegedSendMessage privilegedSendMessage) {
    final CallbackHandler handler = new ProvidedAuthCallback(username, password);
    Document result;
    try {
      final LoginContext lc =
          new LoginContext("", null, handler, new KerberosJaasConfiguration(kerberosDebug));
      lc.login();

      result = Subject.doAs(lc.getSubject(), privilegedSendMessage);
    } catch (LoginException e) {
      throw new WinRMRuntimeIOException(
          "Login failure sending message on " + getTargetURL() + " error: " + e.getMessage(),
          privilegedSendMessage.getRequestDocument(),
          null,
          e);
    } catch (PrivilegedActionException e) {
      throw new WinRMRuntimeIOException(
          "Failure sending message on " + getTargetURL() + " error: " + e.getMessage(),
          privilegedSendMessage.getRequestDocument(),
          null,
          e.getException());
    }
    return result;
  }
 protected void checkKerberosServerAvailable(LoginException le) {
   if (le.getMessage().contains("Port Unreachable")) {
     throw new ModelException("Kerberos unreachable", le);
   }
 }
Exemplo n.º 13
0
  void handleJoinRequest(JoinRequest joinRequest) {
    final long now = Clock.currentTimeMillis();
    String msg =
        "Handling join from "
            + joinRequest.address
            + ", inProgress: "
            + joinInProgress
            + (timeToStartJoin > 0 ? ", timeToStart: " + (timeToStartJoin - now) : "");
    logger.log(Level.FINEST, msg);
    boolean validJoinRequest;
    try {
      validJoinRequest = node.validateJoinRequest(joinRequest);
    } catch (Exception e) {
      validJoinRequest = false;
    }
    final Connection conn = joinRequest.getConnection();
    if (validJoinRequest) {
      final MemberImpl member = getMember(joinRequest.address);
      if (member != null) {
        if (joinRequest.getUuid().equals(member.getUuid())) {
          String message = "Ignoring join request, member already exists.. => " + joinRequest;
          logger.log(Level.FINEST, message);

          // send members update back to node trying to join again...
          final long clusterTime = node.getClusterImpl().getClusterTime();
          sendProcessableTo(new MembersUpdateCall(lsMembers, clusterTime), conn);
          sendProcessableTo(new SyncProcess(), conn);
          return;
        }
        // If this node is master then remove old member and process join request.
        // If requesting address is equal to master node's address, that means master node
        // somehow disconnected and wants to join back.
        // So drop old member and process join request if this node becomes master.
        if (isMaster() || member.getAddress().equals(getMasterAddress())) {
          logger.log(
              Level.WARNING,
              "New join request has been received from an existing endpoint! => "
                  + member
                  + " Removing old member and processing join request...");
          // If existing connection of endpoint is different from current connection
          // destroy it, otherwise keep it.
          //                    final Connection existingConnection =
          // node.connectionManager.getConnection(joinRequest.address);
          //                    final boolean destroyExistingConnection = existingConnection !=
          // conn;
          doRemoveAddress(member.getAddress(), false);
        }
      }
      if (!node.getConfig().getNetworkConfig().getJoin().getMulticastConfig().isEnabled()) {
        if (node.isActive() && node.joined() && node.getMasterAddress() != null && !isMaster()) {
          sendProcessableTo(new Master(node.getMasterAddress()), conn);
        }
      }
      if (isMaster() && node.joined() && node.isActive()) {
        final MemberInfo newMemberInfo =
            new MemberInfo(joinRequest.address, joinRequest.nodeType, joinRequest.getUuid());
        if (node.securityContext != null && !setJoins.contains(newMemberInfo)) {
          final ILogger securityLogger = node.loggingService.getLogger("com.hazelcast.security");
          final Credentials cr = joinRequest.getCredentials();
          if (cr == null) {
            securityLogger.log(
                Level.SEVERE,
                "Expecting security credentials "
                    + "but credentials could not be found in JoinRequest!");
            sendAuthFail(conn);
            return;
          } else {
            try {
              LoginContext lc = node.securityContext.createMemberLoginContext(cr);
              lc.login();
            } catch (LoginException e) {
              securityLogger.log(
                  Level.SEVERE,
                  "Authentication has failed for "
                      + cr.getPrincipal()
                      + '@'
                      + cr.getEndpoint()
                      + " => ("
                      + e.getMessage()
                      + ")");
              securityLogger.log(Level.FINEST, e.getMessage(), e);
              sendAuthFail(conn);
              return;
            }
          }
        }
        if (joinRequest.to != null && !joinRequest.to.equals(thisAddress)) {
          sendProcessableTo(new Master(node.getMasterAddress()), conn);
          return;
        }
        if (!joinInProgress) {
          if (firstJoinRequest != 0
              && now - firstJoinRequest >= MAX_WAIT_SECONDS_BEFORE_JOIN * 1000) {
            startJoin();
          } else {
            if (setJoins.add(newMemberInfo)) {
              sendProcessableTo(new Master(node.getMasterAddress()), conn);
              if (firstJoinRequest == 0) {
                firstJoinRequest = now;
              }
              if (now - firstJoinRequest < MAX_WAIT_SECONDS_BEFORE_JOIN * 1000) {
                timeToStartJoin = now + WAIT_MILLIS_BEFORE_JOIN;
              }
            }
            if (now > timeToStartJoin) {
              startJoin();
            }
          }
        }
      }
    } else {
      conn.close();
    }
  }