Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kharissulistiyo/2c0613436e2c19e24b210e3960e3593c to your computer and use it in GitHub Desktop.
Save kharissulistiyo/2c0613436e2c19e24b210e3960e3593c to your computer and use it in GitHub Desktop.
Patch PHP Arbitrary File Upload vulnerability
<?php
public function upload_file() {
if ( ! current_user_can( 'upload_file' ) ) {
wp_send_json_error( array( 'errorMessage' => esc_html__( 'You are not allowed to upload files.', 'download-monitor' ) ) );
}
$uploadedfile = $_FILES['file'];
$image_url = $uploadedfile['tmp_name'];
$wp_allowed = wp_check_filetype( $image_url );
$dlm_denied_filetypes = array( 'php', 'htaccess' );
// If not allowed file type, return error.
if ( ! $wp_allowed['ext'] || in_array( $wp_allowed['ext'], $dlm_denied_filetypes ) ) {
wp_send_json_error( array( 'errorMessage' => esc_html__( 'File type not allowed.', 'download-monitor' ) ) );
}
$upload_dir = wp_upload_dir();
$image_data = file_get_contents( $image_url );
$filename = $uploadedfile['name'];
$file = $upload_dir['basedir'] . '/dlm_uploads/' . date( 'Y/m/' ) . $filename;
if ( ! file_put_contents( $file, $image_data ) ) {
wp_send_json_error( array( 'errorMessage' => esc_html__( 'Failed to write the file at: ', 'download-monitor' ) . $file ) );
}
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment( $attachment, $file );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment