Stopping invalid file type or file name submissions in coldfusion - file-upload

So, I'm having this lovely issue where people like to submit invalid file types or funky named files... (like.. hey_i_like_"quotes".docx) Sometimes they will even try to upload a .html link...
How should I check for something like this? It seems to create an error every time someone submits a poorly named item.
Should I create a cfscript that checks it before submission? Or is there an easier way?

If it was before submission it would be javascript not cfscript. Javascript can always be got round, so I'd say you'd be better doing it server-side with ColdFusion. Personally I'd just wrap the whole thing in a try/catch (you should do this anyway as a matter of course with all file upload type things), and throw an error back at them if their filename is no good.

When you say submit are you using cffile to allow your users to upload file.
If so, use the attribute "accept" with a try and catch around. for example....
<cftry>
<cffile action = "upload"
fileField = "FileContents"
destination = "c:\files\upload\"
accept="image/jpg, application/msword"
>
<cfcatch type="Any" >
<p>sorry we could not upload your file!</p>
</cfcatch>
</cftry>
I personally would not use "just" JavaScript as this could be disabled and you are back in the same boat.
Hope this helps.

On the server, as part of validation, use reFindNoCase() along with an appropriate regex to check for a properly formatted file path. You can find lots of example regex expressions for a file path on the internet, such at this one. Hope that helps.

As #Duncan pointed out, a client-side validation would most likely be in JavaScript. Personally, if I had time/resources, I would do this as a convenience for the end user. If they upload an enormous PDF when a DOCX is required by the system, it would be annoying for them not to receive a message until the upload is complete.
As far as filenames go, it seems to me that the simplest solution (and one I've used in the past) is to assume all filenames are bad, and rename them. There are several ways to do this. If you need to preserve the original filename, I would just use urlEncodedFormat() ot clean the filename into something that is web-friendly. If you need to preserve all versions, you can append a date/time stamp, so bob.xocx becomes bob_201104051129.docx or somesuch. If you must keep the original filename without any changes, I would recommend seting up a DB table as a pinter system, keeping the original name, timestamp, and other metadata there and referring to the file by renaming it to the ID.
But urlEncodedFormat() is probably enough for what you've outlined.

For user experience it's best to do it client-side but it's not bad at all to double check server side too.
For the client side part, I recommend using the jQuery validation plugin, easy to use.

Related

Override forcedownload behavior in Sitecore

We had a problem with some of our IE clients failing to download a PDF, even after clicking on the link. We found the answer here resolved our problems: set forcedownload=true for PDF mime types in web.config.
However, that created another problem: we are now unable to render a PDF in a browser when we want to. We used to do this with an iframe. However, as you can see, the PDF just downloads, and does not render in the browser.
I learned that the forcedownload=true setting is actually a default in a subsequent version of Sitecore (v7.2). So, I'm hesitant to revert that.
So, how do I render a PDF in a browser in this situation?
You can leave forceDownload=false on the PDF mime type and instead set the following setting to false:
<setting name="Media.EnableRangeRetrievalRequest" value="false"/>
I faced the same dilema a few months back with the same initial fix. Found out the actual issue last week, I wrote a blog post about it. (In fact, I wrote the answer you linked to, I've updated it with the same information now for future visitors)
The issue is basically a combination of Adobe Reader plugin for IE9, chunked transfer encoding and streaming the file directly from the database. I found if you close your browser and try again, or force refresh with Ctrl+F5 it worked fine. Once Sitecore had cached the file to disk it would continue to work for everyone.
The above setting disables chunked transfer encoding, instead sending the file down to the browser as a single piece. This setting was introduced in Sitecore 6.5+
This is one of the flaws in the MediaRequestHandler and in my opinion; the forceDownload option is pretty useless the way it is designed by default. (Why would ever want to configure this option on media extension only?)
You’ll have to basically turn off the forcedownload option again and replace the MediaRequestHandler with your own one. I usually end up with writing my own anyway because if other issues with the default handler, such as dealing properly with CDN’s etc.
In the ProcessRequest pipeline, you can determine if the item should be “downloaded” or not by setting the Content-Disposition header. You basically need to get rid of the default handling of forceDownload and set your headers based on your own logic.
Personally I prefer to set a query string parameter, such as ?dl=1, and base the Content-Disposition header on this. You could also extend the MediaItem template to contain a default behavior on each item or sub tree (leverage from Sitecore inheritance and standard values), and potentially you could thereby also define (override) a specific filename on each item for the attachment part in the Content-Disposition header.
When rendering the link, you can leverage from the properties collection (write a suitable extension method or similar), so that you can clearly mark your code that the link is meant for download, but still leverage from the built in field render methods. Thereby you eliminate the risk of messing up the page editor etc.
/ Mikael
You have to disable range retrieval request in web.config by setting its value to false.
<setting name="Media.EnableRangeRetrievalRequest" value="false" />
MediaRequestHandler enables Sitecore to download PDF content partially in range using HTTP 206 Status code. You can also overwrite MediaRequestHandler and write your own custom implementation to handle media request.

Proper way to check system requirements for a WordPress plugin

I am curious about the proper way to stop a user from activating my plugin if their system does not meet certain requirements. Doing the checks is easy and I don't need any help with that, I am more curious how to tell WordPress to exit and display an error message.
Currently I have tried both exit($error_message) and die($error_message) in the activation hook method. While my message is displayed and the plugin is not activated, a message saying Fatal Error is also displayed (see image below).
Does anyone know of a better way, that would display my message in a proper error box without displaying Fatal error, it just looks really bad for new users to see that.
Thanks for any help in advance.
This is a little undocumented, as you might have noticed. Instead of die(), do it like this:
$plugin = dirname(__FILE__) . '/functions.php';
deactivate_plugins($plugin);
wp_die('<p>The <strong>X</strong> plugin requires version WordPress 2.8 or greater.</p>','Plugin Activation Error',array('response'=>200,'back_link'=>TRUE));
The lines above wp_die() are to deactivate this plugin. Note that we use functions.php in this case because that's where I have my Plugin Name meta data comment declaration -- and if you use a different file, then change the code above. Note that the path is very specific for a match. So, if you want to see what your path would normally be, use print_r(get_option('active_plugins'));die(); to dump that out so that you know what path you need. Since I had a plugin_code.php where the rest of my plugin code was, and since it was in the same directory as functions.php, I merely had to do dirname(__FILE__) for the proper path.
Note that the end of the wp_die() statement is important because it provides a backlink and prevents an error 500 (which is the default Apache code for wp_die()).
It is only a idea though. Try checking the wordpress version and compare then use php to through custom exception/error. PHP 5.0 try catch can be a good way to do it. Here is some resources.
http://www.w3schools.com/php/php_exception.asp
http://php.net/manual/en/internals2.opcodes.throw.php
You can try the first link. It is pretty basic. Thanks! hope the information will be helpful.

Opera extensions (widgets): dynamic config file

I have an Opera 11 extension, which has a background process and an injected script. These communicate very frequently with a remote server (not the webpage the user's viewing), using the background script's cross-site XMLHttpRequest capabilities.
I would like the URL of the server to be a preference, so that it can be modified by the user without editing the package. The config.xml file would good, for it accepts <preference name="serverUri" value="..." />. However, I would like the script to be able to update itself directly from the server (not through Opera's site), which can be achieved using <update-description href="http://myserver.com/client/update" />.
So what I would like to do is have the href attribute of the update-description element to be dependent on the value of the preference serverUri. I would imagine some syntax like this:
<update-description href="{$serverUri}" />
But I could not find any references to this kind of functionality. Is there some way to solve this?
It's not possible to use variables in the config.xml file as you've written and I don't think there are plans to add this.
I'm sure you know that preferences can be set not just with the preference element in config.xml but also using widget.setPreferenceForKey(value, key), but I don't think that solves your problem in this case.
The only workaround I can think of is if you have all your logic in an external script on your server and in your extension's local files (background script or injected script), just have a very simple couple of lines that reference your external script. Something like:
var script = document.createElement('script');
script.src = 'http://www.example.com/script.js';
document.body.appendChild(script);
You could then make the script's URL editable by the user and store it in widget.preferences.
EDIT by hallvors: This solution has serious drawbacks, see my comment below.
As far as I know this is not currently possible. It seems like a bit of an unusual use case, which could potentially be risky to implement, so it would be interesting to hear more about why you want to do this.

CAT.NET "Sanitize the file path prior to passing it to file system routines" message

I'm analyzing my code (C#, desktop application) with CAT.NET Code Analysis and getting "Sanitize the file path prior to passing it to file system routines" message when dealing with file names.
What I don't understand is that to ensure the file name is valid, I use:
void SomeMethod(String filename)
{
filename = System.IO.Path.GetFullPath(filename);
// ... Do stuff
}
Isn't it a "magic solution" to solve problems with invalid file names ? I've read something similar here (first answer), but in my case I'm dealing only with local files, well, something very basic, so...
So why I'm getting this message and how to do to avoid getting it?
I know this is an old question, but I've just come across something that may be helpful specifically related to the CAT.Net error message.
In a blog post about the CAT.Net Data Flow Rules, they have this to say about the FileCanonicalizationRule:
Description
User input used in the file handling routines can potentially lead to
File Canonicalization vulnerability. Code is particularly susceptible
to canonicalization issues if it makes any decisions based on the name
of a resource that is passed to the program as input. Files, paths,
and URLs are resource types that are vulnerable to canonicalization
because in each case there are many different ways to represent the
same name.
Resolution
Sanitize the file path prior to passing it to file handling routines.
Use Path.GetInvalidFileNameChars or Path.GetInvalidPathChars to get
the invalid characters and remove them from the input. More
information can be found at
http://msdn.microsoft.com/en-us/library/system.io.path.getinvalidfilenamechars.aspx.
So, they suggest that you use Path.GetInvalidFileNameChars and Path.GetInvalidPathChars to validate your paths.
Note that their suggestion is to remove the invalid characters. While this will indeed make the path valid, it may cause unexpected behaviour for the user. As the comments on this question/answer suggest it's probably better to quit early and tell the user that their path is invalid, rather than doing something unexpected with their input (like removing bad characters and using the modified version).
If the filename comes from a user, it could be something like "../../../../etc/passwd" - the error message is telling you that you need to sanitize it so that it can't get to directories it's not supposed to.

Up and download directly - no waiting

I would want to program something where you upload a file on the one side and the other person can download it the moment I start uploading. I knew such a service but can't remember the name. If you know the service I'd like to know the name if its not there anymore I'd like to program it as an opensource project.
And it is supposed to be a website
What you're describing sounds a lot like Bit Torrent.
You might be able to achieve this by uploading via a custom ISAPI filter (if you use IIS) -- all CGI implementations won't start to run your script until the request has completed, which makes sense, as you won't have been told all the values just yet, I'd suspect ISAPI may fall foul of this as well.
So, your next best bet is to write a custom HTTP server, that can handle the serving of files yet to finish uploading.
pipebytes.com I found it :)