Wednesday, May 27, 2015

Installing RADIUS Extensions in OpenAM 12

In in my previous post I shared a link for downloading a jar that contained the RADIUS extensions that we have made to the native RADIUS authentication module in OpenAM. In this post I'll show you how to tell OpenAM to expose and use the Radius Server functionality resident in that jar.

Installing

To use the Radius extensions in that jar you must perform the following simple steps:

  1. Shut down your servlet container such as tomcat.
  2. Replace the existing jar (the openam-auth-radius.jar file located in the WEB-INF/lib directory of a deployed, expanded OpenAM war) with the downloaded openam-auth-radius-1.0.1.jar. (The name of the jar is not important and does not have any impact on the runtime system.) The existing authentication module code has not been modified and will continue to work out of the new jar.
  3. Inject the following context listener declaration shown in bold text into the WEB-INF/web.xml file either above or below the existing guice context listener as shown.

    <!-- Initialises the Guice Injector. -->
       <listener>
            <listener-class>
            org.forgerock.guice.core.GuiceInitialisationFilter
            </listener-class>
        </listener>
        <listener>
            <listener-class>
    com.sun.identity.authentication.modules.radius.server.config.ServletContextListenerLauncher
            </listener-class>
        </listener>

  4. Restart your servlet container.
That is it. You now have the extended Radius support. 

As OpenAM starts up you'll now see the following lines logged to catalina.out since I used java.logging in the current implementation and not the OpenAM Debug logger. For brevity I've trimmed out the level, data, time, class, and method doing the logging and added line numbers for the discussion that follows:

1) [localhost-startStop-1] ---> ServletContextListenerLauncher starting RadiusServiceStarter

2) [localhost-startStop-1] Loaded OpenAM Authn Radius Module = 1.0.1 built 2015-05-21 19:54 UTC


3) [RADIUS-RadiusServiceStarter]  RadiusServerService not found. Loading...
4) [RADIUS-RadiusServiceStarter] Service Descriptor file for RadiusServerService found at: jar:file:/Users/boydmr/tomcat8/apache-tomcat-8.0.9/webapps/sso/WEB-INF/lib/openam-auth-radius-1.0.1.jar!/RadiusServerService.xml
5) [RADIUS-RadiusServiceStarter] Loading RADIUS Config...
6) [RADIUS-RadiusServiceStarter] --- Loaded Config ---
7) [RadiusServiceConfig NO 1812 P( 1, 10, 10, 10)]
8) [RADIUS-RadiusServiceStarter] RADIUS service disabled.

There are several important things to note in these lines:  

  • Lines 1 and 2 show the context listener being called and logging its version and build information. 
  • All lines related to Radius after that are logged by a thread launched by the context listener and suitably named as the  RADIUS-RadiusServiceStarter
  • Lines 3 and 4 will change for every start hereafter. It turns out that there is an admin console configuration page that is part of the feature set. When starting up, that service is looked for. If not found, as noted in line 3 due to this being our first startup on the extended features, the service descriptor file will be loaded out of the jar as noted in line 4. When next starting, a version of line 3 will indicate that the service was found in OpenAM configuration and hence doesn't need to be loaded.
  • Line 5 shows that configuration is being loaded from the admin console service which included suitable defaults for loading prior to an administrator ever accessing its page.
  • Lines 6 and 7 then show the specific pieces of information being loaded with the values in line 7 correlating with values found in the main configuration page. Namely, whether the Radius UDP listener is enabled, on what port it will listen if started, and the thread pool parameters. If we have any clients defined we would see an additional line per each configured client.
  • Finally, line 8 indicates that the Radius listener is not currently active to receive requests.
When you now access the admin console you'll see that the Radius configuration pages that I outlined in a previous post will now be accessible and can be used to enable the Radius Listener and define clients that can connect to it.

Enjoy.



Friday, May 15, 2015

Radius Connection Test Tool

I've mentioned in previous posts that changes contributed to OpenAM include making its radius jar executable so that it runs what I refer to as the Console Client. This is a very simple command line tool that should allow you to test connection to any radius server and corresponding server side configuration of the related client. I've used it many times with my enhanced OpenAM instance. Then again it is using the same code that the server is for the conversation. So leave a comment if your mileage varies with some other server.

To run this tool you first need to have an instance of the jar. Since the code is not yet in an instance of OpenAM and won't be until version 13 at the soonest, you can download a copy of the jar by clicking this link. Upon clicking that link you'll get the 1.0.1 version of the contributed code in a jar file named openam-auth-radius-1.0.1.jar.

Once you have the jar you run the console client like this:

java -jar openam-auth-radius-1.0.1.jar

The tool needs a configuration file to be located in the current directory named radius.properties. If not found it will write the following to the command line and exit. I've highlighted some interesting parts:

May 15, 2015 2:56:00 PM com.sun.identity.authentication.modules.radius.server.config.RadiusServiceStarter logModuleBuildVersion
INFO: Loaded OpenAM Authn Radius Module = 1.0.1 built 2015-05-12 22:36 UTC

Missing required config file 'radius.properties' in current directory /Users/boydmr/.
Must Contain:
 secret=<shared-secret-with-server>
 host=<hostname-or-ip-address>
 port=<port-on-target-host>

May Contain:
 show-traffic=true

Create a radius.properties file with suitable values for your test. For example, as noted I have OpenAM with the radius server enhancement running on my local machine. Therefore I create that file with these values pointing to my local server.

secret=letmein
host=127.0.0.1
port=1812
show-traffic=true

It works equally well going against a server located elsewhere. Now when I run Console Client it will prompt me for username and password before starting the radius conversation. I've entered my values already in this screen capture. You'll have to use a user and password that exist in your environment.

May 15, 2015 3:00:40 PM com.sun.identity.authentication.modules.radius.server.config.RadiusServiceStarter logModuleBuildVersion
INFO: Loaded OpenAM Authn Radius Module = 1.0.1 built 2015-05-12 22:36 UTC

? Username: demo
? Password: password 


Now what happens after entering the password depends on if you have defined a client on the server and the nature of the configured flow for this client. You will always see an access-request be sent to the server as shown below. But if, for example, the client is not yet defined, you'll see the following traffic be fired to the server and nothing will happen thereafter. The JVM is waiting for a response that will never come since the radius RFC requires that requests from unregistered IP addresses be dropped silently.

Packet To 127.0.0.1:1812
  ACCESS_REQUEST [1]
    - USER_NAME : demo
    - USER_PASSWORD : *******
    - NAS_IP_ADDRESS : localhost/127.0.0.1
    - NAS_PORT : 0

If the client is defined on the server with the IP address from which you are making this UDP request but the shared secret is incorrect then that packet to the server will be followed by this console output and the client will exit.

Packet From 127.0.0.1:1812
  ACCESS_REJECT [1]

---> Sorry. Not Authenticated.

On the server side for OpenAM it doesn't  log this case but simply indicates that an access-reject response was returned. This is because there is no way to distinguish between an incorrect secret and a packet that is corrupted or tampered with. So access is rejected.

If your server issues challenge responses you'll see a response like the following and the client will allow you to enter whatever information is suitable for that challenge, here a one time passcode ostensibly sent via SMS, and wait for you to press the Enter key to send it back to the server.


Packet From 127.0.0.1:1812
  ACCESS_CHALLENGE [1]
    - STATE : fa66c0a9
    - REPLY_MESSAGE : Enter One-Time Passcode (OTP) A one-time validation code has been sent to *******964

---> Enter One-Time Passcode (OTP) A one-time validation code has been sent to *******964
? Answer:

Once you enter your value it will now cause another access-request packet to be sent to the server. But now it also contains the state field if received in the challenge, and its value is unchanged from what it received. Additionally, your answer to the challenge is embedded within the password field.

Packet To 127.0.0.1:1812
  ACCESS_REQUEST [2]
    - USER_NAME : boydmr
    - USER_PASSWORD : *******
    - NAS_IP_ADDRESS : localhost/127.0.0.1
    - NAS_PORT : 0
    - STATE : fa66c0a9

Once all such challenges are successfully answered, or after username and password are entered if no challenges are issued, you will see either an access-accept response indicating that authentication was successful like so:

Packet From 127.0.0.1:1812
  ACCESS_ACCEPT [2]

---> SUCCESS! You've Authenticated!

Or you'll see an access-reject like the following:

Packet From 127.0.0.1:1812
  ACCESS_REJECT [2]

---> Sorry. Not Authenticated.

In both cases the Console Client will output a suitable message indicating the success or failure as shown and will exit.

Oh, and one caveat on using this jar. If you want to leverage the radius updates in OpenAM it takes a couple more steps than just dropping this version into your WEB-INF/lib directory, removing the old one, and restarting tomcat. That is almost all that there is to it. But not quite. There are two more steps. If anyone wants to give it a test run leave me a comment and I'll add another post illustrating those steps. It isn't hard. I'm just out of time for today. :-)

Enjoy.

Reading Values from Custom OpenAM Admin Console Pages

Back in December I outlined how to add configuration pages into OpenAM's admin console and promised to show how to read those values out. This post fulfills that promise.

The first thing to be aware of before reading content from OpenAM's configuration is that if you access that configuration before OpenAM's infrastructure has started up completely, OpenAM essentially becomes brain dead and won't respond until the container is restarted. See my previous post on that topic to know how to avoid that problem. With that out of the way lets dive into listeners.

Listening for Changes


Since your admin console page can be accessed at any point in time, values could be changing that impact how your code should function. For example, in that previous post on adding console pages I used Radius configuration as the requirements for my page. One of the properties indicates if the radius server should be enabled or not. If it is not running and we enable it in that page and press the Save button we would expect it to start up immediately after. Listeners are the means of doing that.

A listener need only be added once during the lifetime of Open AM's instance in its container. The radius code is enabled with a ServletContextListener. Its contextInitialized method is called once by a single thread as part of the guarantee of such listeners. So I instantiate a ConfigLoader class that has an instance variable that it uses to hold the ID of the registered listener. If that variable is empty then I am safe to register it. If you are using some other mechanism to start your services up and it is possible to have multiple threads in there at the same time, then you'll have to take extra precautions with your concurrency. Another place where concurrency is important is when receiving events as we'll see below.

To register a listener you must implement the com.sun.identity.sm.ServiceListener class located in the openam-core jar. It has the following methods:

public void schemaChanged(String serviceName, String version);
public void globalConfigChanged(String serviceName, String version, 
         String groupName, String serviceComponent, int type);
public void organizationConfigChanged(String serviceName, 
         String version, String orgName, String groupName, 
         String serviceComponent, int type);

As noted in my previous post on adding pages to the console, the radius configuration only uses global pieces (radius server specific pieces like what port to listen on) with subschema items (defined radius clients). When any of those change the only method that gets called is globalConfigChanged. I have not tested beyond that to know when the other two methods are called.

But remember that the configuration may change at any point in time including immediately after it was just called. For example, suppose that I enabled the radius server and pressed Save and then remembered that I needed to change the port as well. So I chang the port and hit Save again. I know, finicky user syndrome. But that's the way it goes sometimes. What happens if I use the thread that is calling my listener to drive the startup and shutdown of the radius server listener? That could be a problem in this case if the service that is calling me doesn't ensure sequential, non-overlapping calls. One thread could be attempting to open the port while the second is attempting to shut it down and then restart on another port. Better to be certain of what is happening and when.

So in the radius server listener's case it accepts an instance of ArrayBlockingQueue in its constructor. Then, when changes occur, it calls the queue's offer method. What you pass to that call is really irrelevant and can be whatever makes sense for your application. I'm passing a String that I then log in the receiver (not shown). And you can see that I'm handling the case where my offer is rejected due to a full queue:

public void globalConfigChanged(String serviceName, String version, String groupName, String serviceComponent, int type) {
    boolean accepted = configChangedQueue.offer("RADIUS Config Changed. Loading...");

    if (! accepted) {
        cLog.log(Level.INFO, "RADIUS Client handlerConfig changed but change queue is full. Only happens when previous " +
            "change event takes too long to load changes. Existing queued events will force loading of these changes. " +
            "Therefore, dropping event.");
    }
}

What is important is that you can separately have a daemon thread waiting for items to be put into the queue, handling updates in configuration, adjusting the server as needed when an item shows up, and then go back waiting for the next item to appear only after all effects from the current change have settled.

Registering Your Listener


To register your listener you need an instance of com.sun.identity.sm.ServiceConfigManager also found in openam-core. Since ServiceConfigManager is a mouthful I'll refer to it as the  SCM in the rest of this post. In my previous post I noted that the name attribute of the Service element in your service descriptor file would be necessary to access your configured values. Well here is where that comes into play. To instantiate an instance of the SCM we pass that value to its constructor. Along with it we need an admin token and once we have the SCM instance for our service, we then register our listener via the addListener method as shown below.


SSOToken admTk = (SSOToken) AccessController.doPrivileged(
    AdminTokenAction.getInstance());
ServiceConfigManager mgr = new ServiceConfigManager(
    Constants.RADIUS_SERVICE_NAME, admTk);

if (mgr != null) {
    if (listenerId == null) {
        this.listenerId = mgr.addListener(
            new ConfigChangeListener(configChangedQueue));
    }
    ... other code as needed.
}

Loading Your Configuration


Now lets load the information. The SCM is specifically for my config page service since I handed it the name of that configuration. At this point I'll show what I was told to use by a forge rock employee but I can't explain much detail on the API  nor could he. I hope forge rock can make this clear via documentation at some point. And if you know of such documentation please leave a comment with a link to it.

Items beneath the Global element from the service descriptor file in my previous post appear in the Radius Server page such as port and whether it is enabled or not. Items in its SubSchema element are mapped to radius client instances and show in the Radius Server page's table. To get the items in the Radius Server page I do the following. No, I don't use strings directly in code like this but I put them in here for this post so that you can associate the handling here with the corresponding name attribute of the AttributeSchema elements in the service descriptor file. I've only included the handling for two of the server specific properties:

ServiceConfig serviceConf = mgr.getGlobalConfig("default");

if (serviceConf != null) {
    List<ClientConfig> definedClientConfigs = 
        new ArrayList<ClientConfig>();
    boolean isEnabled = false;
    int listenerPort = -1;
    Map<String, Set<String>> map = serviceConf.getAttributes();
    int coreThreads = -1;
    int maxThreads = -1;
    int queueSize = -1;
    int keepaliveSeconds = -1;

    for (Map.Entry<String, Set<String>> ent : map.entrySet()) {
        String key = ent.getKey();
        String value = extractValue(ent.getValue());
        if ("radiusListenerEnabled".equals(key)) {
            isEnabled = "YES".equals(value);
        }
        // don't need to catch NumberFormatException due to 
        // limiting values in the xml file enforced by console
        else if ("radiusServerPort".equals(key)) {
            listenerPort = Integer.parseInt(value);
        }
        ...handle other values/client instances (see below)
    }


The extractValue method handles an annoying issue. The object that we get for each attribute is a Set object even if there is only a single item contained there-in.  Its code looks as follows:


String extractValue(Set<String> wrappingSet) {
    String[] vals = wrappingSet.toArray(Constants.STRING_ARY);
    return vals[0];
}

To get the radius clients I do the following. On the ServiceConfig object for that "default" global configuration I call its getSubConfigNames method. The names here correspond to the name of each radius client and to the names that show in the Radius Server page's table. For each of those I then ask for its corresponding ServiceConfig object and get its defined attribute just like the handling above. Again, I've only showed handling for a couple of items:

    Set<String> names = serviceConf.getSubConfigNames();

    for (String s : names) {
        // object for holding values in memory
        ClientConfig clientConfig = new ClientConfig(); 
        clientConfig.name = s;

        // go get our admin console values
        ServiceConfig clientCfg = serviceConf.getSubConfig(s);
        map = clientCfg.getAttributes();

        // now just like above we pull out the values by field name
        for (Map.Entry<String, Set<String>> ent : map.entrySet()) {
            String key = ent.getKey();

            if ("clientIpAddress".equals(key)) {
                clientConfig.ipaddr = extractValue(ent.getValue());
            }
            ... other fields
            else if ("handlerConfig".equals(key)) {
                clientConfig.handlerConfig =
                    extractProperties(ent.getValue());
            }
        }
        definedClientConfigs.add(clientConfig);
    }

The handlerConfig attribute corresponds to the list box in the radius client configuration page in which we can enter any number of Strings. I expect it to be a name and value pair separated by an equals character. (I hope to replace this control altogether shortly with a drop down selection box to avoid user input errors but haven't had the time yet.) The  extractProperties method splits each of those into the name and value and injects them all into a Properties object.

Properties extractProperties(Set<String> wrappingSet) {
    String[] vals = wrappingSet.toArray(Constants.STRING_ARY);
    Properties cfg = new Properties();

    for(String val:vals) {
        int idx = val.indexOf('=');

        if (idx == -1) {
            cfg.setProperty(val, "");
        }
        else {
            cfg.setProperty(val.substring(0, idx), 
                val.substring(idx + 1));
        }
    }
    return cfg;
}


Conclusions And Plea

At this point I have the Radius Server page values and an array of ServiceConfig objects that are just POJOs to hold each client's value. And with that information the daemon thread then goes and make the corresponding changes to the radius server and goes back to listening.

That concludes what I've been able to figure out on how to load values managed within OpenAM's Admin Console and registering for and receiving notification of their changes. As yet I've been unable to write these values via code. If anyone has documentation on this API please leave a comment linking to those resources. It would be very beneficial to us all. I hope this has been helpful to someone.

Enjoy.