google authenticator
12 TopicsAPM Google Authenticator HTTP API
Problem this snippet solves: George Watkins already shared various codes allowing to authenticate users with Google authenticator on APM by executing VPE irule event. This code create a HTTP API that respond if authenticator code is valid and can be used as an HTTP Auth server by APM. 3 URLs are included on this API : /authenticator : Authenticate user with cleartext userkey /secured-authenticator : Authenticate user with AES encrypted user key /encrypt : encode cleartext user key to encrypted user key. this feature is not secured and can be removed if VS is allowed from large network when requesting URL: http://{google api virtual ip}/authenticator?pass={passcode}&key={user key} if passcode is valid, the API respond 200 if passcode is not valid, the API respond 403 when requesting URL: http://{google api virtual ip}/secured-authenticator?pass={passcode}&key={encrypted user key} if passcode is valid, the API respond 200 if passcode is not valid, the API respond 403 This API can be configured to allow devices with 30 seconds offset. it calculate the previous, the current, and the next code. version 1.1 : This version includes new features : the Kai Wilke great optimization code using 11.1+ crypto commands ability to store in database (AD, LDAP ...) AES encrypted user key and decrypt it before OTP code validation version 1.2 : This version includes new features : the Kai Wilke security improvements with the authenticator keys AES encryption Powershell to add encrypted authenticator keys in AD user attribute How to use this snippet: Create a HTTP virtual server and assign the following irule. Change b64key value if user keys are encrypted with the provided powershell script. both keys in PS and irule must be the same. In APM, create a new HTTP AAA server with following parameters: Authentication Type : Form based Method : GET Form Action : http://{google api virtual ip}/authenticator (http://{google api virtual ip}/secured-authenticator if user key is encrypted) Form Parameter For User Name : {no value} Form Parameter For Password : {no value} Hidden Form Parameters/Values : pass %{session.logon.last.otp} userkey %{session.custom.key} -- Replace the variable containing the user key (from AD, LDAP, ... ) offset offset supported for token code (x means x*30 seconds offset) key_size 80 -- for algorithm evolution hmac_mode hmac-sha1 -- for algorithm evolution Successful Logon Detection Match Type = By specific string in response Successful Logon Detection Match Value : 200 OK this configuration use a unencrypted variable to store the OTP code. if the top code is in password variable, the parameter pass must be removed from hidden parameters and the Form Parameter For Password must be set to pass In VPE: provision the user key variable (from AD, LDAP, ... ) create a Logon page requesting the authenticator code (variable name otp) create a HTTP Auth box with the previously created HTTP server the following powershell script insert in AD user attribute "pager" the user encrypted key: function Encrypt-Data($AesKey, $Data) { $Data = [System.Text.Encoding]::UTF8.GetBytes($Data) $AesManaged = New-Object "System.Security.Cryptography.AesManaged" $AesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC $AesManaged.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7 $AesManaged.BlockSize = 128 $AesManaged.KeySize = 256 $AesManaged.Key = [System.Convert]::FromBase64String($AesKey) $Encryptor = $AesManaged.CreateEncryptor() $EncryptedData = $Encryptor.TransformFinalBlock($Data, 0, $Data.Length); [byte[]] $EncryptedData = $AesManaged.IV + $EncryptedData $AesManaged.Dispose() [System.Convert]::ToBase64String($EncryptedData) } $encryptKey = "iTEEieok7//RyzrPe5mWwz1yroPPsm4e5cqghdEHIlU=" $userkey = $Args[1] $username = $Args[0] $encrypted = Encrypt-Data $encryptKey $userkey Set-AdUser -Identity $username -replace @{"pager"="$encrypted"} Thanks to Kai Wilke for this. it make the code less insecure. here is an example of how work the API with curl stanislas$ curl -k 'https://192.168.1.243/secured-authenticator?user=stan&userkey=IyQ+J6l88AW9NQmaRPhLrl0aNkLKw01+vBRpikVfVQk=&key_size=80&hmac_mode=hmac-sha1&offset=1&pass=790054' -i HTTP/1.0 200 OK Server: BigIP Connection: Keep-Alive Content-Length: 0 stanislas$ curl -k 'https://192.168.1.243/secured-authenticator?user=stan&userkey=IyQ+J6l88AW9NQmaRPhLrl0aNkLKw01+vBRpikVfVQk=&key_size=80&hmac_mode=hmac-sha1&offset=0&pass=790054' -i HTTP/1.0 403 Forbidden X-Error-Code: 3-wrong-password Server: BigIP Connection: Keep-Alive Content-Length: 0 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 { ############################################################################################## # Initialize the Encryption keyto decrypt encrypted user Key # set b64key "iTEEieok7//RyzrPe5mWwz1yroPPsm4e5cqghdEHIlU=" set static::KEY [b64decode $b64key] # create a passphrase used during IV random creation set static::IV_RANDOM_PWD "MyIVSeed" } when HTTP_REQUEST { switch [HTTP::path] { "/secured-authenticator" { set user [URI::query [HTTP::uri] user] set auth_code [URI::query [HTTP::uri] pass] if {[set allowed_clock_skew_units [URI::decode [URI::query [HTTP::uri] offset]]] equals ""} {set allowed_clock_skew_units "0"} if {[set key_size [URI::decode [URI::query [HTTP::uri] key_size]]] equals ""} {set key_size "80"} if {[set hmac_mode [URI::decode [URI::query [HTTP::uri] hmac_mode]]] equals ""} {set hmac_mode "hmac-sha1"} set aes_cipherstring [b64decode [URI::decode [URI::query [HTTP::uri] userkey]]] log local0. "[HTTP::uri] $user $aes_cipherstring" binary scan $aes_cipherstring a16a* aes_iv aes_ciphertext set userkey [CRYPTO::decrypt -alg aes-256-cbc -key $static::KEY -iv $aes_iv $aes_ciphertext] log local0. "$userkey / $auth_code" } "/authenticator" { set user [URI::query [HTTP::uri] user] set auth_code [URI::query [HTTP::uri] pass] if {[set allowed_clock_skew_units [URI::decode [URI::query [HTTP::uri] offset]]] equals ""} {set allowed_clock_skew_units "0"} if {[set key_size [URI::decode [URI::query [HTTP::uri] key_size]]] equals ""} {set key_size "80"} if {[set hmac_mode [URI::decode [URI::query [HTTP::uri] hmac_mode]]] equals ""} {set hmac_mode "hmac-sha1"} set userkey [URI::query [HTTP::uri] userkey] #log local0. "$userkey / $auth_code" } "/encrypt" { set userkey [URI::query [HTTP::uri] userkey] set aes_iv [CRYPTO::keygen -alg random -len 128] set aes_ciphertext [CRYPTO::encrypt -alg aes-256-cbc -key $static::KEY -iv $aes_iv $userkey] set aes_cipherstring [b64encode [binary format a*a* $aes_iv $aes_ciphertext]] HTTP::respond 200 content $aes_cipherstring return } default { HTTP::respond 403 X-Error-Code 1-wrong-URL log local0. "erreur 1 : Wrong URL" return } } # Call Authenticator procedure # valid arguments are: # - HMAC mode : "hmac-sha1", "hmac-sha256" or "hmac-sha512" # - Authenticator Key size : Google Authenticator uses a hardcoded 80 bit key length # - User key Base32 encoded # - User OTP code # - Allowed time shift (1 unit = 30 seconds) # procedure returns different values # - -1 : the key is not valid (key size too short) # - 0 : the user code is wrong # - 1 : the user code is rigth log local0. "call ga_validate $hmac_mode $key_size $userkey $auth_code $allowed_clock_skew_units" switch -- [call ga_validate $hmac_mode $key_size $userkey $auth_code $allowed_clock_skew_units] { -1 { # code verification failed HTTP::respond 403 X-Error-Code 2-wrong-user-key log local0. "erreur 2 : wrong User Key" } 0 { # code verification failed HTTP::respond 403 X-Error-Code 3-wrong-password log local0. "erreur 3 : wrong Password" } 1 { # code verification successful HTTP::respond 200 } default {set result "error: unknown"} } } Tested this on version: 11.51.8KViews1like2CommentsRADIUS 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.5KViews0likes0CommentsGoogle Authenticator Verification iRule (TMOS v11.1+ optimized)
Problem this snippet solves: Hi Folks, the provided iRule contains a TMOS v11.1+ compatible fork of the already existing and very lovely Google Authenticator verification iRules here on CodeShare. The iRule adds support for the full TOTP algorithm standard (see RFC 6238 as well as RFC 4226) by including a support for longer shared key sizes and the more complex HMAC-SHA256 as well as HMAC-SHA512 algorithms. In addition, the core functionality of the provided iRule is a complete revamp and contains lot of performance optimizations to reduce the required CPU cycles on TMOS v11.1+ platforms by a great degree. The performance optimizations of this iRule are achieved by: Using the TMOS v11.1+ compatible [CRYPTO::sign -alg hmac-...] syntax to calculate HMAC values. Using a less complex and very minimalistic base32-to-binary [string map] conversation to decode the Google Authenticator keys. Using a serialized verification of multiple clock skews in a relative increasing/decreasing order to Unix epoch time. Using slightly optimized [expr { }] syntaxes. Avoiding unnecessary $variable usage. Avoiding calls into (rather slow) TCL procedures. Performance comparison: The performance data below was gathered by using a maximum allowed clock skew value of +/-5 minutes between clients and the F5, resulting in a calculation of either 1 verfication value (ideal case) or up to 21 verfication values (worst case) for a single token verification . Test Name | This iRule | Previous iRule(s)| Savings Valid verification via Unix epoch time (ideal case) | 191.078 cycles | 5.497.482 cycles | 96,6% Valid verification via -2,5 min clock skew (median case)| 511.067 cycles | 5.504.262 cycles | 90,8% Valid verification via -5 min clock skew (worst case) | 816.676 cycles | 5.502.650 cycles | 85,2% Invalid verification (always worst case) | 849.217 cycles | 5.464.924 cycles | 84,5% Note: The results of the "Previous iRule(s)" was gathered by using a striped down version (e.g. using fixed keys, tokens and clock values with disabled logging and HTTP responses) of Stanislas latest Google Authenticator HTTP API iRule, since it was (until today) the only published version that includes a support to handle token verification using multiple clock skews. The core functionality of Stanislas Google Authenticator HTTP API iRule is heavely based on the original Google Authenticator iRule published by George Watkins, but Stanislas already uses a slightly performance optimized syntax for certain [expr {}] syntaxes. Cheers, Kai Footnote: Special thanks goes to George Watkins for publishing the very first Google Authenticator iRule back in 2012. And also to Stanislas for publishing his Google Authenticator HTTP API iRule, which has introduced a handy HTTP API support for APM Policies and a very useful addition to handle clock skews. How to use this snippet: Integrate the core functionality of this Google Authenticator Verification iRule in your own Google Authenticator solution. Tweak the $static::ga_key_size and $static::ga_hmac_mode settings as needed. Tweak the $static::allowed_clock_skew_units to set the maximum allowed clock skew units between your LTM and the end user devices. The variable $ga(key) is used to set the provisioned Google Authenticator shared user key. The variable $ga(token) is used to set the user provided Google Authenticator token. The variable $result stores the verification results. Enjoy! Code : when RULE_INIT { ############################################################################################## # Configure the Google Authenticator key sizes and HMAC operation modes. # # Note: Google Authenticator uses a hardcoded 80 bit key length with HMAC-SHA1 verification. # The underlying HOTP algorithm (see RFC 4226) and TOTP algorithm (RFC 6238) standards # require at least 128 bit and even recommend a 160 bit key length. In addition, both # RFC standards include HMAC-SHA256 and HMAC-SHA512 operation modes. # So if the Google Authenticator code is changed in the future to match the official # requirements or even recommendations, then you have to change the variables below. # set static::ga_key_size 80 ;# Shared key size in bits set static::ga_hmac_mode "hmac-sha1" ;# Options "hmac-sha1", "hmac-sha256" or "hmac-sha512" ############################################################################################## # Configure the allowed clock skew units (1 unit = +/-30 seconds in both directions) # set static::ga_allowed_clock_skew_units 10 ############################################################################################## # Initialize the Base32 alphabet to binary conversation (see RFC 4648) # set static::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 "" = "" " " "" \ ] } when HTTP_REQUEST { ############################################################################################## # Defining the user provided token code and provisioned user key # set ga(token) "000000" set ga(key) "ZVZG5UZU4D7MY4DH" ############################################################################################## # Initialization of the Google Authentication iRule # # Map the Base32 encoded ga(key) to binary string representation and check length >= $static::ga_key_size if { [string length [set ga(key) [string map -nocase $static::b32_to_binary $ga(key)]]] >= $static::ga_key_size } then { # Convert the translated ga(key) binary string representation to binary set ga(key) [binary format B$static::ga_key_size $ga(key)] # Initialize ga(clock) timeframe based on Unix epoch time in seconds / 30 set ga(clock) [expr { [clock seconds] / 30 } ] ############################################################################################## # Perform verification of the provided ga(token) for current time frame ga(clock) # # Calculate hex encoded HMAC checksum value for wide-int value of time frame ga(clock) using ga(key) as secret binary scan [CRYPTO::sign -alg $static::ga_hmac_mode -key $ga(key) [binary format W* $ga(clock)]] H* ga(verify) # Parse ga(offset) based on the last nibble (= 4 bits / 1 hex) of the ga(verify) HMAC checksum and multiply with 2 for byte to hex conversation set ga(offset) [expr { "0x[string index $ga(verify) end]" * 2 } ] # Parse (= 4 bytes / 8 hex) from ga(verify) starting at the ga(offset) value, then remove the most significant bit, perform the modulo 1000000 and format the result to a 6 digit number set ga(verify) [format %06d [expr { ( "0x[string range $ga(verify) $ga(offset) [expr { $ga(offset) + 7 } ]]" & 0x7FFFFFFF ) % 1000000 } ]] # Compare ga(verify) with user provided ga(token) value if { $ga(verify) equals $ga(token) } then { # The provided ga(token) is valid" set result "valid" } elseif { $static::ga_allowed_clock_skew_units > 0 } then { ############################################################################################## # Perform verification of the provided ga(token) for additional clock skew units # # Note: The order is increasing/decreasing according to ga(clock) (aka. Unix epoch time +30sec, -30sec, +60sec, -60sec, etc.) # set result "invalid" for { set x 1 } { $x <= $static::ga_allowed_clock_skew_units } { incr x } { ############################################################################################## # Perform verification of the provided ga(token) for time frame ga(clock) + $x # # Calculate hex encoded HMAC checksum value for wide-int value of time frame ga(clock) + x using ga(key) as secret binary scan [CRYPTO::sign -alg $static::ga_hmac_mode -key $ga(key) [binary format W* [expr { $ga(clock) + $x }]]] H* ga(verify) # Parse ga(offset) based on the last nibble (= 4 bits / 1 hex) of the ga(verify) HMAC checksum and multiply with 2 for byte to hex conversation set ga(offset) [expr { "0x[string index $ga(verify) end]" * 2 } ] # Parse (= 4 bytes / 8 hex) from ga(verify) starting at the ga(offset) value, then remove the most significant bit, perform the modulo 1000000 and format the result to a 6 digit number set ga(verify) [format %06d [expr { ( "0x[string range $ga(verify) $ga(offset) [expr { $ga(offset) + 7 } ]]" & 0x7FFFFFFF ) % 1000000 } ]] # Compare ga(verify) with user provided ga(token) value if { $ga(verify) equals $ga(token) } then { # The provided ga(token) is valid" set result "valid" break } ############################################################################################## # Perform verification of the provided ga(token) for time frame ga(clock) - $x # # Calculate hex encoded HMAC checksum value for wide-int value of time frame ga(clock) - $x using ga(key) as secret binary scan [CRYPTO::sign -alg $static::ga_hmac_mode -key $ga(key) [binary format W* [expr { $ga(clock) - $x }]]] H* ga(verify) # Parse ga(offset) based on the last nibble (= 4 bits / 1 hex) of the ga(verify) HMAC checksum and multiply with 2 for byte to hex conversation set ga(offset) [expr { "0x[string index $ga(verify) end]" * 2 } ] # Parse (= 4 bytes / 8 hex) from ga(verify) starting at the ga(offset) value, then remove the most significant bit, perform the modulo 1000000 and format the result to a 6 digit number set ga(verify) [format %06d [expr { ( "0x[string range $ga(verify) $ga(offset) [expr { $ga(offset) + 7 } ]]" & 0x7FFFFFFF ) % 1000000 } ]] # Compare ga(verify) with user provided ga(token) value if { $ga(verify) equals $ga(token) } then { # The provided ga(token) is valid" set result "valid" break } } } else { # The provided ga(token) is invalid" set result "invalid" } } else { #The provided ga(key) is malformated set result "error: malformated shared key" } unset -nocomplain ga ############################################################################################## # Handle for token verification results # # log local0.debug "Verification Result: $result" HTTP::respond 200 content "Verification Result: $result" # return $result } Tested this on version: 12.01.5KViews0likes6CommentsComplete MFA solution with GA stored in Active Directory
Problem this snippet solves: All modern business applications require Multi-Factor Authentication (MFA) to be used for remote access by employees. There are many vendors on market selling enterprise MFA solutions that may be utilised with F5 BIG-IP Access Policy Manager (APM). Those solutions are complex and allow customers to create flexible policies which allow them to decide when and whom will be authorised to access protected applications. But what about those customers which have no needs for using complex enterprise solutions or does not have adequate budget for such spendings? How to use this snippet: For those customers I would like to present my One-Time Password (OTP) application which requires BIG-IP LTM/APM/iRulesLX. Shared secret value is stored in Active Directory and QR code is generated in user's browser. All you need after implementing this application on your BIG-IP is. to ask your users to get any OTP-compatible mobile application, like Google Authenticator or Microsoft Authenticator Please see https://github.com/akhmarov/f5_otp/ for instructions UPDATE 1: New version now support APM 15.1+ Modern Customization UPDATE 2: Added trusted device support UPDATE 3: Added multi-tenancy support Tested this on version: 15.11.4KViews1like8CommentsStrong Authentication
It’s authentication, people! Only, wait for it….STRONGER (yes i did use the strong html tag for that.) Strong authentication is a nebulous term. Many will interchange strong authentication with two-factor authentication (2FA), but that is only one method for strong authentication, not necessarily a requirement. You could have a series of “something you know” challenges that makes the authentication process more in depth and thus stronger, but doesn’t require one or more of the other multi-factor pillars in “something you have” or “something you are." So what strong authentication solutions does F5 support? The Access Policy Manager actually shines here, because it is vendor agnostic. You can plug and play a myriad of authentication systems into the process and off you go. Some of the different authentication methods include: LDAP/S HTTP/S RADIUS TACACS+ If your authentication services can talk one or more of these protocols, APM will support it. We’ve posted solutions on DevCentral with Google Authenticator (LTM via ldap and APM,)Yubico Yubikey(LTM and APM,) as well asRSA SecurIDover the years. There are some nuanced differences between all the solutions, but this diagram from Brett Smith’s APM and Yubikey article linked previously shows the general process for APM’s support of multi-factor authentication. This directory server could be Active Directory, LDAP, or RADIUS to a cloud service like Thales' (née SafeNet’s) Authentication Services as discussed in this solution brief. Beyond just authenticating local services, these strong authentication services can be utilized with federation as well, using APM’s SAML support for SP and iDP deployments. Thales (née SafeNet) has quality write-ups for their APM-integrated enterprise and cloudiDP strong authentication services available on their site. For more information about how these authentication services plug in to the larger SAML federation services, take a look at John’s lightboard Lesson on the topic. Additional Resources APM Authentication and Single Sign-On Agility 2015 APM 101 Supporting Infrastructure Lab Documents Thales Authentication799Views0likes0Comments[APM] Ad Query + Google Auth
Hi, I'm triyng to implement an authentification between AD and google Auth. I follow this but it's not exactly what I want to do. Here is what I want : AdAuth (without AD password) + Google Auth. --> I just want to replace AD Password by Google Auth I think "AD Auth" macro is not appropriate. Ad Query is surely better Here is my Policy : And here is my AD Query If i see log, i observe that if I test with AD Password, AD Query Passed but Google Auth Failed. But If test with Google Auth as Password, AD Query Failed. Do you have any idea ? Am I in good direction ? Thanks for replySolved492Views0likes5CommentsGoogle Authenticator iRule Verification
Hi, I've been following this article: https://devcentral.f5.com/articles/two-factor-authentication-with-google-authenticator-and-apm To implement two-factor authentication with APM. After creating an access policy, data group and all the likes, I find that the APM is expecting a different code than the authenticator shows. I found out by printing the variables that I enter as a code, and the variables that the APM expects as a code, into the logs. The whole process itself works. The iRule is triggered, the username is found in the datagroup, and the calculations are made. It's just expecting a different code. For example, my code will say "781023", and the BIGIP will be expecting code "826015". I tested this with multiple different accounts and the same results all around. I'm wondering if Google just changed its algorithm a few years ago and the article became outdated, or if something in recent F5 versions has changed that changes the calculation algorithm. Has anyone done a recent implementation with this iRule without any issues? I quadruple-checked everything and added log entries to every part of the iRule. I know it's being triggered correctly, but it's just coming up with a different expected code than Google is. In that article, there are 2 comments by people with the same issue on 11.5, so at least I'm not alone :-)460Views0likes9CommentsRadius Proxy with Google Authenticator
During Programmability Month, we released a Getting Started with iRules LX series of introductory articles, covering concepts, workflows, troubleshooting techniques, and best practices. This last week, one our community members, Artiom, took to Youtube to start sharing his newfound love of the new iRules LX functionality. He starts his video series with an overview of a solution to support a radius call and translate to an ldap back-end query, shown below. After the intro video, he goes back to square one to start cover setup and then in the last current video in the series, covers the traditional iRules portion of this solution. The Youtube series is embedded here, so as Artiom adds more videos to the series, they'll be automatically added here as well. Way to go, Artiom, looking forward to watching the rest of the series!372Views0likes1CommentNode.JS site to store TOPT Keys in Datagroup
Problem this snippet solves: The Google Auth (TOPT) iRule allows the key that is used to generate the token to be stored in a Data Group. However, iRules are not allowed to write to a data group. This means that the iRule that generates a key can only display the key so it can be cut and pasted into another form for use (AD field or Data Group). This node.js site fixes that problem by interacting with the google_auth_keys data group using the iControl node module. How to use this snippet: The Google Auth APM iRule needs to be set up to use the data group google_auth_keys as the key repository. That is the only change to the Google Auth APM iRule. Next, create a LTM-APM access policy that uses the users normal authentication methods - AD or LDAP - to access the node.js site. The only iRule required adds a magic key that is used by the node.js site to block access via any other avenue. when HTTP_REQUEST_RELEASE { HTTP::query "userid=[ACCESS::session data get session.logon.last.username]&magic=GAsecret" } Now for the fun part. Download the attached .zip file and expend it into a F5vpn directory. Modify the following files: 1. bin\www - Change the port on line 15 to your fav. Note the port number and IP address of the server to create the GAkeys pool used by the virtual server that uses the GAkey_apm created above. 2. F5config.js - Enter the ip addresses of your F5 pair and the other fields. Note that the "admin" user must be used here. iControlRest doesn't allow any other user ID. If you just have one F5, enter the same IP twice. 3. views\index.jade - Adjust the static text to meet your needs. 4. views\layout.jade - Enter the name of your image file. Be sure to copy the file into the public\images directory. 5. routes\index.js - Update the GATsecret (line 43) with the magic word you entered in the APM iRule. Now, just run "npm install" from the base directory - f5VPN - to load the dependencies. Run your node site with the normal tools - I use forever with a short /etc/init.d/f5VPN script. Code : 62799322Views0likes0CommentsAPM Pre-Authentication in front of Google Authenticator Generation iRule
Hi everyone, i'm trying to configure pre-authentication in front of the google authenticator-generation rule. I've used following articel, and everything is working fine from the google auth. side of view. devcentral.f5.com/articles/two-factor-authentication-with-google-authenticator-and-apm The Part where i want to put pre-authentication (Logon Page with AD Auth) in front is following: https://devcentral.f5.com/codeshare?sid=532 I've tried several things already: iRule event and "when ACCESS_POLICY_AGENT_EVENT" in hte Rule VS with irule attached and member of a pool - new VS for APM pre auth and as a resource the google generation pool (-> not working because of limitation, there is an SOL articel about that) What i get in the log is this everytime APM is in front: May 19 11:44:20 Snorre err tmm3[3992]: 011f0007:3: http_process_state_prepend - Invalid action:0x1090b1 (Client side: vip=/Testpartition/google_auth_preauth profile=http addr=10.10.10.1 port=443 rtdom_id=0 client_ip=10.1.1.25) Any suggestions? Many thanks, Mike285Views0likes2Comments