Skip to content

Commit e70caa6

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 e70caa6

2 files changed

Lines changed: 423 additions & 16 deletions

File tree

lib/WebDavAuth.php

Lines changed: 163 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,189 @@
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+
$this->logger->error(
71+
'WebDAV authentication request failed for URL "' . $url . '" using auth type "' . $this->authType . '".',
72+
['app' => 'user_external'],
73+
);
4174
return false;
4275
}
43-
$returnCode = substr($headers[0], 9, 3);
4476

45-
if (substr($returnCode, 0, 1) === '2') {
77+
$returnCode = substr($responseHeaders[0], 9, 3);
78+
if (str_starts_with($returnCode, '2')) {
4679
$this->storeUser($uid);
4780
return $uid;
81+
}
82+
return false;
83+
}
84+
85+
/**
86+
* Perform a GET request with HTTP Basic authentication.
87+
*
88+
* @return string[]|null Response headers, or null on connection failure.
89+
*/
90+
protected function fetchWithBasicAuth(string $url, string $uid, string $password): ?array {
91+
$context = stream_context_create(['http' => [
92+
'method' => 'GET',
93+
'header' => 'Authorization: Basic ' . base64_encode($uid . ':' . $password),
94+
'ignore_errors' => true,
95+
'follow_location' => 0,
96+
]]);
97+
$responseHeaders = $this->fetchUrl($url, $context);
98+
if ($responseHeaders === null) {
99+
return null;
100+
}
101+
102+
$returnCode = substr($responseHeaders[0], 9, 3);
103+
if (str_starts_with($returnCode, '3')) {
104+
return null;
105+
}
106+
107+
return $responseHeaders;
108+
}
109+
110+
/**
111+
* Perform a two-step GET request with HTTP Digest authentication.
112+
*
113+
* @return string[]|null Response headers, or null on connection failure or missing challenge.
114+
*/
115+
protected function fetchWithDigestAuth(string $url, string $uid, string $password): ?array {
116+
// Step 1: unauthenticated request to receive the server challenge
117+
$challengeContext = stream_context_create(['http' => [
118+
'method' => 'GET',
119+
'ignore_errors' => true,
120+
'follow_location' => 0,
121+
]]);
122+
$challengeHeaders = $this->fetchUrl($url, $challengeContext);
123+
if ($challengeHeaders === null) {
124+
$this->logger->error('Not possible to connect to WebDAV URL: "' . $url . '"', ['app' => 'user_external']);
125+
return null;
126+
}
127+
128+
// Step 2: find the WWW-Authenticate: Digest header
129+
$authHeaderValue = null;
130+
foreach ($challengeHeaders as $header) {
131+
if (stripos($header, 'WWW-Authenticate: Digest ') === 0) {
132+
$authHeaderValue = substr($header, strlen('WWW-Authenticate: Digest '));
133+
break;
134+
}
135+
}
136+
137+
if ($authHeaderValue === null) {
138+
$this->logger->error('No Digest challenge received from WebDAV URL: "' . $url . '"', ['app' => 'user_external']);
139+
return null;
140+
}
141+
142+
// Step 3: parse the challenge parameters
143+
$params = [];
144+
preg_match_all('/(\w+)="([^"]*)"/', $authHeaderValue, $matches, PREG_SET_ORDER);
145+
foreach ($matches as $m) {
146+
$params[$m[1]] = $m[2];
147+
}
148+
149+
if (!isset($params['realm'], $params['nonce'])) {
150+
$this->logger->error('Invalid Digest challenge from WebDAV URL: "' . $url . '"', ['app' => 'user_external']);
151+
return null;
152+
}
153+
154+
// Step 4: compute the digest response
155+
$parsedUrl = parse_url($url);
156+
$uri = $parsedUrl['path'] ?? '/';
157+
if (isset($parsedUrl['query'])) {
158+
$uri .= '?' . $parsedUrl['query'];
159+
}
160+
161+
$cnonce = bin2hex(random_bytes(8));
162+
$nc = '00000001';
163+
$A1 = md5($uid . ':' . $params['realm'] . ':' . $password);
164+
$A2 = md5('GET:' . $uri);
165+
$response = md5($A1 . ':' . $params['nonce'] . ':' . $nc . ':' . $cnonce . ':auth:' . $A2);
166+
167+
$digestHeader = sprintf(
168+
'Authorization: Digest username="%s", realm="%s", nonce="%s", uri="%s", cnonce="%s", nc=%s, qop=auth, response="%s"',
169+
$uid, $params['realm'], $params['nonce'], $uri, $cnonce, $nc, $response,
170+
);
171+
if (isset($params['opaque'])) {
172+
$digestHeader .= sprintf(', opaque="%s"', $params['opaque']);
173+
}
174+
175+
// Step 5: send the authenticated request
176+
$context = stream_context_create(['http' => [
177+
'method' => 'GET',
178+
'header' => $digestHeader,
179+
'ignore_errors' => true,
180+
'follow_location' => 0,
181+
]]);
182+
return $this->fetchUrl($url, $context);
183+
}
184+
185+
/**
186+
* Perform a GET request and return the response headers.
187+
* Extracted so tests can stub network calls without hitting the wire.
188+
*
189+
* @return string[]|null Response headers, or null if the server is unreachable.
190+
*/
191+
protected function fetchUrl(string $url, mixed $context = null): ?array {
192+
if ($context !== null) {
193+
@file_get_contents($url, false, $context);
48194
} else {
49-
return false;
195+
@file_get_contents($url);
50196
}
197+
return $http_response_header ?? null;
51198
}
52199
}

0 commit comments

Comments
 (0)