-
Notifications
You must be signed in to change notification settings - Fork 305
/
Copy pathRequestValidator.cs
164 lines (145 loc) · 5.42 KB
/
RequestValidator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Text;
namespace Twilio.Security
{
/// <summary>
/// Twilio request validator
/// </summary>
public class RequestValidator
{
private readonly HMACSHA1 _hmac;
private readonly SHA256 _sha;
/// <summary>
/// Create a new RequestValidator
/// </summary>
/// <param name="secret">Signing secret</param>
public RequestValidator(string secret)
{
_hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret));
_sha = SHA256.Create();
}
/// <summary>
/// Validate against a request
/// </summary>
/// <param name="url">Request URL</param>
/// <param name="parameters">Request parameters</param>
/// <param name="expected">Expected result</param>
/// <returns>true if the signature matches the result; false otherwise</returns>
public bool Validate(string url, NameValueCollection parameters, string expected)
{
return Validate(url, ToDictionary(parameters), expected);
}
/// <summary>
/// Validate against a request
/// </summary>
/// <param name="url">Request URL</param>
/// <param name="parameters">Request parameters</param>
/// <param name="expected">Expected result</param>
/// <returns>true if the signature matches the result; false otherwise</returns>
public bool Validate(string url, IDictionary<string, string> parameters, string expected)
{
// check signature of url with and without port, since sig generation on back end is inconsistent
var signatureWithoutPort = GetValidationSignature(RemovePort(url), parameters);
var signatureWithPort = GetValidationSignature(AddPort(url), parameters);
// If either url produces a valid signature, we accept the request as valid
return SecureCompare(signatureWithoutPort, expected) || SecureCompare(signatureWithPort, expected);
}
public bool Validate(string url, string body, string expected)
{
var paramString = new UriBuilder(url).Query.TrimStart('?');
var bodyHash = "";
foreach (var param in paramString.Split('&'))
{
var split = param.Split('=');
if (split[0] == "bodySHA256")
{
bodyHash = Uri.UnescapeDataString(split[1]);
}
}
return Validate(url, new Dictionary<string, string>(), expected) && ValidateBody(body, bodyHash);
}
public bool ValidateBody(string rawBody, string expected)
{
var signature = _sha.ComputeHash(Encoding.UTF8.GetBytes(rawBody));
return SecureCompare(BitConverter.ToString(signature).Replace("-","").ToLower(), expected);
}
private static IDictionary<string, string> ToDictionary(NameValueCollection col)
{
var dict = new Dictionary<string, string>();
foreach (var k in col.AllKeys)
{
dict.Add(k, col[k]);
}
return dict;
}
private string GetValidationSignature(string url, IDictionary<string, string> parameters)
{
var b = new StringBuilder(url);
if (parameters != null)
{
var sortedKeys = new List<string>(parameters.Keys);
sortedKeys.Sort(StringComparer.Ordinal);
foreach (var key in sortedKeys)
{
b.Append(key).Append(parameters[key] ?? "");
}
}
var hash = _hmac.ComputeHash(Encoding.UTF8.GetBytes(b.ToString()));
return Convert.ToBase64String(hash);
}
private static bool SecureCompare(string a, string b)
{
if (a == null || b == null)
{
return false;
}
var n = a.Length;
if (n != b.Length)
{
return false;
}
var mismatch = 0;
for (var i = 0; i < n; i++)
{
mismatch |= a[i] ^ b[i];
}
return mismatch == 0;
}
private string RemovePort(string url)
{
return SetPort(url, -1);
}
private string AddPort(string url)
{
var uri = new UriBuilder(url);
return SetPort(url, uri.Port);
}
private string SetPort(string url, int port)
{
var uri = new UriBuilder(url);
uri.Host = PreserveCase(url, uri.Host);
if (port == -1)
{
uri.Port = port;
}
else if ((port != 443) && (port != 80))
{
uri.Port = port;
}
else
{
uri.Port = uri.Scheme == "https" ? 443 : 80;
}
var scheme = PreserveCase(url, uri.Scheme);
return uri.Uri.OriginalString.Replace(uri.Scheme, scheme);
}
private string PreserveCase(string url, string replacementString)
{
var startIndex = url.IndexOf(replacementString, StringComparison.OrdinalIgnoreCase);
return url.Substring(startIndex, replacementString.Length);
}
}
}