Search in sources :

Example 1 with AccessToken

use of org.eclipse.kapua.service.authentication.AccessToken in project kapua by eclipse.

the class KapuaSecurityBrokerFilter method addExternalConnection.

private void addExternalConnection(ConnectionContext context, ConnectionInfo info) throws Exception {
    // Clean-up credentials possibly associated with the current thread by previous connection.
    ThreadContext.unbindSubject();
    Context loginTotalContext = metricLoginAddConnectionTime.time();
    String username = info.getUserName();
    String password = info.getPassword();
    String clientId = info.getClientId();
    String clientIp = info.getClientIp();
    ConnectionId connectionId = info.getConnectionId();
    List<String> authDestinations = null;
    if (logger.isDebugEnabled()) {
        authDestinations = new ArrayList<>();
    }
    try {
        // Build KapuaUsername
        // User username = User.parse(username);//KapuaUserName
        logger.info("User name {} - client id {}", new Object[] { username, clientId });
        Context loginPreCheckTimeContext = metricLoginPreCheckTime.time();
        // 1) validate client id
        // Check the device Mqtt ClientId
        // TODO move to deviceservice
        // MqttUtils.checkDeviceClientId(clientId);
        loginPreCheckTimeContext.stop();
        Context loginShiroLoginTimeContext = metricLoginShiroLoginTime.time();
        AuthenticationCredentials credentials = credentialsFactory.newInstance(username, password.toCharArray());
        AccessToken accessToken = authenticationService.login(credentials);
        KapuaId scopeId = accessToken.getScopeId();
        KapuaId userId = accessToken.getUserId();
        final Account account;
        try {
            account = KapuaSecurityUtils.doPriviledge(() -> accountService.find(scopeId));
        } catch (Exception e) {
            // to preserve the original exception message (if possible)
            if (e instanceof AuthenticationException) {
                throw (AuthenticationException) e;
            } else {
                throw new ShiroException("Error while find account!", e);
            }
        }
        String accountName = account.getName();
        loginShiroLoginTimeContext.stop();
        // if a user acts as a child MOVED INSIDE KapuaAuthorizingRealm otherwise through REST API and console this @accountName won't work
        // get account id and name from kapua session methods that check for the run as
        // 
        // String accountName = kapuaSession.getSessionAccountName();
        // long accountId = kapuaSession.getSessionAccountId();
        // multiple account stealing link fix
        String fullClientId = MessageFormat.format(AclConstants.MULTI_ACCOUNT_CLIENT_ID, scopeId.getId().longValue(), clientId);
        KapuaPrincipal principal = new KapuaPrincipalImpl(accessToken, username, clientId, clientIp);
        DeviceConnection deviceConnection = null;
        // 3) check authorization
        DefaultAuthorizationMap authMap = null;
        if (isAdminUser(username)) {
            metricLoginKapuasysTokenAttempt.inc();
            // 3-1) admin authMap
            authMap = buildAdminAuthMap(authDestinations, principal, fullClientId);
            metricClientConnectedKapuasys.inc();
        } else {
            Context loginNormalUserTimeContext = metricLoginNormalUserTime.time();
            metricLoginNormalUserAttempt.inc();
            // 3-3) check permissions
            Context loginCheckAccessTimeContext = metricLoginCheckAccessTime.time();
            boolean[] hasPermissions = new boolean[] { // TODO check the permissions... move them to a constants class?
            authorizationService.isPermitted(permissionFactory.newPermission(DeviceLifecycleDomain.DEVICE_LIFECYCLE, Actions.connect, scopeId)), authorizationService.isPermitted(permissionFactory.newPermission(DeviceManagementDomain.DEVICE_MANAGEMENT, Actions.write, scopeId)), authorizationService.isPermitted(permissionFactory.newPermission(DatastoreDomain.DATA_STORE, Actions.read, scopeId)), authorizationService.isPermitted(permissionFactory.newPermission(DatastoreDomain.DATA_STORE, Actions.write, scopeId)) };
            if (!hasPermissions[AclConstants.BROKER_CONNECT_IDX]) {
                throw new KapuaIllegalAccessException(permissionFactory.newPermission(DeviceLifecycleDomain.DEVICE_LIFECYCLE, Actions.connect, scopeId).toString());
            }
            loginCheckAccessTimeContext.stop();
            // 3-4) build authMap
            authMap = buildAuthMap(authDestinations, principal, hasPermissions, accountName, clientId, fullClientId);
            // 4) find device
            Context loginFindClientIdTimeContext = metricLoginFindClientIdTime.time();
            deviceConnection = deviceConnectionService.findByClientId(scopeId, clientId);
            loginFindClientIdTimeContext.stop();
            Context loginFindDevTimeContext = metricLoginFindDevTime.time();
            // send connect message
            ConnectionId previousConnectionId = connectionMap.get(fullClientId);
            boolean stealingLinkDetected = (previousConnectionId != null);
            // Update map for stealing link detection on disconnect
            connectionMap.put(fullClientId, info.getConnectionId());
            if (deviceConnection == null) {
                DeviceConnectionCreator deviceConnectionCreator = deviceConnectionFactory.newCreator(scopeId);
                deviceConnectionCreator.setClientId(clientId);
                deviceConnectionCreator.setClientIp(clientIp);
                deviceConnectionCreator.setProtocol("MQTT");
                // TODO to be filled with the proper value
                deviceConnectionCreator.setServerIp(null);
                deviceConnectionCreator.setUserId(userId);
                deviceConnection = deviceConnectionService.create(deviceConnectionCreator);
            } else {
                deviceConnection.setClientIp(clientIp);
                deviceConnection.setProtocol("MQTT");
                // TODO to be filled with the proper value
                deviceConnection.setServerIp(null);
                deviceConnection.setUserId(userId);
                deviceConnection.setStatus(DeviceConnectionStatus.CONNECTED);
                deviceConnectionService.update(deviceConnection);
                // TODO manage the stealing link event (may be a good idea to use different connect status (connect -stealing)?
                if (stealingLinkDetected) {
                    metricLoginStealingLinkConnect.inc();
                    // stealing link detected, skip info
                    logger.warn("Detected Stealing link for cliend id {} - account - last connection id was {} - current connection id is {} - IP: {} - No connection status changes!", new Object[] { clientId, accountName, previousConnectionId, info.getConnectionId(), info.getClientIp() });
                }
            }
            loginFindDevTimeContext.stop();
            loginNormalUserTimeContext.stop();
            Context loginSendLogingUpdateMsgTimeContex = metricLoginSendLoginUpdateMsgTime.time();
            loginSendLogingUpdateMsgTimeContex.stop();
            metricClientConnectedClient.inc();
        }
        logAuthDestinationToLog(authDestinations);
        ConnectorDescriptor connectorDescriptor = connectorsDescriptorMap.get((((TransportConnector) context.getConnector()).getName()));
        KapuaSecurityContext securityCtx = new KapuaSecurityContext(principal, authMap, (deviceConnection != null ? deviceConnection.getId() : null), connectionId, connectorDescriptor);
        context.setSecurityContext(securityCtx);
        // multiple account stealing link fix
        info.setClientId(fullClientId);
        context.setClientId(fullClientId);
    } catch (Exception e) {
        metricLoginFailure.inc();
        // fix ENTMQ-731
        if (e instanceof KapuaAuthenticationException) {
            KapuaAuthenticationException kapuaException = (KapuaAuthenticationException) e;
            KapuaErrorCode errorCode = kapuaException.getCode();
            if (errorCode.equals(KapuaAuthenticationErrorCodes.INVALID_USERNAME) || errorCode.equals(KapuaAuthenticationErrorCodes.INVALID_CREDENTIALS) || errorCode.equals(KapuaAuthenticationErrorCodes.INVALID_CREDENTIALS_TOKEN_PROVIDED)) {
                logger.warn("Invalid username or password for user {} ({})", username, e.getMessage());
                // activeMQ will map CredentialException into a CONNECTION_REFUSED_BAD_USERNAME_OR_PASSWORD message (see javadoc on top of this method)
                CredentialException ce = new CredentialException("Invalid username and/or password or disabled or expired account!");
                ce.setStackTrace(e.getStackTrace());
                metricLoginInvalidUserPassword.inc();
                throw ce;
            } else if (errorCode.equals(KapuaAuthenticationErrorCodes.LOCKED_USERNAME) || errorCode.equals(KapuaAuthenticationErrorCodes.DISABLED_USERNAME) || errorCode.equals(KapuaAuthenticationErrorCodes.EXPIRED_CREDENTIALS)) {
                logger.warn("User {} not authorized ({})", username, e.getMessage());
                // activeMQ-MQ will map SecurityException into a CONNECTION_REFUSED_NOT_AUTHORIZED message (see javadoc on top of this method)
                SecurityException se = new SecurityException("User not authorized!");
                se.setStackTrace(e.getStackTrace());
                throw se;
            }
        }
        // Excluded CredentialException, InvalidClientIDException, SecurityException all others exceptions will be mapped by activeMQ to a CONNECTION_REFUSED_SERVER_UNAVAILABLE message (see
        // javadoc on top of this method)
        // Not trapped exception now:
        // KapuaException
        logger.info("@@ error", e);
        throw e;
    } finally {
        // 7) logout
        Context loginShiroLogoutTimeContext = metricLoginShiroLogoutTime.time();
        authenticationService.logout();
        ThreadContext.unbindSubject();
        loginShiroLogoutTimeContext.stop();
        loginTotalContext.stop();
    }
}
Also used : Account(org.eclipse.kapua.service.account.Account) KapuaAuthenticationException(org.eclipse.kapua.service.authentication.shiro.KapuaAuthenticationException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) ShiroException(org.apache.shiro.ShiroException) AuthenticationCredentials(org.eclipse.kapua.service.authentication.AuthenticationCredentials) TransportConnector(org.apache.activemq.broker.TransportConnector) ConnectionId(org.apache.activemq.command.ConnectionId) KapuaAuthenticationException(org.eclipse.kapua.service.authentication.shiro.KapuaAuthenticationException) CredentialException(javax.security.auth.login.CredentialException) AccessToken(org.eclipse.kapua.service.authentication.AccessToken) KapuaId(org.eclipse.kapua.model.id.KapuaId) SecurityContext(org.apache.activemq.security.SecurityContext) ConnectionContext(org.apache.activemq.broker.ConnectionContext) Context(com.codahale.metrics.Timer.Context) ThreadContext(org.apache.shiro.util.ThreadContext) KapuaPrincipal(org.eclipse.kapua.service.authentication.KapuaPrincipal) ShiroException(org.apache.shiro.ShiroException) KapuaAuthenticationException(org.eclipse.kapua.service.authentication.shiro.KapuaAuthenticationException) KapuaIllegalAccessException(org.eclipse.kapua.KapuaIllegalAccessException) CredentialException(javax.security.auth.login.CredentialException) AuthenticationException(org.apache.shiro.authc.AuthenticationException) KapuaException(org.eclipse.kapua.KapuaException) KapuaIllegalAccessException(org.eclipse.kapua.KapuaIllegalAccessException) KapuaErrorCode(org.eclipse.kapua.KapuaErrorCode) DeviceConnection(org.eclipse.kapua.service.device.registry.connection.DeviceConnection) DefaultAuthorizationMap(org.apache.activemq.security.DefaultAuthorizationMap) DeviceConnectionCreator(org.eclipse.kapua.service.device.registry.connection.DeviceConnectionCreator)

Example 2 with AccessToken

use of org.eclipse.kapua.service.authentication.AccessToken in project kapua by eclipse.

the class AuthenticationServiceShiroImpl method login.

@Override
public AccessToken login(AuthenticationCredentials authenticationToken) throws KapuaException {
    Subject currentUser = SecurityUtils.getSubject();
    if (currentUser.isAuthenticated()) {
        logger.info("Thread already authenticated for thread '{}' - '{}' - '{}'", new Object[] { Thread.currentThread().getId(), Thread.currentThread().getName(), currentUser.toString() });
        throw new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.SUBJECT_ALREADY_LOGGED);
    }
    // AccessToken accessToken = null;
    if (authenticationToken instanceof UsernamePasswordTokenImpl) {
        UsernamePasswordTokenImpl usernamePasswordToken = (UsernamePasswordTokenImpl) authenticationToken;
        MDC.put(KapuaSecurityUtils.MDC_USERNAME, usernamePasswordToken.getUsername());
        UsernamePasswordToken shiroToken = new UsernamePasswordToken(usernamePasswordToken.getUsername(), usernamePasswordToken.getPassword());
        try {
            currentUser.login(shiroToken);
            Subject shiroSubject = SecurityUtils.getSubject();
            Session shiroSession = shiroSubject.getSession();
            KapuaEid scopeId = (KapuaEid) shiroSession.getAttribute("scopeId");
            KapuaEid userScopeId = (KapuaEid) shiroSession.getAttribute("userScopeId");
            KapuaEid userId = (KapuaEid) shiroSession.getAttribute("userId");
            // create the access token
            String generatedTokenKey = generateToken();
            AccessToken accessToken = new AccessTokenImpl(userId, scopeId, userScopeId, generatedTokenKey);
            KapuaSession kapuaSession = new KapuaSession(accessToken, scopeId, userScopeId, userId, usernamePasswordToken.getUsername());
            KapuaSecurityUtils.setSession(kapuaSession);
            shiroSubject.getSession().setAttribute(KapuaSession.KAPUA_SESSION_KEY, kapuaSession);
            logger.info("Login for thread '{}' - '{}' - '{}'", new Object[] { Thread.currentThread().getId(), Thread.currentThread().getName(), shiroSubject.toString() });
            return kapuaSession.getAccessToken();
        } catch (ShiroException se) {
            KapuaAuthenticationException kae = null;
            if (se instanceof UnknownAccountException) {
                kae = new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.INVALID_USERNAME, se, usernamePasswordToken.getUsername());
            } else if (se instanceof DisabledAccountException) {
                kae = new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.DISABLED_USERNAME, se, usernamePasswordToken.getUsername());
            } else if (se instanceof LockedAccountException) {
                kae = new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.LOCKED_USERNAME, se, usernamePasswordToken.getUsername());
            } else if (se instanceof IncorrectCredentialsException) {
                kae = new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.INVALID_CREDENTIALS, se, usernamePasswordToken.getUsername());
            } else if (se instanceof ExpiredCredentialsException) {
                kae = new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.EXPIRED_CREDENTIALS, se, usernamePasswordToken.getUsername());
            } else {
                throw KapuaAuthenticationException.internalError(se);
            }
            currentUser.logout();
            throw kae;
        }
    } else {
        throw new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.INVALID_CREDENTIALS_TOKEN_PROVIDED);
    }
}
Also used : DisabledAccountException(org.apache.shiro.authc.DisabledAccountException) IncorrectCredentialsException(org.apache.shiro.authc.IncorrectCredentialsException) KapuaSession(org.eclipse.kapua.commons.security.KapuaSession) AccessTokenImpl(org.eclipse.kapua.service.authentication.AccessTokenImpl) UnknownAccountException(org.apache.shiro.authc.UnknownAccountException) KapuaEid(org.eclipse.kapua.commons.model.id.KapuaEid) Subject(org.apache.shiro.subject.Subject) ExpiredCredentialsException(org.apache.shiro.authc.ExpiredCredentialsException) UsernamePasswordToken(org.apache.shiro.authc.UsernamePasswordToken) ShiroException(org.apache.shiro.ShiroException) AccessToken(org.eclipse.kapua.service.authentication.AccessToken) LockedAccountException(org.apache.shiro.authc.LockedAccountException) Session(org.apache.shiro.session.Session) KapuaSession(org.eclipse.kapua.commons.security.KapuaSession)

Example 3 with AccessToken

use of org.eclipse.kapua.service.authentication.AccessToken in project kapua by eclipse.

the class KapuaSessionAuthFilter method executeChain.

protected void executeChain(ServletRequest request, ServletResponse response, FilterChain origChain) throws IOException, ServletException {
    // bind kapua session
    // TODO workaround to fix the null kapua session on webconsole requests.
    // to be removed and substitute with getToken or another solution?
    KapuaSession kapuaSession = null;
    Subject shiroSubject = SecurityUtils.getSubject();
    if (shiroSubject != null && shiroSubject.isAuthenticated()) {
        Session s = shiroSubject.getSession();
        KapuaEid scopeId = (KapuaEid) s.getAttribute("scopeId");
        KapuaEid userScopeId = (KapuaEid) s.getAttribute("userScopeId");
        KapuaEid userId = (KapuaEid) s.getAttribute("userId");
        // create the access token
        String generatedTokenKey = UUID.randomUUID().toString();
        AccessToken accessToken = new AccessTokenImpl(userId, scopeId, userScopeId, generatedTokenKey);
        kapuaSession = new KapuaSession(accessToken, scopeId, userScopeId, userId, "");
    }
    try {
        KapuaSecurityUtils.setSession(kapuaSession);
        super.executeChain(request, response, origChain);
    } finally {
        // unbind kapua session
        KapuaSecurityUtils.clearSession();
    }
}
Also used : KapuaSession(org.eclipse.kapua.commons.security.KapuaSession) AccessToken(org.eclipse.kapua.service.authentication.AccessToken) AccessTokenImpl(org.eclipse.kapua.service.authentication.AccessTokenImpl) KapuaEid(org.eclipse.kapua.commons.model.id.KapuaEid) Subject(org.apache.shiro.subject.Subject) Session(org.apache.shiro.session.Session) KapuaSession(org.eclipse.kapua.commons.security.KapuaSession)

Aggregations

AccessToken (org.eclipse.kapua.service.authentication.AccessToken)3 ShiroException (org.apache.shiro.ShiroException)2 Session (org.apache.shiro.session.Session)2 Subject (org.apache.shiro.subject.Subject)2 KapuaEid (org.eclipse.kapua.commons.model.id.KapuaEid)2 KapuaSession (org.eclipse.kapua.commons.security.KapuaSession)2 AccessTokenImpl (org.eclipse.kapua.service.authentication.AccessTokenImpl)2 Context (com.codahale.metrics.Timer.Context)1 CredentialException (javax.security.auth.login.CredentialException)1 ConnectionContext (org.apache.activemq.broker.ConnectionContext)1 TransportConnector (org.apache.activemq.broker.TransportConnector)1 ConnectionId (org.apache.activemq.command.ConnectionId)1 DefaultAuthorizationMap (org.apache.activemq.security.DefaultAuthorizationMap)1 SecurityContext (org.apache.activemq.security.SecurityContext)1 AuthenticationException (org.apache.shiro.authc.AuthenticationException)1 DisabledAccountException (org.apache.shiro.authc.DisabledAccountException)1 ExpiredCredentialsException (org.apache.shiro.authc.ExpiredCredentialsException)1 IncorrectCredentialsException (org.apache.shiro.authc.IncorrectCredentialsException)1 LockedAccountException (org.apache.shiro.authc.LockedAccountException)1 UnknownAccountException (org.apache.shiro.authc.UnknownAccountException)1