radius
39 TopicsiRule to decrypt and rewrite RADIUS User-Password AVP
In the RADIUS protocol, the user's cleartext password is transmitted inside Attribute-Value Pair (AVP) 2, padded with null characters as necessary, and then encrypted by the shared secret by XOR'ing it across the authenticator somehow or other. The technical details of how this works is a bit above my level of understanding as I'm not a cryptography expert. We have an infrastructure where our PAN VPN Gateway prompts a user for their username and password. In our environment, after the password, the user appends a fixed-length HOTP token from a Yubikey. The backend FreeRADIUS server has been configured to decrypt the password received, extract the fixed-length token, and perform backend checks to our LDAP and token servers. FYI, the password is encoded as PAP prior to RADIUS encryption in our setup, which is why this works; CHAP would prevent this from working. We've been having trouble with the stability of our FreeRADIUS server and we would like to leverage our much more stable Aruba ClearPass infrastructure which is load balanced globally with our GTMs and LTMs and highly stable. This also moves control of the RADIUS piece away from the systems team and onto the network team (me, specifically). Unfortunately, ClearPass doesn't have a direct mechanism to break the password from the token, and PAN doesn't have a way to transmit the token separately. This is where we would like to leverage an iRule. Basically, the way I envision this working is as such: Decrypt the password+OTP that is received from PAN using the authenticator value and shared secret Rewrite AVP 2 as just the password, encrypted by the shared secret (make sure to adjust the length of the AVP) Insert AVP 17 (which is not defined by the IEFT) with the token (ClearPass can be configured to look for this by modifying its RADIUS dictionary). Rewrite the length value at layer 7 if necessary - not sure if this would happen automatically by the F5; probably not. Ship the modified RADIUS packet to ClearPass I know how to accomplish all of this on the ClearPass side, but my dev skills are weak, I'm not very familiary with Tcl, and I don't have a solid understanding of how to encrypt/decrypt the password correctly. I've search high and low but the only solutions for decrypting the password seem to be written in languages that are even more difficult to understand like C. I obviously understand it is too much to expect someone to write the entire solution for me, but any advice on where to start would be very helpful. I think the trickiest part for me would be the encrypt/decrypt step.Solved2.8KViews0likes21CommentsCisco ISE load-balancing and Change of Authorization (CoA)
First, let me clearly state that I do not have a Cisco background. I have no experience with the RADIUS protocol, and am not familiar with the details of the CoA, so I am not in a position to know if what I'm being asked to do is appropriate/necessary/makes sense or not. Our Cisco guys came to me asking for a RADIUS load-balancing VIP, with persistence based on CALLING-STATION-ID. I found https://devcentral.f5.com/questions/load-balance-cisco-ise-servers easily enough. So I created a wildcard UDP VIP with the iRule. But, they came back with an additional CoA requirement. They claim that the ISE servers periodically send "a CoA packet" to the clients of the RADIUS VIP. They want the LTM to intercept these packets, and SNAT it from the RADIUS VIP address. They claim that the clients of the RADIUS service will only accept CoA packets from the VIP address. Apart from the link above, the only good resource on the subject I can find is https://supportforums.cisco.com/blog/153056/ise-and-load-balancing. I get somewhat lost in the terminology, but this statement seems important: Each PSN gets listed individually in the Dynamic-Authorization (CoA). Use the real IP Address of the PSN, not the VIP. In the context of this document it sounds to me like the "PSN" is also the Pool Member of the RADIUS VIP, and that we should be adding the IP address of the Pool Member in some CoA field on the clients of the RADIUS VIP. But again not being familiar with RADIUS, I'm very uncertain. Apart from the question of whether or not I can SNAT from a VIP address at all (which I highly doubt), does anyone have some insight into how to account for these RADIUS/CoA packets in a load-balancing context?2.8KViews0likes8CommentsRadius Authentication role not working
Hi Guys, We setup authentication setup using this article: https://support.f5.com/csp/article/K14324#3 But when we logged in using the accounts on the radius, f5 sets the user as admin account even the account should be read only. Are we missing some configurat2.2KViews0likes13CommentsRADIUS 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: Create an Access Policy authenticating users. Define Access profile name in variable static::apmpolicy 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 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.02.2KViews0likes21CommentsRADIUS Access-Challenge Response Issue
Hi, I'm trying to configure the APM functionality on a BigIP running 13.1.02 to support the "Change PIN" request of the Swivel Secure PINsafe authentication; but I seem to be hitting a more fundamental issue with the BigIP's RADIUS Access-Challenge support. Normal RADIUS authentication against the Swivel authentication server is working fine. The user logs in; with their credentials submitted over HTTP to the F5 and from there via a RADIUS Access-Request to the Swivel server: RADIUS Protocol Code: Access-Request (1) Packet identifier: 0xf2 (242) Length: 103 Authenticator: f25**********************aa92 [The response to this request is in frame 3] Attribute Value Pairs AVP: t=User-Name(1) l=10 val=XXXXXXXXX AVP: t=User-Password(2) l=18 val=Decrypted: 3407 Type: 2 Length: 18 User-Password: 3407 AVP: t=NAS-IP-Address(4) l=6 val=10.XXX.XXX.XXX AVP: t=NAS-Identifier(32) l=21 val=XXXXXXXXXXXXX AVP: t=Service-Type(6) l=6 val=Authenticate-Only(8) AVP: t=Tunnel-Client-Endpoint(66) l=16 val=192.168.86.142 AVP: t=NAS-Port(5) l=6 val=0 If the user requires that their PIN be changed; the Swivel authentication server responds with a RADIUS Access-Challenge: RADIUS Protocol Code: Access-Challenge (11) Packet identifier: 0xf2 (242) Length: 31 Authenticator: f034de3****************586dd5 [This is a response to a request in frame 2] [Time from request: 0.021004000 seconds] Attribute Value Pairs AVP: t=Reply-Message(18) l=11 val=changepin Type: 18 Length: 11 Reply-Message: changepin The F5 successfully detects this Access-Challenge request and presents the user with a further login page containing the Reply-Message as the header (so "changepin" in this case); followed by a single input element (id of "input_1" and name of "_F5_challenge") into which the user can respond. With the user's response typed into the single input element and the new form submitted; I can see in the HTTP request from the web browser to the F5 the form variable of "_F5_challenge" correctly set to the value typed into the input element. Looks good so far... From the RADIUS RFC 2865: "If the client receives an Access-Challenge and supports challenge/response it MAY display the text message, if any, to the user, and then prompt the user for a response. The client then re-submits its original Access-Request with a new request ID, with the User-Password Attribute replaced by the response (encrypted), and including the State Attribute from the Access-Challenge, if any." I would therefore expect that the F5 would use value it received in _F5_challenge HTTP form parameter as the new User-Password value within theRADIUS Access-Request that responds to the Access-Challenge. This is not what I see – if I capture and decode this RADIUS Access-Request I can see that User-Password is the same value as from the original RADIUS Access-Request from the initial logon page: RADIUS Protocol Code: Access-Request (1) Packet identifier: 0xaa (170) Length: 105 Authenticator: aaf*********************3075 [The response to this request is in frame 5] Attribute Value Pairs AVP: t=User-Name(1) l=10 val=XXXXXXXXXX AVP: t=User-Password(2) l=18 val=Decrypted: 3407 Type: 2 Length: 18 User-Password: 3407 AVP: t=NAS-IP-Address(4) l=6 val=10.XXX.XXX.XX AVP: t=NAS-Identifier(32) l=21 val=XXXXXXXXXXXXXXX AVP: t=Service-Type(6) l=6 val=Authenticate-Only(8) AVP: t=Tunnel-Client-Endpoint(66) l=16 val=192.168.86.142 AVP: t=NAS-Port(5) l=6 val=0 AVP: t=State(24) l=2 val= Type: 24 Length: 2 State: <MISSING> Of course; the original password (PIN in this case) is not valid for the replacement PIN within the Swivel server and therefore the PIN change process fails. The fundamental issue seems to be that I'm unable to control the User-Password element of the F5's reply to the Access-Challenge based on that HTML input element. Any idea what could be wrong here? Many thanks aid1.5KViews0likes0CommentsBIG-IP APM: RADIUS and SSO mapping broken
Hi All I think that using a combination of RADIUS authentication (with one-time token) and SSO credential mapping within APM is broken. Credentials entered on the logon page are stored in the username & password session variables. If you do a RADIUS authentication with one-time token, the password variable will be overwritten with the token. So an SSO credential mapping after the RADIUS authentication will get a wrong password. You can prevent this with either putting the SSO credential mapping before the RADIUS block, or "caching" the initial password in a separate variable with variable assign before ( password2 = password ) and after ( password = password2 ) the RADIUS block. However, this fix will not work if the user enters the wrong password initially. The RADIUS block will reload the login page and show you the "wrong credential" warning as often as you define, but the SSO credential mapping or variable assign defined BEFORE the RADIUS authentication won't be updated with the correct password. I know that I could set the "max. attempts allowed" to 1 and have a completely new APM session after every wrong credential or I could build a loop and lose the "wrong credential" message, but those 2 options are not that pretty in my opinion. I'm just wondering if someone has a nice solution to this problem. Cheers PatrickSolved1.5KViews1like4CommentsRADIUS server authenticating user with Google Authenticator
Problem this snippet solves: This code create a RADIUS server to authenticate users with Authenticator algorithm (Google Authenticator and Microsoft Authenticator apps) 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, the request username is searched in a datagroup and the user key is extracted The code is calculated and compared with radius password provided in the RADIUS request. return Access-Accept or Access-Reject response code based on the authenticator algorithm 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 : Many thanks to Kai wilke, John McInnes and George Watkins who shared their snippets I used to write this irule. 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 in RADIUS server using APM to authenticate users code). 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) How to use this snippet: Create an Access Policy authenticating users. Define Access profile name in variable static::apmpolicy create a data group list google_auth_keys with values: username := "Authenticator key" create a data group list radius_clients with values: IPAddress := "radius secret" create a virtual server with RADIUS profile to manage RADIUS::avp commands. Code : proc ga_validate {hmac_mode key_size b32_key token allowed_clock_skew_units} { ############################################################################################## # Initialize the Base32 alphabet to binary conversation (see RFC 4648) # set b32_to_binary [list \ A 00000 B 00001 C 00010 D 00011 E 00100 F 00101 G 00110 H 00111 \ I 01000 J 01001 K 01010 L 01011 M 01100 N 01101 O 01110 P 01111 \ Q 10000 R 10001 S 10010 T 10011 U 10100 V 10101 W 10110 X 10111 \ Y 11000 Z 11001 2 11010 3 11011 4 11100 5 11101 6 11110 7 11111 \ 0 "" 1 "" = "" " " "" \ ] if { [string length [set key [string map -nocase $b32_to_binary $b32_key]]] >= $key_size } then { # Convert the translated ga(key) binary string representation to binary set binary_key [binary format B$key_size $key] # Initialize clock timeframe based on Unix epoch time in seconds / 30 set clock [expr { [clock seconds] / 30 } ] ############################################################################################## # Configure the allowed clock skew units (1 unit = +/-30 seconds in both directions) # set allowed_clock_range {0} for {set i 1} {$i <= $allowed_clock_skew_units} {incr i} {lappend allowed_clock_range -$i $i} ############################################################################################## # Perform verification of the provided token foreach x $allowed_clock_range { ############################################################################################## # Perform verification of the provided token for time frame clock + $x # # Calculate hex encoded HMAC checksum value for wide-int value of time frame clock+ x using key_binary as secret binary scan [CRYPTO::sign -alg $hmac_mode -key $binary_key [binary format W* [expr { $clock + $x }]]] H* hmac_tmp # Parse offset based on the last nibble (= 4 bits / 1 hex) of the hmac_tmp HMAC checksum and multiply with 2 for byte to hex conversation set offset [expr { "0x[string index $hmac_tmp end]" * 2 } ] # Parse (= 4 bytes / 8 hex) from hmac_tmp starting at the offset value, then remove the most significant bit, perform the modulo 1000000 and format the result to a 6 digit number set token_calculated [format %06d [expr { ( "0x[string range $hmac_tmp $offset [expr { $offset + 7 } ]]" & 0x7FFFFFFF ) % 1000000 } ]] # Compare token_calculated with user provided token value if { $token_calculated equals $token } then { # The provided token is valid" return 1 break } } } else { return -1 } return 0 } when RULE_INIT { set static::client_list "radius_clients" set static::RFC_2865_FULL_COMPLIANCE 1 set static::MESSAGE_AUTHENTICATOR_REQUIRED 1 } when CLIENT_ACCEPTED { 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 UDP::drop return } #Retreive RADIUS client shared secret set secret [class match -value [IP::client_addr] equals $static::client_list] if {[binary scan [UDP::payload] cH2Sa16a* QCODE QID QLEN Q_AUTHENTICATOR QAVP] != 5} { set REQUEST_NOT_ALLOWED 1 set RAVP(18) "REQUEST AUTHENTICATOR FAILURE" } #Store Request ID in Response ID set RID $QID switch $QCODE { 1 { set REQUEST_NOT_ALLOWED 0 set USER_NAME "" set USER_PASSWORD "" set CHAP_PASSWORD "" set NAS_IP_ADDRESS "" set NAS_PORT "" set NAS_PORT_TYPE "" set MESSAGE_AUTHENTICATOR "" set UNSIGNED_REQUEST [UDP::payload] set NAS_IDENTIFIER "" set QAVP_LIST_LEN [expr {$QLEN - 20}] set record_offset 0 while {[expr {$QAVP_LIST_LEN - $record_offset}] > 4} { binary scan $QAVP @${record_offset}cc QAVP_TYPE QAVP_LEN set QAVP_VAL_LEN [expr {$QAVP_LEN -2}] binary scan $QAVP @${record_offset}x2a${QAVP_VAL_LEN} QAVP_VAL switch $QAVP_TYPE { 1 { set USER_NAME $QAVP_VAL } 2 { set USER_PASSWORD $QAVP_VAL } 3 { set CHAP_PASSWORD $QAVP_VAL } 4 { binary scan $QAVP_VAL c4 octets foreach octet $octets { lappend r [expr {$octet & 0xFF}] } set NAS_IP_ADDRESS [join $r .] } 5 { binary scan $QAVP_VAL I NAS_PORT set NAS_PORT [expr {$NAS_PORT & 0xFFFFFFFF}] } 24 { set STATE $QAVP_VAL } 32 { set NAS_IDENTIFIER $QAVP_VAL } 61 { binary scan $QAVP_VAL I NAS_PORT_TYPE; set NAS_PORT_TYPE [expr {$NAS_PORT_TYPE & 0xFFFFFFFF}]; } 80 { set MESSAGE_AUTHENTICATOR $QAVP_VAL set UNSIGNED_RAVP [string replace $QAVP $record_offset [expr {$record_offset + 18}] [binary format ccH32 80 18 [string repeat 0 32]]] set UNSIGNED_REQUEST [binary format cH2Sa16a* $QCODE $QID $QLEN $Q_AUTHENTICATOR $UNSIGNED_RAVP] } default { } } set record_offset [expr {$record_offset + $QAVP_LEN}] } #EVALUATE REQUEST MESSAGE-AUTHENTICATOR if {$static::MESSAGE_AUTHENTICATOR_REQUIRED && ($MESSAGE_AUTHENTICATOR equals "" || ![CRYPTO::verify -alg hmac-md5 -key $secret -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" UDP::drop return } if {$static::RFC_2865_FULL_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" } elseif {[set userkey [class lookup $USER_NAME "google_auth_keys"]] equals ""} { 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 "$secret$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 "$secret[binary format H* $px_hex]"] H* bx_hex } binary scan $Password_Padded A* PASSWORD ########## END OF PASSWORD DECRYPTION ############################ ########## START OF GOOGLE AUTHENTICATION ############################ switch -- [call ga_validate "hmac-sha1" 80 $userkey $PASSWORD 10] { -1 { # code verification failed set ResponseCode 3 if {![info exists RAVP(18)] } {set RAVP(18) "wrong username Password"} log local0. "erreur 2 : wrong User Key" } 0 { # code verification failed set ResponseCode 3 if {![info exists RAVP(18)] } {set RAVP(18) "wrong username Password"} } 1 { # code verification successful set ResponseCode 2 if {![info exists RAVP(18)] } {set RAVP(18) "Good username Password"} } default {set result "error: unknown"} } ########## END OF GOOGLE 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] { set RespLength [expr {[set attrLength [expr {[string length $RAVP($attrID)]+2}]] + $RespLength}] append RespAVP [binary format cca* $attrID $attrLength $RAVP($attrID)] } #CALCULATE RESPONSE MESSAGE-AUTHENTICATOR set UNSIGNED_RespAVP $RespAVP[binary format ccH32 80 18 [string repeat 0 32]] #set UNSIGNED_RespAVP $RespAVP[binary format ccH32 80 18 "00000000000000000000000000000000"] set RespLength [expr {18 + $RespLength}] append RespAVP [binary format cc 80 18][CRYPTO::sign -alg hmac-md5 -key $secret [binary format cH2Sa16a* $ResponseCode $RID $RespLength $Q_AUTHENTICATOR $UNSIGNED_RespAVP]] #append RespAVP [binary format ccH32 80 18 "1234567890ABCDEF1234567890ABCDEF"] binary scan [md5 [binary format cH2Sa16a[expr {$RespLength-20}]a[string length $secret] $ResponseCode $RID $RespLength $Q_AUTHENTICATOR $RespAVP $secret ]] H* ResponseAuth UDP::respond [binary format cH2SH32a* $ResponseCode $RID $RespLength $ResponseAuth $RespAVP] }1.5KViews0likes0CommentsRadius External Monitor (Python)
Problem this snippet solves: Note: This script works and is usable however currently the only issue is that for some unknown reason it fails authentication on valid credentials, but since it still gets a valid response from the Radius server it will still mark the pool member as up. This only occurs via a configured monitor using either variable or arguments, running the script via command line with the same arguments works. This python script is an external monitor for radius that checks for any radius response in order to mark a pool member as up. If the connection times out the script does not output any response and as such will result in the member being marked as down. The script strips of routing domain tags and the IPv6 padding of the Node IPs. How to use this snippet: Installation: Import as an External Monitor Program File and name it however you want. Get and copy python modules Six (six py) and Py-Radius (radius py) then copy them to a directory with suitable permissions such as the /config/eav directory. If you're running python 2.6, which you probably will, then the radius module will need to be modified as per Code Mods section in the code below. Monitor Configuration: Set up a monitor with at the very least a valid SECRET, if you're looking to simply test whether the Radius server is alive and responding then the user account does not need to be valid. Valid Environment Variables are as follows: DEBUG = 0, 1, 2 (Default: 0) MOD_PATH = Directory containing the Python modules (Default: /config/eav) SECRET = Radius server secret (Default: NoSecret) USER = User account (Default: radius_monitor) PASSWD = Account Password (Default: NoPassword) Notes: The configured environment variables can overridden using Arguments with TESTME as the first argument followed by the variables you want to override in the same format as above, eg. KEY=Value. This is usedful for troubleshooting and can be used to override the F5 supplied NODE_IP and NODE_PORT variables. Log file location: /var/log/monitors Debug level 2 outputs environment variables, command line arguments and radius module into the log file. Code : #!/usr/bin/env python # -*- coding: utf-8 -*- # # Filename : radius_mon.py # Author : ATennent # Version : 1.1 # Date : 2018/09/14 # Python ver: 2.6+ # F5 version: 12.0+ # ========== Installation # Import this script via GUI: # System > File Management > External Monitor Program File List > Import... # Name it however you want. # Get, modify and copy the following modules: # ========== Required modules # -- six -- # https://pypi.org/project/six/ # Copy six.py into /config/eav # # -- py-radius -- # https://pypi.org/project/py-radius/ # Copy radius.py into /config/eav # If running python2.6 modify radius.py as per "Code mods -- python.py --" section below # ========== Notes # NB: Any and all outputs from EAV scripts equate to a POSITIVE result by the F5 monitor # so to make the result of the script to be a NEGATIVE result, ie. a DOWN state, we need # to ensure that the script does not output anything when the attempt results in a time out. # ========== Environment Variables # NODE_IP - Supplied by F5 monitor # NODE_PORT - Supplied by F5 monitor # MOD_PATH - Path to location of Python modules six.py and radius.py, default: /config/eav # SECRET - Radius server secret # USER - Username for test account # PASSWD - Password for user account # DEBUG - Enable/Disable Debugging # ========== Additional Environment Variables (supplied at execution) # MON_TMPL_NAME - Monitor Name, eg. '/Common/radius_monitor' # RUN_I - Run file, eg. '/Common/radius_mon.py' # SECURITY_FIPS140_COMPLIANCE - 'true'/'false' # PATH - Colon delimited and not editable. # ARGS_I - Copy of command line Arguments # NODE_NAME - Node Name, eg, '/Common/SNGPCTXWEB01' # MON_INST_LOG_NAME - Pool member's monitor log, eg. '/var/log/monitors/Common_radius_monitor-Common_MyNode-1812.log' # SECURITY_COMMONCRITERIA - 'true'/'false' # ========== Code mods -- python.py -- # Dictionary comprehension fixes: # https://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension-in-python#1747827 # LINE:193; replace with #ATTR_NAMES = dict((v.lower(), k) for (k, v) in ATTRS.items()) # # LINE:100; replace with #CODE_NAMES = dict((v.lower(), k) for (k, v) in CODES.items()) # # Logger.NullHandler fix: # https://stackoverflow.com/questions/33175763/how-to-use-logging-nullhandler-in-python-2-6#34939479 # LINE:64-65; replace with #LOGGER = logging.getLogger(__name__) #try: # Python 2.7+ # LOGGER.addHandler(logging.NullHandler()) #except AttributeError: # class NullHandler(logging.Handler): # def emit(self, record): # pass # LOGGER.addHandler(NullHandler()) # ========== Imports/Modules from sys import path from sys import argv from sys import stdout from os import environ import logging.handlers import re if environ.get('MOD_PATH'): path.append(environ.get('MOD_PATH')) else: path.append('/config/eav') import radius # ========== Dictionary Defaults opts_dict = {'NODE_IP': '', 'NODE_PORT': '', 'SECRET': 'NoSecret', 'USER': 'radius_monitor', 'PASSWD': 'NoPassword', 'DEBUG': '0', } # ========== TEST w/ command line try: if argv[3] == 'TESTME': environ['NODE_IP'] = argv[1] environ['NODE_PORT'] = argv[2] for cmd_opt in argv[3:]: if 'DEBUG' in cmd_opt: environ['DEBUG'] = cmd_opt.split('=')[1] elif 'SECRET' in cmd_opt: environ['SECRET'] = cmd_opt.split('=')[1] elif 'USER' in cmd_opt: environ['USER'] = cmd_opt.split('=')[1] elif 'PASSWD' in cmd_opt: environ['PASSWD'] = cmd_opt.split('=')[1] else: continue except: pass # ========== Logging Config try: if int(environ.get('DEBUG')) == 0: log_file = '/dev/null' elif int(environ.get('DEBUG')) <=2: log_file = environ.get('MON_INST_LOG_NAME') else: log_file = '/dev/null' except: # DEBUG not supplied as ENV variable environ['DEBUG'] = opts_dict['DEBUG'] log_file = '/dev/null' if int(environ.get('DEBUG')) == 2: logging.basicConfig( filename=log_file, level=logging.DEBUG, format='%(asctime)s %(name)s:%(levelname)s %(message)s') else: logging.basicConfig( filename=log_file, level=logging.INFO, format='%(asctime)s %(name)s:%(levelname)s %(message)s') log = logging.getLogger('radius_mon') syslog_handler = logging.handlers.SysLogHandler(address='/dev/log', facility=0) log.addHandler(syslog_handler) if int(environ.get('DEBUG')) == 0: log.setLevel(logging.INFO) opts_dict['DEBUG'] = environ.get('DEBUG') elif int(environ.get('DEBUG')) == 1: log.setLevel(logging.DEBUG) opts_dict['DEBUG'] = environ.get('DEBUG') elif int(environ.get('DEBUG')) == 2: log.setLevel(logging.DEBUG) opts_dict['DEBUG'] = environ.get('DEBUG') log.debug('VERBOSE Debug Enabled, CMD line and ENV variables will be dumped to file.') else: log.error('Bad DEBUG value!') # ========== CMD Line and ENV Dump if int(opts_dict['DEBUG']) == 2: log.debug('=========== CMD ARGS') log.debug(argv[0:]) log.debug('=========== ENV VARS') log.debug(environ) # ========== Update Dictionary if environ.get('NODE_IP'): opts_dict['NODE_IP'] = environ.get('NODE_IP') log.debug('Set NODE_IP, %s', opts_dict['NODE_IP']) else: log.error('NODE_IP not supplied as ENV variable') log.error('Exiting..') exit(0) if environ.get('NODE_PORT'): opts_dict['NODE_PORT'] = environ.get('NODE_PORT') log.debug('Set NODE_PORT, %s', opts_dict['NODE_PORT']) else: log.error('NODE_PORT not supplied as ENV variable') log.error('Exiting..') exit(0) if environ.get('SECRET'): opts_dict['SECRET'] = environ.get('SECRET') log.debug('Set SECRET, %s', opts_dict['SECRET']) else: log.debug('SECRET not supplied as ENV variable') if environ.get('USER'): opts_dict['USER'] = environ.get('USER') log.debug('Set USER, %s', opts_dict['USER']) else: log.debug('USER not supplied as ENV variable') if environ.get('PASSWD'): opts_dict['PASSWD'] = environ.get('PASSWD') log.debug('Set PASSWD, %s', opts_dict['PASSWD']) else: log.debug('PASSWD not supplied as ENV variable') # ========== Clean up NODE_IP for IPv4 if '::ffff:' in opts_dict['NODE_IP']: opts_dict['NODE_IP'] = re.sub(r'::ffff:','', opts_dict['NODE_IP']) log.debug('Stripped IPv6 notation from IPv4 address') # ========== Strip routing domain from NODE_IP if '%' in opts_dict['NODE_IP']: opts_dict['NODE_IP'] = re.sub(r'%\d{1,4}$', '', opts_dict['NODE_IP']) log.debug('Stripped routing domain from IP address') # ========== Dictionary debug if int(opts_dict['DEBUG']) == 2: log.debug('----- KEY, VALUE pairs:') for key in opts_dict.keys(): log.debug('%s, %s', key, opts_dict[key]) log.debug('-----') # ========== Main r = radius.Radius(opts_dict['SECRET'], host=opts_dict['NODE_IP'], port=int(opts_dict['NODE_PORT'])) try: if r.authenticate(opts_dict['USER'], opts_dict['PASSWD']): log.debug('Service UP, Authentication attempt Successful') stdout.write('UP') else: log.debug('Service UP, Authentication attempt Failure') stdout.write('UP') except radius.ChallengeResponse: log.debug('Service UP, Authentication attempt Challenge Response') stdout.write('UP') except (radius.NoResponse, radius.SocketError): # This includes bad SECRET keys, the radius RFC states that Invalid responses from the radius # server are to be silently dropped which, from a client perspective, will result ina timeout. # This cannot be changed without modifying radius.py to instead raise an Exception. log.debug('No Response from %s:%s', opts_dict['NODE_IP'], int(opts_dict['NODE_PORT'])) exit(0) except Exception as msg: log.error('Exception due to %s, marking as DOWN', msg) exit(0) Tested this on version: 12.01KViews1like0CommentsAPM Cookbook: Okta MFA Integration
Since the launch of the Okta and F5 Integration Guide I've seen interest in leveraging this partnership take off. One aspect I've enjoyed is watching how customers address pain points they were not able to address previously. For example, providing multi-factor authentication (MFA) for Microsoft Exchange Outlook Web Access (OWA). This particular customer standardized on Okta's MFA solution but OWA was behind Microsoft Threat Management Gateway (TMG) and could not easily integrate with Okta. For this solution F5's Access Policy Manager (APM) will replace the TMG servers and leverage Okta's on-premises RADIUS agent for MFA via Okta Verify, which supports push notification - by far my favorite feature. I've included a video below that walks through the process of configuring Okta for RADIUS based multifactor as well as configuring APM to leverage Okta's RADIUS agent. https://youtu.be/jpoVo0nuilQ?list=PLAVmgu9Rja5Cyu7KhQ3CUJFNOI5Tr-Wk2 Okta Configuration On the Okta administrator portal you'll need to create a new Okta Sign-on policy: Security -> Policies. Once you name the new policy you'll need to add a rule: The crucial part here is to select RADIUS for the And Authenticates via option. F5 Configuration The F5 APM configuration is pretty straight forward since you can use the built-in VPE macro template for RADIUS authentication but we'll need to create a RADIUS AAA object first. Once the RADIUS AAA object is created go ahead and create a new Access Profile and customize your VPE as shown below - for detailed steps please watch the attached video. Pretty easy solution and we're just scratching the surface on what is possible. Can't wait to start playing with Okta's API via iRules LX!832Views0likes4CommentsAdmin Auth via NPS Radius
Hi Everyone, Am wating to implement radius auth of our BIG-IP administrators (GUI and SSH), radius is a supported auth method so we would like to use the Microsoft NPS services. Has anyone successfully implemented GUI / SSH authentication of BIG-IP Administrators via radius to Microsoft NPS? Would be great to hear of your learnings and any advice you can provide. TIA (currently running v16.1.3.1)799Views0likes3Comments