jump to navigation

Obfuscation in .NET July 6, 2009

Posted by thinkparallel in .NET.
Tags:
add a comment

Obfuscation in .NET

Prevent Your Source Code from Being Open Source

With so many decompilers available in the software industry today, your application’s source code faces security threats from a variety of prying eyes. This alludes to the potential loss of your intellectual property. But what makes this possible? .NET reflection, ILDASM.exe, and .NET decompilers.

So, then, what’s the solution? This potential threat has facilitated the development of a technology called obfuscation.

What Is Obfuscation?

Without changing its functionality, obfuscation protects source code from being disassembled/decompiled. This is a technology that makes the .NET assemblies more difficult to decompile and impedes the reverse-engineering efforts, hence, protecting the source code from potential threats. Obfuscation works by shrouding the facts in your code. Encryption suffers from the drawback that it needs to keep the decryption key along with the encrypted data. Therefore, it is possible to decrypt your source code. On the other hand, obfuscation can increase the protection against decompilation to a great extent, while leaving the application’s functionality intact.

Why Obfuscate?

There are several reasons why we should obfuscate:

Obfuscation reduces the size of an executable
Obfuscation improves the application’s performance at run time
Obfuscation protects intellectual property

How Does It Work?

Obfuscation encrypts the source code and removes some unnecessary information from the assembly metadata when it deems that it is safe to do so, thus making the assembly more difficult to understand or read after it is decompiled. The assembly metadata and manifest are used by the dissemblers to decompile them and get the original source code. Note that even if an application is compiled to native code at the time of execution, the Microsoft .NET runtime environment still requires that the assembly metadata and IL code be embedded in an assembly before it starts its execution. There are a number of techniques that can be used to obfuscate. However, the disadvantage of obfuscation is that it can affect performance (but not to a great extent).

Obfuscation never changes your source code. Rather, the obfuscators obfuscate your assemblies using a specific encryption methodology and transform them into another assembly that is obfuscated, but the functionality of it remains unaltered.

How to Obfuscate?

Obfuscation in .NET can be achieved by scrambling the meaningful names in the assembly metadata with non-meaningful ones and trimming the non-essential metadata, but without affecting any functionality. The techniques used include, but are not limited to:

Changing the Assembly Metadata
String Encryption
Size Reduction

Is this the Best Solution?

Unfortunately, the available obfuscators are unable to completely protect your intellectual property. Even if obfuscators can be a good tool for preventing most decompilers from stealing your code, if you are determined and possess a good knowledge of data structures and algorithms, you can steal the code even from an obfuscated assembly. So, obfuscation can be a good solution, but there is no software that is absolutely safe.

The Future

Microsoft realized the importance of this technology and introduced the Dotfuscator tool for obfuscation with Visual Studio .NET. In addition, these .NET obfuscator tools are available:

http://www.junglecreatures.com
http://www.9rays.net/Products/Spices.Obfuscator/

Obfuscation is a very powerful technology and will continue to be a part of the application build and deployment process in the years to come.

Working extensively in Microsoft technologies for more than 7 years, Syed Raheel Ali is a Senior Technical Team Leader / SharePoint Consultant for a company in a Dubai, UAE. His programming skills include C, C++, Java, C#, VB, VC++, ASP.NET, XML, and UML. He has worked with .NET and C# for more than five years. Reach raheel at mailto:rahil.alee@gmail.com.

Deployment for 2007 Microsoft Office SharePoint Server June 26, 2009

Posted by thinkparallel in Moss 2007.
add a comment

SharePoint and ASP.NET Integration June 26, 2009

Posted by thinkparallel in Moss 2007.
add a comment

Whenever we create a new WSS web application in SharePoint, behind the scene a new IIS Web site gets created. Now to make it SharePoint specific, WSS does the following 

  • WSS makes few entries into the IIS Metabase. (IIS Metabase stores conifiguration information about it IIS Web Sites and Virtual Directories)
  • Creates virtual directories which maps to 12 hive (installation directory\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\)
    • _controltemplates – where user controls are kept.
    • _layouts – has application pages in it.
    • _vti_bin – dlls and web services repository
    • _wpresources – resource file repository for Web Parts
  • Adds WSS-specific web.config to the root directory of the IIS Web site.
  • Adds wildcard application map to route all incoming to aspnet_isapi.dll. (Right click your iis web site, select home directory, click on Configuration – there we could find the wildcard application map entry.

 

Finally WSS extends the routing architecture of IIS and ASP.NET to properly route all incoming requests through WSS runtime.

 

IIS maps an incoming request to a physical file within root directory of an IIS Web Site or virtual directory. (Virtual directory – an entity defining a child URL space nested within the URL space of its parent IIS Web Site. IIS provides the flexibility of defining the root directory for a virtual directory at any location)

 

IIS supports Internet Server Application Programming Interface (ISAPI) programming model, it allows us to configure an IIS Web Site or virtual directory so that incoming requests trigger the execution of the custom code on the Web Server.

 

ISAPI programming models consists of ISAPI extension and ISAPI filters.

ISAPI extension is a dll that serves as an endpoint for all the incoming requests.

More on ISAPI extension

http://msdn.microsoft.com/en-us/library/ms525172.aspx

 

ISAPI filter-acts as an interceptor. It provides pre as well post processing for each and every incoming request. These extensions are however difficult to develop as they are written in C++.

 

More on ISAPI filters

http://msdn.microsoft.com/en-us/library/ms524610.aspx

 

For better understanding of low level look at ASP.NET architecture

 

http://www.west-wind.com/presentations/howaspnetworks/howaspnetworks.asp

 

In short, ASP.NET framework is implemented as an ISAPI extension named aspnet_isapi.dll. Whenever IIS sees an incoming request targeting a file with extension like .aspx,.ascx,.asmx, based on the application map defined, it forwards the request to aspnet_isapi.dll, which effectively passes control over to ASP.NET framework.

 

ASP.NET framework compiles an .aspx page to .dll. It parses the .aspx file to generate a C# file that inherits from Page class. Once the ASP.NET page parser builds the source c# file for an .aspx page, it than compile it into a dll. This occurs only the first time when the page is requested; afterwards the same dll is used for all the subsequent requests that target the same page.

 

Now comes into picture HTTP request pipeline exposed by ASP.NET framework. It provides the developer with a degree of control comparable with ISAPI programming model. Http Request Pipeline contains HttpHandler, HttpApplication nad HttpModule components.

 

Once a request comes into the AppDomain managed by the ASP.NET runtime, ASP.NET uses the HttpWorkerRequest class to store the request information. Following that, the runtime wraps the request’s information in a class named HttpContext. The HttpContext class includes all the information you’d ever want to know about a request, including references to the current request’s HttpRequest and HttpResponse objects. The runtime produces an instance of HttpApplication (if one is not already available) and then fires a number of application-wide events (such as BeginRequest and AuthenticateRequest). These events are also pumped through any HttpModules attached to the pipeline. Finally, ASP.NET figures out what kind of handler is required to handle the request, creates one, and asks the handler to process the request. After the handler deals with the request, ASP.NET fires a number of post-processing events (like EndRequest) through the HttpApplication object and the HttpModules.

 

 

HttpApplication – During the lifetime of a Web application, the HttpApplication objects serve as places to hold application-wide data and handle application-side events.

HttpModules – While the Application object is suitable for handling application-wide events and data on a small scale, sometimes application-wide tasks need a little heavier machinery. HttpModules serve that purpose.ASP.NET includes a number of predefined HttpModules. For example, session state, authentication, and authorization are handled via HttpModules.

HttpHandlers -The last stop a request makes in the pipeline is an HttpHandler. Any class implementing the interface IHttpHandler qualifies as a handler. When a request finally reaches the end of the pipeline, ASP.NET consults the configuration file to see if the particular file extension is mapped to an HttpHandler. If it is, the ASP.NET loads the handler and calls the handler’s IHttpHandler.ProcessRequest method to execute the request.

ASP.NET includes several HTTPHandlers already, including System.Web.UI.Page and System.Web.Services.WebService

http://www.brainbell.com/tutorials/ASP/The_ASP.NET_Pipeline.html

WSS uses the above ASP.NET technique to extend the HTTP Request Pipeline.

Configures each web application with custom HttpApplication object using SPHttpApplication class. This class is within Microsoft.SharePoint.dll. It creates a custom global.asax file at the root of Web Application that inherits from SPHttpApplication.

<%@ Assembly Name=”Microsoft.SharePoint”%><%@ Application Language=”C#” Inherits=”Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication” %>

It also makes use of custom HttpHandler and HttpModule as well.

We could find their entries in web.config of the web applciation

  <httpHandlers>

      <remove verb=“GET,HEAD,POST“ path=“*“ />

      <add verb=“GET,HEAD,POST“ path=“*“ type=“Microsoft.SharePoint.ApplicationRuntime.SPHttpHandler, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c“ />

      <add verb=“OPTIONS,PROPFIND,PUT,LOCK,UNLOCK,MOVE,COPY,GETLIB,PROPPATCH,MKCOL,DELETE,(GETSOURCE),(HEADSOURCE),(POSTSOURCE)“ path=“*“ type=“Microsoft.SharePoint.ApplicationRuntime.SPHttpHandler, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c“ />

// other handlers

    </httpHandlers>

<httpModules>

      <clear />

      <add name=“SPRequest“ type=“Microsoft.SharePoint.ApplicationRuntime.SPRequestModule, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c“ />

// other http modules

    </httpModules>

 

 

 

And finally it makes use of SPVirtualPathProvider, which abstracts the details of where page files are stored away from the ASP.NET runtime, using which the pages are served from content database. Once the content are retrieved by Virtual path provider it is passed to asp.net runtime for parsing. SPRequestModule component contains code to register SPVirutalPathProvider class with ASP.NET framework. SPVirutalPathProvider class works toghether with SPPageParserFilter to supply processing instructions to ASP.NET page parser whether to compile the aspx page to dll or process it in no compile mode.

More on virual path provider

http://weblogs.asp.net/scottgu/archive/2005/11/27/431650.aspx

Launching an application from a link in SharePoint May 7, 2009

Posted by thinkparallel in Moss 2007.
add a comment
When you are viewing lists of items in SharePoint, the context menu is fantastic as it allows you to edit documents directly from certain native applications. For example with a Word document you are able to select ‘Edit In Microsoft Word’ from the context menu, which when clicked fires up Microsoft Word and enables you to edit the document. However when you start creating your own custom webparts from SharePoint list items, you lose this ability. Today I had the challenge of providing a link to a document that was stored in a SharePoint list, but I needed to be able to fire the document up directly from the link.
 
After quite a bit of trawling through the web I found this great article which really got me going in the right direction:

http://wiki.threewill.com/display/is/2007/10/.

Basically you need to call a javascript method called dispex() which will open the application for you (instead of opening the document as read only).

So within my code I already had my Hyperlink control (lnkDocumentDownload) which was populated by an SPListItem. This also has the URL of the document set in lnkDocumentDownload.NavigateUrl. This needs to be set for this to work, and of course for applications that don’t have integration with SharePoint, they will just use this link to go to the document.

What I needed to additionally add to enable the launching of the application was:

lnkDocumentDownload.Attributes.Add(“onfocus”, “OnLink(this)”);
lnkDocumentDownload.Attributes.Add(
“onclick”, @”DispEx(this,event,’TRUE’,'FALSE’,'FALSE’,'SharePoint.OpenDocuments.3′,’0′,’SharePoint.OpenDocuments’,”,”,”,’2′,’0′,’0′,’0×7fffffffffffffff’)”);

Once I added this in, whenever I clicked the link in my control, it would behave in the same way as clicking on ‘Edit in Microsoft Word’.

I also found some ‘kind of’ (not really) helpful documentation on the javascript methods on the Microsoft website here: http://msdn.microsoft.com/en-us/library/cc264013.aspx

Saving files in ItemUpdated for a SharePoint List May 7, 2009

Posted by thinkparallel in Moss 2007.
add a comment
I had an issue today trying to call File.SaveBinary() method of an SPListItem in the ItemUpdated method. Everytime I treid to call it it seemed to throw an error. In the end there was an easy fix for this – make sure AllowUnsafeUpdates is set to true. Once this is set, the binary can be saved no problem. The other method you should call before you save the binary is the this.DisableEventFiring(); method to ensure that the event does not go into an endless loop.
 
ie 
this.DisableEventFiring();
SPListItem item = properties.ListItem;
item.Web.AllowUnsafeUpdates = true;
item.File.SaveBinary(updatedFile);
item.Web.AllowUnsafeUpdates = false;
this.EnableEventFiring();

Invalid Security Validation in SharePoint code May 7, 2009

Posted by thinkparallel in Moss 2007.
add a comment

Twice in the past week I have had the issue in my MOSS code where it is throwing an exception: “The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again”

As it turns out the problem isn’t so had to fix. Basically you need to set FormDigestSettings to disabled. This can be done in your code as follows:

SPWebApplication webApp = site.WebApplication;
bool formDigestSettingsEnabled = webApp.FormDigestSettings.Enabled;
webApp.FormDigestSettings.Enabled =
false;
//Do all your code in here where it is throwing the error..
webApp.FormDigestSettings.Enabled = formDigestSettingsEnabled;

This can also be fixed by turning off the security validation for an application in Central Admin (however I probably wouldn’t recommend this):

Central Admin -> Application Management -> General Settings -> Turn security validation off

Impersonation in MOSS 2007 May 7, 2009

Posted by thinkparallel in Moss 2007.
add a comment

I recently had an issue where I attached a SharePoint event handler to a list item, and when the list item was approved it fired off a group email. Problem was that if the user who approved the item did not have super powered privileges on the system, the event handler would fail due to a permissions error. 

To run the SPSecurity.RunWithElevatedPrivileges method 

This also meant that I could create a method in this class which is called in the SPSecurity.CodeToRunElevated constructor. Also it is worth noting that if you are still getting security validation errors, you need to wrap update() methods with the AllowSafeUpdates method (also shown in code below).

sealed class ScheduleMail
{
   private Guid _siteGuid;
   private string _webUrl;   

   public ScheduleMail(Guid siteGuid, string

webUrl)
   {
      _siteGuid = siteGuid;
      _webUrl = webUrl;
   }   

 

public void SendScheduledMail()
   {
      SPSite mySite = new SPSite(_siteGuid);
      SPWeb myWeb = mySite.OpenWeb(_webUrl);

      // Do the rest of the code requiring privileges      … //Created dispatcher job in here

      //Get around security 

 

 

      myWeb.AllowUnsafeUpdates = true;
      dispatcherJob.Update();
      myWeb.AllowUnsafeUpdates =
false;
   }
}

In the end the final code I implemented was along these lines

override void ItemUpdated(SPItemEventProperties properties)
{
   base.ItemUpdating(properties);
   ScheduleMail mailToSend = new ScheduleMail(properties.SiteId, properties.RelativeWebUrl);
   SPSecurity.CodeToRunElevated codeRequiringElevated = new SPSecurity.CodeToRunElevated(mailToSend.SendScheduledMail);
   SPSecurity.RunWithElevatedPrivileges(codeRequiringElevated);
}

To Access the attached File in Sharepoint List April 13, 2009

Posted by thinkparallel in Moss 2007.
Tags:
add a comment

I am in office, woking on data migration for one of my project module. I felt bored so came here to share some of my code and to write another blog.

Today I will show you how to Access the attached File in Sharepoint List, this is one of my intial stage code i wrote for one of the web part for Flash banner; this might helpfull for those who might looking for the same.

try
        {
            //Page.Request.Url.ToString()
            //”http://srv:17604

            Microsoft.SharePoint.SPSite _site = new SPSite(Page.Request.Url.ToString());
            Microsoft.SharePoint.SPWeb _web = null;
            Microsoft.SharePoint.SPList _newsList = null;
            //_web = _site.OpenWeb(“en”);

            if (_site.AllWebs.Count > 0)
            {
                //get the web in my case i was having the variations in my web collections so this is to choose the web

                if (Request.Url.AbsolutePath.ToLower().IndexOf(“/ar/”) >= 0)
                {
                    _web = _site.OpenWeb(“Ar”);
                }
                else
                {
                    _web = _site.OpenWeb(“En”);
                }
            }

            if (_web != null)
            {
                //get the Banner List  Put the nme list here
                _newsList = _web.Lists[strListName];

            }

           SPQuery query = new SPQuery();

           query.Query = “<OrderBy>” +
                                          “<FieldRef Name=’Title’ />” +
                                          ”</OrderBy>” ;
           

            SPListItemCollection _myListItems = _newsList.GetItems(query);
           

             //string sFilePath = “”;
            bannerPath = _myListItems[0].Attachments.UrlPrefix;

            foreach (SPListItem currentItem in _myListItems)
            {
                SPAttachmentCollection currentAttachments = currentItem.Attachments;
                string urlString = “”;

                if (Convert.ToBoolean(currentItem["Active"].ToString()))
                {
                    urlString = currentItem.Attachments.UrlPrefix;
                    int nofAttachments = currentAttachments.Count;
                    bannerPath = SPEncode.HtmlEncode(urlString); // the URL is also correctly dispayed
                   
                    string fileName;
                    string fileUrl;
                    for (int p = 0; p < 1; p++)
                    {
                        fileName = currentAttachments[p];
                        fileUrl = currentAttachments.UrlPrefix + fileName;
                        bannerPath = SPEncode.HtmlEncode(fileUrl);
                    }
                }
            }

        }

        catch (Exception ex)
        {

        }

Enjoy Coding. You cant learn until you code to solve prb.

Best Regards.

To Get Current User Task from a Task List March 26, 2009

Posted by thinkparallel in Moss 2007.
Tags:
add a comment

void loadMyTaskGrid()
{
        _myPortalSite = new SPSite(SPContext.Current.Site.Url);
        _myTeamSite = _myPortalSite.OpenWeb();

        if (SPContext.Current.Web.CurrentUser != null)
        {
            //——————————————————————————————————————————
            SPQuery Q = new SPQuery();
            Q.Query = @”<Where><Eq><FieldRef Name=’AssignedTo’/><Value Type=’Text’>” + SPContext.Current.Web.CurrentUser.Name + “</Value></Eq></Where>”;
            SPListItemCollection spColTaskListItems = _myTeamSite.Lists[msTaskListName].GetItems(Q);

            ////——————————————————————————————————————————
            try
            {
                if (spColTaskListItems != null )
                {
                    if (spColTaskListItems.Count > 0)
                    {
                        lblUserName.Text = “, <b><font color=’red’>” + SPContext.Current.Web.CurrentUser.Name.ToString() + “</font></b>”;
                        DataView dv = new DataView(spColTaskListItems.GetDataTable());
                        dv.RowFilter = “Status=’Not Started’”;
                        lblNewTasks.Text = “( ” + dv.Count.ToString() + ” )”;
                        dv.RowFilter = “”;
                        dv.RowFilter = “Status=’In Progress’”;
                        lblInprogress.Text = “( ” + dv.Count.ToString() + ” )”;
                        dv.RowFilter = “”;
                        radGrdTaskList.DataSource = spColTaskListItems.GetDataTable().Select(“Status=’Not Started’”);
                        //radGrdTaskList.DataBind();
                    }
                }
            }
            catch (Exception ex)
            {
           
            }
        }
}

To Define Master page from code behind March 26, 2009

Posted by thinkparallel in Moss 2007.
Tags:
1 comment so far

#region Portal and Site Variables
    private SPSite _myPortalSite; // http://Localhost/
    private SPWeb _myTeamSite;    // http://localhost/Demosite
    private string msUrl;
    #endregion
protected override void OnPreInit(EventArgs e)
{
        base.OnPreInit(e);
        string sPageName = Page.AppRelativeVirtualPath.Substring(Page.AppRelativeVirtualPath.LastIndexOf(‘/’) + 1);

        if (sPageName.Substring(0, 6).ToUpper() == “Design”.ToUpper())
        {
            //setting the sharepoint site as context URL
            this._myPortalSite = new SPSite(“http://raheel“);
            SPControl.SetContextSite(Context, this._myPortalSite);

            //Now setting the website
            this._myTeamSite = SPControl.GetContextWeb(Context).Webs["sns"];
        }
        else
        {
            this._myTeamSite = SPControl.GetContextWeb(Context);

            this.MasterPageFile = “/_Catalogs/masterpage/GCAA_en_default.master”; //_myTeamSite.ParentWeb.MasterUrl; // .MasterUrl; // code to set master page to the site
            // i could use “/_layouts/application.master”
        }
}