Global Event Receiver to Block Malicious Files

In this article we can explore the scenario to block malicious files by content.

Scenario

Assume your customer requests a specific feature for all the document libraries in a site. The document libraries should allow uploading of Executable files (.exe) plus a virus check must also be done on the content. If an exe file is infected then the upload should be aborted.

Solution

In this case you can create a Global Event Handler for all the document libraries. This event handler is invoked whenever a file is being uploaded. A virus check can be performed using the Antivirus software installed. The upload can be aborted using the Cancel property in the event handler method.

Implementation

The following are the steps involved in implementing the solution:

  • Manage the Blocked File Types
  • Test an exe file insertion into Library
  • Create the Event Receiver
  • Make the Event Receiver Global
  • Test the Application

Manage the Blocked File Types

As you might have noticed the executable extension (.exe) is blocked in all SharePoint libraries. This restriction can be removed by using Central Administration.

In our case we need to allow this extension (.exe) and later our own event handler will do the file scanning before adding it to the library.

To change the restriction open Central Administration > Security link.

MalFLS1.jpg



In the page that appears click on the Define blocked file types link as shown below:

MalFLS2.jpg

In the page that appears you will see that there are many extensions being blocked. Remove the exe entry from the list and click the OK button.

MalFLS3.jpg

Test an exe file insertion into Library

After making the change (removing the exe extension) you can try inserting an exe file into a document library. For the time being I tested by inserting Calculator (c:\windows\system32\calc.exe) into my library.

Now I was able to successfully insert an exe file into the library.

MalFLS4.jpg

Note: Please make sure that you selected the right web application from the top-right menu.

Create the Event Receiver

Our job is not finished yet. The current situation may create a Security Threat of malicious exe files being uploaded by users unknowingly. Later other users may execute it and create chaos. So we need to ensure that the content of the Executable file does not have any malicious code in it.

The actual way of scanning the exe file is to integrate some third party Anti-Virus SDK with our application. As this exceeds our scope of the article I prefer checking the exe file name containing any special characters like !, @, #. If any of the characters are found, the file will be cancelled from insertion and a message will be shown to the user.

Now let us create the event handler which blocks the file if file name contains special characters.

Create a new project of type Event Receiver inside Visual Studio 2010. Name the project as GlobalEventReceiver.

MalFLS5.jpg

Choose the site for the project and In the Event Receiver Settings dialog select the options like Document library and Add, Update events as shown below:

MalFLS6.jpg

Click the Finish button to continue.

In the event file that appears replace the Item Adding event as following:

public class EventReceiver1 : SPItemEventReceiver

{

    public override void ItemAdding(SPItemEventProperties properties)

    {

        if (properties.List is SPDocumentLibrary)

        {

            if (properties.AfterProperties != null)

            {

                if (properties.AfterProperties["vti_filesize"] != null)

                {

                    if (properties.AfterUrl != null)

                    {

                        if (properties.AfterUrl.Contains("!") || properties.AfterUrl.Contains("@") || properties.AfterUrl.Contains("#"))

                        {

                            properties.Cancel = true;

                            properties.ErrorMessage = "Potential malicious content in file!";

                        }

                    }

                }

            }

        }

    }

 }

The event is invoked with the SPItemEventProperties server object model which contains the document, URL and related properties. As we are making this event Global, all the lists and libraries will be invoking this event handler.

To prevent the event from being blocked in Lists/Folders we are ensuring the properties.List is of the type Document Library in the first if block.

In the second and third if blocks we are ensuring the file size is not null.

In the fourth and fifth if blocks we are ensuring the file URL does not contain the special characters like !, @, #. (our dummy malicious check)

If the malicious check resulted in true, then the Cancel property is set to true, which will prevent the file from being inserted. An Error Message is set for the user.

Make the Event Receiver Global

The current event receiver is hard-coded for document template Id 101. We need to make this global so that all the document libraries will be attached to this event.

Open the Elements.xml from the EventReceiver1 folder.

MalFLS7.jpg

Remove the ListTemplatId="101" attribute from the Receivers tag (third line) as below:

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

  <Receivers>

      <Receiver>

        <Name>EventReceiver1ItemAdding</Name>

        <Type>ItemAdding</Type>

        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>

        <Class>GlobalEventReceiver.EventReceiver1.EventReceiver1</Class>

        <SequenceNumber>10000</SequenceNumber>

      </Receiver>

      <Receiver>

        <Name>EventReceiver1ItemUpdating</Name>

        <Type>ItemUpdating</Type>

        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>

        <Class>GlobalEventReceiver.EventReceiver1.EventReceiver1</Class>

        <SequenceNumber>10000</SequenceNumber>

      </Receiver>

  </Receivers>

</Elements>

Now build the application.

Test the Application

Execute the application and in the launched SharePoint site, open a document library and try to add an exe file with a "@" character in the file name.

For example: [email protected]

You should get the following error:

MalFLS8.jpg

So this confirms that the Global Event Handler is working.

Note: The Item Add event handler is needed to handle the document insert event. The Item Update event handler is needed to handle the document update event. Note: The scenario explained above is for conditional blocking purposes and in the real world the same Global Event Handler mechanism can be used to handle other situations like:

  • Prevent PDF file insertion on Document Libraries

  • Disable Copy Paste among various document library types

  • Disable file insertion based on validation etc.

References


http://tinyurl.com/sp2010-list-event 


Summary 

In this chapter we have approached a real world scenario to create a global event handler. The same mechanism can be extended to resolve other complex requirements associated with list/library item add/update/delete.
 

Up Next
    Ebook Download
    View all
    Learn
    View all