Wednesday, October 14, 2015

Twilio Request Validator

Been developing some voip apps that also provide SMS notifications. For the most part everything seems to work very well with Twilio. One thing that i wanted to make sure is that inbound messages were not being spoofed. Twilio provides just the thing https://www.twilio.com/docs/security

Great! But it doesn't work - it looks like someone hasn't updated this for a very long time. Most of the post variables they indicate in the snip of code are no longer in use. This is very important because without the exact post variables you can't verify if the message is legit. Twilio does not provide a list of IP's that their messages arrives from so you have to use other options.

// The post variables in the Twilio request. You may be able to use
// $postVars = $_POST
$postVars = array(
'CallSid' => 'CA1234567890ABCDE',
'Caller' => '+14158675309',
'Digits' => '1234',
'From' => '+14158675309',
'To' => '+18005551212'
);

CallSid, Caller, and digits are no longer used. The comment says you may be able to  $postVars = $_POST This is exactly what you need to do. Take some security precautions.

// The Twilio request URL. You may be able to retrieve this from
// $_SERVER['SCRIPT_URI']
$url = 'https://mycompany.com/myapp.php?foo=1&bar=2';

No - this is completely wrong also. no such thing as SCRIPT_URI. The url they need to refer is what you create in your control panel for your numbers  "Request URL". It should be exactly the same. There is an example program included with official SDK https://www.twilio.com/docs/libraries

This also includes variables that the service no longer uses. So what  do you actually need to create a signature validation? You need the following items to create proper validation.

1. All the variables that Twilio posts to your Request URL - yes all of them. everything in $_POST
2.$_SERVER["HTTP_X_TWILIO_SIGNATURE"]; //this is still correct
3. AuthToken

If you make these changes in the example code you can properly calculate the validation code.