microsoft authenticator
3 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.5KViews0likes0CommentsF5 APM with Microsoft Authenticator
Hi team, has anyone tested Microsoft Authenticator with F5 APM for 2FA? Lot of articles are there for google Authenticator, but none for Microsoft Authenticator, pls let me know or point me in right direction if anyone has ever tested it??2.7KViews0likes17Comments