Skip to content

Commit 6ccef8f

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 6ccef8f

2 files changed

Lines changed: 517 additions & 16 deletions

File tree

lib/WebDavAuth.php

Lines changed: 197 additions & 16 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,223 @@
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

3146
$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']);
47+
if (count($arr) !== 2) {
48+
$this->logger->error('Invalid WebDAV URL: "' . $this->webDavAuthUrl . '"', ['app' => 'user_external']);
3449
return false;
3550
}
3651
[$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']);
52+
$url = $protocol . '://' . $path;
53+
54+
switch ($this->authType) {
55+
case 'basic':
56+
$responseHeaders = $this->fetchWithBasicAuth($url, $uid, $password);
57+
break;
58+
case 'digest':
59+
$responseHeaders = $this->fetchWithDigestAuth($url, $uid, $password);
60+
break;
61+
default:
62+
$this->logger->error(
63+
'Invalid WebDAV auth type: "' . $this->authType . '". Expected "basic" or "digest".',
64+
['app' => 'user_external'],
65+
);
66+
return false;
67+
}
68+
69+
if ($responseHeaders === null) {
70+
if ($this->authType !== 'digest') {
71+
$this->logger->error(
72+
'WebDAV authentication request failed for URL "' . $url . '" using auth type "' . $this->authType . '".',
73+
['app' => 'user_external'],
74+
);
75+
}
4176
return false;
4277
}
43-
$returnCode = substr($headers[0], 9, 3);
4478

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

0 commit comments

Comments
 (0)