Insecure fmath editor fmath is an extremely powerful plug-in library for wysiwyg editors.

It provides an editor for mathematical formulas, which generates images that can be used in drupal sites. It processes mathml and latex.

There is a problem though, images are saved on a server using the following php file.

if($_POST["save"]){
   $type = $_POST["type"];
   if($_POST["name"] and ($type=="JPG" or $type=="PNG")){
      $img = base64_decode($_POST["image"]);
      $myFile = "img/".$_POST["name"].".".$type ;
      $fh = fopen($myFile, 'w');
      fwrite($fh, $img);
      fclose($fh);
      echo "http://your_server/capture/img/".$_POST["name"].".".$type;
   }
}else{
   header('Content-Type: image/jpeg');
   echo base64_decode($_POST["image"]);
}


This file is publicly available, and can not be restricted with .htaccess to localhost only (the whole library will not work). 

From my understanding the file is called by scripts on a user side via an url, and the image is passed by the POST method. That makes the file very dangerous as it allows anyone to save anything on the server. 

Are my suspicions correct?
How can I make this safe to use?

The whole library weights 11MB so I don't feel like debugging it.
This should really be addressed to the fmath project maintainers. I've mailed them to point out some security concerns in the code. If they don't respond I'll edit this post to answer the question here, but hopefully they will respond with a new version ;)

Original comment - mailed to fmath maintainer:

Some key things this is missing that you would want to get right:


CSRF protection - If you don't use the form API (which includes this already) then you can manually use drupal_get_token and drupal_valid_token are helpers.
Malicious file types - file_munge_filename is a helper here
Too many/too big of files
Temporarily uploading the file to a temporary directory outside of the webroot and giving it a random name so that it can be validated in that temporary location before moving it to the final location
Ideally you would validate the file contents (e.g. virus scan, confirm the file is a valid file of whatever the extension/mime type says it is).
Control where the file can be placed.


This script looks like it would only allow jpg or png files to be uploaded, but it misses out on a few other security features

There are probably a few other things to worry about, but I think that list is a good start.

I also wonder about this piece and whether you could sneak base64 encoded html into a "jpg" file and then some veresions of internet explorer and safari will do mime type detection and execute the html (i.e. cross site scripting attack):

   echo base64_decode($_POST["image"]);