Skip to content

Commit e697b67

Browse files
committed
feat: add HTTP Digest authentication support for WebDAV backend
Implements the feature requested in PR #225 / proposed in PR #227. Adds an optional second constructor argument ('basic' or 'digest', defaulting to 'basic' for full backward compatibility). AI-assisted-by: Claude Sonnet 4.6 <noreply@anthropic.com> Signed-off-by: Anna Larch <anna@nextcloud.com>
1 parent 69d1cc6 commit e697b67

2 files changed

Lines changed: 570 additions & 18 deletions

File tree

lib/WebDavAuth.php

Lines changed: 209 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php
22

3+
declare(strict_types=1);
4+
35
/**
46
* Copyright (c) 2015 Thomas Müller <thomas.mueller@tmit.eu>
57
* This file is licensed under the Affero General Public License version 3 or
@@ -9,44 +11,233 @@
911

1012
namespace OCA\UserExternal;
1113

14+
use OCP\IDBConnection;
15+
use OCP\IGroupManager;
16+
use OCP\IUserManager;
17+
use Psr\Log\LoggerInterface;
18+
1219
class WebDavAuth extends Base {
13-
private $webDavAuthUrl;
20+
private string $webDavAuthUrl;
21+
private string $authType;
1422

15-
public function __construct($webDavAuthUrl) {
16-
parent::__construct($webDavAuthUrl);
23+
public function __construct(
24+
string $webDavAuthUrl,
25+
string $authType = 'basic',
26+
?IDBConnection $db = null,
27+
?IUserManager $userManager = null,
28+
?IGroupManager $groupManager = null,
29+
?LoggerInterface $logger = null,
30+
) {
31+
parent::__construct($webDavAuthUrl, $db, $userManager, $groupManager, $logger);
1732
$this->webDavAuthUrl = $webDavAuthUrl;
33+
$this->authType = $authType;
1834
}
1935

2036
/**
21-
* Check if the password is correct without logging in the user
37+
* Check if the password is correct without logging in the user.
2238
*
2339
* @param string $uid The username
2440
* @param string $password The password
25-
*
26-
* @return true/false
41+
* @return string|false The uid on success, false on failure
2742
*/
28-
public function checkPassword($uid, $password) {
43+
public function checkPassword($uid, $password): string|false {
2944
$uid = $this->resolveUid($uid);
3045

31-
$arr = explode('://', $this->webDavAuthUrl, 2);
32-
if (! isset($arr) or count($arr) !== 2) {
33-
$this->logger->error('ERROR: Invalid WebdavUrl: "' . $this->webDavAuthUrl . '" ', ['app' => 'user_external']);
46+
$parsed = parse_url($this->webDavAuthUrl);
47+
if ($parsed === false
48+
|| !isset($parsed['scheme'], $parsed['host'])
49+
|| !in_array($parsed['scheme'], ['http', 'https'], true)
50+
|| isset($parsed['user'])
51+
) {
52+
$this->logger->error('Invalid WebDAV URL: "' . $this->webDavAuthUrl . '"', ['app' => 'user_external']);
3453
return false;
3554
}
36-
[$protocol, $path] = $arr;
37-
$url = $protocol . '://' . urlencode($uid) . ':' . urlencode($password) . '@' . $path;
38-
$headers = get_headers($url);
39-
if ($headers === false) {
40-
$this->logger->error('ERROR: Not possible to connect to WebDAV Url: "' . $protocol . '://' . $path . '" ', ['app' => 'user_external']);
55+
$url = $this->webDavAuthUrl;
56+
57+
switch ($this->authType) {
58+
case 'basic':
59+
$responseHeaders = $this->fetchWithBasicAuth($url, $uid, $password);
60+
break;
61+
case 'digest':
62+
$responseHeaders = $this->fetchWithDigestAuth($url, $uid, $password);
63+
break;
64+
default:
65+
$this->logger->error(
66+
'Invalid WebDAV auth type: "' . $this->authType . '". Expected "basic" or "digest".',
67+
['app' => 'user_external'],
68+
);
69+
return false;
70+
}
71+
72+
if ($responseHeaders === null) {
73+
if ($this->authType !== 'digest') {
74+
$this->logger->error(
75+
'WebDAV authentication request failed for URL "' . $url . '" using auth type "' . $this->authType . '".',
76+
['app' => 'user_external'],
77+
);
78+
}
4179
return false;
4280
}
43-
$returnCode = substr($headers[0], 9, 3);
4481

45-
if (substr($returnCode, 0, 1) === '2') {
82+
$returnCode = substr($responseHeaders[0], 9, 3);
83+
if (str_starts_with($returnCode, '2')) {
4684
$this->storeUser($uid);
4785
return $uid;
86+
}
87+
return false;
88+
}
89+
90+
/**
91+
* Perform a HEAD request with HTTP Basic authentication.
92+
*
93+
* @return string[]|null Response headers, or null on connection failure.
94+
*/
95+
protected function fetchWithBasicAuth(string $url, string $uid, string $password): ?array {
96+
$context = stream_context_create(['http' => [
97+
'method' => 'HEAD',
98+
'header' => 'Authorization: Basic ' . base64_encode($uid . ':' . $password),
99+
'ignore_errors' => true,
100+
'follow_location' => 0,
101+
]]);
102+
$responseHeaders = $this->fetchUrl($url, $context);
103+
if ($responseHeaders === null) {
104+
return null;
105+
}
106+
107+
$returnCode = substr($responseHeaders[0], 9, 3);
108+
if (str_starts_with($returnCode, '3')) {
109+
$this->logger->error(
110+
'WebDAV URL returned a redirect (' . $returnCode . '). Redirects are not followed for authenticated requests to prevent credential leaking.',
111+
['app' => 'user_external'],
112+
);
113+
return null;
114+
}
115+
116+
return $responseHeaders;
117+
}
118+
119+
/**
120+
* Perform a two-step HEAD request with HTTP Digest authentication.
121+
*
122+
* @return string[]|null Response headers, or null on connection failure or missing challenge.
123+
*/
124+
protected function fetchWithDigestAuth(string $url, string $uid, string $password): ?array {
125+
// Step 1: unauthenticated request to receive the server challenge
126+
// Redirects are safe here since no credentials are sent
127+
$challengeContext = stream_context_create(['http' => [
128+
'method' => 'HEAD',
129+
'ignore_errors' => true,
130+
'follow_location' => 1,
131+
'max_redirects' => 5,
132+
]]);
133+
$challengeHeaders = $this->fetchUrl($url, $challengeContext);
134+
if ($challengeHeaders === null) {
135+
$this->logger->error('Not possible to connect to WebDAV URL: "' . $url . '"', ['app' => 'user_external']);
136+
return null;
137+
}
138+
139+
// Step 2: find the WWW-Authenticate: Digest header
140+
$authHeaderValue = null;
141+
foreach ($challengeHeaders as $header) {
142+
if (stripos($header, 'WWW-Authenticate: Digest ') === 0) {
143+
$authHeaderValue = substr($header, strlen('WWW-Authenticate: Digest '));
144+
break;
145+
}
146+
}
147+
148+
if ($authHeaderValue === null) {
149+
$this->logger->error('No Digest challenge received from WebDAV URL: "' . $url . '"', ['app' => 'user_external']);
150+
return null;
151+
}
152+
153+
// Step 3: parse the challenge parameters
154+
$params = [];
155+
preg_match_all('/(\w+)="([^"]*)"/', $authHeaderValue, $matches, PREG_SET_ORDER);
156+
foreach ($matches as $m) {
157+
$params[$m[1]] = $m[2];
158+
}
159+
160+
if (!isset($params['realm'], $params['nonce'])) {
161+
$this->logger->error('Invalid Digest challenge from WebDAV URL: "' . $url . '"', ['app' => 'user_external']);
162+
return null;
163+
}
164+
165+
$algorithm = $params['algorithm'] ?? 'MD5';
166+
if ($algorithm !== 'MD5') {
167+
$this->logger->error(
168+
'Unsupported Digest algorithm: "' . $algorithm . '". Only MD5 is supported.',
169+
['app' => 'user_external'],
170+
);
171+
return null;
172+
}
173+
174+
// Step 4: compute the digest response
175+
$parsedUrl = parse_url($url);
176+
$uri = $parsedUrl['path'] ?? '/';
177+
if (isset($parsedUrl['query'])) {
178+
$uri .= '?' . $parsedUrl['query'];
179+
}
180+
181+
$A1 = md5($uid . ':' . $params['realm'] . ':' . $password);
182+
$A2 = md5('HEAD:' . $uri);
183+
184+
$qopTokens = isset($params['qop']) ? array_map('trim', explode(',', $params['qop'])) : [];
185+
$useQop = in_array('auth', $qopTokens, true);
186+
if ($useQop) {
187+
$cnonce = bin2hex(random_bytes(8));
188+
$nc = '00000001';
189+
$response = md5($A1 . ':' . $params['nonce'] . ':' . $nc . ':' . $cnonce . ':auth:' . $A2);
48190
} else {
49-
return false;
191+
$response = md5($A1 . ':' . $params['nonce'] . ':' . $A2);
192+
}
193+
194+
$digestHeader = sprintf(
195+
'Authorization: Digest username="%s", realm="%s", nonce="%s", uri="%s", response="%s"',
196+
$this->escapeDigestValue($uid),
197+
$this->escapeDigestValue($params['realm']),
198+
$this->escapeDigestValue($params['nonce']),
199+
$this->escapeDigestValue($uri),
200+
$response,
201+
);
202+
if ($useQop) {
203+
$digestHeader .= sprintf(', cnonce="%s", nc=%s, qop=auth', $cnonce, $nc);
204+
}
205+
if (isset($params['opaque'])) {
206+
$digestHeader .= sprintf(', opaque="%s"', $this->escapeDigestValue($params['opaque']));
207+
}
208+
209+
// Step 5: send the authenticated request
210+
$context = stream_context_create(['http' => [
211+
'method' => 'HEAD',
212+
'header' => $digestHeader,
213+
'ignore_errors' => true,
214+
'follow_location' => 0,
215+
]]);
216+
$responseHeaders = $this->fetchUrl($url, $context);
217+
if ($responseHeaders === null) {
218+
$this->logger->error('Digest authenticated request failed for WebDAV URL: "' . $url . '"', ['app' => 'user_external']);
219+
return null;
220+
}
221+
return $responseHeaders;
222+
}
223+
224+
private function escapeDigestValue(string $value): string {
225+
$value = str_replace(["\r", "\n"], '', $value);
226+
return addcslashes($value, '"\\');
227+
}
228+
229+
/**
230+
* Perform an HTTP request and return the response headers.
231+
* Extracted so tests can stub network calls without hitting the wire.
232+
*
233+
* @return string[]|null Response headers, or null if the server is unreachable.
234+
*/
235+
protected function fetchUrl(string $url, mixed $context = null): ?array {
236+
if ($context !== null) {
237+
@file_get_contents($url, false, $context);
238+
} else {
239+
@file_get_contents($url);
50240
}
241+
return $http_response_header ?? null;
51242
}
52243
}

0 commit comments

Comments
 (0)