27 October 2016

Easily prevent cookie replay attacks in Sitecore

Imagine you have a site which is (partially) protected and you use forms authentication to let your users gain access. Then you might be vulnerable to a cookie replay attack. Apparently this is a weakness that has been around in the .NET framework for ages. That article explains very well what a cookie replay attack is. There is also an old Microsoft Knowledge Base article on that subject.

To protect your site against such a cookie replay attack, you must implement the following security measures:
  • When signing in, set a boolean session variable to true.
  • When signing out, set the session variable to false.
  • Check the session variable on each request. If the value is false (or non-existing), return not authenticated.
Now to make your life and those of your team easier, you can create a custom forms authentication provider for Sitecore which implement the security measures mentioned above. With this custom provider, you nor any other developer on the team must think about this weakness.  As long as the custom provider is in place, that is.

Developers can keep doing what they did before:
  • On login, call: AuthenticationManager.Login(username, password);
  • On logout, call: AuthenticationManager.Logout();

Time to bring the custom provider!

using System;
using System.Linq;
using System.Web;
using Sitecore;
using Sitecore.Security.Accounts;
using Sitecore.Security.Domains;

namespace Custom.Security.Authentication
{
    public class CustomFormsAuthenticationProvider : Sitecore.Security.Authentication.FormsAuthenticationProvider
    {
        private const string LoggedInSessionKey = "LoggedIn";
        private static readonly string[] SitesToSkip = new[] { "shell", "login", "admin" };

        public override bool Login(User user)
        {
            if (!base.Login(user))
            {
                return false;
            }

            if (IsValidSite())
            {
                HttpContext.Current.Session[LoggedInSessionKey] = true;
            }

            return true;
        }

        public override bool Login(string userName, bool persistent)
        {
            if (!base.Login(userName, persistent))
            {
                return false;
            }

            if (IsValidSite())
            {
                HttpContext.Current.Session[LoggedInSessionKey] = true;
            }

            return true;
        }

        public override bool Login(string userName, string password, bool persistent)
        {
            if (!base.Login(userName, password, persistent))
            {
                return false;
            }

            if (IsValidSite())
            {
                HttpContext.Current.Session[LoggedInSessionKey] = true;
            }

            return true;
        }

        public override void Logout()
        {
            if (HttpContext.Current.Session != null && HttpContext.Current.Session[LoggedInSessionKey] != null)
            {
                HttpContext.Current.Session.Remove(LoggedInSessionKey);
            }

            base.Logout();
        }

        public override User GetActiveUser()
        {
            if (!IsValidSite() || IsMarkedAsLoggedInOrNoSession())
            {
                return base.GetActiveUser();
            }

            return Context.Domain.GetAnonymousUser() ?? Domain.GetDefaultAnonymousUser();
        }
        
        private static bool IsValidSite()
        {
            return !SitesToSkip.Contains(Sitecore.Context.GetSiteName(), StringComparer.OrdinalIgnoreCase);
        }

        public static bool IsMarkedAsLoggedInOrNoSession()
        {
            return HttpContext.Current == null
                || HttpContext.Current.Session == null
                || HttpContext.Current.Session[LoggedInSessionKey] != null;
        }
    }
}

Plain and simple. With one caveat. Sitecore calls GetActiveUser() several times when signing in to the Sitecore backend. It does not call any of the login methods. On recommendation of Sitecore Support, we just call base.GetActiveUser() if we are on any of the backend sites.

The only thing to do, is to let Sitecore know about your custom authentication provider. Adjust the web.config as follows:

<authentication defaultProvider="forms">
  <providers>
    <clear />
    <add name="forms" type="Custom.Security.Authentication.CustomFormsAuthenticationProvider, Custom" />
  </providers>
</authentication>


04 October 2016

Dependency injection in a modular architecture like Sitecore Helix

Registering all your types using your favorite IoC container in a modular architecture based solution (cfr Sitecore Helix) might become time consuming and cumbersome over time. Not to mention the times you've developed a new feature and published it to find out you've forgotten to register your new types! That means an extra site recycle...

To overcome this you can implement a system which registers your types automatically. No more forgetting, no more adding project references; just develop and play! The sample code uses Autofac, but you can use any other IoC container you like.

Setting up the basics

First thing to do, is to create an interface that will be used in every module and scanned for when registering the types.
using Autofac;

public interface IModuleInitializer
{
    ContainerBuilder Register(ContainerBuilder builder);
}

Having defined the interface, let's implement a default implementation for it. This one will do all of the registering work for every type in each module in your solution.

What it does:
  1. First it gets the current assembly.
  2. Then it scans the assembly for types where the names ends with a few pre-defined keywords. This is a convention that you must agree upon with your team.
  3. The types it finds will be registered as the interface it implements. Any other configuration is done as well, like single instance or auto-wiring properties.
  4. The last step is to register the controllers and API controllers.
using System;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;

public class DefaultModuleInitializer : IModuleInitializer
{
    public virtual ContainerBuilder Register(ContainerBuilder builder)
    {
        var assembly = GetType().Assembly;

        builder.RegisterAssemblyTypes(assembly)
            .Where(
                x =>
                x.Name.EndsWith("Repository", StringComparison.OrdinalIgnoreCase) ||
                x.Name.EndsWith("Factory", StringComparison.OrdinalIgnoreCase) ||
                x.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase))
            .AsImplementedInterfaces()
            .SingleInstance()
            .PropertiesAutowired();

        builder.RegisterControllers(assembly).PropertiesAutowired();
        builder.RegisterApiControllers(assembly).PropertiesAutowired();

        return builder;
    }
}

You may already have noticed that the method is marked as virtual. This comes in handy if you need to add types that don't match the predicate, or in case you need to overwrite the default implementation.

Add it to every module

In order to have it register your module's types, you'll need to create a class which inherits the DefaultModuleInitializer in each module. You can also implement IModuleInitializer instead if your module is way off your default implementation. Remember to have one implementation in each module!

In most cases your class will look like this:
public class ModuleInitializer : DefaultModuleInitializer
{
}

However, if you need extra registrations, then it might look like this:
using Autofac;

public class ModuleInitializer : DefaultModuleInitializer
{
    public override ContainerBuilder Register(ContainerBuilder builder)
    {
        builder = base.OnContainerInitializing(builder);
        builder.RegisterType().AsSelf().PropertiesAutowired();

        return builder;
    }
}

Let your IoC container know!

Now it's time to actually register your types. The GetModuleInitializers() method searches for classes implementing IModuleInitializer by scanning all bin files starting with your custom namespace. Each class found is then instantiated and returned. The Register() method will loop all found IModuleInitializers and call its Register() method. Et voila, you're done!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Http;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.Web;
using Autofac.Integration.WebApi;
using Sitecore.IO;

public static class AutofacConfiguration
{
    public static IContainerProvider Register()
    {
        var builder = new ContainerBuilder();
        var modules = GetModuleInitializers().ToList();

        foreach (var moduleInitializer in modules)
        {
            moduleInitializer.Register(builder);
        }

        var container = builder.Build();

        GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        return new ContainerProvider(container);
    }

    public static IEnumerable<IModuleInitializer> GetModuleInitializers()
    {
        var assemblyFilenames = FileUtil.GetFiles(FileUtil.MapPath("/bin"), "YourNamespace.*.dll", false);
        var moduleInitializerType = typeof(IModuleInitializer);

        foreach (var assemblyFileName in assemblyFilenames)
        {
            var assembly = Assembly.LoadFrom(assemblyFileName);
            var initializerTypes = assembly.GetTypes().Where(x => moduleInitializerType.IsAssignableFrom(x) && !x.IsInterface);

            foreach (var initializerType in initializerTypes)
            {
                yield return Activator.CreateInstance(initializerType) as IModuleInitializer;
            }
        }
    }
}

03 March 2016

E-mail address validation in Sitecore WFFM

The e-mail validation that comes with WFFM marks e-mail addresses with top level domains of 5 characters or more as invalid (for instance sitecoredeveloper@some.education). Luckily, you can change the regular expression that is being used. Open the Sitecore Client and go to /sitecore/system/Modules/Web Forms for Marketers/Settings/Validation/E-mail and alter the Validation Expression field.

The default value is: ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$
Change it to: ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$

The difference is that the last part of the e-mail address has no limitations on the number of characters.

07 December 2015

Incorrect data is saved for list fields in Sitecore WFFM MVC

When you use Sitecore WebForms for Marketers MVC, then chances are you run into the problem that the chosen values for list fields are saved incorrectly or not at all when submitting the form. For instance, when I submitted a form, no data was saved for drop lists and System.String[] was saved as value for a date picker. At the time of writing, this applies to WFFM 2.4+.

The solution is two-folded. First of all, there is a known issue described on the Sitecore Knowledge Base. The remedy is to download the support dll and to make changes to some WFFM files and items. Make sure you pick the right Sitecore version.

But even after applying that fix, I still ran into the same issue. It turned out that Sitecore WFFM MVC relies on the default dependency resolver and that I've set that resolver according to the Autofac documentation as follows:

var builder = new ContainerBuilder();

// Register your types
// ...

var container = builder.Build();

// Set the resolver to Autofac
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

WFFM expects to find the Sitecore dependency resolver there, but finds Autofac instead. A resolver that doesn't know anything about the WFFM types. To overcome that issue, you must register the WFFM types yourself.

// Sitecore WFFM
builder.RegisterType<Sitecore.Forms.Mvc.Controllers.ModelBinders.FieldBinders.DefaultFieldValueBinder>().AsSelf();
builder.RegisterType<Sitecore.Forms.Mvc.Controllers.ModelBinders.FieldBinders.CaptchaFieldBinder>().AsSelf();
builder.RegisterType<Sitecore.Forms.Mvc.Controllers.ModelBinders.FieldBinders.CheckboxFieldValueBinder>().AsSelf();
builder.RegisterType<Sitecore.Forms.Mvc.Controllers.ModelBinders.FieldBinders.DatePickerFieldValueBinder>().AsSelf();
builder.RegisterType<Sitecore.Forms.Mvc.Controllers.ModelBinders.FieldBinders.ListFieldValueBinder>().AsSelf();

After that, data from list fields should be saved properly again!

02 December 2015

Multilingual e-mail and date selector in Sitecore Web Forms for Marketers (WFFM)

Multilingual e-mails

Sitecore WFFM does not support multilingual e-mails out of the box. In other words, the e-mail sent will always be in the default language. To enable multilingual e-mails, open /sitecore/templates/Web Forms for Marketers/Form/Submit/Save Actions, uncheck the “Shared” checkbox and save.

If you already have existing forms, then you will need to re-add all the save actions in each language for all forms. You must do this in a specific way: use the Form Designer inside Sitecore Client and only change the language in the form designer.




Multilingual date selector

When using a field of type 'Date' (or 'DateSelector'), you’ll get 3 dropdowns, with a label on top of it. These labels are in English.


To add translations for these labels, do the following:
  1. Go to /sitecore/system/Dictionary
  2. Create a new dictionary folder, e.g. WFM, just to keep things organized.
  3. Create a dictionary entry for each label
    1. Use the following rule for the Key value: "{0}WFM: {1}" (without the quotes)
      where {1} is your key (i.e. 'Day' - 'Month' - 'Year')
      and {0} is the first letter of the key in uppercase.
    2. Enter a Phrase in each language