Fix Mass Assignment in Yii
Mass Assignment in Yii (ActiveRecord) occurs when an application takes user-provided input and assigns it to a model's attributes without proper filtering. In a 'hacker' context, this allows an attacker to overwrite sensitive database columns—like 'is_admin', 'role_id', or 'balance'—by simply adding those fields to the HTTP request payload. If the model doesn't explicitly define which attributes are 'safe', Yii might blindly persist whatever garbage the client sends.
The Vulnerable Pattern
// Controller: Directly dumping POST data into the model
public function actionUpdate($id) {
$model = User::findOne($id);
// CRITICAL VULNERABILITY: Blind assignment of all POST parameters
// An attacker can send {'is_admin': 1} in the request body
$model->attributes = Yii::$app->request->post();
$model->save();
}
The Secure Implementation
The fix relies on Yii's 'Safe Attribute' concept. When using $model->load() or assigning to $model->attributes, Yii only permits assignment to attributes that have an associated rule in the rules() method. To secure your app: 1. Never use raw assignment from $_POST. 2. Explicitly define validation rules for every field you want the user to control. 3. Use 'scenarios' to differentiate between a 'user_update' (where fields like 'role' are hidden) and an 'admin_update' (where 'role' is safe). If an attribute does not have a rule, it is considered unsafe and will be ignored during mass assignment.
// Model: Define strict validation rules public function rules() { return [ [['username', 'email'], 'required'], [['username', 'email'], 'string', 'max' => 255], ['email', 'email'], // 'is_admin' is NOT in this list, making it 'unsafe' for mass assignment ]; }
// Controller: Use load() which respects rules() public function actionUpdate($id) { $model = User::findOne($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect([‘view’, ‘id’ => $model->id]); } }
Your Yii API
might be exposed to Mass Assignment
74% of Yii apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.