Debian Codegraph @

lib/3rdParty/composer/duosecurity/duo_universal_php/src/Client.php

raw symbols SCIP
1 <?php
2 /**
3 * This contains the Client class for the Universal flow
4 *
5 * This SDK allows a web developer to quickly add Duo's interactive,
6 * self-service, two-factor authentication to any Python web login form.
7 *
8 * PHP version 7
9 *
10 * @category Duo
11 * @package DuoUniversal
12 * @author Duo Security <[email protected]>
13 * @license https://opensource.org/licenses/BSD-3-Clause
14 * @link https://duo.com/docs/duoweb-v4
15 * @file
16 */
17 namespace Duo\DuoUniversal;
18
19 use \Firebase\JWT\JWT;
20 use \Firebase\JWT\Key;
21 use \Firebase\JWT\BeforeValidException;
22 use \Firebase\JWT\ExpiredException;
23 use \Firebase\JWT\SignatureInvalidException;
24 use UnexpectedValueException;
25
26 /**
27 * This class contains the client for the Universal flow.
28 */
29 class Client
30 {
31 const MAX_STATE_LENGTH = 1024;
32 const MIN_STATE_LENGTH = 22;
33 const JTI_LENGTH = 36;
34 const DEFAULT_STATE_LENGTH = 36;
35 const CLIENT_ID_LENGTH = 20;
36 const CLIENT_SECRET_LENGTH = 40;
37 const HS512_MIN_KEY_LENGTH = 64;
38 const JWT_EXPIRATION = 300;
39 const JWT_LEEWAY = 60;
40 const SUCCESS_STATUS_CODE = 200;
41
42 const USER_AGENT = "duo_universal_php/1.1.2";
43 const SIG_ALGORITHM = "HS512";
44 const GRANT_TYPE = "authorization_code";
45 const CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
46
47 const HEALTH_CHECK_ENDPOINT = "/oauth/v1/health_check";
48 const TOKEN_ENDPOINT = "/oauth/v1/token";
49 const AUTHORIZE_ENDPOINT = "/oauth/v1/authorize";
50
51 const USERNAME_ERROR = "The username is invalid.";
52 const NONCE_ERROR = "The nonce is invalid.";
53 const JWT_DECODE_ERROR = "Error decoding JWT";
54 const INVALID_CLIENT_ID_ERROR = "The Client ID is invalid";
55 const INVALID_CLIENT_SECRET_ERROR = "The Client Secret is invalid";
56 const DUO_STATE_ERROR = "State must be at least " . self::MIN_STATE_LENGTH . " characters long and no longer than " . self::MAX_STATE_LENGTH . " characters";
57 const FAILED_CONNECTION = "Unable to connect to Duo";
58 const MALFORMED_RESPONSE = "Result missing expected data.";
59 const DUO_CERTS = __DIR__ . "/ca_certs.pem";
60
61 public $client_id;
62 public $api_host;
63 public $http_proxy;
64 public $redirect_url;
65 public $use_duo_code_attribute;
66 private $client_secret;
67 private $user_agent_extension;
68
69 /**
70 * Retrieves exception message for DuoException from HTTPS result message.
71 *
72 * @param array $result The result from the HTTPS request
73 *
74 * @return string The exception message taken from the message or MALFORMED_RESPONSE
75 */
76 private function getExceptionFromResult(array $result): string
77 {
78 if (isset($result["message"]) && isset($result["message_detail"])) {
79 return $result["message"] . ": " . $result["message_detail"];
80 } elseif (isset($result["error"]) && isset($result["error_description"])) {
81 return $result["error"] . ": " . $result["error_description"];
82 }
83 return self::MALFORMED_RESPONSE;
84 }
85
86 /**
87 * Make HTTPS calls to Duo.
88 *
89 * @param string $endpoint The endpoint we are trying to hit
90 * @param array $request Information to send to Duo
91 * @param string|null $user_agent (Optional) A user-agent string
92 *
93 * @return array of strings
94 * @throws DuoException For failure to connect to Duo
95 */
96 protected function makeHttpsCall(string $endpoint, array $request, ?string $user_agent = null): array
97 {
98 $ch = curl_init();
99 curl_setopt($ch, CURLOPT_URL, "https://" . $this->api_host . $endpoint);
100 curl_setopt($ch, CURLOPT_POST, true);
101 curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
102 curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
103 curl_setopt($ch, CURLOPT_CAINFO, self::DUO_CERTS);
104 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
105 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
106 if ($user_agent !== null) {
107 curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
108 }
109 if (!is_null($this->http_proxy)) {
110 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
111 curl_setopt($ch, CURLOPT_PROXY, $this->http_proxy);
112 };
113 $result = curl_exec($ch);
114
115 /* Throw an error if the result doesn't exist or if our request returned a 5XX status */
116 if (!$result) {
117 throw new DuoException(self::FAILED_CONNECTION);
118 }
119 if (self::SUCCESS_STATUS_CODE !== curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
120 throw new DuoException($this->getExceptionFromResult(json_decode($result, true)));
121 }
122 return json_decode($result, true);
123 }
124
125 /**
126 * Pads the client secret to meet minimum key length requirements for HS512.
127 * HMAC-SHA512 in php-jwt v7+ requires 64-byte keys. Padding with null bytes
128 * doesn't affect HMAC output because HMAC internally pads to block size.
129 *
130 * @return string The padded client secret
131 */
132 private function getPaddedSecret(): string
133 {
134 return str_pad($this->client_secret, self::HS512_MIN_KEY_LENGTH, "\0");
135 }
136
137 private function createJwtPayload(string $audience): string
138 {
139 $date = new \DateTime();
140 $current_date = $date->getTimestamp();
141 $payload = [ "iss" => $this->client_id,
142 "sub" => $this->client_id,
143 "aud" => $audience,
144 "jti" => $this->generateRandomString(self::JTI_LENGTH),
145 "iat" => $current_date,
146 "exp" => $current_date + self::JWT_EXPIRATION
147 ];
148 return JWT::encode($payload, $this->getPaddedSecret(), self::SIG_ALGORITHM);
149 }
150
151 /**
152 * Generates a random hex string.
153 *
154 * @param int $state_length The length of the hex string
155 *
156 * @return string A hexadecimal string
157 * @throws DuoException For lengths that are shorter than MIN_STATE_LENGTH or longer than MAX_STATE_LENGTH
158 */
159 private function generateRandomString(int $state_length): string
160 {
161 if ($state_length > self::MAX_STATE_LENGTH || $state_length < self::MIN_STATE_LENGTH
162 ) {
163 throw new DuoException(self::DUO_STATE_ERROR);
164 }
165
166 $ALPHANUMERICS = array_merge(range('A', 'Z'), range('a', 'z'), range(0, 9));
167 $state = "";
168
169 for ($i = 0; $i < $state_length; ++$i) {
170 $state = $state . $ALPHANUMERICS[random_int(0, count($ALPHANUMERICS) - 1)];
171 }
172 return $state;
173 }
174
175 /**
176 * Constructor for Client class.
177 *
178 * @param string $client_id The Client ID found in the admin panel
179 * @param string $client_secret The Client Secret found in the admin panel
180 * @param string $api_host The api-host found in the admin panel
181 * @param string $redirect_url The URL to redirect back to after the prompt
182 * @param bool $use_duo_code_attribute (Optional: default true) Flag to use `duo_code` instead of `code` for returned authorization parameter
183 * @param string|null $http_proxy (Optional) HTTP proxy to tunnel requests through
184 *
185 * @throws DuoException For invalid Client ID or Client Secret
186 */
187 public function __construct(
188 string $client_id,
189 string $client_secret,
190 string $api_host,
191 string $redirect_url,
192 bool $use_duo_code_attribute = true,
193 ?string $http_proxy = null
194 ) {
195 if (strlen($client_id) !== self::CLIENT_ID_LENGTH) {
196 throw new DuoException(self::INVALID_CLIENT_ID_ERROR);
197 }
198 if (strlen($client_secret) !== self::CLIENT_SECRET_LENGTH) {
199 throw new DuoException(self::INVALID_CLIENT_SECRET_ERROR);
200 }
201 $this->client_id = $client_id;
202 $this->client_secret = $client_secret;
203 $this->api_host = $api_host;
204 $this->redirect_url = $redirect_url;
205 $this->use_duo_code_attribute = $use_duo_code_attribute;
206 $this->http_proxy = $http_proxy;
207 $this->user_agent_extension = null;
208 }
209
210 /**
211 * Append custom information to the user agent string.
212 *
213 * @param string $user_agent_extension Custom user agent information
214 *
215 * @return void
216 */
217 public function appendToUserAgent(string $user_agent_extension): void
218 {
219 $this->user_agent_extension = trim($user_agent_extension);
220 }
221
222 /**
223 * Build the complete user agent string.
224 *
225 * @return string The complete user agent string
226 */
227 private function buildUserAgent(): string
228 {
229 $base_user_agent = self::USER_AGENT . " php/" . phpversion() . " "
230 . php_uname();
231 if (!empty($this->user_agent_extension)) {
232 return $base_user_agent . " " . $this->user_agent_extension;
233 }
234 return $base_user_agent;
235 }
236
237 /**
238 * Generate a random hex string with a length of DEFAULT_STATE_LENGTH.
239 *
240 * @return string
241 */
242 public function generateState(): string
243 {
244 return $this->generateRandomString(self::DEFAULT_STATE_LENGTH);
245 }
246
247 /**
248 * Makes a call to HEALTH_CHECK_ENDPOINT to see if Duo is available.
249 *
250 * @return array The result of the health check
251 * @throws DuoException For failure to connect to Duo or failed health check
252 */
253 public function healthCheck(): array
254 {
255 $audience = "https://" . $this->api_host . self::HEALTH_CHECK_ENDPOINT;
256 $jwt = $this->createJwtPayload($audience);
257 $request = ["client_id" => $this->client_id, "client_assertion" => $jwt];
258
259 $result = $this->makeHttpsCall(self::HEALTH_CHECK_ENDPOINT, $request);
260
261 if (!isset($result["stat"]) || $result["stat"] !== "OK") {
262 throw new DuoException($this->getExceptionFromResult($result));
263 }
264 return $result;
265 }
266
267 /**
268 * Generate URI to redirect to for the Duo prompt.
269 *
270 * @param string $username The username of the user trying to auth
271 * @param string $state Randomly generated character string of at least 22
272 * chars returned to the integration by Duo after 2FA
273 *
274 * @return string The URI used to redirect to the Duo prompt
275 * @throws DuoException For invalid inputs
276 */
277 public function createAuthUrl(string $username, string $state): string
278 {
279 if (strlen($state) < self::MIN_STATE_LENGTH || strlen($state) > self::MAX_STATE_LENGTH
280 ) {
281 throw new DuoException(self::DUO_STATE_ERROR);
282 }
283
284 $date = new \DateTime();
285 $current_date = $date->getTimestamp();
286 $payload = [
287 'scope' => 'openid',
288 'redirect_uri' => $this->redirect_url,
289 'client_id' => $this->client_id,
290 'iss' => $this->client_id,
291 'aud' => "https://" . $this->api_host,
292 'exp' => $current_date + self::JWT_EXPIRATION,
293 'state' => $state,
294 'response_type' => 'code',
295 'duo_uname' => $username,
296 'use_duo_code_attribute' => $this->use_duo_code_attribute
297 ];
298
299 $jwt = JWT::encode($payload, $this->getPaddedSecret(), self::SIG_ALGORITHM);
300 $allArgs = [
301 'response_type' => 'code',
302 'client_id' => $this->client_id,
303 'scope' => 'openid',
304 'redirect_uri' => $this->redirect_url,
305 'request' => $jwt
306 ];
307
308 $arguments = http_build_query($allArgs);
309 return "https://" . $this->api_host . self::AUTHORIZE_ENDPOINT . "?" . $arguments;
310 }
311
312 /**
313 * Exchange a code returned by Duo for a token that contains information about the authorization.
314 *
315 * @param string $duoCode The code returned by Duo as a URL parameter after a successful authentication
316 * @param string $username The username of the user trying to authenticate with Duo
317 * @param string|null $nonce (Optional) Random 36B string used to associate a session with an ID token
318 *
319 * @return array of strings that contains information about the authentication
320 *
321 * @throws DuoException For malformed response from Duo, problems decoding the JWT,
322 * the wrong username, and the wrong nonce
323 */
324 public function exchangeAuthorizationCodeFor2FAResult(string $duoCode, string $username, ?string $nonce = null): array
325 {
326 $token_endpoint = "https://" . $this->api_host . self::TOKEN_ENDPOINT;
327 $useragent = $this->buildUserAgent();
328 $jwt = $this->createJwtPayload($token_endpoint);
329 $request = ["grant_type" => self::GRANT_TYPE,
330 "code" => $duoCode,
331 "redirect_uri" => $this->redirect_url,
332 "client_id" => $this->client_id,
333 "client_assertion_type" => self::CLIENT_ASSERTION_TYPE,
334 "client_assertion" => $jwt];
335 $result = $this->makeHttpsCall(self::TOKEN_ENDPOINT, $request, $useragent);
336
337 /* Verify that we are receiving the expected response from Duo */
338 $required_keys = ["id_token", "access_token", "expires_in", "token_type"];
339 foreach ($required_keys as $key) {
340 if (!isset($result[$key])) {
341 throw new DuoException(self::MALFORMED_RESPONSE);
342 }
343 }
344 if ($result["token_type"] !== "Bearer") {
345 throw new DuoException(self::MALFORMED_RESPONSE);
346 }
347
348 try {
349 JWT::$leeway = self::JWT_LEEWAY;
350 $jwt_key = new Key($this->getPaddedSecret(), self::SIG_ALGORITHM);
351 $token_obj = JWT::decode($result['id_token'], @$jwt_key);
352 /* JWT::decode returns a PHP object, this will turn the object into a multidimensional array */
353 $token = json_decode(json_encode($token_obj), true);
354 } catch (SignatureInvalidException | BeforeValidException | ExpiredException | UnexpectedValueException $e) {
355 throw new DuoException(self::JWT_DECODE_ERROR);
356 }
357
358 $required_token_key = ["exp", "iat", "iss", "aud"];
359 foreach ($required_token_key as $key) {
360 if (!isset($token[$key])) {
361 throw new DuoException(self::MALFORMED_RESPONSE);
362 }
363 }
364 /* Verify we have all expected fields in our token */
365 if ($token['iss'] !== $token_endpoint || $token['aud'] !== $this->client_id) {
366 throw new DuoException(self::MALFORMED_RESPONSE);
367 }
368
369 if (!isset($token['preferred_username']) || $token['preferred_username'] !== $username) {
370 throw new DuoException(self::USERNAME_ERROR);
371 }
372 if (is_string($nonce) && (!isset($token['nonce']) || $token['nonce'] !== $nonce)) {
373 throw new DuoException(self::NONCE_ERROR);
374 }
375 return $token;
376 }
377 }