Ollama relies on a defense-in-depth model that secures model provenance, multi-tenant file operations, local network boundaries, and execution controls. Developers must explicitly validate model paths, enforce strict loopback bindings, and sanitize untrusted prompt inputs and native binding payloads. Any ambiguity in configuration sources, path traversals, or memory limits must fail closed to prevent resource exhaustion and unauthorized access.
Essential implementation rules
Enforce Interactive Authorization Checks for Tool Execution
Keep AllowAllTools set to false and require explicit ApprovalPrompter configurations so that sensitive model-initiated tool executions and shell commands require human authorization.
Validate File Inputs Before Processing OpenAI Adapter Requests
Filter out unsupported file inputs before invoking OpenAI request processing to prevent unexpected error handling and parsing failures in convertResponsesContent.
Enforce Token Validation and Server Security Settings for UI APIs
Ensure Server.Dev is set to false in production to enforce incoming token cookie validation on all protected UI endpoints.
Validate Authentication Tokens and Realms in Registry Transfers
Implement dynamic GetToken callbacks that inspect challenge parameters and strictly validate that challenge realm URLs match trusted registry prefixes.
Validate Model Namespaces and Paths to Prevent Traversal
Parse and validate model names, resolve symbolic links via filepath.EvalSymlinks, and ensure IsFullyQualified() returns true before calling .Filepath() or loading tokenizers.
Validate Native Binding Arguments at the Bridge Boundary
Treat incoming JSON parameters in native binding callbacks as untrusted input, fully parsing and validating all arguments before executing system or file operations.
Enforce Loopback Restrictions and Secure Provenance for Configuration
Restrict cloud base URLs to secure HTTPS loopback enclaves, verify tokenizer and model file checksums, and control configuration directory environment variables.
Disable Agent Shell Tool Execution in Restricted Environments
Export OLLAMA_AGENT_DISABLE_SHELL=1 prior to launching agent sessions to prevent the runtime from registering and executing local shell commands.
Validate Model File Formats and Metadata Prior to Deserialization
Enforce strict MIME type and extension checks, prioritize safe formats like Safetensors and GGUF, and safely decode tensor headers and shapes before parsing binary weights.
Enforce Restrictive File Permissions and Extension Allowlists
Create sensitive configuration and token files with 0600 permissions and validate uploaded files against explicit allowed extension sets.
Sanitize Prompt Control Tags in Untrusted User Inputs
Strip or encode structural prompt control tags such as <start_of_turn> and <escape> from user inputs and tool responses before submitting them to model APIs.
Validate API Request Parameters Against Expected Input Contracts
Enforce valid numerical ranges for generation parameters like top_logprobs and supply strict JSON schema definitions for structured outputs and tool definitions.
Canonicalize and Sanitize Untrusted Prompt Inputs and Control Tokens
Sanitize untrusted user input before tokenization or prompt generation, and remember that tokenizer decodes omit null bytes (0x00) during reconstruction.
Strip Hop-by-Hop Headers During Request Proxying
Strip hop-by-hop headers and custom headers enumerated inside the Connection header token list before forwarding requests or responses between clients and cloud endpoints.
Restrict Network Endpoints and Bind Backends to Loopback
Validate remote model hostnames against allowed remote configurations, reject non-loopback proxy targets in release mode, and bind backend processes to 127.0.0.1.
Configure Context Limits, Token Budgets, and Upload Size Constraints
Specify explicit context limits via num_ctx, cap generation budgets using NumPredict, and enforce maximum file and decompressed payload size limits.
Manage Model Memory Residency, Concurrency, and Cache Sessions
Explicitly unload idle models using keep_alive, set conservative concurrency limits for blob transfers, and close cache sessions securely using defer session.close().
Disable Developer Tools in Production Webview Builds
Set the debug parameter passed to webview_create to 0 in production builds to prevent internal developer tooling inspection and interactive API execution.
Redact Sensitive Environment Variables Before Logging Subprocess State
Filter and redact environment variable keys containing API keys, tokens, or credentials before passing them to application logs.
Fail Closed on SQLite Foreign Key Constraint Initialization
Configure SQLite connections with _foreign_keys=on and execute PRAGMA foreign_keys = ON immediately upon initialization to maintain database integrity.
ollama: All Security Cards
Approximately 5,895 tokens
On this card
Category: access control
Enforce Interactive Authorization Checks for Agent Tool Execution
Use when
Configuring chat sessions and agent workflows where models can execute external tools or perform sensitive actions.
When configuring agent sessions or chat options, keep AllowAllTools set to false or DisableTools set to false only if a custom ApprovalPrompter and ApprovalState are supplied. This ensures that sensitive file system or system commands require explicit human authorization before being executed by the engine.
Handle Unsupported File Inputs Before OpenAI Requests
Use when
When building OpenAI compatibility adapter requests and passing input items to convertResponsesContent.
Secure rules
Rule 1: Filter out unsupported file inputs before invoking OpenAI request processing.
Do not pass file content items in OpenAI Responses request payloads, as convertResponsesContent explicitly rejects file inputs and returns an error. Filter out file content inputs or convert supported content into text or base64 image objects before calling FromResponsesRequest.
Enforce Token Cookies and Server Security Settings for UI APIs
Use when
When configuring UI server instances and handling requests to application UI endpoints.
Secure rules
Rule 1: Disable development mode in production to enforce token validation.
Ensure Server.Dev is set to false when instantiating the UI server in production environments, ensuring incoming requests are properly authenticated via token cookies.
s := &ui.Server{ Logger: logger, Token: requiredAuthToken, Dev: false,}
Rule 2: Attach valid token cookies to API requests targeting protected UI server routes.
Attach the secret token cookie matching the server configuration on every client request to avoid receiving HTTP 403 Forbidden rejection responses.
Rule 2: Validate challenge realms and domains before issuing token requests.
Ensure that challenge realm URLs match the expected registry host and trusted prefixes before returning authorization secrets to prevent leaking credentials to external hosts.
Validate Model Namespaces and Names in Multi-Tenant Model Serving
Use when
Developing multi-tenant model serving endpoints where clients supply model names and paths that must be restricted to authorized tenant namespaces.
Secure rules
Rule 1: Enforce authorization for every model request outside Ollama
Parse and validate the canonical model name, then authorize that full name in the authenticated application or proxy before forwarding the request to Ollama.
parsed := model.ParseName(userRequestedModel)if !parsed.IsValid() { return errors.New("invalid model name")}if !authorizeModel(currentTenant, parsed.String()) { return errors.New("access denied")}// Proceed with model serving
Rule 2: Prevent traversal vulnerabilities by validating model paths and qualification.
Always parse model paths using model.ParseNameFromFilepath and ensure IsFullyQualified() returns true before calling .Filepath() to prevent unauthorized cross-tenant file access and runtime panics.
import "github.com/ollama/ollama/types/model"func LoadTenantModel(userSuppliedPath string) (model.Name, bool) { n := model.ParseNameFromFilepath(userSuppliedPath) if !n.IsValid() || n.Namespace == "" || n.Model == "" { return model.Name{}, false } return n, true}
Validate native binding arguments at the bridge boundary
Use when
Registering and implementing native host functions exposed to untrusted JavaScript via webview bindings.
Secure rules
Rule 1: Treat incoming JSON request parameters in native binding callbacks as untrusted input and validate all arguments before processing.
When exposing native C or C++ host functions using webview_bind, always parse and validate the JSON request parameter (req) completely before passing any values into system functions, file operations, or native APIs.
Enforce Strict Loopback Restrictions and Secure Provenance for Ollama Configuration Sources
Use when
When configuring base URLs, environment variables, model tokenizer files, or integration settings for Ollama to prevent untrusted or ambiguous sources from altering security behavior.
Secure rules
Rule 1: Restrict cloud base URL overrides to secure loopback enclaves in production modes.
When configuring OLLAMA_CLOUD_BASE_URL, ensure the URL uses HTTPS and contains no path, query, fragment, or user credentials to prevent unauthorized redirection of proxied cloud requests.
Rule 2: Verify tokenizer and model configuration files before import and conversion.
Verify the checksums and origin of all model configuration files such as tokenizer.json, tokenizer_config.json, and generation_config.json prior to parsing to prevent prompt injection or context misalignment.
Rule 3: Control configuration directory environment variables to prevent path hijacking.
Applications invoking agent configuration logic must validate or explicitly override environment variables such as PI_CODING_AGENT_DIR and PI_CONFIG_DIR to prevent file redirection and tampering.
Disable agent shell tool execution in restricted environments
Use when
Running Ollama agent sessions in environments where local shell command execution by the model is unsafe or unmonitored.
Secure rules
Rule 1: Set OLLAMA_AGENT_DISABLE_SHELL to restrict the agent runtime from registering and executing shell execution tools.
Export OLLAMA_AGENT_DISABLE_SHELL=1 before launching Ollama agent sessions to prevent the model from executing local shell commands.
export OLLAMA_AGENT_DISABLE_SHELL=1ollama
Category: deserialization
Validate Model File Formats, Headers, and Metadata Prior to Deserialization
Use when
Use when loading, parsing, or creating model files from untrusted user inputs or local paths in Ollama model workflows.
Secure rules
Rule 1: Enforce strict format validation, MIME type checks, and content-type detection on model files before invoking deserialization or parsing backends.
Validate model file extensions and MIME content types before allowing model backends to load them. Prioritize safe serialization formats such as Safetensors and GGUF, which do not support executable code. If legacy PyTorch model formats are allowed, enforce strict content-type detection to ensure conformity and prevent loading arbitrary or unverified serialized streams.
files, err := filesForModel(modelDirPath)if err != nil { return nil, fmt.Errorf("failed to validate model file formats: %w", err)}
Rule 2: Validate GGUF and Safetensors headers, shapes, and metadata boundaries before decoding binary weight payloads
When parsing Safetensors model weight files, decode metadata using safe JSON parsers rather than executable object deserializers, and validate tensor headers, shapes, and offset bounds. Ensure metadata type constraints and structures are verified to prevent out-of-bounds access, type confusion, or unexpected behavior.
Rule 2: Validate file extensions and types against explicit allowed sets when processing uploads.
When processing user files in UI components, validate file extensions against explicit allowed sets and custom validation rules to prevent processing unexpected file types or malicious inputs.
Prevent Path Traversal and Enforce Containment during File and Model Operations
Use when
Processing user-supplied paths, model directories, tokenizers, skill imports, and output save operations in Ollama.
Secure rules
Rule 1: Resolve symbolic links using filepath.EvalSymlinks and ensure local paths stay contained within storage boundaries.
When processing filesystem paths for model components or files, always resolve symbolic links using filepath.EvalSymlinks before opening files to prevent unauthorized access outside expected directories. Ensure paths satisfy containment constraints such as filepath.IsLocal(rel) or prefix validation.
Rule 2: Sanitize path parameters and filenames to prevent directory traversal in file saving and import routines.
When handling commands that write files to disk or import external assets, sanitize and reject path parameters containing directory traversal sequences (..) or directory separators to restrict writes and reads strictly to the intended working directory.
if filepath.Base(filename) != filename || strings.Contains(filename, "..") { return fmt.Errorf("invalid path: filename must not contain directory paths")}
Rule 3: Validate and sanitize model directory paths before invoking tokenizer loading
If accepting an untrusted model path, resolve symlinks and verify that the resolved path remains within an allowed base before calling tokenizer.Load, which reads the supplied file or fixed companion files from the supplied directory.
Sanitize prompt control tags in untrusted user inputs for FunctionGemma
Use when
Passing user messages, tool definitions, or tool arguments into the FunctionGemma renderer where control tokens could break prompt encapsulation.
Secure rules
Rule 1: Sanitize prompt framing control tags from user inputs before submission
Strip or encode Gemma structural tags such as <start_of_turn>, <end_of_turn>, and <escape> from user inputs and tool responses before submitting them to the API. This prevents attackers from prematurely closing message blocks and injecting fake tool calls or developer instructions.
Validate API request payloads and parameters against expected input contracts
Use when
When building and handling API requests, generating model outputs, and configuring parameters in Ollama.
Secure rules
Rule 1: Enforce valid ranges for numerical generation parameters
Validate that input parameters such as top_logprobs fall within their accepted boundaries prior to processing requests to prevent error responses and interrupted operations.
Rule 3: Validate required model creation metadata types
Ensure supported Info values use the types expected by the create endpoint to avoid rejected requests.
Category: input interpretation safety
Canonicalize and Sanitize Untrusted Prompt Inputs and Control Tokens
Use when
Processing untrusted user strings, custom prompt templates, tokenizer encodings, and inline control tokens before passing them to model inference handlers.
Secure rules
Rule 1: Sanitize and isolate untrusted user input before tokenization or raw prompt generation to prevent control token injection and prompt boundary spoofing.
When encoding text or setting raw prompt mode, ensure untrusted user input is sanitized or kept strictly within designated user data boundaries. Unsanitized strings containing special token substrings or inline directives can alter prompt evaluation logic or inject control sequences.
Rule 2: Account for null byte omission during tokenizer decoding steps.
When decoding token IDs using tokenizer implementations, null bytes (0x00) are explicitly omitted from the decoded string output. Developers must not rely on tokenizer Decode calls for exact binary roundtrips or string reconstruction when inputs may contain null bytes to prevent canonicalization mismatches.
Sanitize Hop-by-Hop Headers During Request Proxying
Use when
When proxying requests and responses between clients and cloud endpoints
Secure rules
Rule 1: Strip hop-by-hop headers and connection-token headers before forwarding requests or responses
When proxying requests or responses between clients and cloud endpoints, always strip hop-by-hop headers, including headers enumerated inside the Connection header token list. Custom headers marked in Connection must not be forwarded upstream or downstream to prevent HTTP request smuggling and proxy confusion.
src := http.Header{}src.Add("Connection", "keep-alive, X-Trace-Hop")src.Add("X-Trace-Hop", "drop-me")dst := http.Header{}copyProxyRequestHeaders(dst, src)// dst will have Connection and X-Trace-Hop removed
Category: network boundary
Enforce Strict Loopback and Endpoint Allowlisting for Network Boundaries
Use when
Configuring network endpoints, proxy targets, remote model destinations, and subprocess bindings across trust boundaries.
Secure rules
Rule 1: Validate remote model hostnames against allowed remote configurations.
Ensure remote model requests target endpoints matching allowed remote domains specified in allowed remote configurations and environment variables.
req := api.GenerateRequest{ Model: "remote-model-alias", Prompt: "Summarize this context",}
Rule 2: Restrict production proxy target overrides to loopback addresses.
In release mode, enforce strict validation of proxy target base URLs so that non-loopback HTTP endpoints are rejected and only loopback addresses are allowed.
Configure Context Limits and Truncation Options for Generation Requests
Use when
When building multi-turn chat sessions or text generation pipelines where prompt sizes or conversation histories risk exceeding model context window bounds.
Secure rules
Rule 1: Specify explicit context limits and enable truncation for prompt histories
Always supply an explicit context window limit via num_ctx in request options and enable context truncation to ensure that prompt history exceeding the maximum context length is truncated deterministically prior to tokenization and execution.
Rule 2: Cap model prediction token limits and generation budgets
Set explicit prediction limits using NumPredict or max_tokens parameters to cap open-ended generation requests and prevent unbounded text generation from exhausting system resources.
message = client.messages.create( model='qwen3-coder', max_tokens=1024, messages=[ {'role': 'user', 'content': 'Hello, how are you?'} ])
Rule 3: Validate prompt length before initiating generation pipelines
Execute request validation via Prepare prior to running text generation pipelines to enforce model context window limits and constrain token generation budgets.
Enforce Input Size Limits on File Uploads and Compressed Payload Streams
Use when
When handling client-side file validations, user uploads, or incoming compressed request bodies on server endpoints.
Secure rules
Rule 1: Enforce maximum file size limits during client-side file validation
Specify an explicit maxFileSize threshold using validateFile to reject oversized files before reading or transferring them, preventing client-side memory exhaustion.
Rule 2: Enforce strict size limits on compressed request payloads
Enforce explicit size limits on decompressed streams or check uncompressed payload lengths prior to handling compressed incoming requests to prevent decompression bombs.
if len(uncompressedPayload) > 20<<20 { return errors.New("payload exceeds maximum allowed decompressed limit of 20MB")}
Manage Model Memory Residency and Concurrency Limits to Prevent Resource Exhaustion
Use when
When managing model lifecycle persistence, concurrent file/blob transfers, or server request queues in resource-constrained environments.
Secure rules
Rule 1: Unload idle models explicitly using keep_alive parameters
Manage loaded model memory residency explicitly by passing the keep_alive parameter or setting keep_alive to 0 with an empty prompt to immediately unload idle models from VRAM and RAM.
Rule 2: Set conservative concurrency limits for blob transfer operations
Explicitly configure Concurrency and BodyConcurrency when initializing transfer options rather than relying on high default settings that can cause socket exhaustion or IOPS saturation.
Rule 3: Close cache sessions securely to prevent memory leaks
Ensure session.close() is invoked via defer after beginning an MLX prefix cache session to release pending prefill snapshots and free allocated memory if execution fails or is canceled.
Disable Developer Tools in Production Webview Builds
Use when
When configuring production builds that utilize webview interfaces to ensure developer inspection tools and context menus are disabled.
Secure rules
Rule 1: Set the debug parameter to zero when creating production webview instances to disable internal developer tools.
Ensure that the debug parameter passed to webview_create is explicitly set to 0 in production builds. This prevents attackers from inspecting internal application state, manipulating the webview context, or executing bound native host APIs interactively.
Rule 2: Regularly update Ollama deployments to the latest official release version
Keep Ollama deployments updated to the latest official release or Docker image to maintain runtime security and incorporate necessary vulnerability patches.
# Update Ollama using the official installer on Linux:curl -fsSL https://ollama.com/install.sh | sh# Or update a Docker-based deployment:docker pull ollama/ollama:latest
Category: secret handling
Redact Sensitive Environment Variables Before Logging Subprocess State
Use when
When logging execution environments or configuration maps for model runners that may contain sensitive credentials.
Secure rules
Rule 1: Filter and redact sensitive key-value pairs containing API keys, tokens, secrets, or credentials before passing them to application logs.
Sanitize environment variable keys and redact sensitive values using helper functions before passing them to loggers to prevent credential leakage in log output.
func redactEnvValue(key, value string) string { for _, token := range []string{"API", "KEY", "TOKEN", "SECRET", "PASSWORD", "CREDENTIAL", "AUTH"} { if strings.Contains(strings.ToUpper(key), token) { return "[redacted]" } } return value}
Category: security control integrity
Fail Closed on SQLite Foreign Key Constraint Initialization
Use when
When initializing SQLite database connections for data storage and state management.
Secure rules
Rule 1: Enforce SQLite foreign key constraints immediately during connection establishment and database initialization.
Always configure SQLite database connections to enforce foreign key constraints by appending _foreign_keys=on to the DSN and executing PRAGMA foreign_keys = ON upon initialization to maintain data integrity and prevent cascading delete failures.
When configuring agent sessions or chat options, keep AllowAllTools set to false or DisableTools set to false only if a custom ApprovalPrompter and ApprovalState are supplied. This ensures that sensitive file system or system commands require explicit human authorization before being executed by the engine.
Handle Unsupported File Inputs Before OpenAI Requests
Approximately 199 tokens
Use when
When building OpenAI compatibility adapter requests and passing input items to convertResponsesContent.
Secure rules
Rule 1: Filter out unsupported file inputs before invoking OpenAI request processing.
Do not pass file content items in OpenAI Responses request payloads, as convertResponsesContent explicitly rejects file inputs and returns an error. Filter out file content inputs or convert supported content into text or base64 image objects before calling FromResponsesRequest.
Enforce Token Cookies and Server Security Settings for UI APIs
Approximately 550 tokens
Use when
When configuring UI server instances and handling requests to application UI endpoints.
Secure rules
Rule 1: Disable development mode in production to enforce token validation.
Ensure Server.Dev is set to false when instantiating the UI server in production environments, ensuring incoming requests are properly authenticated via token cookies.
s := &ui.Server{ Logger: logger, Token: requiredAuthToken, Dev: false,}
Rule 2: Attach valid token cookies to API requests targeting protected UI server routes.
Attach the secret token cookie matching the server configuration on every client request to avoid receiving HTTP 403 Forbidden rejection responses.
Rule 2: Validate challenge realms and domains before issuing token requests.
Ensure that challenge realm URLs match the expected registry host and trusted prefixes before returning authorization secrets to prevent leaking credentials to external hosts.
Validate Model Namespaces and Names in Multi-Tenant Model Serving
Approximately 506 tokens
Use when
Developing multi-tenant model serving endpoints where clients supply model names and paths that must be restricted to authorized tenant namespaces.
Secure rules
Rule 1: Enforce authorization for every model request outside Ollama
Parse and validate the canonical model name, then authorize that full name in the authenticated application or proxy before forwarding the request to Ollama.
parsed := model.ParseName(userRequestedModel)if !parsed.IsValid() { return errors.New("invalid model name")}if !authorizeModel(currentTenant, parsed.String()) { return errors.New("access denied")}// Proceed with model serving
Rule 2: Prevent traversal vulnerabilities by validating model paths and qualification.
Always parse model paths using model.ParseNameFromFilepath and ensure IsFullyQualified() returns true before calling .Filepath() to prevent unauthorized cross-tenant file access and runtime panics.
import "github.com/ollama/ollama/types/model"func LoadTenantModel(userSuppliedPath string) (model.Name, bool) { n := model.ParseNameFromFilepath(userSuppliedPath) if !n.IsValid() || n.Namespace == "" || n.Model == "" { return model.Name{}, false } return n, true}
Validate native binding arguments at the bridge boundary
Use when
Registering and implementing native host functions exposed to untrusted JavaScript via webview bindings.
Secure rules
Rule 1: Treat incoming JSON request parameters in native binding callbacks as untrusted input and validate all arguments before processing.
When exposing native C or C++ host functions using webview_bind, always parse and validate the JSON request parameter (req) completely before passing any values into system functions, file operations, or native APIs.
Enforce Strict Loopback Restrictions and Secure Provenance for Ollama Configuration Sources
Approximately 428 tokens
Use when
When configuring base URLs, environment variables, model tokenizer files, or integration settings for Ollama to prevent untrusted or ambiguous sources from altering security behavior.
Secure rules
Rule 1: Restrict cloud base URL overrides to secure loopback enclaves in production modes.
When configuring OLLAMA_CLOUD_BASE_URL, ensure the URL uses HTTPS and contains no path, query, fragment, or user credentials to prevent unauthorized redirection of proxied cloud requests.
Rule 2: Verify tokenizer and model configuration files before import and conversion.
Verify the checksums and origin of all model configuration files such as tokenizer.json, tokenizer_config.json, and generation_config.json prior to parsing to prevent prompt injection or context misalignment.
Rule 3: Control configuration directory environment variables to prevent path hijacking.
Applications invoking agent configuration logic must validate or explicitly override environment variables such as PI_CODING_AGENT_DIR and PI_CONFIG_DIR to prevent file redirection and tampering.
Disable agent shell tool execution in restricted environments
Approximately 147 tokens
Use when
Running Ollama agent sessions in environments where local shell command execution by the model is unsafe or unmonitored.
Secure rules
Rule 1: Set OLLAMA_AGENT_DISABLE_SHELL to restrict the agent runtime from registering and executing shell execution tools.
Export OLLAMA_AGENT_DISABLE_SHELL=1 before launching Ollama agent sessions to prevent the model from executing local shell commands.
export OLLAMA_AGENT_DISABLE_SHELL=1ollama
Validate Model File Formats, Headers, and Metadata Prior to Deserialization
Approximately 492 tokens
Use when
Use when loading, parsing, or creating model files from untrusted user inputs or local paths in Ollama model workflows.
Secure rules
Rule 1: Enforce strict format validation, MIME type checks, and content-type detection on model files before invoking deserialization or parsing backends.
Validate model file extensions and MIME content types before allowing model backends to load them. Prioritize safe serialization formats such as Safetensors and GGUF, which do not support executable code. If legacy PyTorch model formats are allowed, enforce strict content-type detection to ensure conformity and prevent loading arbitrary or unverified serialized streams.
files, err := filesForModel(modelDirPath)if err != nil { return nil, fmt.Errorf("failed to validate model file formats: %w", err)}
Rule 2: Validate GGUF and Safetensors headers, shapes, and metadata boundaries before decoding binary weight payloads
When parsing Safetensors model weight files, decode metadata using safe JSON parsers rather than executable object deserializers, and validate tensor headers, shapes, and offset bounds. Ensure metadata type constraints and structures are verified to prevent out-of-bounds access, type confusion, or unexpected behavior.
Rule 2: Validate file extensions and types against explicit allowed sets when processing uploads.
When processing user files in UI components, validate file extensions against explicit allowed sets and custom validation rules to prevent processing unexpected file types or malicious inputs.
Prevent Path Traversal and Enforce Containment during File and Model Operations
Use when
Processing user-supplied paths, model directories, tokenizers, skill imports, and output save operations in Ollama.
Secure rules
Rule 1: Resolve symbolic links using filepath.EvalSymlinks and ensure local paths stay contained within storage boundaries.
When processing filesystem paths for model components or files, always resolve symbolic links using filepath.EvalSymlinks before opening files to prevent unauthorized access outside expected directories. Ensure paths satisfy containment constraints such as filepath.IsLocal(rel) or prefix validation.
Rule 2: Sanitize path parameters and filenames to prevent directory traversal in file saving and import routines.
When handling commands that write files to disk or import external assets, sanitize and reject path parameters containing directory traversal sequences (..) or directory separators to restrict writes and reads strictly to the intended working directory.
if filepath.Base(filename) != filename || strings.Contains(filename, "..") { return fmt.Errorf("invalid path: filename must not contain directory paths")}
Rule 3: Validate and sanitize model directory paths before invoking tokenizer loading
If accepting an untrusted model path, resolve symlinks and verify that the resolved path remains within an allowed base before calling tokenizer.Load, which reads the supplied file or fixed companion files from the supplied directory.
Sanitize prompt control tags in untrusted user inputs for FunctionGemma
Approximately 255 tokens
Use when
Passing user messages, tool definitions, or tool arguments into the FunctionGemma renderer where control tokens could break prompt encapsulation.
Secure rules
Rule 1: Sanitize prompt framing control tags from user inputs before submission
Strip or encode Gemma structural tags such as <start_of_turn>, <end_of_turn>, and <escape> from user inputs and tool responses before submitting them to the API. This prevents attackers from prematurely closing message blocks and injecting fake tool calls or developer instructions.
Validate API request payloads and parameters against expected input contracts
Approximately 328 tokens
Use when
When building and handling API requests, generating model outputs, and configuring parameters in Ollama.
Secure rules
Rule 1: Enforce valid ranges for numerical generation parameters
Validate that input parameters such as top_logprobs fall within their accepted boundaries prior to processing requests to prevent error responses and interrupted operations.
Rule 3: Validate required model creation metadata types
Ensure supported Info values use the types expected by the create endpoint to avoid rejected requests.
Canonicalize and Sanitize Untrusted Prompt Inputs and Control Tokens
Approximately 309 tokens
Use when
Processing untrusted user strings, custom prompt templates, tokenizer encodings, and inline control tokens before passing them to model inference handlers.
Secure rules
Rule 1: Sanitize and isolate untrusted user input before tokenization or raw prompt generation to prevent control token injection and prompt boundary spoofing.
When encoding text or setting raw prompt mode, ensure untrusted user input is sanitized or kept strictly within designated user data boundaries. Unsanitized strings containing special token substrings or inline directives can alter prompt evaluation logic or inject control sequences.
Rule 2: Account for null byte omission during tokenizer decoding steps.
When decoding token IDs using tokenizer implementations, null bytes (0x00) are explicitly omitted from the decoded string output. Developers must not rely on tokenizer Decode calls for exact binary roundtrips or string reconstruction when inputs may contain null bytes to prevent canonicalization mismatches.
Sanitize Hop-by-Hop Headers During Request Proxying
Approximately 207 tokens
Use when
When proxying requests and responses between clients and cloud endpoints
Secure rules
Rule 1: Strip hop-by-hop headers and connection-token headers before forwarding requests or responses
When proxying requests or responses between clients and cloud endpoints, always strip hop-by-hop headers, including headers enumerated inside the Connection header token list. Custom headers marked in Connection must not be forwarded upstream or downstream to prevent HTTP request smuggling and proxy confusion.
src := http.Header{}src.Add("Connection", "keep-alive, X-Trace-Hop")src.Add("X-Trace-Hop", "drop-me")dst := http.Header{}copyProxyRequestHeaders(dst, src)// dst will have Connection and X-Trace-Hop removed
Enforce Strict Loopback and Endpoint Allowlisting for Network Boundaries
Approximately 343 tokens
Use when
Configuring network endpoints, proxy targets, remote model destinations, and subprocess bindings across trust boundaries.
Secure rules
Rule 1: Validate remote model hostnames against allowed remote configurations.
Ensure remote model requests target endpoints matching allowed remote domains specified in allowed remote configurations and environment variables.
req := api.GenerateRequest{ Model: "remote-model-alias", Prompt: "Summarize this context",}
Rule 2: Restrict production proxy target overrides to loopback addresses.
In release mode, enforce strict validation of proxy target base URLs so that non-loopback HTTP endpoints are rejected and only loopback addresses are allowed.
Configure Context Limits and Truncation Options for Generation Requests
Approximately 895 tokens
Use when
When building multi-turn chat sessions or text generation pipelines where prompt sizes or conversation histories risk exceeding model context window bounds.
Secure rules
Rule 1: Specify explicit context limits and enable truncation for prompt histories
Always supply an explicit context window limit via num_ctx in request options and enable context truncation to ensure that prompt history exceeding the maximum context length is truncated deterministically prior to tokenization and execution.
Rule 2: Cap model prediction token limits and generation budgets
Set explicit prediction limits using NumPredict or max_tokens parameters to cap open-ended generation requests and prevent unbounded text generation from exhausting system resources.
message = client.messages.create( model='qwen3-coder', max_tokens=1024, messages=[ {'role': 'user', 'content': 'Hello, how are you?'} ])
Rule 3: Validate prompt length before initiating generation pipelines
Execute request validation via Prepare prior to running text generation pipelines to enforce model context window limits and constrain token generation budgets.
Enforce Input Size Limits on File Uploads and Compressed Payload Streams
Use when
When handling client-side file validations, user uploads, or incoming compressed request bodies on server endpoints.
Secure rules
Rule 1: Enforce maximum file size limits during client-side file validation
Specify an explicit maxFileSize threshold using validateFile to reject oversized files before reading or transferring them, preventing client-side memory exhaustion.
Rule 2: Enforce strict size limits on compressed request payloads
Enforce explicit size limits on decompressed streams or check uncompressed payload lengths prior to handling compressed incoming requests to prevent decompression bombs.
if len(uncompressedPayload) > 20<<20 { return errors.New("payload exceeds maximum allowed decompressed limit of 20MB")}
Manage Model Memory Residency and Concurrency Limits to Prevent Resource Exhaustion
Use when
When managing model lifecycle persistence, concurrent file/blob transfers, or server request queues in resource-constrained environments.
Secure rules
Rule 1: Unload idle models explicitly using keep_alive parameters
Manage loaded model memory residency explicitly by passing the keep_alive parameter or setting keep_alive to 0 with an empty prompt to immediately unload idle models from VRAM and RAM.
Rule 2: Set conservative concurrency limits for blob transfer operations
Explicitly configure Concurrency and BodyConcurrency when initializing transfer options rather than relying on high default settings that can cause socket exhaustion or IOPS saturation.
Rule 3: Close cache sessions securely to prevent memory leaks
Ensure session.close() is invoked via defer after beginning an MLX prefix cache session to release pending prefill snapshots and free allocated memory if execution fails or is canceled.
Disable Developer Tools in Production Webview Builds
Approximately 278 tokens
Use when
When configuring production builds that utilize webview interfaces to ensure developer inspection tools and context menus are disabled.
Secure rules
Rule 1: Set the debug parameter to zero when creating production webview instances to disable internal developer tools.
Ensure that the debug parameter passed to webview_create is explicitly set to 0 in production builds. This prevents attackers from inspecting internal application state, manipulating the webview context, or executing bound native host APIs interactively.
Rule 2: Regularly update Ollama deployments to the latest official release version
Keep Ollama deployments updated to the latest official release or Docker image to maintain runtime security and incorporate necessary vulnerability patches.
# Update Ollama using the official installer on Linux:curl -fsSL https://ollama.com/install.sh | sh# Or update a Docker-based deployment:docker pull ollama/ollama:latest
Redact Sensitive Environment Variables Before Logging Subprocess State
Approximately 200 tokens
Use when
When logging execution environments or configuration maps for model runners that may contain sensitive credentials.
Secure rules
Rule 1: Filter and redact sensitive key-value pairs containing API keys, tokens, secrets, or credentials before passing them to application logs.
Sanitize environment variable keys and redact sensitive values using helper functions before passing them to loggers to prevent credential leakage in log output.
func redactEnvValue(key, value string) string { for _, token := range []string{"API", "KEY", "TOKEN", "SECRET", "PASSWORD", "CREDENTIAL", "AUTH"} { if strings.Contains(strings.ToUpper(key), token) { return "[redacted]" } } return value}
Fail Closed on SQLite Foreign Key Constraint Initialization
Approximately 197 tokens
Use when
When initializing SQLite database connections for data storage and state management.
Secure rules
Rule 1: Enforce SQLite foreign key constraints immediately during connection establishment and database initialization.
Always configure SQLite database connections to enforce foreign key constraints by appending _foreign_keys=on to the DSN and executing PRAGMA foreign_keys = ON upon initialization to maintain data integrity and prevent cascading delete failures.