从PHP中的Microsoft Teams自定义Bot验证HMAC [英] Verifying HMAC from Microsoft Teams custom Bot in PHP

查看:138
本文介绍了从PHP中的Microsoft Teams自定义Bot验证HMAC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照Microsoft

I am trying to authenticate a Microsoft Teams custom Bot with PHP, following the Microsoft instructions and read de C# example code.

Microsoft指令步骤:
1.从消息的请求正文生成hmac.大多数平台上都有标准库. Microsoft Teams使用标准 SHA256 HMAC加密.您将需要将主体转换为字节 UTF8中的数组.
2.要计算哈希,请提供共享密钥的字节数组.
3.使用UTF8编码将哈希转换为字符串.
4.将生成的哈希值的字符串值与HTTP请求中提供的值进行比较.

Microsoft Intructions steps:
1. Generate the hmac from the request body of the message. There are standard libraries on most platforms. Microsoft Teams uses standard SHA256 HMAC cryptography. You will need to convert the body to a byte array in UTF8.
2. To compute the hash, provide the byte array of the shared secret.
3. Convert the hash to a string using UTF8 encoding.
4. Compare the string value of the generated hash with the value provided in the HTTP request.

我写了一个小的php脚本来在本地进行测试:

I had write a small php script to test this in local:

        <?php
        //Function to generate C# byte[] equivalent
        function unpak_str($val){
            $b = unpack('C*', $val);
            foreach ($b as $key => $value)
                $byte_a .= $value;

           return $byte_a;
          }

        //multi test outputs
        function hasher($values=[], &$output){
            //my secret share
            $secret="ejWiKHgsKY1ZfpJwJ+wIiN4+bgsFad/lkpu9/MWNXgM=";
            //diferent test
            $secret_64=base64_decode($secret);
            $secret_b=unpak_str($secret);
            $secret_b_64=unpak_str(base64_decode($secret));

            foreach($values as $msg){
                $hs = hash_hmac("sha256",$msg,$secret, true);
                $hs_64 = hash_hmac("sha256",$msg,$secret_64, true);
                $hs_b = hash_hmac("sha256",$msg,$secret_b, true);
                $hs_b_64 = hash_hmac("sha256",$msg,$secret_b_64, true);

                $output.=base64_encode($hs)." <BR>";
                $output.=base64_encode($hs_64)." <BR>";
                $output.=base64_encode($hs_b)." <BR>";
                $output.=base64_encode($hs_b_64)." <BR>";
             }
          }

    //Get data
    $data=file_get_contents('php://input');

    //real data request content for test
    $data ='{type":"message","id":"1512376018086","timestamp":"2017-12-04T08:26:58.237Z","localTimestamp":"2017-12-04T09:26:58.237+01:00","serviceUrl":"https://smba.trafficmanager.net/emea-client-ss.msg/","channelId":"msteams","from":{"id":"29:1aq6GCrC6lM9dv3YkAYi1gxTPiLnojGFgVr0_Th-2x6DhqmHAOhFwQHFzSyDy5RruXY4_FZjJebKHU7bpxfHpXA","name":"ROBERTO ALONSO FERNANDEZ","aadObjectId":"1e0dc7a0-9d5e-488b-bcf2-7e39c84076b8"},"conversation":{"isGroup":true,"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype;messageid=1512376018086","name":null},"recipient":null,"textFormat":"plain","attachmentLayout":null,"membersAdded":[],"membersRemoved":[],"topicName":null,"historyDisclosed":null,"locale":null,"text":"<at>PandoBot</at> fff","speak":null,"inputHint":null,"summary":null,"suggestedActions":null,"attachments":[{"contentType":"text/html","contentUrl":null,"content":"<div><span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">PandoBot</span> fff</div>","name":null,"thumbnailUrl":null}],"entities":[{"type":"clientInfo","locale":"es-ES","country":"ES","platform":"iOS"}],"channelData":{"teamsChannelId":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype","teamsTeamId":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype","channel":{"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979@thread.skype"},"team":{"id":"19:1e04f564ce5e4596bf2f266dbcff439e@thread.skype"},"tenant":{"id":"9744600e-3e04-492e-baa1-25ec245c6f10"}},"action":null,"replyToId":null,"value":null,"name":null,"relatesTo":null,"code":null}';


    //generate HMAC hash with diferent $data formats
    $test = [$data, unpak_str($data), base64_encode($data), unpak_str(base64_encode($data))];
    hasher($test, $output);


    //microsoft provided HMAC
    $output.="<HR>EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE="; 


    echo $output;
    /*
    Calculates: 
    0HsKoHza/QBvdz+nZw9tOti/eSWjyMMt/U77bfDqiE8=
    3jSq3I0HNQkjB9QfnnsxC1c3pF5PjqweHlSVcicrShY=
    bTQcGVTHX8/Gh4xovnN0WiJUiNaOQwvUZnwyFfiCaJE=
    qHBT2Y2ITyoxz2gmBbG8P1CrClvETus6dTffET3bAR8=
    8BcrXEQDDi77qgxCZLYyb/6ez8p9Qg2ZhTyZPWkdn/g=
    +8RSU5SSJKxqRLKkI+NkTE01xwu6PwPkKKMuvyyUvlo=
    PdL5ZpEwcN6Fe5kfX7zeAZLJvt0uLNTzu7lhuoOcr2o=
    s6M5pYruEgWeNMEOFfQRjVKQqtPBVaW3TJb2MzObF2c=
    xOTLhddbAwczQVneuTDQhPzmoIXGQljpf27c+hlhQII=
    aUMm5b2sKfmwGZOglfiu228fWqoLlwjc7z1QRdIbakE=
    5a7bAj9tzqhP9l85OvfVasURW0GSV5rykRutFFPO2fk=
    kwg6P2LoDL9rc3SSwJxQeoYJzZYlh+FHFefe38UokBM=
    eHeAzI7TV6vYDzxTxwyKWxMeVKFiFlIffWRiIMAk6fk=
    ZCyj2UppacQOTXogLPMFLDeMArQg03rhhlIwhynDvng=
    uQYK+7u9fppb62zXqtVYfkNK9wVawB3g+BlTyu4dc74=
    vjOFA3fqpwUx/VO9dQv3XviNhpjTNQsUwaJIwH4JjdY=
    ------------ MS PROVIDED HMAC ---------------
    EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=
     */

我的哈希匹配为零...

I've zero hash matching...

推荐答案

最后,经过大量的尝试,这让我发疯了,并决定启动一个具有新机密的新bot.现在工作正常.我是人类,而MS Teams不...我想那是我在复制/粘贴上的错,但这是一件很奇怪的事情,而另一方面,旧机器人在很多情况下都失败了,没有响应,没有最新的消息.

Finally after lots of trial, it maked me crazy and decided to start a new bot with a new secret. Now works fine. I'm human while MS Teams no... I suppos that was my fault with copy/paste but is a really stranger thing and the other hand old bot fails a lot of times with no response and the newest no

用于Microsoft Teams Custom Bot的PHP中的完整示例验证HMAC:

        <?php

        //The secret share with Microsoft Teams
        $secret="jond3021g9imMkrt8txF5AVPIwPFouNV/I72cQFii18=";

        //get headers
        $a = getallheaders();
        $provided_hmac=substr($a['Authorization'],5);

        //Get data from request
        $data=file_get_contents('php://input');

        //json decode into array
        $json=json_decode($data, true);

        //hashing
        $hash = hash_hmac("sha256",$data,base64_decode($secret), true);
        $calculated_hmac = base64_encode($hash);

        //start log var
        $log = "\n========".date("Y-m-d H:i:s")."========\n".$provided_hmac."\n".$calculated_hmac."\n";

        try{
            //compare hashs
            if(!hash_equals($provided_hmac,$calculated_hmac))
                throw new Exception("No hash matching");
            //response text
            $txt="Hi {$json["from"]["name"]} welcome to your custom bot";
            echo '{
                "type": "message",
                "text": "'.$txt.'"
                 }';
            $log .= "Sended: {$txt}";
        }catch (Exception $e){
            $log .= $e->getMessage();
        }
        //write log
        $fp = fopen("log.txt","a");
        fwrite($fp, $log . PHP_EOL);
        fclose($fp);

这篇关于从PHP中的Microsoft Teams自定义Bot验证HMAC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆