Category: Software Licensing Best Practices

Usage-based (pay per use) software licensing in .NET

Many software vendors nowadays move away from one-time payments to other licensing models. One such example is the usage-based model. By doing so helps lowering the barrier of entry for new customers, as they no longer need to commit to the product long term, which is usually the case with one-time payments. If you already have a subscription model, supporting usage-based payments can help you to monetise a group of users who would otherwise not buy the product.

You can read the entire tutorial here.

Getting started

In Cryptolens, usage-based licensing can be implemented using data objects, aka custom variables. We can use these variables to record how often features are used and keep track of any usage credits that a customer has purchased. There are two ways of billing customers:

  • Upfront payment: customers need to purchase usage credits in advance.
  • Based on actual usage: customers pay for the actual usage in the end of the billing period.

Charging based on actual usage

If you choose to charge your customers based on actual usage, we can simply use the code below:

var auth = "Access token with AddDataObject, ListDataObject and IncrementIntValue permission. Please also set KeyLock value to '-1'";
var licenseKey = "LZKZU-MPJEW-TARNP-UHDBQ";

var result = Data.ListDataObjects(auth, new ListDataObjectsToKeyModel 
{
    Contains = "usagecount",
    Key = licenseKey,
    ProductId = 3349 
});

var obj = result.DataObjects.Get("usagecount");

if (obj == null)
{
    // make sure to create it in case it does not exist.
    Data.AddDataObject(auth, new AddDataObjectToKeyModel { Key = licenseKey, ProductId = 3349, Name = "usagecount", IntValue = 1 });

    if(res == null || res.Result == ResultType.Error)
    {
        Console.WriteLine("Could not create new data object. Terminate." + res.Message);
    }
}
else
{
    var res = obj.IncrementIntValue(auth, 1, licenseKey: new LicenseKey { Key = licenseKey, ProductId = 3349 });

    if (res == false) 
    {
        Console.WriteLine("We could not update the data object. Terminate.");
    }
}

Upfront payments

If you instead want to charge your users upfront, we need to create the data objects when creating the license. If you are using payment forms, we can set up two requests, one creating a new license and another creating a new data object (inspired by this tutorial), as the result from key creation will be “piped” into data object creation request. You can then have another payment form that allows users to refill their credits, in which case the custom field can be used.

You can use the code below to verify if the limit was reached inside your application:

var auth = "Access token with AddDataObject, ListDataObject and IncrementIntValue permission. Please also set KeyLock value to '-1'";
var licenseKey = "LZKZU-MPJEW-TARNP-UHDBQ";

var result = Data.ListDataObjects(auth, new ListDataObjectsToKeyModel { Contains = "usagecount", Key = licenseKey, ProductId = 3349 });
var obj = result.DataObjects.Get("usagecount");

var res = obj.DecrementIntValue(auth, decrementValue: 1, enableBound:true, lowerBound: 0, licenseKey: new LicenseKey { Key = licenseKey, ProductId = 3349 });

if (!res)
{
    Console.WriteLine("Could not decrement the data object. The limit was reached.");
}

Not a customer yet? Sign Up for a free trial and implement our software licensing system within minutes.

Protecting Software with Obfuscation and Software Licensing

Software applications can be secured with two layers of protection. The first layer is software licensing, whose aim is to enforce a license model (eg. by restricting the number of machines where the application can run). The second layer is software obfuscation, where the end goal is to make it hard or impossible for the end users read and alter the source code. In this article, we will focus on obfuscation.

Types of obfuscations

There are two ways of making it harder for the adversary to read or alter the source code. We can either achieve it by altering the source in such a way that more time is necessary to understand how the code works and to make it harder to remove existing licensing logic (eg. for key verification). This is usually what is thought of as obfuscation. The second approach is to move critical code away from the client machine to your own servers and provide it as an API endpoint that your application will call.

Both methods have their pros and cons. In the case of code obfuscation, you can relative easily increase the difficultly of reverse engineering at the cost of that eventually the source code will be reversed engineered or licensing logic bypassed. With custom API endpoints, you always retain control of code execution (since it runs on your servers) and if everything is correctly implemented, it’s impossible to reverse engineer the code. This is at the cost of requiring active internet connection to your server and potentially some regulatory issues (since data has to be transferred to your servers).

Conventional obfuscators

There are many obfuscators out there, some that even are free of charge. For the .NET platform, you can either use Ofuscar or ConfuserEx. The idea behind all of them is to make the IL code (which C# and VB.NET compile to) harder to read for an adversary. They should be quite easy to use, so you can simply add the key verification logic anywhere in the software.

API endpoints

Creating an API endpoint for highly sensitive code is the best way to protect it against reverse engineering. Although it may sound as very cumbersome to set up and maintain, the good news is that most cloud providers today support some form of serverless computing. We will describe how this is achieved using Azure Functions, but it should be fairly similar to other cloud platforms. The reason why we chose the serverless model is because it abstracts most things away, allowing you to focus on expressing the actual method. Moreover, cloud providers tend to allow a “per request” model, meaning that you do not have to pay for the time when the application is idle.

Azure Functions demo

To create an Azure function, go to the Azure portal and create a new “Function App”. You can then select either “consumption plan” or “app service plan” (please see this for more details). Once it’s set up, create a new HTTP Trigger and change the run.csx as shown below. To get the license verification to work, we will need to add an additional file, function.proj (or project.json for older versions of the runtime), which we cover further down in the article.

run.csx
#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

using SKM.V3;
using SKM.V3.Models;
using SKM.V3.Methods;

public static async Task Run(HttpRequest req, ILogger log)
{
    // this function will return 'Hello, <name>' if the correct license key is provided.

    // licensekey and machinecode stored as query string
    if(!KeyVerification(req.Query["licensekey"], req.Query["machinecode"])) 
    {
        return new BadRequestObjectResult("License key verification failed");        
    }
    
    string name = req.Query["name"];

    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

public static bool KeyVerification(string licenseKey, string machineCode) {

    var RSAPubKey = "<RSA public key>";

    var auth = "<access token>";
    var result = Key.Activate(token: auth, parameters: new ActivateModel()
    {
        Key = licenseKey,
        ProductId = 3349,
        Sign = true,
        MachineCode = machineCode
    });

    if (result == null || result.Result == ResultType.Error ||
        !result.LicenseKey.HasValidSignature(RSAPubKey).IsValid())
    {
        // an error occurred or the key is invalid or it cannot be activated
        // (eg. the limit of activated devices was achieved)
        Console.WriteLine("The license does not work.");
        return false;
    }
    else
    {
        // everything went fine if we are here!
        Console.WriteLine("The license is valid!");
        return true;
    }
}
function.proj

In order to add support for license key verification, we need to add Cryptolens.Licensing. Depending on the version of function apps that you are using, you might either need to create a project.json or function.proj file. The newest version of the runtime uses function.proj.

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Cryptolens.Licensing" Version="4.0.9.2"/>
  </ItemGroup>
 
</Project> 

In case you get any issues with namespaces not being found, it can be useful to try to re-create the function entirely.

Accessing form client side

In order to access your method through the client application, we can use RestSharp or similar library. When you click on “Get function url”, you will get a string similar to “https://<cluster-name>.azurewebsites.net/api/HttpTriggerCSharp1?live=<secret key>”. The live parameter may not be present for some access levels

var client = new RestClient("https://<cluster-name>.azurewebsites.net/api/");
var request = new RestRequest("HttpTriggerCSharp1", Method.GET);
//request.AddParameter("code", "<secret key>"); // depending on access level of the function in Azure

// for licensing
request.AddParameter("licensekey", "AAAA-BBBB-CCCC-DDDD");
request.AddParameter("machinecode", Helpers.GetMachineCode());

// parameter to our function
request.AddParameter("name", "Bob");

var result = client.Get(request);

Console.WriteLine(result.Content);

Console.ReadLine();

If all worked out correctly, we should see “Hello, Bob” in the terminal.

Privacy

The best advice when it comes to privacy is to send as little personal identifiable information as possible. Always ask yourself what data really needs to be processed externally. Even if it is not always possible to make it entirely anonymous, it’s good to strive to at least pseudo-anonymize data (i.e. associate an id to each user instead of using their real name). In some cases, such as with IP address, you can remove the last digits, eg. from 10.1.1.5 to 10.1.1.0 without affecting the geographical data of the IP. For advanced users, you might want to look into homomorphic encryption and follow the recent research.


Not a customer yet? Sign Up for a free trial and implement our software licensing system within minutes.

How to protect SDKs with Software Licensing in .NET

Software Development Kits (SDKs) are a great way to give your users the ability to build on top of the functionality offered by your library/package. From a licensing perspective, desktop apps and SDKs are quite similar, which we will go through in this article. We will first take a look at the applicable licensing models and then skim through some example code. You can jump directly to the tutorial here.

Licensing Models

SDK licensing is special since the developer of the SDK (the customer) is not its end user. Instead, it’s their customers that will be the end users. In this article we focus on “node-locked” and “pay per install” licensing models (you can read about all applicable licensing models here).

Node-locked is equivalent to “pay per machine”, which essentially means that each time a new machine activates the license, this is recorded so that it can be taken into account when you charge the developers (your customers). Each user will be able to re-install the app that uses the SDK any number of times, without affecting the counter.

Pay per install is similar to “pay per machine”, with the only difference being that fingerprints of the end user machines are not recorded. Instead, a counter is used that increment whenever the SDK is first launched. With this model you get a bit less control of end user instances, but since the fingerprints (aka machines codes) are not tracked, the subscription cost for Cryptolens will reduce significantly (since you are only paying per license key).

In both of the models above, you could create multiple plans for your customers that depend on the actual usage of the SDK. Eg. 1-10 could be a testing tier, 10-10,000 could be another pricing tier, and so on.

Example

From a developer standpoint (eg. your customer), the license key will have to be specified to unlock functionality of your SDK. You could potentially have different pricing tiers depending on the methods that your customers will use. Below is an example of class initialisation that requires a license key to work.

var math = new MathMethods("FULXY-NADQW-ZAMPX-PQHUT");

Console.WriteLine(math.Abs(5));
Console.WriteLine(math.Fibonacci(5));

To see all the code, please take a look at the entire tutorial.

Obfuscation

If you have algorithms in your SDK that you want to be 100% secure from reverse-engineering, we would recommend to create an API endpoint for them hosted in the cloud. Most of the cloud providers support “server less” functions, eg Azure Functions and AWS Lambdas. These are quite simple to setup. Your server less functions would require a license key and potentially a machine code to return a successful response. On the client side, you could use libraries such as RestSharp to access your API endpoint. We will cover this in a future article.


Not a customer yet? Sign Up for a free trial and implement our software licensing system within minutes.

Computing and verifying VAT in .NET (for EU businesses)

When you sell your software as an EU business, you need to take into account the VAT, which depends on whether you sell to a private individual or a company, and their country of residence. Moreover, you need to ensure that the VAT id that they have provided is correct.

In order to solve these two problems, we have published a library for .NET, available as a NuGet package (with source code on GitHub).

Examples

The library has two methods, CalculateVAT and IsValidVAT, which are quite simple to use. We explain their purpose below:

  • CalculateVATThis method asks for the country of residence of the individual or the company, and their VAT id (if applicable). Based on this information, it will calculate the necessary tax that should be applied to the order. Note, we assume you sell products or services that are covered by the standard VAT (i.e. some categories such as books have a lower tax in some countries).
  • IsValidVATThis method is responsible for VAT id verification. We use the European Commission’s API for that. Note, this API is not up 24/7 and can be unresponsive some times. You can view all the times it is down (given the country of residence) here.


Not a customer yet? Sign Up for a free trial and implement our software licensing system within minutes.

3 steps how to protect your software application before release

Let’s assume that you have developed a software application (eg. app) that you are about to sell. Then, there are three things you need to consider:

  • Licensing – this is used to keep track of the type of features that end users have bought. A simple example of this when your user has to type a license key to unlock more functionality. When selecting these kinds of systems, it’s important that the system both supports offline mode and is cloud-based. The advantage of cloud-based systems is that they are more scalable and secure (eg. you have full control of all end users).
  • Obfuscation – this is used to make your program binaries (eg. exe and dll files) harder to disassemble. This is especially important for .NET apps, since existing tools make this very simple. A word of warning though: none of the available systems are 100% safe, and even the well-respected systems are being cracked within days of software release.
  • Web API – imagine your algorithm is so important that you don’t want to risk it being leaked. Since obfuscators are never 100% safe (mainly because in the end, the code will be executed on the client machine), the only secure way is to never run this code on client machines that you don’t control. Instead, you can create a Web API method that you host yourself and then allow your program to consume it. In this case, the algorithm is safe at the cost of constant internet access requirement.

To sum up, the first system to consider is licensing, since this will remove the administrative burden of keeping track of the type of rights your customers have to the software. As a bonus, many cloud-based licensing systems support integration with payment processors. In the end of the day, the goal is to ensure payments and license verification are automated, so that you can focus on developing the features that really matter to your customers.

For more information, please see this page.


Not a customer yet? Sign Up for a free trial and implement our software licensing system within minutes.

Secure your account using 2-step verification

Now you can secure your account even further using two-factor authentication (2FA). In addition to your password, you will have to enter a short 6-digit code each time you log in, which helps to keep your account protected.

Enable 2-step verification

You can access this page directly here.

  1. Go to the Account Settings page
  2. Click on “Configure 2-step verification”
  3. Check “Enable Two Step Authentication” checkbox
  4. Scan the QR code with Google Authenticator (note: there are other alternatives such as Authy if you already have oen of them installed). If you want to get Google Authenticator, you can get it for

Open Source

At SKM, open-mindedness and transparency are at the core of everything we are doing. Therefore, we’ve open-sourced the core parts of 2-step verification, freely available on GitHub. You can learn more about our other open-source projects at cryptolens.io/open-source.


Not a customer yet? Sign Up for a free trial and implement our software licensing system within minutes.

Fixed downtime Dec 18th due to invalid certificate

Today we had a major downtime because the new TLS certificate was not upgraded properly. This caused most of the versions of SKM Client API (aka SKGL Extension) not being able to validate license keys.

I’m very sorry for all the problems that this caused you. Downtimes occur because of various issues; at SKM we are constantly working on making sure to reduce them and their impact.

I’my happy to tell that this issue is now fixed!

/Artem

Lead Developer