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
orallow
resultdeny
-
If the Access policy include radius attribute stored in variable
, attributes are added to the radius responsesession.result.radius_attr
-
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:
- Create an Access Policy authenticating users.
- Define Access profile name in variable
static::apmpolicy
-
create a data group list
with values:radius_clients
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
-
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
Code :
when RULE_INIT { set static::apmpolicy "/Common/AP_RADIUS_SERVICE" set static::client_list "radius_clients" } when CLIENT_ACCEPTED { binary scan [md5 [UDP::payload]] H* PAYLOAD_HASH switch [set DUPLICATE_RESPONSE [table lookup -subtable [IP::client_addr] $PAYLOAD_HASH]] { "" { # Do nothing, not in table } drop { log local0. "Duplicate packet detected with drop decision... dropping again" UDP::drop; return } default { log local0. "Duplicate packet detected sending same answer from table" UDP::respond [binary format H* $DUPLICATE_RESPONSE] return } } set RespLength 20 set RespAVP "" ############## START OF ALLOWED RADIUS CLIENT IP VALIDATION ################# if {![class match [IP::client_addr] equals $static::client_list]} { log local0. "RADIUS Client not in Datagroup : [IP::client_addr]" # RFC 2865 : A request from a client for which the RADIUS server does not have a shared secret MUST be silently discarded table add -subtable [IP::client_addr] $PAYLOAD_HASH "drop" 30 600 UDP::drop return } # Set default values if Datagroup miss this configuration set RADCLIENT(REQMSGAUTH_REQUIRE) 0 set RADCLIENT(RESPMSGAUTH_INSERT) 0 set RADCLIENT(RFC_2865_COMPLIANCE) 1 #Retreive RADIUS client shared secret and radius client capabilities. array set RADCLIENT [class match -value [IP::client_addr] equals $static::client_list] if {[binary scan [UDP::payload] cH2Sa16 QCODE IDENTIFIER QLEN Q_AUTHENTICATOR] != 4 || [set QLEN [expr {$QLEN & 0xFFFF}]] > [UDP::payload length] || $QLEN > 4096} { table add -subtable [IP::client_addr] $PAYLOAD_HASH "drop" 30 600 UDP::drop return } 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] } switch $QCODE { 1 { set REQUEST_NOT_ALLOWED 0 #Store All attribute in array QUERY_ATTR with Attrbute ID as Key for {set record_offset 20} {$record_offset < $QLEN } {incr record_offset $QAVP_LEN} { # 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 {([binary scan $PAYLOAD @${record_offset}cc QAVP_TYPE QAVP_LEN] != 2) || ([set QAVP_LEN [expr {$QAVP_LEN & 0xFF}]] < 3) || ($record_offset+$QAVP_LEN > $QLEN) } { table add -subtable [IP::client_addr] $PAYLOAD_HASH "drop" 30 600 UDP::drop return } switch -- [set QAVP_TYPE [expr { $QAVP_TYPE & 0xFF}]] { 1 - 2 - 3 - 4 - 5 - 24 - 32 - 61 {binary scan $PAYLOAD @${record_offset}x2a[expr {$QAVP_LEN -2}] QUERY_ATTR($QAVP_TYPE)} 80 { binary scan $PAYLOAD @${record_offset}x2a[expr {$QAVP_LEN -2}] QUERY_ATTR($QAVP_TYPE) binary scan [string replace $PAYLOAD $record_offset [expr {$record_offset + 18}] [binary format ccH32 80 18 [string repeat 0 32]]] a* UNSIGNED_REQUEST } } } #Assign attibutes to expected variable, with decoding if required. 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) : ""}] if {[info exists QUERY_ATTR(4)]} {binary scan $QUERY_ATTR(4) c4 octets; foreach octet $octets {lappend r [expr {$octet & 0xFF}]}; set NAS_IP_ADDRESS [join $r .] } else {set NAS_IP_ADDRESS "" } if {[info exists QUERY_ATTR(5)]} {binary scan $QUERY_ATTR(5) I NAS_PORT; set NAS_PORT [expr {$NAS_PORT & 0xFFFFFFFF}] } else {set NAS_PORT "" } set STATE [expr {[info exists QUERY_ATTR(24)] ? $QUERY_ATTR(24) : ""}] set NAS_IDENTIFIER [expr {[info exists QUERY_ATTR(32)] ? $QUERY_ATTR(32) : ""}] #if {[info exists QUERY_ATTR(61)]} {binary scan $QUERY_ATTR(61) I NAS_PORT_TYPE; set NAS_PORT_TYPE [expr {$NAS_PORT_TYPE & 0xFFFFFFFF}] } else {set NAS_PORT_TYPE "" } set MESSAGE_AUTHENTICATOR [expr {[info exists QUERY_ATTR(80)] ? $QUERY_ATTR(80) : ""}] #EVALUATE REQUEST MESSAGE-AUTHENTICATOR if {$RADCLIENT(REQMSGAUTH_REQUIRE) && ($MESSAGE_AUTHENTICATOR equals "" || ![CRYPTO::verify -alg hmac-md5 -key $RADCLIENT(KEY) -signature $MESSAGE_AUTHENTICATOR $UNSIGNED_REQUEST])} { # RFC 2869 : A RADIUS Server receiving an Access-Request with a Message-Authenticator Attribute present MUST calculate the correct value # of the Message-Authenticator and silently discard the packet if it does not match the value sent. log local0. "[IP::client_addr] : wrong or missing Message-Authenticator attribute" table add -subtable [IP::client_addr] $PAYLOAD_HASH "drop" 30 600 UDP::drop return } if {$RADCLIENT(RFC_2865_COMPLIANCE)} { if {$NAS_IP_ADDRESS == "" && $NAS_IDENTIFIER == ""} { # RFC 2865 : It MUST contain either a NAS-IP-Address attribute or a NAS-Identifier attribute (or both). set REQUEST_NOT_ALLOWED 1 set RAVP(18) "REQUEST NOT RFC COMPLIANT" } elseif {$USER_PASSWORD == "" && $CHAP_PASSWORD == "" && $STATE == ""} { # RFC 2865 : An Access-Request MUST contain either a User-Password or a CHAP-Password or a State. set REQUEST_NOT_ALLOWED 1 set RAVP(18) "REQUEST NOT RFC COMPLIANT" } elseif {$USER_PASSWORD ne "" && $CHAP_PASSWORD ne ""} { # RFC 2865 : An Access-Request MUST NOT contain both a User-Password and a CHAP-Password. set REQUEST_NOT_ALLOWED 1 set RAVP(18) "REQUEST NOT RFC COMPLIANT" } } if {$USER_PASSWORD == ""} { set REQUEST_NOT_ALLOWED 1 set RAVP(18) "USER-PASSWORD NOT SET BUT REQUIRED" } elseif {$USER_NAME == ""} { set REQUEST_NOT_ALLOWED 1 set RAVP(18) "USER-NAME NOT SET BUT REQUIRED" } } 2 - 3 - 11 { set REQUEST_NOT_ALLOWED 1 set RAVP(18) "RADIUS CODE NOT SUPPORTED - NOT A RADIUS CLIENT" } 4 - 5 - 6 - 10 { set REQUEST_NOT_ALLOWED 1 set RAVP(18) "RADIUS CODE NOT SUPPORTED - NOT A RADIUS ACCOUNTING SERVER" } default { set REQUEST_NOT_ALLOWED 1 set RAVP(18) "RADIUS CODE NOT SUPPORTED" } } ############## END OF RFC COMPLIANCE AND SERVER FEATURES VALIDATION ################# # DO NOT RELEASE UDP PACKET. Drop it to prevent further process by irule or load balancing to an internal server. # When UDP packet dropped, PAYLOAD is dropped and RADIUS Commands not available anymore. UDP::drop if {$REQUEST_NOT_ALLOWED == 0} { ########## START OF PASSWORD DECRYPTION ############################ binary scan [md5 "$RADCLIENT(KEY)$Q_AUTHENTICATOR"] H* bx_hex binary scan $USER_PASSWORD H* px_full_hex set Password_Padded "" for {set x 0} {$x<[string length $px_full_hex]} {set x [expr {$x+32}]} { set px_hex [string range $px_full_hex $x [expr {$x+31}]] append Password_Padded [binary format W [expr 0x[string range $px_hex 0 15] ^ 0x[string range $bx_hex 0 15]]] append Password_Padded [binary format W [expr 0x[string range $px_hex 16 31] ^ 0x[string range $bx_hex 16 31]]] binary scan [md5 "$RADCLIENT(KEY)[binary format H* $px_hex]"] H* bx_hex } binary scan $Password_Padded A* PASSWORD ########## END OF PASSWORD DECRYPTION ############################ ########## START OF APM AUTHENTICATION ############################ set flow_sid [ACCESS::session create -timeout 60 -lifetime 300] ACCESS::policy evaluate -sid $flow_sid -profile $static::apmpolicy \ session.logon.last.username $USER_NAME \ session.logon.last.password $PASSWORD \ session.server.landinguri "/" \ session.logon.last.NAS_IP_Address $NAS_IP_ADDRESS \ session.logon.last.NAS_Port $NAS_PORT \ session.logon.last.NAS_Identifier $NAS_IDENTIFIER \ session.logon.last.NAS_Port_Type $NAS_PORT if {[ACCESS::policy result -sid $flow_sid] equals "allow"} { set ResponseCode 2 if {![info exists RAVP(18)] } {set RAVP(18) "Good username Password"} } else { set ResponseCode 3 if {![info exists RAVP(18)] } {set RAVP(18) "wrong username Password"} } array set RAVP [ACCESS::session data get -sid $flow_sid session.result.radius_attr] ACCESS::session remove -sid $flow_sid ########## END OF APM AUTHENTICATION ############################ } else { set ResponseCode 3 if {[info exists RAVP(18)] } { log local0. $RAVP(18)} } ########## ENCODING AND DELIVERY OF RADIUS RESONSE ############################ foreach attrID [array names RAVP] { incr RespLength [set attrLength [expr {[string length $RAVP($attrID)]+2}]] append RespAVP [binary format cca* $attrID $attrLength $RAVP($attrID)] } #CALCULATE RESPONSE MESSAGE-AUTHENTICATOR if {$RADCLIENT(RESPMSGAUTH_INSERT)} { set UNSIGNED_RespAVP $RespAVP[binary format ccH32 80 18 [string repeat 0 32]] incr RespLength 18 append RespAVP [binary format cc 80 18][CRYPTO::sign -alg hmac-md5 -key $RADCLIENT(KEY) [binary format cH2Sa16a* $ResponseCode $IDENTIFIER $RespLength $Q_AUTHENTICATOR $UNSIGNED_RespAVP]] } binary scan [md5 [binary format cH2Sa16a[expr {$RespLength-20}]a[string length $RADCLIENT(KEY)] $ResponseCode $IDENTIFIER $RespLength $Q_AUTHENTICATOR $RespAVP $RADCLIENT(KEY) ]] H* ResponseAuth set RESPONSE [binary format cH2SH32a* $ResponseCode $IDENTIFIER $RespLength $ResponseAuth $RespAVP] UDP::respond $RESPONSE binary scan $RESPONSE H* RESPONSE_HEX table add -subtable [IP::client_addr] $PAYLOAD_HASH $RESPONSE_HEX 15 60 }
Tested this on version:
12.0- WunaNimbostratus
Thank you for your work.
- Sam_HallNimbostratus
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?
- Stanislas_Piro2Cumulonimbus
@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
- Sam_HallNimbostratus
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.
- Stanislas_Piro2Cumulonimbus
@Sam Hall : The code is updated to support Message-authenticator validation / insertion.
- Sam_HallNimbostratus
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.
- Stanislas_Piro2Cumulonimbus
@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. 😉
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 UDP::drop return } } 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 UDP::drop return } } 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
- Stanislas_Piro2Cumulonimbus
@Kai I remember an expert who recommended to not edit payload to store variables. ;-)
Glad to see you again here.
Hey Stanislas,
I'm not storing a variables. I'm rather then initializing a value within binary data. A small but big difference.... 😛
Anyhow, using
for this task is much more elegant and also faster than any manual parsing... 😉[RADIUS:avp replace]
Cheers, Kai