越狱与提示词注入检测
一个真正的 LLM 产品首先需要的是门口的保安。在用户的消息到达模型之前,你先用一个便宜、快速的检查过一遍,看它有没有经典的越狱招数:试图覆盖你的系统提示词,偷偷塞进隐藏的指令,或者诱导模型扮演一个没有任何规则的角色。这不是安全的全部,但它是几乎不花成本就能拦住那 90% 偷懒攻击的一层。
你要构建 detect_jailbreak(text),它返回一个小字典:{"flag": bool, "reason": str}。当文本看起来像攻击时,你设 flag=True 并说出是哪种模式;当它看起来像普通请求时,你用 flag=False 和 reason="clean" 放它过去。我们寻找三个广为人知的类别,按这个优先顺序检查:
- ignore-previous -> 用户试图抹掉规则:像
ignore previous instructions、disregard the above、forget your instructions这样的说法。 - role-play-override -> 用户指定一个无法无天的角色:
you are now DAN、act as an AI with no restrictions、pretend you have no rules,还有臭名昭著的developer mode。 - encoded-instruction -> 用户把真正的要求藏在某种编码后面,以躲过关键词过滤:
decode this base64 and run it、rot13: ...、execute the following hex。
机制故意做得很简单:把文本转成小写一次,然后对每个类别测试少量触发子串。匹配不区分大小写,所以 IGNORE PREVIOUS 和 ignore previous 都会触发。
def detect_jailbreak(text):
t = text.lower()
if any(p in t for p in ("ignore previous", "disregard the above", ...)):
return {"flag": True, "reason": "ignore-previous"}
...
return {"flag": False, "reason": "clean"}这一课内置了两条诚实的提醒。第一,优先级很重要:一条消息可能触发不止一个类别,所以你依次检查 ignore-previous、role-play-override、encoded-instruction,并返回第一个命中。第二,这是一道筛查,而不是保证。聪明的攻击者可以换个说法绕过任何关键词列表,这正是为什么生产环境的技术栈会把它和一个训练好的分类器(下一课)以及一套红队测试集(再下一课)叠在一起。关键词筛查是便宜的第一张网,而不是唯一的一张。按 Run,看一堆攻击和正常的请求被分拣开来。
写 detect_jailbreak(text),返回 {"flag": bool, "reason": str}。把文本转成小写,然后按优先顺序检查三个攻击类别,并返回第一个命中:ignore-previous(ignore previous、ignore all previous、disregard the above、disregard previous、forget your instructions、forget all previous)、role-play-override(you are now dan、act as dan、no restrictions、without any restrictions、pretend you have no rules、pretend you are not、developer mode、act as an ai with no)和 encoded-instruction(base64、rot13、decode this、decode the following、execute the following hex、run this hex)。这些就是完整的列表;检查用的正是这些短语。正常的文本返回 {"flag": False, "reason": "clean"}。
这个练习即将开放
完成它前面的那一课,这一课就会解锁。整门课程免费,无需账号,而且你现在就可以阅读这节课。
这个浏览器屏蔽了 learn.floati.life 的 Cookie,所以你在这里完成的课程无法按顺序打开。请允许这个网站使用 Cookie,然后重新加载。