Logo Moodle Security Audit

Moodle Security Audit

Cộng đồng
SaadRahman01
moodle-security-audit

Use when reviewing or hardening Moodle plugin code for security — capability checks, sesskey CSRF, input validation, SQL injection, XSS, file serving, SSRF, IDOR, secrets handling, and Moodle's specific anti-patterns.

Tổng quan

Nhà phát hànhSaadRahman01
Kho mãclaude-moodle-dev
Tên kỹ năngmoodle-security-audit
Sao
42
Bản fork
7
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được SaadRahman01 công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Moodle Security Audit trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-security-audit
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/SaadRahman01/claude-moodle-dev.git /tmp/claude-moodle-dev
mkdir -p .claude/skills
cp -r /tmp/claude-moodle-dev/skills/moodle-security-audit .claude/skills/moodle-security-audit
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Moodle Security Audit trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Moodle Security Audit ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Moodle Security Audit với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Moodle Security Audit

Overview

Moodle has framework-level protections (capability system, sesskey, $DB placeholders, output escaping) — but only if used. Most Moodle plugin CVEs come from skipping these. This skill enforces the checklist.

When to Use

  • Reviewing a PR for security
  • Auditing existing plugin code
  • Responding to a vulnerability report
  • Pre-submission review for moodle.org plugin directory

Skip when: writing new feature code (use moodle-plugin-development — it covers the basics).

Audit checklist (every entry script)

php
require('../../config.php');                            // bootstrap
require_login();                                        // 1. session + cookies
$context = context_course::instance($courseid);         // 2. context
$PAGE->set_context($context);
require_capability('local/example:view', $context);     // 3. capability
require_sesskey();                                      // 4. CSRF (POST only)

$id   = required_param('id', PARAM_INT);                // 5. typed input
$name = optional_param('name', '', PARAM_TEXT);

Order matters. require_login before context_*::instance because login resolves $USER.

1. Authentication — require_login()

VariantUse
require_login()Logged-in user, any context
require_login($course)Logged-in + enrolled in course
require_login($course, true, $cm)Logged-in + activity-level access
require_admin()Site admin only
require_login(null, false)Skips guest auto-login (rare)

Bug: Forgetting require_login() on AJAX endpoints. AJAX still needs it — session might be valid but unauthorized.

2. Authorization — capabilities

php
require_capability('local/example:edit', $context);
// or for soft check:
if (!has_capability('local/example:edit', $context)) {
    redirect(...);
}

Bug — IDOR (Insecure Direct Object Reference):

php
// BAD — checks site-level cap, but $item belongs to a course user can't access
$item = $DB->get_record('local_example_items', ['id' => $id], '*', MUST_EXIST);
require_capability('local/example:view', context_system::instance());

// GOOD — derive context from the object
$item = $DB->get_record('local_example_items', ['id' => $id], '*', MUST_EXIST);
$context = context_course::instance($item->courseid);
require_capability('local/example:view', $context);

Always derive $context from the object being acted on, not from URL params.

3. CSRF — sesskey

Every state-changing request (POST, GET that mutates) needs:

php
require_sesskey();

In forms via formslib: MoodleQuickForm adds it automatically. In raw HTML forms:

php
<input type="hidden" name="sesskey" value="<?php echo sesskey(); ?>">

In AJAX core/ajax: token attached automatically. In raw fetch:

javascript
import {sesskey} from 'core/config';
// include in body

Bug: GET request that mutates DB without sesskey check.

4. Input — never raw $_GET/$_POST/$_REQUEST

php
$id    = required_param('id', PARAM_INT);                // throws if missing
$name  = optional_param('name', '', PARAM_TEXT);
$ids   = required_param_array('ids', PARAM_INT);
$tags  = optional_param_array('tags', [], PARAM_RAW);

PARAM_RAW accepts any input — use only with explicit downstream sanitization. PARAM_TEXT strips tags; PARAM_NOTAGS is similar; PARAM_CLEANHTML allows safe HTML.

Bug: $_REQUEST['id'] direct access — bypasses type coercion, vulnerable to type juggling.

5. SQL — placeholders only

php
// GOOD
$DB->get_records_sql('SELECT * FROM {local_example_items} WHERE name = ?', [$name]);
$DB->get_records_sql('... WHERE name = :name', ['name' => $name]);
$DB->get_records('local_example_items', ['courseid' => $cid]);

// BAD — concatenation
$DB->get_records_sql("SELECT * FROM {local_example_items} WHERE name = '$name'");

// SUBTLE BUG — string interpolation in IN clause
$ids = implode(',', $idarray);
$DB->get_records_sql("... WHERE id IN ($ids)");

// FIX — get_in_or_equal
[$insql, $params] = $DB->get_in_or_equal($idarray);
$DB->get_records_sql("... WHERE id $insql", $params);

Bug: Building LIKE patterns by concatenation — use $DB->sql_like() + $DB->sql_like_escape().

php
$pattern = '%' . $DB->sql_like_escape($search) . '%';
$where = $DB->sql_like('name', '?', false);   // case-insensitive
$DB->get_records_sql("SELECT * FROM {t} WHERE $where", [$pattern]);

6. Output — escape everything

FunctionUse
s($str)Escape for HTML attribute / text
format_string($str, true, ['context' => $c])Plain string with filters (multi-lang, etc.)
format_text($html, FORMAT_HTML, ['context' => $c])Rich text — runs filters + cleans
clean_text($str, FORMAT_HTML)Strip dangerous tags
html_writer::tag('div', $content, $attrs)Build HTML safely
$OUTPUT->render_from_template(...)Mustache auto-escapes {{var}}; raw via {{{var}}}

Always pass context to format_string/format_text — controls which filters run.

Bug: echo $row->name directly — XSS if name contains tags.

mustache
{{name}}        ← escaped (safe)
{{{name}}}      ← raw HTML (dangerous unless format_text'd in PHP first)

7. File serving — pluginfile.php

Never expose $CFG->dataroot paths directly. File areas served via pluginfile.php callback in lib.php:

php
function local_example_pluginfile($course, $cm, $context, $filearea, $args, $forcedl, $options = []) {
    require_login($course, false, $cm);

    if ($filearea !== 'attachments') {
        return false;
    }

    $itemid = (int)array_shift($args);
    require_capability('local/example:viewfile', $context);

    $filename = array_pop($args);
    $filepath = '/' . implode('/', $args) . '/';
    $filepath = $filepath === '//' ? '/' : $filepath;

    $fs = get_file_storage();
    $file = $fs->get_file($context->id, 'local_example', $filearea, $itemid, $filepath, $filename);
    if (!$file || $file->is_directory()) {
        return false;
    }

    send_stored_file($file, 0, 0, $forcedl, $options);
}

Bug: Skipping capability check inside callback. Yes, pluginfile.php does session auth but not plugin-specific authorization.

8. SSRF / external HTTP

php
$curl = new \curl();                        // Moodle's curl wrapper
$response = $curl->get($url);

\curl respects $CFG->curlsecurityblockedhosts + $CFG->curlsecurityallowedport. Don't use raw curl_exec() or file_get_contents($url) for user-supplied URLs.

php
// Validate URL belongs to allowed scheme
$url = clean_param($url, PARAM_URL);
if (!$url) {
    throw new moodle_exception('invalidurl');
}

9. File uploads

  • Always go through Moodle's draft area + file_save_draft_area_files
  • Check MIME via \core_form\filetypes_util or accept filemanager option
  • Set maxfiles, maxbytes, accepted_types
  • Never trust client-provided $_FILES['file']['type']

10. Secrets

  • Never commit tokens / API keys to version.php / source
  • Store in mdl_config_plugins via set_config('apikey', $value, 'local_example')
  • Read with get_config('local_example', 'apikey')
  • For very sensitive data, encrypt with \core\encryption (Moodle 4.0+)

11. Logging

User actions trigger events; events flow to logs. Don't log sensitive data:

php
// BAD
debugging("Token: $token");

// GOOD
debugging('Token issued for user ' . $userid);

12. Redirect open-redirect

php
// BAD
$next = optional_param('returnto', '', PARAM_URL);
redirect($next);

// GOOD — whitelist or use moodle_url
$next = new moodle_url($next);
if ($next->get_host() !== (new moodle_url($CFG->wwwroot))->get_host()) {
    throw new moodle_exception('invalidurl');
}
redirect($next);

Anti-patterns checklist

Anti-patternFix
$_GET['id']required_param('id', PARAM_INT)
Raw SQL concatPlaceholders ? or :name
echo $userdatas() / format_string / format_text
Missing require_login()Add at top of every entry script
Missing require_capability()Check on object's context, not arbitrary system
Missing require_sesskey() on POSTAlways
Direct $CFG->dataroot accessGo through \file_storage
eval() / create_function()Never
unserialize($userdata)Never on user input — use JSON
file_get_contents($userurl)Use \curl wrapper
print_error()Deprecated — throw new \moodle_exception(...)
Hard-coded admin user check ($USER->id == 2)is_siteadmin() or capability
Trusting $_SERVER['HTTP_*']Check $_SERVER['SERVER_NAME'] instead; headers spoofable
md5($password) for new codepassword_hash() / Moodle's hash_internal_user_password()
Skipping cap check in pluginfile callbackAdd explicitly — session auth ≠ authorization

Static analysis

bash
# Moodle's local_codechecker (phpcs)
phpcs --standard=moodle local/example

# Psalm / PHPStan with Moodle stubs (community projects)
# https://github.com/MoodleHQ/moodle-local_codechecker

Reporting vulnerabilities upstream

Found a bug in Moodle core? Don't open a public issue. Email security@moodle.org per the Moodle security policy.

References

Câu hỏi thường gặp

Kỹ năng AI Moodle Security Audit làm được gì?

Use when reviewing or hardening Moodle plugin code for security — capability checks, sesskey CSRF, input validation, SQL injection, XSS, file serving, SSRF, IDOR, secrets handling, and Moodle's specific anti-patterns.

Vì sao nên dùng Moodle Security Audit trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Moodle Security Audit là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Moodle Security Audit trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/SaadRahman01/claude-moodle-dev/tree/main/skills/moodle-security-audit. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Moodle Security Audit?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Moodle Security Audit với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Moodle Security Audit với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Moodle Security Audit có miễn phí không?

Có. Kỹ năng này được SaadRahman01 phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇