Search in sources :

Example 1 with AttributeList

use of net.jradius.packet.attribute.AttributeList in project cas by apereo.

the class JRadiusServerImpl method authenticate.

@Override
public RadiusResponse authenticate(final String username, final String password) throws Exception {
    final AttributeList attributeList = new AttributeList();
    attributeList.add(new Attr_UserName(username));
    attributeList.add(new Attr_UserPassword(password));
    if (StringUtils.isNotBlank(this.nasIpAddress)) {
        attributeList.add(new Attr_NASIPAddress(this.nasIpAddress));
    }
    if (StringUtils.isNotBlank(this.nasIpv6Address)) {
        attributeList.add(new Attr_NASIPv6Address(this.nasIpv6Address));
    }
    if (this.nasPort != -1) {
        attributeList.add(new Attr_NASPort(this.nasPort));
    }
    if (this.nasPortId != -1) {
        attributeList.add(new Attr_NASPortId(this.nasPortId));
    }
    if (StringUtils.isNotBlank(this.nasIdentifier)) {
        attributeList.add(new Attr_NASIdentifier(this.nasIdentifier));
    }
    if (this.nasRealPort != -1) {
        attributeList.add(new Attr_NASRealPort(this.nasRealPort));
    }
    if (this.nasPortType != -1) {
        attributeList.add(new Attr_NASPortType(this.nasPortType));
    }
    RadiusClient client = null;
    try {
        client = this.radiusClientFactory.newInstance();
        final AccessRequest request = new AccessRequest(client, attributeList);
        final RadiusPacket response = client.authenticate(request, RadiusClient.getAuthProtocol(this.protocol.getName()), this.retries);
        LOGGER.debug("RADIUS response from [{}]: [{}]", client.getRemoteInetAddress().getCanonicalHostName(), response.getClass().getName());
        if (response instanceof AccessAccept) {
            final List<RadiusAttribute> attributes = response.getAttributes().getAttributeList();
            LOGGER.debug("Radius response code [{}] accepted with attributes [{}] and identifier [{}]", response.getCode(), attributes, response.getIdentifier());
            return new RadiusResponse(response.getCode(), response.getIdentifier(), attributes);
        }
        LOGGER.debug("Response is not recognized");
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}
Also used : Attr_NASRealPort(net.jradius.dictionary.vsa_redback.Attr_NASRealPort) RadiusClient(net.jradius.client.RadiusClient) AccessRequest(net.jradius.packet.AccessRequest) AttributeList(net.jradius.packet.attribute.AttributeList) Attr_NASPort(net.jradius.dictionary.Attr_NASPort) Attr_NASIPAddress(net.jradius.dictionary.Attr_NASIPAddress) Attr_NASPortId(net.jradius.dictionary.Attr_NASPortId) Attr_UserPassword(net.jradius.dictionary.Attr_UserPassword) Attr_NASPortType(net.jradius.dictionary.Attr_NASPortType) RadiusAttribute(net.jradius.packet.attribute.RadiusAttribute) RadiusPacket(net.jradius.packet.RadiusPacket) Attr_UserName(net.jradius.dictionary.Attr_UserName) Attr_NASIPv6Address(net.jradius.dictionary.Attr_NASIPv6Address) Attr_NASIdentifier(net.jradius.dictionary.Attr_NASIdentifier) AccessAccept(net.jradius.packet.AccessAccept)

Example 2 with AttributeList

use of net.jradius.packet.attribute.AttributeList in project opennms by OpenNMS.

the class RadiusAuthMonitor method poll.

/**
 * {@inheritDoc}
 *
 * Radius Authentication Poller
 *
 * Note that the poller will return SERVICE_AVAILABLE only if the
 * authentication Request actually succeeds. A failed authentication
 * request will result in SERVICE_UNAVILABLE, although the radius
 * server may actually be up.
 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_AVAILABLE
 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_UNAVAILABLE
 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_UNRESPONSIVE
 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_AVAILABLE
 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_UNAVAILABLE
 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_UNRESPONSIVE
 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_AVAILABLE
 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_UNAVAILABLE
 * @see org.opennms.netmgt.poller.ServiceMonitor#SERVICE_UNRESPONSIVE
 */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // Assume that the service is down
    PollStatus status = PollStatus.unavailable();
    if (parameters == null) {
        throw new NullPointerException();
    }
    final TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    int authport = ParameterMap.getKeyedInteger(parameters, "authport", DEFAULT_AUTH_PORT);
    int acctport = ParameterMap.getKeyedInteger(parameters, "acctport", DEFAULT_ACCT_PORT);
    String user = ParameterMap.getKeyedString(parameters, "user", DEFAULT_USER);
    String password = ParameterMap.getKeyedString(parameters, "password", DEFAULT_PASSWORD);
    String secret = ParameterMap.getKeyedString(parameters, "secret", DEFAULT_SECRET);
    String authType = ParameterMap.getKeyedString(parameters, "authtype", DEFAULT_AUTH_TYPE);
    String nasid = ParameterMap.getKeyedString(parameters, "nasid", DEFAULT_NASID);
    String innerProtocol = ParameterMap.getKeyedString(parameters, "inner-protocol", DEFAULT_TTLS_INNER_AUTH_TYPE);
    String innerUser = ParameterMap.getKeyedString(parameters, "inner-user", DEFAULT_INNER_USER);
    String certFile = ParameterMap.getKeyedString(parameters, "certificate", null);
    InetAddress addr = svc.getAddress();
    AttributeFactory.loadAttributeDictionary("net.jradius.dictionary.AttributeDictionaryImpl");
    int timeout = convertTimeoutToSeconds(ParameterMap.getKeyedInteger(parameters, "timeout", DEFAULT_TIMEOUT));
    try {
        final RadiusClient rc = new RadiusClient(addr, secret, authport, acctport, timeout);
        for (tracker.reset(); tracker.shouldRetry(); tracker.nextAttempt()) {
            final AttributeList attributes = new AttributeList();
            attributes.add(new Attr_UserName(user));
            attributes.add(new Attr_NASIdentifier(nasid));
            attributes.add(new Attr_UserPassword(password));
            final AccessRequest accessRequest = new AccessRequest(rc, attributes);
            final RadiusAuthenticator auth;
            if (authType.equalsIgnoreCase("chap")) {
                auth = new CHAPAuthenticator();
            } else if (authType.equalsIgnoreCase("pap")) {
                auth = new PAPAuthenticator();
            } else if (authType.equalsIgnoreCase("mschapv1")) {
                auth = new MSCHAPv1Authenticator();
            } else if (authType.equalsIgnoreCase("mschapv2")) {
                auth = new MSCHAPv2Authenticator();
            } else if (authType.equalsIgnoreCase("eapmd5") || authType.equalsIgnoreCase("eap-md5")) {
                auth = new EAPMD5Authenticator();
            } else if (authType.equalsIgnoreCase("eapmschapv2") || authType.equalsIgnoreCase("eap-mschapv2")) {
                auth = new EAPMSCHAPv2Authenticator();
            } else if (RadiusUtils.isTunneling(authType)) {
                if (innerUser == null) {
                    String reason = "TLS AAA type requested but no inner user defined. Authtype: '" + authType + "'";
                    RadiusAuthMonitor.LOG.debug(reason);
                    return PollStatus.unavailable(reason);
                }
                EAPTLSAuthenticator tlsAuth = null;
                if (RadiusUtils.isEAPTTLS(authType)) {
                    tlsAuth = new EAPTTLSAuthenticator();
                    final EAPTTLSAuthenticator ttlsAuth = (EAPTTLSAuthenticator) tlsAuth;
                    if (innerProtocol != DEFAULT_TTLS_INNER_AUTH_TYPE) {
                        String reason = "RadiusMonitor can only use 'pap' as inner auth protocol, not " + innerProtocol;
                        LOG.debug(reason);
                        return PollStatus.unavailable(reason);
                    } else {
                        ttlsAuth.setInnerProtocol(innerProtocol);
                    }
                    AttributeList attrs = new AttributeList();
                    attrs.add(new Attr_UserName(innerUser));
                    attrs.add(new Attr_Password(password));
                    ttlsAuth.setTunneledAttributes(attrs);
                } else if (authType.equalsIgnoreCase("peap")) {
                    String reason = "Support for eap peap is not ready yet";
                    LOG.debug(reason);
                    return PollStatus.unavailable(reason);
                }
                /* Cert. processing is common to EAPTLS protocols */
                /* We trust any certificate for now */
                LOG.warn("Server certificate will be trusted");
                if (certFile == null)
                    tlsAuth.setTrustAll(true);
                auth = tlsAuth;
            } else {
                String reason = "Unknown authenticator type '" + authType + "'";
                RadiusAuthMonitor.LOG.debug(reason);
                return PollStatus.unavailable(reason);
            }
            tracker.startAttempt();
            // The retry should be handled by the RadiusClient because otherwise it will thrown an exception.
            RadiusPacket reply = rc.authenticate(accessRequest, auth, ParameterMap.getKeyedInteger(parameters, "retry", DEFAULT_RETRY));
            if (reply instanceof AccessAccept) {
                double responseTime = tracker.elapsedTimeInMillis();
                status = PollStatus.available(responseTime);
                LOG.debug("Radius service is AVAILABLE on: {}", addr.getCanonicalHostName());
                LOG.debug("poll: responseTime= {}", responseTime);
                break;
            } else if (reply != null) {
                LOG.debug("response returned, but request was not accepted: {}", reply);
            }
            String reason = "Invalid RADIUS reply: " + reply;
            RadiusAuthMonitor.LOG.debug(reason);
            status = PollStatus.unavailable(reason);
        }
    } catch (final Throwable e) {
        String reason = "Error while attempting to connect to the RADIUS service on " + addr.getCanonicalHostName();
        RadiusAuthMonitor.LOG.debug(reason, e);
        status = PollStatus.unavailable(reason);
    }
    return status;
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus) RadiusClient(net.jradius.client.RadiusClient) AttributeList(net.jradius.packet.attribute.AttributeList) EAPMSCHAPv2Authenticator(net.jradius.client.auth.EAPMSCHAPv2Authenticator) MSCHAPv1Authenticator(net.jradius.client.auth.MSCHAPv1Authenticator) Attr_Password(net.jradius.dictionary.Attr_Password) Attr_UserPassword(net.jradius.dictionary.Attr_UserPassword) EAPTLSAuthenticator(net.jradius.client.auth.EAPTLSAuthenticator) EAPMSCHAPv2Authenticator(net.jradius.client.auth.EAPMSCHAPv2Authenticator) MSCHAPv2Authenticator(net.jradius.client.auth.MSCHAPv2Authenticator) EAPTTLSAuthenticator(net.jradius.client.auth.EAPTTLSAuthenticator) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) PAPAuthenticator(net.jradius.client.auth.PAPAuthenticator) RadiusAuthenticator(net.jradius.client.auth.RadiusAuthenticator) AccessRequest(net.jradius.packet.AccessRequest) EAPMD5Authenticator(net.jradius.client.auth.EAPMD5Authenticator) CHAPAuthenticator(net.jradius.client.auth.CHAPAuthenticator) RadiusPacket(net.jradius.packet.RadiusPacket) Attr_UserName(net.jradius.dictionary.Attr_UserName) InetAddress(java.net.InetAddress) Attr_NASIdentifier(net.jradius.dictionary.Attr_NASIdentifier) AccessAccept(net.jradius.packet.AccessAccept)

Example 3 with AttributeList

use of net.jradius.packet.attribute.AttributeList in project opennms by OpenNMS.

the class RadiusAuthenticationProvider method retrieveUser.

/* (non-Javadoc)
     * @see org.springframework.security.providers.dao.AbstractUserDetailsAuthenticationProvider#retrieveUser(java.lang.String, org.springframework.security.providers.UsernamePasswordAuthenticationToken)
     */
/**
 * {@inheritDoc}
 */
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken token) throws AuthenticationException {
    if (!StringUtils.hasLength(username)) {
        LOG.info("Authentication attempted with empty username");
        throw new BadCredentialsException(messages.getMessage("RadiusAuthenticationProvider.emptyUsername", "Username cannot be empty"));
    }
    String password = (String) token.getCredentials();
    if (!StringUtils.hasLength(password)) {
        LOG.info("Authentication attempted with empty password");
        throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    InetAddress serverIP = null;
    serverIP = InetAddressUtils.addr(server);
    if (serverIP == null) {
        LOG.error("Could not resolve radius server address {}", server);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.unknownServer", "Could not resolve radius server address"));
    }
    AttributeFactory.loadAttributeDictionary("net.jradius.dictionary.AttributeDictionaryImpl");
    AttributeList attributeList = new AttributeList();
    attributeList.add(new Attr_UserName(username));
    attributeList.add(new Attr_UserPassword(password));
    RadiusPacket reply;
    try {
        RadiusClient radiusClient = new RadiusClient(serverIP, secret, port, port + 1, timeout);
        AccessRequest request = new AccessRequest(radiusClient, attributeList);
        LOG.debug("Sending AccessRequest message to {}:{} using {} protocol with timeout = {}, retries = {}, attributes:\n{}", InetAddressUtils.str(serverIP), port, (authTypeClass == null ? "PAP" : authTypeClass.getAuthName()), timeout, retries, attributeList.toString());
        reply = radiusClient.authenticate(request, authTypeClass, retries);
    } catch (RadiusException e) {
        LOG.error("Error connecting to radius server {} : {}", server, e);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError", new Object[] { e }, "Error connecting to radius server: " + e));
    } catch (IOException e) {
        LOG.error("Error connecting to radius server {} : {}", server, e);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError", new Object[] { e }, "Error connecting to radius server: " + e));
    } catch (NoSuchAlgorithmException e) {
        LOG.error("Error no such algorithm {} : {}", this.authTypeClass.getClass().getName(), e);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError", new Object[] { e }, "Error connecting to radius server: " + e));
    }
    if (reply == null) {
        LOG.error("Timed out connecting to radius server {}", server);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusTimeout", "Timed out connecting to radius server"));
    }
    if (!(reply instanceof AccessAccept)) {
        LOG.info("Received a reply other than AccessAccept from radius server {} for user {} :\n{}", server, username, reply.toString());
        throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    LOG.debug("Received AccessAccept message from {}:{} for user {} with attributes:\n{}", InetAddressUtils.str(serverIP), port, username, reply.getAttributes().toString());
    String roles = null;
    if (!StringUtils.hasLength(rolesAttribute)) {
        LOG.debug("rolesAttribute not set, using default roles ({}) for user {}", defaultRoles, username);
        roles = new String(defaultRoles);
    } else {
        Iterator<RadiusAttribute> attributes = reply.getAttributes().getAttributeList().iterator();
        while (attributes.hasNext()) {
            RadiusAttribute attribute = attributes.next();
            if (rolesAttribute.equals(attribute.getAttributeName())) {
                roles = new String(attribute.getValue().getBytes());
                break;
            }
        }
        if (roles == null) {
            LOG.info("Radius attribute {} not found, using default roles ({}) for user {}", rolesAttribute, defaultRoles, username);
            roles = new String(defaultRoles);
        }
    }
    String[] rolesArray = roles.replaceAll("\\s*", "").split(",");
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(rolesArray.length);
    for (String role : rolesArray) {
        authorities.add(new SimpleGrantedAuthority(role));
    }
    final StringBuilder readRoles = new StringBuilder();
    for (GrantedAuthority authority : authorities) {
        readRoles.append(authority.toString() + ", ");
    }
    if (readRoles.length() > 0) {
        readRoles.delete(readRoles.length() - 2, readRoles.length());
    }
    LOG.debug("Parsed roles {} for user {}", readRoles, username);
    return new User(username, password, true, true, true, true, authorities);
}
Also used : RadiusClient(net.jradius.client.RadiusClient) User(org.springframework.security.core.userdetails.User) AccessRequest(net.jradius.packet.AccessRequest) AttributeList(net.jradius.packet.attribute.AttributeList) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Attr_UserPassword(net.jradius.dictionary.Attr_UserPassword) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) RadiusAttribute(net.jradius.packet.attribute.RadiusAttribute) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) RadiusPacket(net.jradius.packet.RadiusPacket) Attr_UserName(net.jradius.dictionary.Attr_UserName) InetAddress(java.net.InetAddress) RadiusException(net.jradius.exception.RadiusException) AccessAccept(net.jradius.packet.AccessAccept)

Example 4 with AttributeList

use of net.jradius.packet.attribute.AttributeList in project cas by apereo.

the class AbstractRadiusServer method authenticate.

@Override
public final CasRadiusResponse authenticate(final String username, final String password, final Optional state) throws Exception {
    val attributeList = new AttributeList();
    if (StringUtils.isNotBlank(username)) {
        attributeList.add(new Attr_UserName(username));
    }
    if (StringUtils.isNotBlank(password)) {
        attributeList.add(new Attr_UserPassword(password));
    }
    val clientInfo = ClientInfoHolder.getClientInfo();
    if (clientInfo != null) {
        val clientIpAddress = clientInfo.getClientIpAddress();
        val clientIpAttribute = new Attr_ClientIPAddress(clientIpAddress);
        LOGGER.debug("Adding client IP address attribute [{}]", clientIpAttribute);
        attributeList.add(clientIpAttribute);
    }
    state.ifPresent(value -> attributeList.add(new Attr_State(Serializable.class.cast(value))));
    if (StringUtils.isNotBlank(configurationContext.getNasIpAddress())) {
        attributeList.add(new Attr_NASIPAddress(configurationContext.getNasIpAddress()));
    }
    if (StringUtils.isNotBlank(configurationContext.getNasIpv6Address())) {
        attributeList.add(new Attr_NASIPv6Address(configurationContext.getNasIpv6Address()));
    }
    if (configurationContext.getNasPort() != -1) {
        attributeList.add(new Attr_NASPort(configurationContext.getNasPort()));
    }
    if (configurationContext.getNasPortId() != -1) {
        attributeList.add(new Attr_NASPortId(configurationContext.getNasPortId()));
    }
    if (StringUtils.isNotBlank(configurationContext.getNasIdentifier())) {
        attributeList.add(new Attr_NASIdentifier(configurationContext.getNasIdentifier()));
    }
    if (configurationContext.getNasRealPort() != -1) {
        attributeList.add(new Attr_NASRealPort(configurationContext.getNasRealPort()));
    }
    if (configurationContext.getNasPortType() != -1) {
        attributeList.add(new Attr_NASPortType(configurationContext.getNasPortType()));
    }
    val client = configurationContext.getRadiusClientFactory().newInstance();
    try {
        val request = new AccessRequest(client, attributeList);
        LOGGER.debug("RADIUS access request prepared as [{}]", request.toString(true, true));
        val response = authenticateRequest(client, request);
        LOGGER.debug("RADIUS response from [{}]: [{}] as [{}]", client.getRemoteInetAddress().getCanonicalHostName(), response.getClass().getName(), response.toString(true, true));
        if (response instanceof AccessAccept || response instanceof AccessChallenge) {
            val attributes = response.getAttributes().getAttributeList();
            LOGGER.debug("Radius response code [{}] accepted with attributes [{}] and identifier [{}]", response.getCode(), attributes, response.getIdentifier());
            return new CasRadiusResponse(response.getCode(), response.getIdentifier(), attributes);
        }
        LOGGER.warn("Response [{}] is not recognized", response);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}
Also used : lombok.val(lombok.val) Serializable(java.io.Serializable) Attr_NASRealPort(net.jradius.dictionary.vsa_redback.Attr_NASRealPort) CasRadiusResponse(org.apereo.cas.adaptors.radius.CasRadiusResponse) AccessRequest(net.jradius.packet.AccessRequest) AttributeList(net.jradius.packet.attribute.AttributeList) Attr_NASPort(net.jradius.dictionary.Attr_NASPort) Attr_NASIPAddress(net.jradius.dictionary.Attr_NASIPAddress) Attr_ClientIPAddress(net.jradius.dictionary.Attr_ClientIPAddress) Attr_NASPortId(net.jradius.dictionary.Attr_NASPortId) Attr_UserPassword(net.jradius.dictionary.Attr_UserPassword) Attr_NASPortType(net.jradius.dictionary.Attr_NASPortType) Attr_UserName(net.jradius.dictionary.Attr_UserName) Attr_NASIPv6Address(net.jradius.dictionary.Attr_NASIPv6Address) Attr_State(net.jradius.dictionary.Attr_State) AccessChallenge(net.jradius.packet.AccessChallenge) Attr_NASIdentifier(net.jradius.dictionary.Attr_NASIdentifier) AccessAccept(net.jradius.packet.AccessAccept)

Aggregations

Attr_UserName (net.jradius.dictionary.Attr_UserName)4 Attr_UserPassword (net.jradius.dictionary.Attr_UserPassword)4 AccessAccept (net.jradius.packet.AccessAccept)4 AccessRequest (net.jradius.packet.AccessRequest)4 AttributeList (net.jradius.packet.attribute.AttributeList)4 RadiusClient (net.jradius.client.RadiusClient)3 Attr_NASIdentifier (net.jradius.dictionary.Attr_NASIdentifier)3 RadiusPacket (net.jradius.packet.RadiusPacket)3 InetAddress (java.net.InetAddress)2 Attr_NASIPAddress (net.jradius.dictionary.Attr_NASIPAddress)2 Attr_NASIPv6Address (net.jradius.dictionary.Attr_NASIPv6Address)2 Attr_NASPort (net.jradius.dictionary.Attr_NASPort)2 Attr_NASPortId (net.jradius.dictionary.Attr_NASPortId)2 Attr_NASPortType (net.jradius.dictionary.Attr_NASPortType)2 Attr_NASRealPort (net.jradius.dictionary.vsa_redback.Attr_NASRealPort)2 RadiusAttribute (net.jradius.packet.attribute.RadiusAttribute)2 IOException (java.io.IOException)1 Serializable (java.io.Serializable)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 ArrayList (java.util.ArrayList)1