Debian Codegraph @

lib/3rdParty/yubico/Yubico.php

raw symbols SCIP
1 <?php
2 /**
3 * Class for verifying Yubico One-Time-Passcodes
4 *
5 * @category Auth
6 * @package Auth_Yubico
7 * @author Simon Josefsson <[email protected]>, Olov Danielson <[email protected]>
8 * @author Roland Gruber
9 * @copyright 2007-2015 Yubico AB
10 * @copyright 2018 - 2026 Roland Gruber
11 * @license https://opensource.org/licenses/bsd-license.php New BSD License
12 * @version 2.0
13 * @link https://www.yubico.com/
14 *
15 * Adapted for LAM.
16 */
17
18 /**
19 * Class for verifying Yubico One-Time-Passcodes
20 */
21 class Auth_Yubico {
22
23 /**
24 * Yubico client ID
25 *
26 * @var string
27 */
28 private $clientId;
29
30 /**
31 * Yubico client key
32 *
33 * @var string
34 */
35 private $clientKey;
36
37 /**
38 * URL part of validation server
39 *
40 * @var string
41 */
42 private $url;
43
44 /**
45 * Flag whether to verify HTTPS server certificates or not.
46 *
47 * @var boolean
48 */
49 private $httpsVerify;
50
51 /**
52 * Constructor
53 *
54 * Sets up the object
55 *
56 * @param string $id The client identity
57 * @param string $key The client MAC key
58 * @param string $url URL
59 * @param boolean $httpsverify Flag whether to use verify HTTPS
60 * server certificates
61 */
62 public function __construct($id, $key, $url, $httpsverify) {
63 $this->clientId = $id;
64 $this->clientKey = base64_decode($key);
65 $this->httpsVerify = $httpsverify;
66 $this->url = $url;
67 }
68
69 /**
70 * Parse input string into password, yubikey prefix,
71 * ciphertext, and OTP.
72 *
73 * @param string Input string to parse
74 * @param string Optional delimiter re-class, default is '[:]'
75 * @return array|false Keyed array with fields
76 */
77 private function parsePasswordOTP($str, $delim = '[:]') {
78 if (!preg_match("/^((.*)" . $delim . ")?(([cbdefghijklnrtuv]{0,12})([cbdefghijklnrtuv]{32}))$/i", $str, $matches)) {
79 /* Dvorak? */
80 if (!preg_match("/^((.*)" . $delim . ")?(([jxe\\.uidchtnbpygk]{0,12})([jxe\\.uidchtnbpygk]{32}))$/i", $str, $matches)) {
81 return false;
82 }
83 else {
84 $ret['otp'] = strtr($matches[3], "jxe.uidchtnbpygk", "cbdefghijklnrtuv");
85 }
86 }
87 else {
88 $ret['otp'] = $matches[3];
89 }
90 $ret['password'] = $matches[2];
91 $ret['prefix'] = $matches[4];
92 $ret['ciphertext'] = $matches[5];
93 return $ret;
94 }
95
96 /**
97 * Verify Yubico OTP against multiple URLs
98 * Protocol specification 2.0 is used to construct validation requests
99 *
100 * @param string $token Yubico OTP
101 * @param int $use_timestamp 1=>send request with &timestamp=1 to
102 * get timestamp and session information
103 * in the response
104 * @throws LAMException if verification failed
105 */
106 public function verify($token, $use_timestamp = null) {
107 $timeout = 10;
108 /* Construct parameters string */
109 $ret = $this->parsePasswordOTP($token);
110 if (!$ret) {
111 throw new LAMException(_('Error'), 'Could not parse Yubikey OTP');
112 }
113 $params = array(
114 'id' => $this->clientId,
115 'otp' => $ret['otp'],
116 'nonce' => md5(uniqid(getRandomNumber()))
117 );
118 /* Take care of protocol version 2 parameters */
119 if ($use_timestamp) {
120 $params['timestamp'] = 1;
121 }
122 $params['timeout'] = $timeout;
123 ksort($params);
124 $parameters = '';
125 foreach ($params as $p => $v) {
126 $parameters .= "&" . $p . "=" . $v;
127 }
128 $parameters = ltrim($parameters, "&");
129
130 /* Generate signature. */
131 if ($this->clientKey != "") {
132 $signature = base64_encode(hash_hmac('sha1', $parameters, $this->clientKey, true));
133 $signature = preg_replace('/\+/', '%2B', $signature);
134 $parameters .= '&h=' . $signature;
135 }
136
137 $query = $this->url . "?" . $parameters;
138
139 logNewMessage(LOG_DEBUG, 'Yubico url: ' . $query);
140
141 $handle = curl_init($query);
142 curl_setopt($handle, CURLOPT_USERAGENT, "LAM Auth Yubico");
143 curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
144 if (!$this->httpsVerify) {
145 curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, 0);
146 curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0);
147 }
148 curl_setopt($handle, CURLOPT_FAILONERROR, true);
149 curl_setopt($handle, CURLOPT_TIMEOUT, $timeout);
150
151 /* Execute and read request. */
152 $str = curl_exec($handle);
153 $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
154 logNewMessage(LOG_DEBUG, 'Server answer: ' . $str);
155 if (is_string($str) && ($httpCode == 200) && preg_match("/status=([a-zA-Z0-9_]+)/", $str, $out)) {
156 $status = $out[1];
157
158 /*
159 * There are 3 cases.
160 *
161 * 1. OTP or Nonce values doesn't match - ignore
162 * response.
163 *
164 * 2. We have a HMAC key. If signature is invalid -
165 * ignore response. Return if status=OK/REPLAYED_OTP/BAD_OTP.
166 *
167 * 3. Return if status=OK or status=REPLAYED_OTP.
168 */
169 if (!preg_match("/otp=" . $params['otp'] . "/", $str) || !preg_match("/nonce=" . $params['nonce'] . "/", $str)) {
170 if ($status == 'BAD_OTP') {
171 throw new LAMException(_('Error'), 'OTP not accepted. Maybe key is not registered.');
172 }
173 throw new LAMException(_('Error'), 'Invalid answer ' . $str);
174 }
175 elseif ($this->clientKey != "") {
176 /* Case 2. Verify signature first */
177 $rows = explode("\r\n", trim($str));
178 $response = array();
179 foreach ($rows as $val) {
180 /*
181 * '=' is also used in BASE64 encoding so we only replace the first = by # which is not
182 * used in BASE64
183 */
184 $val = preg_replace('/=/', '#', $val, 1);
185 $row = explode("#", $val);
186 $response[$row[0]] = $row[1];
187 }
188
189 $parameters = array(
190 'nonce',
191 'otp',
192 'sessioncounter',
193 'sessionuse',
194 'sl',
195 'status',
196 't',
197 'timeout',
198 'timestamp'
199 );
200 sort($parameters);
201 $check = Null;
202 foreach ($parameters as $param) {
203 if (array_key_exists($param, $response)) {
204 if ($check) {
205 $check = $check . '&';
206 }
207 $check = $check . $param . '=' . $response[$param];
208 }
209 }
210
211 $checksignature = base64_encode(hash_hmac('sha1', $check, $this->clientKey, true));
212
213 if ($response['h'] == $checksignature) {
214 $this->checkStatus($status);
215 return;
216 }
217 else {
218 throw new LAMException(_('Error'), 'Invalid signature, expected ' . $checksignature);
219 }
220 }
221 else {
222 /* Case 3. We check the status directly */
223 $this->checkStatus($status);
224 return;
225 }
226 }
227 throw new LAMException(_('Error'), 'Call to verification service failed with ' . $httpCode);
228 }
229
230 /**
231 * Checks if the status is ok.
232 *
233 * @param string $status status
234 * @throws LAMException invalid status
235 */
236 private function checkStatus($status) {
237 if ($status == 'REPLAYED_OTP') {
238 throw new LAMException(_('Error'), 'OTP replay detected.');
239 }
240 elseif ($status == 'BAD_OTP') {
241 throw new LAMException(_('Error'), 'OTP not accepted. Maybe key is not registered.');
242 }
243 elseif ($status == 'OK') {
244 return;
245 }
246 throw new LAMException(_('Error'), 'Invalid status: ' . $status);
247 }
248
249 }