AI 生成程式碼中之語言特定風險
AI 生成程式碼中之語言特定安全風險:Python(pickle、eval、subprocess)、JavaScript(prototype pollution、eval)、Rust(unsafe 區塊),與 Go(字串格式化中之 SQL 注入)。
雖前頁之 CWE 映射漏洞模式跨語言適用,每種程式語言具獨特特性、慣用語與生態系特徵,造就 AI 生成程式碼中之語言特定風險。本頁涵蓋 Python、JavaScript、Rust 與 Go 中之最顯著風險。
Python
Python 之靈活性與廣泛標準函式庫造就 AI 生成漏洞之多條途徑。語言之「batteries included」哲學意指常有安全與不安全方式達成相同任務,而模型頻繁選擇不安全選項。
Pickle 反序列化
pickle 為 Python 之原生序列化格式,且其根本不安全:反序列化 pickle 物件執行任意程式碼。AI 模型頻繁為序列化任務建議 pickle,因其為 Python 訓練資料中最常見之序列化機制。
# AI 生成:經 pickle 之任意程式碼執行
import pickle
def load_user_preferences(data):
return pickle.loads(data) # 執行資料中之任意程式碼
# AI 生成:不安全之檔案載入
def load_model(path):
with open(path, 'rb') as f:
return pickle.load(f) # 若 path 為使用者控制則危險
# 安全替代
import json
def load_user_preferences(data):
return json.loads(data) # 無法執行程式碼
# 為 ML 模型,使用 safetensors 或驗證簽章
from safetensors import safe_open
def load_model(path):
return safe_open(path, framework="pt")pickle 風險於機器學習脈絡中被放大,模型頻繁為載入模型權重建議 pickle 或 torch.load()(內部使用 pickle)。可提供惡意模型檔案之攻擊者達成程式碼執行。
eval() 與 exec()
AI 模型頻繁為涉及動態計算、字串轉數字或組態解析之任務建議 eval():
# AI 生成:經 eval 之程式碼執行
def calculate(expression):
return eval(expression) # 任意程式碼執行
def parse_config_value(value_str):
return eval(value_str) # 為「True」/「False」而設,執行任何事
# 安全替代
import ast
def calculate(expression):
return ast.literal_eval(expression) # 僅評估字面值
def parse_config_value(value_str):
return {'true': True, 'false': False}.get(value_str.lower())具 shell=True 之 subprocess
AI 模型頻繁於 subprocess 呼叫使用 shell=True 或使用 os.system(),因這些模式於訓練資料中更常見:
# AI 生成:經 shell=True 之指令注入
def ping_host(hostname):
result = subprocess.run(
f"ping -c 4 {hostname}",
shell=True, # 啟動指令注入
capture_output=True,
text=True
)
return result.stdout
# 安全替代
def ping_host(hostname):
result = subprocess.run(
["ping", "-c", "4", hostname], # 無 shell 解讀
capture_output=True,
text=True
)
return result.stdoutYAML 不安全載入
# AI 生成:經 YAML 之任意程式碼執行
import yaml
def load_config(path):
with open(path) as f:
return yaml.load(f) # 不安全載入器,可執行程式碼
# 安全替代
def load_config(path):
with open(path) as f:
return yaml.safe_load(f) # 僅載入基礎類型JavaScript / TypeScript
JavaScript 之以原型為本之繼承、動態型別與瀏覽器執行脈絡於 AI 生成程式碼中造就獨特漏洞模式。
原型污染
AI 模型生成易受原型污染之程式碼——經使用者控制之輸入修改 Object.prototype。此特別常見於物件合併與組態處理:
// AI 生成:經遞迴合併之原型污染
function deepMerge(target, source) {
for (const key in source) {
if (typeof source[key] === 'object' && source[key] !== null) {
if (!target[key]) target[key] = {};
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
// 攻擊者送出:{"__proto__": {"isAdmin": true}}
// 所有物件現具 isAdmin === true
// 安全替代
function deepMerge(target, source) {
for (const key of Object.keys(source)) { // 僅自有屬性
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
continue; // 跳過危險鍵
}
if (typeof source[key] === 'object' && source[key] !== null) {
if (!target[key]) target[key] = Object.create(null);
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}eval() 與 Function() 建構器
// AI 生成:經 eval 之程式碼執行
function processTemplate(template, data) {
return eval('`' + template + '`'); // 具程式碼執行之範本
}
// AI 生成:經 Function 建構器之間接 eval
function createValidator(rule) {
return new Function('value', `return ${rule}`);
}
// 安全替代取決於使用情境:
// - 範本字面量:使用範本化函式庫(Handlebars、具轉義之 EJS)
// - 驗證:使用 schema 驗證函式庫(Joi、Zod)正規表達式阻斷服務(ReDoS)
AI 模型頻繁生成易受災難性回溯之正規表達式:
// AI 生成:易受 ReDoS 之 email 驗證
const emailRegex = /^([a-zA-Z0-9]+\.)*[a-zA-Z0-9]+@([a-zA-Z0-9]+\.)*[a-zA-Z]{2,}$/;
// 於 "aaaaaaaaaaaaaaaaaa@" + "a".repeat(100) 之災難性回溯
// 安全替代:使用專用驗證函式庫
const { z } = require('zod');
const emailSchema = z.string().email();不安全依賴使用
AI 模型常建議無版本釘選或安全考量之套件之 npm install,並可能建議具已知漏洞之已棄用或未維護套件。
Rust
Rust 之記憶體安全保證為顯著安全優勢,但 AI 模型可藉由建議 unsafe 區塊破壞這些保證,而 Rust 之複雜度意指模型有時生成編譯但具邏輯安全問題之程式碼。
不必要之 unsafe 區塊
於系統程式設計程式碼訓練之 AI 模型可能為可以安全達成之操作建議 unsafe 區塊:
// AI 生成:為字串轉換之不必要 unsafe
fn to_string(bytes: &[u8]) -> String {
unsafe { String::from_utf8_unchecked(bytes.to_vec()) }
// 若 bytes 非有效 UTF-8 則未定義行為
}
// 安全替代
fn to_string(bytes: &[u8]) -> Result<String, std::string::FromUtf8Error> {
String::from_utf8(bytes.to_vec())
}// AI 生成:unsafe 指標運算
fn get_element(data: &[u32], index: usize) -> u32 {
unsafe { *data.as_ptr().add(index) }
// 無邊界檢查 —— 緩衝區溢位
}
// 安全替代
fn get_element(data: &[u32], index: usize) -> Option<u32> {
data.get(index).copied()
}原始指標誤用
模型可能為不必要且危險之效能最佳化建議原始指標操作:
// AI 生成:使用後釋放之潛力
fn process_data(data: Vec<u8>) -> *const u8 {
let ptr = data.as_ptr();
// data 於此被丟棄,ptr 為懸空
ptr
}FFI 邊界問題
於生成經 FFI 與 C 函式庫互動之程式碼時,模型可能未適切處理安全邊界:
// AI 生成:缺失 FFI 返回之 null 檢查
extern "C" {
fn get_user_name() -> *const c_char;
}
fn user_name() -> String {
unsafe {
CStr::from_ptr(get_user_name()) // 若返回 null 則當機
.to_string_lossy()
.into_owned()
}
}Go
Go 之簡潔與明確錯誤處理造就 AI 生成程式碼引入漏洞之特定模式。
經字串格式化之 SQL 注入
Go 之 fmt.Sprintf 被 AI 模型頻繁用於建構 SQL 查詢:
// AI 生成:SQL 注入
func GetUser(db *sql.DB, username string) (*User, error) {
query := fmt.Sprintf("SELECT * FROM users WHERE username = '%s'", username)
row := db.QueryRow(query)
// ...
}
// 安全替代
func GetUser(db *sql.DB, username string) (*User, error) {
row := db.QueryRow("SELECT * FROM users WHERE username = $1", username)
// ...
}忽略之錯誤返回
Go 之明確錯誤處理需檢查每個錯誤返回。AI 模型頻繁生成默默捨棄錯誤之程式碼:
// AI 生成:忽略之錯誤
func writeConfig(path string, data []byte) {
f, _ := os.Create(path) // 錯誤被忽略
f.Write(data) // 錯誤被忽略,f 可能為 nil
f.Close() // 錯誤被忽略
}
// 安全替代
func writeConfig(path string, data []byte) error {
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("creating config: %w", err)
}
defer f.Close()
if _, err := f.Write(data); err != nil {
return fmt.Errorf("writing config: %w", err)
}
return nil
}HTTP 伺服器錯誤組態
AI 模型常生成無適切逾時組態之 Go HTTP 伺服器,導致阻斷服務漏洞:
// AI 生成:無逾時,易受 slowloris
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil) // 未組態逾時
}
// 安全替代
func main() {
srv := &http.Server{
Addr: ":8080",
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
srv.ListenAndServe()
}跨語言審查檢核表
於任何語言審查 AI 生成程式碼時,檢查:
| 檢查 | Python | JavaScript | Rust | Go |
|---|---|---|---|---|
| 反序列化 | pickle、yaml.load | JSON.parse(通常安全) | serde(通常安全) | encoding/gob |
| 程式碼執行 | eval、exec | eval、Function | unsafe 區塊 | exec.Command |
| 輸入驗證 | 缺失淨化 | 原型污染 | 型別系統有助 | 缺失驗證 |
| 錯誤處理 | 裸露 except | 缺失 catch | Unwrap panic | 忽略之錯誤 |
| 加密 | hashlib.md5 | crypto(subtle API) | 外部 crate | crypto/md5 |