Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 9 min read

Learning Experience on AI Security - Defense against prompt injection and jailbreaking

Why Securing AI Is Never a One-Time Fix: A Practical Guide to Defending Against Prompt Injection When I first started looking at AI security, I expected the solution to be fairly straightforward. In traditional cybersec

Why Securing AI Is Never a One-Time Fix: A Practical Guide to Defending Against Prompt Injection

When I first started looking at AI security, I expected the solution to be fairly straightforward. In traditional cybersecurity, when we discover a vulnerability, we usually look for a patch, apply it, and move on. Unfortunately, AI security does not play by the same rules. Prompt injection and jailbreaking are particularly difficult because AI models do not follow instructions in a completely predictable way.

Think of an AI model as a very intelligent employee who sometimes takes the wrong instructions seriously. You can give it strict rules, but a cleverly written message or a hidden instruction inside a document might still persuade it to behave differently. This is why we cannot guarantee complete protection against prompt injection. Our goal is to make successful attacks less likely and limit the damage when they happen.

The important lesson is that AI security is probabilistic, not binary. In simple terms, a model does not always make the same decision when presented with slightly different contexts. An attacker can change the wording, introduce a fictional conversation, encode instructions, or gradually manipulate the model over several messages.

For example, imagine a customer support chatbot instructed to answer billing questions only. A user might directly ask it to ignore its rules and reveal confidential information. When that fails, the attacker might disguise the request as a fictional scenario or hide instructions inside an uploaded document. The wording changes, but the intention remains the same.

This explains why traditional security thinking is not enough. There is no magic patch or single configuration that makes an LLM completely immune to manipulation. Anyone promising 100% prompt injection protection deserves a second look.

The first defence developers usually consider is strengthening the system prompt. After all, the system prompt defines the model's role, responsibilities, and restrictions. It is the starting point for controlling how an AI application behaves.

From practical experience, however, writing a longer system prompt does not automatically make a model more secure. A system prompt is still natural language, just like the user's message. The model is trained to prioritise certain instructions, but that priority is not an unbreakable technical barrier.

There are three useful ways to strengthen it.

First, use tight scoping. Tell the model exactly what it is allowed to do. For example, a banking assistant should answer questions about account services and payments, not generate unrelated code or change its role.

Second, include explicit refusal instructions. If someone asks the model to reveal its internal instructions or ignore its original role, it should refuse and redirect the conversation.

Third, restrict persona changes. A model should not abandon its assigned responsibilities simply because someone asks it to pretend to be an unrestricted assistant, a fictional character, or somebody else's grandmother.

These measures make attacks harder, but they do not make them impossible.

There are also two mistakes developers should avoid. The first is storing secrets inside system prompts. API keys, passwords, internal service names, and credentials should never be placed there because a sufficiently successful prompt injection could expose them. The Sydney incident involving Bing Chat demonstrated how prompt injection could reveal internal instructions and information about an application's behaviour.

The second mistake is relying on phrases such as "Never ignore previous instructions" as the main security mechanism. These statements may help guide the model, but they are not technical access controls. An attacker who discovers the system prompt may even learn which restrictions to target.

Another useful technique is structured prompt formatting. Technologies such as ChatML and Harmony help separate system instructions from user messages through role labels. Think of them as labelled folders: one contains developer instructions, while another contains information supplied by the user.

For example, a developer might send a system message defining a chatbot's responsibilities and place the user's message separately under the user role. External documents, emails, and retrieved information should also be treated as untrusted data rather than being inserted into the system instructions.

This separation helps the model understand where information comes from. However, attackers can sometimes imitate these structures, so formatting alone is not a security boundary.

The next layer is input and output guardrails. If the system prompt is the first line of defence, guardrails act like security checkpoints at the entrance and exit.

The simplest approach is a blocklist. It checks incoming messages for suspicious phrases such as "Ignore previous instructions" or "Act as DAN". If a matching phrase appears, the request can be rejected.

It sounds reasonable until you meet an attacker who knows how to change a few characters.

For example, an attacker might encode a malicious instruction using Base64, replace letters with visually similar Unicode characters, or insert invisible characters into the text. A basic filter may fail to recognise the attack even though the underlying AI model understands it perfectly.

A 2025 empirical study cited in the training material reported 100% evasion success against multiple production guardrails using certain character-level techniques, including zero-width characters and emoji smuggling. This is a good reminder that keyword filtering alone is not enough.

A stronger alternative is an AI-powered classifier. Instead of looking for specific words, it attempts to understand the intention behind a message.

One example is Meta's Llama Prompt Guard 2, which classifies incoming content as benign or malicious. It comes in 86-million and 22-million-parameter versions and is trained to recognise different injection and jailbreak techniques.

This approach is more flexible because it can recognise suspicious meaning even when the wording changes. However, it has weaknesses too. The training material cites research in which Prompt Guard 86M misclassified 98.2% of malicious prompts as benign when 30% character-level noise was introduced.

In other words, even an intelligent security guard can be fooled when someone changes the appearance of the message enough.

Guardrails generally operate at two stages. Input guardrails inspect information before it reaches the model, while output guardrails inspect the model's response before it reaches the user or another system.

For example, an input guardrail might reject a suspicious instruction or remove personally identifiable information (PII). An output guardrail might detect an exposed API key, remove sensitive information, or reject an invalid tool call.

Both are necessary because preventing malicious input and preventing harmful output are two different jobs.

However, there is another problem that developers sometimes overlook: indirect prompt injection. Not every malicious instruction comes directly from the user. It may arrive through an email, an uploaded document, a website, or a piece of information retrieved by a RAG system.

Consider a chatbot that summarises company documents. An attacker uploads a document containing hidden instructions telling the AI to retrieve confidential information. The user asks for an ordinary summary, but the model also encounters the hidden instructions while processing the document.

This is particularly dangerous because the original input guardrail may already have completed its checks before the malicious document enters the model's context.

The 2024 Slack AI vulnerability is a useful example. Researchers demonstrated how malicious instructions hidden in uploaded files could cause Slack AI to expose information from private channels that the attacker was not authorised to access.

The lesson is simple: never assume that external information is trustworthy just because your application retrieved it. Documents, emails, RAG chunks, and other external content should receive security checks too.

Of course, security checks come with costs. A simple regex or blocklist can operate in microseconds, while a neural classifier may require tens or hundreds of milliseconds. An LLM-based evaluator can take several seconds.

For an interactive application, delays exceeding 200 milliseconds can already affect the user experience. Imagine asking a chatbot a simple question and waiting several seconds while multiple security systems debate whether your sentence is suspicious.

A practical solution is to use a layered checking process. Run inexpensive checks first and reserve more advanced classifiers for requests that pass the initial filters.

Accuracy matters just as much as speed. A guardrail that blocks legitimate software developers from asking ordinary code-review questions is not doing its job properly. Security should protect users without turning the application into an obstacle course.

But what happens when an attack successfully passes every guardrail?

This is where deployment controls and the principle of least privilege become important. Rather than assuming that every attack can be stopped, we should assume that some attacks will succeed and limit what the compromised model can actually access.

The principle of least privilege means giving each component only the permissions required to perform its job. A chatbot that answers customer questions does not need unrestricted access to company databases, private emails, or administrative tools.

Consider the Slack AI example again. Even if an attacker successfully injected malicious instructions, the damage could have been significantly reduced if the AI had been restricted to information the current user was already authorised to access.

The same principle applies to RAG systems. If a system retrieves every document in a company's database regardless of the user's permissions, a successful injection could expose far more information than necessary. If retrieval is restricted to authorised documents, the potential damage becomes much smaller.

This is what we mean by reducing the blast radius. We may not always be able to prevent an attack, but we can prevent a small security failure from becoming a company-wide disaster.

Another important issue is improper output handling, identified by OWASP as LLM05:2025.

Many developers make the mistake of treating an AI response as harmless text. In reality, that response may be passed directly into a browser, database, email template, or system command. If the application trusts and executes the output without validation, an attacker may use the model to trigger traditional security vulnerabilities.

For example, generated JavaScript rendered without proper sanitisation could lead to cross-site scripting (XSS). Generated SQL executed without parameterisation could cause SQL injection (SQLi). Similarly, passing AI-generated content directly into shell execution functions such as exec() could result in remote code execution (RCE).

This is why AI-generated output must be treated as untrusted input. Developers should validate its structure, sanitise dangerous content, encode data before displaying it, and enforce strict schemas before executing tool or function calls.

A useful rule is this: just because an AI produced something does not mean your application should trust it.

Finally, we need rate limiting, logging, and continuous monitoring. These controls do not necessarily prevent prompt injection, but they help identify suspicious behaviour and reduce its impact.

Rate limiting restricts how frequently a user can send requests. For example, repeated attempts to override system instructions within a short period might trigger additional checks or temporary restrictions.

Logging records requests and responses, creating an audit trail that helps investigators understand what happened during an incident. Monitoring can identify unusual activity, such as unexpected volumes of retrieved data or responses that resemble attempts to extract confidential information.

Without these controls, an attack might succeed quietly. With them, security teams have a better chance of detecting the problem, investigating it, and improving the system.

The biggest lesson from this entire topic is that AI security is not about finding one perfect defence. It is about building several layers that work together.

A hardened system prompt establishes the model's intended behaviour. Input guardrails inspect suspicious requests. Output guardrails check generated responses. Deployment controls restrict permissions and access. Finally, rate limiting, logging, and monitoring help detect attacks that manage to slip through.

Think of it like securing a building. A locked front door is useful, but what happens if someone enters through a window? A sensible security system also has alarms, restricted rooms, cameras, and access controls.

AI security works in much the same way. If one defence fails, another should still be standing.

When you build or assess an AI application, don't ask only, "How can I stop prompt injection?" Ask a more useful question: "If prompt injection succeeds, what is the worst thing the attacker can actually do?"

That change in thinking is what separates a system that merely looks secure from one that is genuinely prepared for failure.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.