Search in sources :

Example 1 with KapuaSession

use of org.eclipse.kapua.commons.security.KapuaSession in project kapua by eclipse.

the class KapuaSecurityBrokerFilter method removeConnection.

@Override
public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception {
    if (!isPassThroughConnection(context)) {
        Context loginRemoveConnectionTimeContext = metricLoginRemoveConnectionTime.time();
        try {
            KapuaSecurityContext kapuaSecurityContext = getKapuaSecurityContext(context);
            // TODO fix the kapua session when run as feature will be implemented
            KapuaPrincipal kapuaPrincipal = ((KapuaPrincipal) kapuaSecurityContext.getMainPrincipal());
            KapuaSession kapuaSession = new KapuaSession(null, kapuaPrincipal.getAccountId(), kapuaPrincipal.getAccountId(), kapuaPrincipal.getUserId(), kapuaPrincipal.getName());
            KapuaSecurityUtils.setSession(kapuaSession);
            String clientId = kapuaPrincipal.getClientId();
            KapuaId accountId = kapuaPrincipal.getAccountId();
            String username = kapuaSecurityContext.getUserName();
            String remoteAddress = (context.getConnection() != null) ? context.getConnection().getRemoteAddress() : "";
            KapuaId scopeId = ((KapuaPrincipal) kapuaSecurityContext.getMainPrincipal()).getAccountId();
            // multiple account stealing link fix
            String fullClientId = MessageFormat.format(AclConstants.MULTI_ACCOUNT_CLIENT_ID, accountId, clientId);
            if (!isAdminUser(username)) {
                // Stealing link check
                ConnectionId connectionId = connectionMap.get(fullClientId);
                boolean stealingLinkDetected = false;
                if (connectionId != null) {
                    stealingLinkDetected = !connectionId.equals(info.getConnectionId());
                } else {
                    logger.error("Cannot find connection id for client id {} on connection map. Currect connection id is {} - IP: {}", new Object[] { clientId, info.getConnectionId(), info.getClientIp() });
                }
                if (stealingLinkDetected) {
                    metricLoginStealingLinkDisconnect.inc();
                    // stealing link detected, skip info
                    logger.warn("Detected Stealing link for cliend id {} - account id {} - last connection id was {} - current connection id is {} - IP: {} - No disconnection info will be added!", new Object[] { clientId, accountId, connectionId, info.getConnectionId(), info.getClientIp() });
                } else {
                    KapuaId deviceConnectionId = kapuaSecurityContext.getConnectionId();
                    DeviceConnection deviceConnection = null;
                    try {
                        deviceConnection = KapuaSecurityUtils.doPriviledge(new Callable<DeviceConnection>() {

                            @Override
                            public DeviceConnection call() throws Exception {
                                return deviceConnectionService.findByClientId(scopeId, clientId);
                            }
                        });
                    } catch (Exception e) {
                        throw new ShiroException("Error while updating the device connection!", e);
                    }
                    // the device connection must be not null
                    // cleanup stealing link detection map
                    connectionMap.remove(fullClientId);
                    final DeviceConnection deviceConnectionToUpdate = deviceConnection;
                    if (error == null) {
                        // update device connection
                        deviceConnectionToUpdate.setStatus(DeviceConnectionStatus.DISCONNECTED);
                        try {
                            KapuaSecurityUtils.doPriviledge(() -> {
                                deviceConnectionService.update(deviceConnectionToUpdate);
                                return null;
                            });
                        } catch (Exception e) {
                            throw new ShiroException("Error while updating the device connection status!", e);
                        }
                    } else {
                        // send missing message
                        // update device connection
                        deviceConnectionToUpdate.setStatus(DeviceConnectionStatus.MISSING);
                        try {
                            KapuaSecurityUtils.doPriviledge(() -> {
                                deviceConnectionService.update(deviceConnectionToUpdate);
                                return null;
                            });
                        } catch (Exception e) {
                            throw new ShiroException("Error while updating the device connection status!", e);
                        }
                    }
                }
                metricClientDisconnectionClient.inc();
            } else {
                metricClientDisconnectionKapuasys.inc();
            }
            // multiple account stealing link fix
            info.setClientId(fullClientId);
            context.setClientId(fullClientId);
        } finally {
            loginRemoveConnectionTimeContext.stop();
            authenticationService.logout();
        }
    }
    super.removeConnection(context, info, error);
    context.setSecurityContext(null);
}
Also used : SecurityContext(org.apache.activemq.security.SecurityContext) ConnectionContext(org.apache.activemq.broker.ConnectionContext) Context(com.codahale.metrics.Timer.Context) ThreadContext(org.apache.shiro.util.ThreadContext) ConnectionId(org.apache.activemq.command.ConnectionId) KapuaSession(org.eclipse.kapua.commons.security.KapuaSession) DeviceConnection(org.eclipse.kapua.service.device.registry.connection.DeviceConnection) KapuaPrincipal(org.eclipse.kapua.service.authentication.KapuaPrincipal) KapuaId(org.eclipse.kapua.model.id.KapuaId) Callable(java.util.concurrent.Callable) 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) ShiroException(org.apache.shiro.ShiroException)

Example 2 with KapuaSession

use of org.eclipse.kapua.commons.security.KapuaSession 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 KapuaSession

use of org.eclipse.kapua.commons.security.KapuaSession in project kapua by eclipse.

the class AuthorizationServiceImpl method checkPermission.

@Override
public void checkPermission(Permission permission) throws KapuaException {
    KapuaSession session = KapuaSecurityUtils.getSession();
    // FIXME: this should throw something like unauthenticated exception
    if (session == null) {
        throw new KapuaIllegalStateException("null KapuaSession");
    }
    if (!session.isTrustedMode()) {
        Subject subject = SecurityUtils.getSubject();
        subject.checkPermission(permission.toString());
    }
}
Also used : KapuaSession(org.eclipse.kapua.commons.security.KapuaSession) KapuaIllegalStateException(org.eclipse.kapua.KapuaIllegalStateException) Subject(org.apache.shiro.subject.Subject)

Example 4 with KapuaSession

use of org.eclipse.kapua.commons.security.KapuaSession in project kapua by eclipse.

the class AuthenticationServiceMock method login.

@Override
public AccessToken login(AuthenticationCredentials authenticationToken) throws KapuaException {
    if (!(authenticationToken instanceof UsernamePasswordTokenMock))
        throw KapuaException.internalError("Unmanaged credentials type");
    UsernamePasswordTokenMock usrPwdTokenMock = (UsernamePasswordTokenMock) authenticationToken;
    KapuaLocator serviceLocator = KapuaLocator.getInstance();
    UserService userService = serviceLocator.getService(UserService.class);
    User user = userService.findByName(usrPwdTokenMock.getUsername());
    KapuaSession kapuaSession = new KapuaSession(null, null, user.getScopeId(), user.getId(), user.getName());
    KapuaSecurityUtils.setSession(kapuaSession);
    // TODO Auto-generated method stub
    return null;
}
Also used : KapuaLocator(org.eclipse.kapua.locator.KapuaLocator) User(org.eclipse.kapua.service.user.User) UserService(org.eclipse.kapua.service.user.UserService) KapuaSession(org.eclipse.kapua.commons.security.KapuaSession)

Example 5 with KapuaSession

use of org.eclipse.kapua.commons.security.KapuaSession 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

KapuaSession (org.eclipse.kapua.commons.security.KapuaSession)9 Subject (org.apache.shiro.subject.Subject)4 ShiroException (org.apache.shiro.ShiroException)2 Session (org.apache.shiro.session.Session)2 KapuaEid (org.eclipse.kapua.commons.model.id.KapuaEid)2 KapuaLocator (org.eclipse.kapua.locator.KapuaLocator)2 AccessToken (org.eclipse.kapua.service.authentication.AccessToken)2 AccessTokenImpl (org.eclipse.kapua.service.authentication.AccessTokenImpl)2 User (org.eclipse.kapua.service.user.User)2 UserService (org.eclipse.kapua.service.user.UserService)2 Context (com.codahale.metrics.Timer.Context)1 Callable (java.util.concurrent.Callable)1 CredentialException (javax.security.auth.login.CredentialException)1 GET (javax.ws.rs.GET)1 Produces (javax.ws.rs.Produces)1 ConnectionContext (org.apache.activemq.broker.ConnectionContext)1 ConnectionId (org.apache.activemq.command.ConnectionId)1 SecurityContext (org.apache.activemq.security.SecurityContext)1 AuthenticationException (org.apache.shiro.authc.AuthenticationException)1 DisabledAccountException (org.apache.shiro.authc.DisabledAccountException)1