Learn F5 Technologies, Get Answers & Share Community Solutions Join DevCentral

Filter by:
  • Solution
  • Technology
code share

RADIUS server using APM to authenticate users

Problem this snippet solves:

this code convert APM policy to a RADIUS server.

Code description

When a Radius request is accepted by the VS:

  • the radius client IP address is checked against a Datagroup list.

    • if in list : The shared secret is extracted from Datagroup list
    • if not : drop the packet
  • the password is decrypted with radius secret

  • if request code is Access-Request, an APM session is created and radius attributes are set as session variable (including username and password)

  • Access session is evaluated and return allow or deny result

  • If the Access policy include radius attribute stored in variable session.result.radius_attr, attributes are added to the radius response

  • return Access-Accept or Access-Reject response code based on the session result.

Supported request Packet types:

  • Access-Request (1)

Returned Packet types:

  • Access-Accept (2)
  • Access-Reject (3)

Required request attributes

  • User-Name (1)
  • User-Password (2)

Optional request attributes

  • NAS-IP-Address (4) : IP address
  • NAS-Port (5) : Integer
  • NAS-Identifier (32) : String
  • NAS-Port-Type (61) : Integer

All other attributes are ignored by this irule

Supported response Attributes

All RFC2865 attributes are allowed. Vendor specific attributes are not supported yet.

Note : First version of this code was an enhancement of John McInnes RADIUS Server iRule who had to parse all RADIUS Data (RADIUS::avp did not exist when he wrote it's irule). The irule structure is still the same, but binary operations are optimized and more than 16 bytes passwords support is now included. thanks to Kai Wilke who show previous limitations and leads me to the right direction on how to decode long passwords.

Versions :

1.0 : First version based on RADIUS commands. Required RADIUS profile assigned to the virtual server

1.1 : Added Request Message-Authenticator attribute validation / Response Message-Authenticator insertion (Asked by Sam Hall). To support this feature, the code is rewritten to decode binary data. Radius profile is not required anymore. (31/05/2018)

1.2 : correction on the Request Message-Authenticator attribute validation, a binary conversion to same type is required after [string replace ...]command (1/06/2018)

1.3 : Changed Datagroup radius_clients values format to list of parameters and values. this allow to configure per radius client parameters instead of global parameters (Message-Authenticator validation, ...) (1/06/2018)

1.4 : Security improvement while decoding packet (default decoded integer are signed values, where packet decoding length must be unsigned integer. Thank you Kai wilke for the advices) and added duplicate packet detection (4/06/2018)

How to use this snippet:
  1. Create an Access Policy authenticating users.
  2. Define Access profile name in variable static::apmpolicy
  3. create a data group list radius_clients with values:

    IPAddress := "KEY radius\\ secret [REQMSGAUTH_REQUIRE 1] [RESPMSGAUTH_INSERT 1] [RFC_2865_COMPLIANCE 1]"
    IPAddress := "KEY another\\ radius\\ secret [REQMSGAUTH_REQUIRE 1] [RESPMSGAUTH_INSERT 0] [RFC_2865_COMPLIANCE 1]"
    • KEY parameter must be followed by the shared secret, if it contains space, add 2 \ characters before each space. this parameter is required.
    • REQMSGAUTH_REQUIRE (optional) define if Message-Authenticator attribute is required in request. default value is 0* RESPMSGAUTH_INSERT (optional) define if Message-Authenticator attribute is inserted in response. default value is 0
    • RFC_2865_COMPLIANCE (optional) define if the request must respect RFC 2865 (required attributes). default value is 0
  4. create a virtual server with RADIUS profile to manage RADIUS::avp commands. If you requires to add radius attributes in RADIUS response, create the APM variable session.result.radius_attr with text value (one line, space characters must be escaped):

    Attribute1ID Attribute1Value Attribute2ID Attribute2Value Attribute3ID Attribute3Value

    example :

    18 Authentication\ Successful 27 3600
Tested on Version:
Comments on this Snippet
Comment made 07-Sep-2017 by wuna 1

Thank you for your work.

Comment made 27-May-2018 by Sam Hall 383

This is very nice work. It seems though [RADIUS:id] returns an integer, but in the format string you are interpreting it as a 2 digit hexidecimal. When I test this using radtest tool, I get error messages like "radclient: received response to request we did not send. (id=16 socket 3)". I'm on version 12.1.2. I overcame this by changing those two format strings at the end of your iRule from cH2S... to ccS...

In comparing the features of this iRule to those of node-radius. I'm wondering if there is a need to verify "Message-Authenticator" in the request and also generate one for the response? Or is that just overkill?

Comment made 28-May-2018 by Stanislas Piron 10454

@Sam Hall, I didn’t have issue with radius id, thank you for the feedback, I will change to integer in the code!

This code doesn’t verify Authenticator but retrieve it and check if the variable is set with binary scan!

Then it is used to create the response auth data encoded with md5

Comment made 28-May-2018 by Sam Hall 383

The Message-Authenticator I'm talking about is RADIUS attribute 80. It seems to have became standard practice to include it in all RADIUS request and response for additional security. I noticed it was one thing missing when using radtest tool to compare node-radius server responses with the responses from your iRule. Just something to be aware of, a client may not accept the response if it expects this attribute to be provided.

Comment made 31-May-2018 by Stanislas Piron 10454

@Sam Hall : The code is updated to support Message-authenticator validation / insertion.

Comment made 31-May-2018 by Sam Hall 383

Wow, thanks! I needed to add some conditions like if{$MESSAGE_AUTHENTICATOR ne ""} to accommodate both scenarios, then it worked perfectly. Here are my amendments... https://gist.github.com/Sam-Hall/2de75dcfc6423d55173778743efd38aa

FYI, I can use this to apply our iRule based 2FA solution to VPN clients. I was considering the iRules-LX option posted by Artiom Lichtenstein a while ago, but now there's no need. Thank you very much for this.

Comment made 01-Jun-2018 by Stanislas Piron 10454

@Sam Hall I view this issue but it was hidden by a misconfiguration in the condition (I forgot the not before CRYPTO::verify)

Even if the client doesn't provide Message-Authenticator attribute, the server can answer with it.

I tried it with F5 APM and I was surprised APM doesn't insert This attribute in requests.

If this code helps you, don't forget to rate it. After several month published, this code is still unrated. ;-)

Comment made 01-Jun-2018 by Kai Wilke 6942

Hi Stanislas,

per RFCs there is only a "MAY" demant for PAP based Radius authentication to include the Message-Authenticator attribute, since the User-Password field already provides some sort of origin checks by encrypting its value using the Radius Client specifc shared-key. Maybe this is the reason why APM didn't adopted this field...

But the Message-Authenticator attribute is still the better security mechanism to protect PAP based Radius requests, since it protects the entire request and not just the value of the password.

Without Message-Authenticator a spoofed but still valid Radius Request can be constructed even if you don't know the shared-key. But the authentication will most like fail and probably lock the account at some point since the password will become garbage after decryption...

With Message-Authenticator and a Radius policy configured to enforce Message-Authenticator usage the Radius stack can completely verify the Radius Request integrity before any heavy processing and the actual authentication is performed. So in the end it the Message-Authenticator may help to protect the Radius Server from overloading and may protect your account from becomming locked out.

Note: You don't have to include the Message-Authenticator attribute for non-EAP Radius responses. Its wasted computing power since the regular Radius Response Authenticator already signs the entire Radius Response in an as secure way. Furthermore Radius Client won't expect to receive this attribute on a response if the corresponding request was protected...

FYI: This is the code I'm using in my iRiule Radius Server implementation to verify the Message Authenticator attribute...

#+ Handler for HMAC-based message authenticator attribute verification

#log8 "Checking if HMAC-based message authenticator attribute usage is required for the RADIUS client."

if { $client(require_hmac) == 1 } then {

    #log8 "HMAC-based RADIUS request message authenticator usage is required. 
    #log8 "Checking if the RADIUS request contains a HMAC-based message authenticator attribute."

    if { [string length [set radius(request_hmac) [RADIUS::avp 80]]] == 16 } then {

        #log8 "The RADIUS request contains a HMAC-based message authenticator attribute. 
        #log8 "Re-initializing the message authenticator attribute field (16 bytes) with 0x00 values."

        RADIUS::avp replace 80 "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"

        #log8 "Performing HMAC-MD5 calculation on the initialized UDP payload using clients shared key."
        #log8 "Comparing the HMAC-MD5 calculation result with the received attribute value."

        if { [CRYPTO::sign -alg hmac-md5 -key $client(shared_key) [UDP::payload]] eq $radius(request_hmac) } then {

            #log7 "The HMAC-MD5 signature could be sucessfully verified."
            #istats ISTATS::incr "ltm.virtual [virtual name] c Radius_HMAC_Verified" 1

        } else {

            #log6 "The HMAC-MD5 signature from RADIUS client \"[IP::client_addr]\" could not be verified. Silently discard the packet..."
            #istats ISTATS::incr "ltm.virtual [virtual name] c Radius_HMAC_Failure" 1
            #istats ISTATS::incr "ltm.virtual [virtual name] c Radius_UDP_Drop" 1



    } else {

        #log6 "HMAC-based message authenticator attribute was not send by RADIUS client \"[IP::client_addr]\". Silently discard the packet..."
        #istats ISTATS::incr "ltm.virtual [virtual name] c Radius_HMAC_Missing" 1
        #istats ISTATS::incr "ltm.virtual [virtual name] c Radius_UDP_Drop" 1



} else {

    #log7 "HMAC-based message authenticator attribute usage is not required for this RADIUS client."


# Handler for HMAC-based message authenticator attribute verification

Note: The outlined code is my development-friendly syntax which gets slightly pre-compiled during run-time to make it more efficent and to enable istats and logs as needed.

Cheers, Kai

Comment made 01-Jun-2018 by Stanislas Piron 10454

@Kai I remember an expert who recommended to not edit payload to store variables. ;-)

Glad to see you again here.

Comment made 01-Jun-2018 by Kai Wilke 6942

Hey Stanislas,

I'm not storing a variables. I'm rather then initializing a value within binary data. A small but big difference.... :-P

Anyhow, using [RADIUS:avp replace] for this task is much more elegant and also faster than any manual parsing... ;-)

Cheers, Kai

Comment made 01-Jun-2018 by Stanislas Piron 10454


to make it more elegant, I changed the decoding code to (all attributes are stored in a array with ID as key)

for {set record_offset 0} {$QLEN - $record_offset > 20} {incr record_offset $QAVP_LEN} {
   binary scan $QAVP @${record_offset}cc QAVP_TYPE QAVP_LEN
   binary scan $QAVP @${record_offset}x2a[expr {$QAVP_LEN -2}] QUERY_ATTR($QAVP_TYPE)
   if {$QAVP_TYPE == 80} {
        set UNSIGNED_RAVP [string replace $QAVP $record_offset [expr {$record_offset + 18}] [binary format ccH32 80 18 [string repeat 0 32]]]

then each required attribute is copied to the expected variable

set USER_NAME [expr {[info exists QUERY_ATTR(1)] ? $QUERY_ATTR(1) : ""}]
set USER_PASSWORD [expr {[info exists QUERY_ATTR(2)] ? $QUERY_ATTR(2) : ""}]
set CHAP_PASSWORD [expr {[info exists QUERY_ATTR(3)] ? $QUERY_ATTR(3) : ""}]
Comment made 03-Jun-2018 by Sam Hall 383

@Kai, have a read through RFC 5080. Page 6 states "Any Access-Request packet that performs authorization checks, including Call Check, SHOULD contain a Message-Authenticator attribute.". Then later "Requests not containing a Message-Authenticator attribute MAY then be silently discarded."

Comment made 04-Jun-2018 by Kai Wilke 6942

@Sam: A Radius Access-Request packet "MAY" contain a Message-Authenticator attribute and Radius implementers "SHOULD" adopt this security feature. But in the end its still not a "MUST" requirement for both. Please don't get me wrong, I do personally recommend to adopt this attribute (and also other useful post RFC2865 extensions, recommendations and clarifications) every single day.

@Stanislas: Well, its up to you to store every single attribute in a variable. But keep in mind, that some attributes may be included more than once in a single Radius request. Last but not least, you may also want to check your input validation twice. With the recent additions you are allowing an attacker to crash your TMM by sending a single handcrafted UDP datagram...

Cheers, Kai

Comment made 04-Jun-2018 by Stanislas Piron 10454

@Kai : You're right again.

I was working on a simplification / security improvement.

  1. check payload length according to RFC

    if {[binary scan [UDP::payload] cH2Sa16 QCODE IDENTIFIER QLEN Q_AUTHENTICATOR] != 4 || $QLEN > [UDP::payload length] || $QLEN > 4096} {
    } else {
        # Store only PAYLOAD in variable if Length field is valid (less than 4096 and less than payload length). prevent variable allocation if payload not valid.
        # Octets outside the range of the Length field MUST be treated as padding and ignored on reception.
        set PAYLOAD [UDP::payload $QLEN]
  2. create a hash of payload to manage "Duplicate Detection"
    I was thinking to store payload md5 hash as session variable key (one subtable per IP address) with response payload in value and with 30s timeout.

Comment made 04-Jun-2018 by Kai Wilke 6942

Hi Stanislas,

1.) I prefer to check if at least 20 bytes are received instead of starting to parsing the outer protocol encapsulation and then count the resulting fields, but its a personal preference.

2.) I'm glad you found out that the UDP-layer needs some attention too, to make the Radius Server RFC compliant and also stable enough for OTP operations. I recommend to use the algorythm mentioned in RFC 5080 to maintain the caches...

In addition to that...

1.) Learn the small but important difference between a signed and unsigned integer.

2.) Test your iRule with the UDP payloads below and watch your TMM entering an endless [for] loop and finally crashing...

set PAYLOAD "\x01\xff\x00\x18\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x02\x01\xfe"
set PAYLOAD "\x01\xff\x00\x16\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x00"

3.) Make sure to spent me a beer during the next MVP summit for pointing out some coding flaws... ;-)

4.) And spent me another beer to get a free copy of my iRule based Radius Server stack... ;-)

Cheers, Kai

Comment made 04-Jun-2018 by Stanislas Piron 10454

I guess this is better:

    for {set record_offset 20} {$record_offset < $QLEN } {incr record_offset $QAVP_LEN} {
       binary scan $PAYLOAD @${record_offset}cc QAVP_TYPE QAVP_LEN
       set QAVP_LEN [expr {$QAVP_LEN & 0xFF}]
       # If an Attribute is received in an Access-Accept, Access-Reject or Access-Challenge packet with an invalid length, 
       # the packet MUST either be treated as an Access-Reject or else silently discarded.
       if {($QAVP_LEN < 3) || ($record_offset+$QAVP_LEN > $QLEN) } {UDP::drop; return}
       binary scan $PAYLOAD @${record_offset}x2a[expr {$QAVP_LEN -2}] QUERY_ATTR($QAVP_TYPE)
       if {$QAVP_TYPE == 80} {
            binary scan [string replace $PAYLOAD $record_offset [expr {$record_offset + 18}] [binary format ccH32 80 18 [string repeat 0 32]]] a* UNSIGNED_REQUEST
Comment made 04-Jun-2018 by Kai Wilke 6942

My additional 1.) and 2.) puzzles should be solved now. 3.) is still unsolved and 4.) remains optional... ;-)

Cheers, Kai

Comment made 04-Jun-2018 by Stanislas Piron 10454

3 - of course. but with this agreement, I'm afraid some other people will try to help me too ;-)

4 - No really need the code, I wrote it for learning and have fun during free time. I expected your's last september ;-). But I'll be happy for this one too (the beer I mean)

Comment made 04-Jun-2018 by Stanislas Piron 10454

I just updated the code thanks to kai’s advices.

Read version history to see changes.

Comment made 04-Jun-2018 by Kai Wilke 6942

4 - Did sold my Radius stack to a customer. Will check up with them again to get the approval for publishing...

Cheers, Kai

Comment made 04-Jul-2018 by Sam Hall 383

Thanks for keeping all the APM logic in one place, it was easy to replace with my 2FA iRule logic and update it to v1.4. One thing I amended was the duplicate package logic, since we are sometimes authenticating "Time-based One Time Passwords". I only store a response at the end if it wasn't an "Access-Accept", and only for 1 second maximum life time. Thanks for the heroic effort!