Debian Codegraph @

lib/3rdParty/composer/duosecurity/duo_universal_php/example/index.php

raw symbols SCIP
1 <?php
2
3 ob_start();
4
5 use Psr\Http\Message\ResponseInterface as Response;
6 use Psr\Http\Message\ServerRequestInterface as Request;
7 use Slim\Logger;
8 use Slim\Middleware\Session;
9 use Slim\Views\PhpRenderer;
10 use Slim\Factory\AppFactory;
11 use Duo\DuoUniversal\Client;
12 use Duo\DuoUniversal\DuoException;
13
14 require __DIR__ . '/vendor/autoload.php';
15
16
17 $config = parse_ini_file("duo.conf");
18
19 try {
20 $duo_client = new Client(
21 $config['client_id'],
22 $config['client_secret'],
23 $config['api_hostname'],
24 $config['redirect_uri'],
25 true,
26 $config['http_proxy'] ?? null,
27 );
28 } catch (DuoException $e) {
29 throw new ErrorException("*** Duo config error. Verify the values in duo.conf are correct ***\n" . $e->getMessage());
30 }
31 $duo_failmode = strtoupper($config['failmode']);
32
33 $app = AppFactory::create();
34 $logger = new Logger();
35 $errorMiddleware = $app->addErrorMiddleware(true, true, true, $logger);
36 $app->add(new Session());
37
38 $app->get('/', function (Request $request, Response $response, $args) {
39 # Helpfully redirect to `localhost` if accessed via 127.0.0.1 or 0.0.0.0 to ensure session cookie consistency and avoid state errors.
40 # (The url used in redirect_uri must match the url used to access the app)
41 if (in_array($request->getUri()->getHost(), ['127.0.0.1', '0.0.0.0'])) {
42 header('Location: http://localhost:' . $request->getUri()->getPort());
43 exit();
44 }
45
46 $renderer = new PhpRenderer('./templates');
47 $args["message"] = "This is a demo";
48 return $renderer->render($response, "login.php", $args);
49 });
50
51 $app->post('/', function (Request $request, Response $response, $args) use ($app, $duo_client, $duo_failmode, $logger) {
52 $renderer = new PhpRenderer('./templates');
53
54 $request_body = $request->getParsedBody();
55 $username = $request_body['username'];
56 $password = $request_body['password'];
57
58 # Check user's first factor
59 if (empty($username) || empty($password)) {
60 $args["message"] = "Incorrect username or password";
61 return $renderer->render($response, "login.php", $args);
62 }
63
64 try {
65 $duo_client->healthCheck();
66 } catch (DuoException $e) {
67 $logger->error($e->getMessage());
68 if ($duo_failmode == "OPEN") {
69 # If we're failing open, errors in 2FA still allow for success
70 $args["message"] = "Login 'Successful', but 2FA Not Performed. Confirm Duo client/secret/host values are correct";
71 $render_template = "success.php";
72 } else {
73 # Otherwise the login fails and redirect user to the login page
74 $args["message"] = "2FA Unavailable. Confirm Duo client/secret/host values are correct";
75 $render_template = "login.php";
76 }
77 return $renderer->render($response, $render_template, $args);
78 }
79
80 # Generate random string to act as a state for the exchange.
81 # Store it in the session to be later used by the callback.
82 # This example demonstrates use of the http session (cookie-based)
83 # for storing the state. In some applications, strict cookie
84 # controls or other session security measures will mean a different
85 # mechanism to persist the state and username will be necessary.
86 $state = $duo_client->generateState();
87 $session = new \SlimSession\Helper();
88 $session->set("state", $state);
89 $session->set("username", $username);
90 unset($session);
91
92 # Redirect to prompt URI which will redirect to the client's redirect URI after 2FA
93 $prompt_uri = $duo_client->createAuthUrl($username, $state);
94 return $response
95 ->withHeader('Location', $prompt_uri)
96 ->withStatus(302);
97 });
98
99 # This route URL must match the redirect_uri passed to the duo client
100 $app->get('/duo-callback', function (Request $request, Response $response, $args) use ($duo_client, $logger) {
101 $query_params = $request->getQueryParams();
102 $renderer = new PhpRenderer('./templates');
103
104 # Check for errors from the Duo authentication
105 if (isset($query_params["error"])) {
106 $error_msg = $query_params["error"] . ":" . $query_params["error_description"];
107 $logger->error($error_msg);
108 $response->getBody()->write("Got Error: " . $error_msg);
109 return $response;
110 }
111
112 # Get authorization token to trade for 2FA
113 $code = $query_params["duo_code"];
114
115 # Get state to verify consistency and originality
116 $state = $query_params["state"];
117
118 # Retrieve the previously stored state and username from the session
119 $session = new \SlimSession\Helper();
120 $saved_state = $session->get("state");
121 $username = $session->get("username");
122 unset($session);
123
124 if (empty($saved_state) || empty($username)) {
125 # If the URL used to get to login.php is not localhost, (e.g. 127.0.0.1), then the sessions will be different
126 # and the localhost session will not have the state.
127 $args["message"] = "No saved state please login again";
128 return $renderer->render($response, "login.php", $args);
129 }
130
131 # Ensure nonce matches from initial request
132 if ($state != $saved_state) {
133 $args["message"] = "Duo state does not match saved state";
134 return $renderer->render($response, "login.php", $args);
135 }
136
137 try {
138 $decoded_token = $duo_client->exchangeAuthorizationCodeFor2FAResult($code, $username);
139 } catch (DuoException $e) {
140 $logger->error($e->getMessage());
141 $args["message"] = "Error decoding Duo result. Confirm device clock is correct.";
142 return $renderer->render($response, "login.php", $args);
143 }
144
145 # Exchange happened successfully so render success page
146 $args["message"] = json_encode($decoded_token, JSON_PRETTY_PRINT);
147 return $renderer->render($response, "success.php", $args);
148 });
149
150 $app->run();