forked from duosecurity/duo_api_php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.php
More file actions
306 lines (254 loc) · 9.55 KB
/
Client.php
File metadata and controls
306 lines (254 loc) · 9.55 KB
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
<?php
namespace DuoAPI;
use DateTime;
const VERSION = "1.2.0-dev";
const INITIAL_BACKOFF_SECONDS = 1;
const MAX_BACKOFF_SECONDS = 32;
const BACKOFF_FACTOR = 2;
const RATE_LIMIT_HTTP_CODE = 429;
class Client
{
const DEFAULT_PAGING_LIMIT = '100';
public $ikey;
public $skey;
public $host;
public $requester;
public $paging;
public $options;
public $sleep_service;
public function __construct(
$ikey,
$skey,
$host,
$requester = null,
$paging = true
) {
assert(is_string($ikey));
assert(is_string($skey));
assert(is_string($host));
assert(is_null($requester) || is_subclass_of($requester, "DuoAPI\\Requester"));
assert(is_bool($paging));
$this->ikey = $ikey;
$this->skey = $skey;
$this->host = $host;
if ($requester !== null) {
$this->requester = $requester;
} elseif (in_array("curl", get_loaded_extensions(), true)) {
$this->requester = new CurlRequester();
} else {
$this->requester = new FileRequester();
}
$this->paging = $paging;
// Default requester options
$this->options = [
"timeout" => 10,
];
$this->sleep_service = new USleepService();
}
/*
* We're trusting the caller to set appropriate types here. We won't
* assert on the type. We're also providing a fluent interface so it can
* be called like:
*
* $client->setRequesterOption("option1", "value1")
* ->setRequesterOption("option2", "value2")
* ->setRequesterOption("option3", "value3");
*/
public function setRequesterOption($option, $value)
{
$this->options[$option] = $value;
return $this;
}
private function signParameters($method, $host, $path, $params, $skey, $ikey, $now, $body, $additional_headers)
{
assert(is_string($method));
assert(is_string($host));
assert(is_string($path));
assert(is_array($params));
assert(is_string($skey));
assert(is_string($ikey));
assert(is_string($now));
$canon = self::canonicalize($method, $host, $path, $params, $now, $body, $additional_headers);
$signature = self::sign($canon, $skey);
$auth = sprintf("%s:%s", $ikey, $signature);
$b64auth = base64_encode($auth);
return sprintf("Basic %s", $b64auth);
}
private function sign($msg, $key)
{
assert(is_string($msg));
assert(is_string($key));
$msg = mb_convert_encoding($msg ?? '', 'UTF-8', 'ISO-8859-1');
$key = mb_convert_encoding($key ?? '', 'UTF-8', 'ISO-8859-1');
return hash_hmac("sha512", $msg, $key);
}
private function canonicalize($method, $host, $path, $params, $now, $body = null, $additional_headers = [])
{
assert(is_string($method));
assert(is_string($host));
assert(is_string($path));
assert(is_array($params));
assert(is_string($now));
assert(is_string($body) || $body === null);
assert(is_array($additional_headers));
$args = self::urlEncodeParameters($params);
$canon = array(
$now,
strtoupper($method),
strtolower($host),
$path,
$args,
hash('sha512', mb_convert_encoding($body ?? '', 'UTF-8', 'ISO-8859-1')),
self::canonXDuoHeaders($additional_headers),
);
$canon = implode("\n", $canon);
return $canon;
}
private function canonXDuoHeaders($additional_headers = [])
{
assert(is_array($additional_headers));
$lowered_headers = array_change_key_case($additional_headers, CASE_LOWER);
ksort($lowered_headers);
$canon_list = [];
$added_headers = [];
foreach ($lowered_headers as $header_name => $value) {
self::validateAdditionalHeader($header_name, $value, $added_headers);
array_push($canon_list, $header_name, $value);
array_push($added_headers, $header_name);
}
$canon = implode("\x00", $canon_list);
return hash('sha512', mb_convert_encoding($canon ?? '', 'UTF-8', 'ISO-8859-1'));
}
private function validateAdditionalHeader($name, $value, $addedHeaders)
{
if ($name === null || $value === null)
{
throw new \InvalidArgumentException("Not allowed 'null' as a header name or value");
} elseif (str_contains($name,"\x00"))
{
throw new \InvalidArgumentException("Not allowed 'Null' character in header name");
} elseif (str_contains($value,"\x00"))
{
throw new \InvalidArgumentException("Not allowed 'Null' character in header value");
} elseif (!str_starts_with(strtolower($name),"x-duo-"))
{
throw new \InvalidArgumentException("Additional headers must start with 'X-Duo-'");
} elseif (in_array(strtolower($name), $addedHeaders, true))
{
throw new \InvalidArgumentException("Duplicate header passed, header=$name");
}
}
private function urlEncodeParameters($params)
{
assert(is_array($params));
ksort($params);
$args = array_map(function ($key, $value) {
return sprintf("%s=%s", rawurlencode($key), rawurlencode($value));
}, array_keys($params), array_values($params));
return implode("&", $args);
}
private function makeRequest($method, $uri, $body, $headers)
{
assert(is_string($method));
assert(is_string($uri));
assert(is_string($body) || is_null($body));
assert(is_array($headers));
$url = "https://" . $this->host . $uri;
$this->requester->options($this->options);
$backoff_seconds = INITIAL_BACKOFF_SECONDS;
while (true) {
$result = $this->requester->execute($url, $method, $headers, $body);
if ($result["http_status_code"] != RATE_LIMIT_HTTP_CODE || $backoff_seconds > MAX_BACKOFF_SECONDS) {
return $result;
}
$this->sleep_service->sleep($backoff_seconds + (rand(0, 1000) / 1000.0));
$backoff_seconds *= BACKOFF_FACTOR;
}
}
public function apiCall($method, $path, $params, $additional_headers = [])
{
assert(is_string($method));
assert(is_string($path));
assert(is_array($params));
assert(is_array($additional_headers));
$now = date(DateTime::RFC2822);
$headers = [];
if (in_array($method, ["POST", "PUT", "PATCH"], true)) {
ksort($params);
$body = json_encode($params);
$params = [];
$headers["Content-Type"] = "application/json";
$uri = $path;
} else {
$body = "";
$uri = $path . (!empty($params) ? "?" . self::urlEncodeParameters($params) : "");
}
$headers["Date"] = $now;
$headers["User-Agent"] = "duo_api_php/" . VERSION;
$headers["Authorization"] = self::signParameters(
$method,
$this->host,
$path,
$params,
$this->skey,
$this->ikey,
$now,
$body,
$additional_headers,
);
return self::makeRequest($method, $uri, $body, $headers);
}
public function jsonApiCall($method, $path, $params)
{
assert(is_string($method));
assert(is_string($path));
assert(is_array($params));
$result = self::apiCall($method, $path, $params);
$result["response"] = json_decode($result["response"], true);
return $result;
}
public function jsonPagingApiCall($method, $path, $params)
{
assert(is_string($method));
assert(is_string($path));
assert(is_array($params));
$offset = 0;
if (!isset($params["limit"])) {
$params["limit"] = self::DEFAULT_PAGING_LIMIT;
}
$result = [];
while ($offset !== false) {
$params["offset"] = strval($offset);
$paged_result = self::jsonApiCall($method, $path, $params);
/*
* If we receive any sort of error during paging calls we're going
* to bail. This is so we don't return partial results.
*/
$network_error = !isset($paged_result["success"]) || $paged_result["success"] !== true;
$api_error = !isset($paged_result["response"]["stat"]) || $paged_result["response"]["stat"] !== "OK";
if ($network_error || $api_error) {
return $paged_result;
}
$offset = isset($paged_result["response"]["metadata"]["next_offset"]) ?
$paged_result["response"]["metadata"]["next_offset"] : false;
if (isset($paged_result["response"]["metadata"])) {
unset($paged_result["response"]["metadata"]);
}
/*
* All the auxiliary data should be the same for successful paged
* calls. So let's just take the first one and merge all the
* subsequent response data into a single list to make it look
* like it was a single call.
*/
if (empty($result)) {
$result = $paged_result;
} else {
$result["response"]["response"] = array_merge(
$result["response"]["response"],
$paged_result["response"]["response"]
);
}
}
return $result;
}
}