Skip to content

Commit cef63ad

Browse files
fix: add CSRF protection and input validation
1 parent aa0b9a9 commit cef63ad

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

assets/js/single-attachment.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ jQuery(document).ready(function($) {
125125
function uploadFile() {
126126
var formData = new FormData();
127127
formData.append("action", "optml_replace_file");
128+
formData.append("optml_replace_nonce", OMAttachmentEdit.nonce);
128129
formData.append("attachment_id", OMAttachmentEdit.attachmentId);
129130
formData.append("file", $("#optml-replace-file-field")[0].files[0]);
130131

inc/media_rename/attachment_edit.php

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ public function enqueue_scripts( $hook ) {
9292
'maxFileSize' => $max_file_size,
9393
'attachmentId' => $id,
9494
'mimeType' => $mime_type,
95+
'nonce' => wp_create_nonce( 'optml_replace_media_nonce' ),
9596
'i18n' => [
9697
'maxFileSizeError' => $max_file_size_error,
9798
'replaceFileError' => __( 'Error replacing file', 'optimole-wp' ),
@@ -329,7 +330,17 @@ public function save_attachment_filename( $post_id ) {
329330
* Replace the file
330331
*/
331332
public function replace_file() {
332-
$id = (int) sanitize_text_field( $_POST['attachment_id'] );
333+
check_ajax_referer( 'optml_replace_media_nonce', 'optml_replace_nonce' );
334+
335+
$id = absint( $_POST['attachment_id'] ?? 0 );
336+
337+
if ( ! $id ) {
338+
wp_send_json_error( __( 'Invalid attachment ID', 'optimole-wp' ) );
339+
}
340+
341+
if ( get_post_type( $id ) !== 'attachment' ) {
342+
wp_send_json_error( __( 'Invalid attachment ID', 'optimole-wp' ) );
343+
}
333344

334345
if ( ! current_user_can( 'edit_post', $id ) ) {
335346
wp_send_json_error( __( 'You are not allowed to replace this file', 'optimole-wp' ) );
@@ -339,6 +350,17 @@ public function replace_file() {
339350
wp_send_json_error( __( 'No file uploaded', 'optimole-wp' ) );
340351
}
341352

353+
$file_info = wp_check_filetype_and_ext( $_FILES['file']['tmp_name'], $_FILES['file']['name'] );
354+
355+
if ( empty( $file_info['type'] ) ) {
356+
wp_send_json_error( __( 'Could not determine uploaded file type', 'optimole-wp' ) );
357+
}
358+
359+
$original_mime = get_post_mime_type( $id );
360+
if ( $file_info['type'] !== $original_mime ) {
361+
wp_send_json_error( __( 'Uploaded file type does not match the original attachment', 'optimole-wp' ) );
362+
}
363+
342364
$replacer = new Optml_Attachment_Replace( $id, $_FILES['file'] );
343365

344366
$replaced = $replacer->replace();

0 commit comments

Comments
 (0)