Threat Hunting for Typosquatting and Masquerading Using Damerau-Levenshtein Distance

Series - LevenshteinDistance

Typosquatting and masquerading are cyberattack techniques in which adversaries exploit spelling errors, visual similarities, or deceptive naming to create misleading domains or filenames. Their goal is to trick users into interacting with malicious resources by making them appear legitimate or by impersonating trusted entities. Typosquatting typically involves registering domain names that closely resemble legitimate ones, often differing by only a few characters, whereas masquerading involves disguising malicious files. A few examples are provided below:

  • microsoft.com → micros0ft.com
  • svchost.exe → scvhost.exe
  • google.com → gooogle.com
  • explorer.exe → explrer.exe
  • paypal.com → pay-pal.com
  • winlogon.exe → winlogonn.exe
  • facebook.com → facebok.com
  • powershell.exe → powershel.exe
  • linkedin.com → linkdein.com
  • services.exe → servcies.exe

These examples show how attackers can make small changes to a legitimate domain name, such as microsoft.com, or filenames like svchost.exe, to create similar looking names.

Luckily for us, we spent all this effort creating the Levenshtein distance, OSA, and unrestricted Damerau–Levenshtein functions in the previous parts of this series, which we can now use to hunt for this kind of behavior. But before that, we’ll slightly modify the unrestricted Damerau–Levenshtein function to facilitate our investigation and threat hunts.

We are going to introduce two context columns to retain contextual information for each pair of words being compared. We’ll define CtxColumnC and CtxColumnD, whose values will be collected using make_set() for each unique (WordA, WordB) pair and returned alongside the calculated distance.

kusto

let DamerauLevenshteinUnrestricted = (tbl: (*), ColumnA: string, ColumnB: string, CtxColumnC: string, CtxColumnD: string) {
    let T = materialize(
        tbl
        | extend
            WordA = tostring(column_ifexists(ColumnA, "")),
            WordB = tostring(column_ifexists(ColumnB, "")),
            CtxC = tostring(column_ifexists(CtxColumnC, "")),
            CtxD = tostring(column_ifexists(CtxColumnD, ""))
        | summarize CtxC=make_set(CtxC), CtxD=make_set(CtxD) by WordA, WordB
    );
    T
    | serialize
    | extend _id = row_number()
    | extend LengthA = strlen(WordA)
    | extend LengthB = strlen(WordB)
    | mv-expand i = range(0, LengthA) to typeof(long)
    | mv-expand j = range(0, LengthB) to typeof(long)
    | sort by _id asc, i asc, j asc
    | scan declare (
        dl_matrix: dynamic = dynamic({}),
        da: dynamic = dynamic({}),
        db: long = 0
        )
    with (
        step s: true =>
        dl_matrix = bag_set_key(
            iff(i == 0 and j == 0, dynamic({}), s.dl_matrix),
            strcat(i, "_", j),
            case(
                i == 0, j,
                j == 0, i,
                min_of(
                    tolong(s.dl_matrix[strcat(i - 1, "_", j)]) + 1,
                    tolong(s.dl_matrix[strcat(i, "_", j - 1)]) + 1,
                    tolong(s.dl_matrix[strcat(i - 1, "_", j - 1)])
                    + iff(
                        substring(WordA, i - 1, 1)
                        == substring(WordB, j - 1, 1),
                        0,
                        1
                    ),
                    iff(
                        coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0) > 0 and s.db > 0,
                        tolong(
                            s.dl_matrix[strcat(
                                coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0) - 1,
                                "_",
                                s.db - 1
                            )]
                        )
                        + (i - coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0) - 1)
                        + 1
                        + (j - s.db - 1),
                        long(null)
                    )
                )
            )
        ),
        db = iff(
            j == 0,
            0,
            iff(
                i >= 1 and substring(WordA, i - 1, 1) == substring(WordB, j - 1, 1),
                j,
                s.db
            )
        ),
        da = iff(
            i == 0 and j == 0,
            dynamic({}),
            iff(
                j == LengthB and i >= 1,
                bag_set_key(s.da, substring(WordA, i - 1, 1), i),
                s.da
            )
        );
    )
    | where i == LengthA and j == LengthB
    | extend Distance = tolong(dl_matrix[strcat(LengthA, "_", LengthB)])
    | project
        WordA,
        WordB,
        Distance,
        CtxC,
        CtxD
};

Now that we’ve modified our function, let’s put it to use in a practical hunting scenario. Suppose we want to hunt for masqueraded filenames that resemble legitimate Windows executables, such as svchost.exe, powershell.exe, and notepad.exe.

We’ll start by querying the DeviceProcessEvents table to compare each observed filename against our list of known executables. After normalizing the filenames to lowercase, we’ll invoke our unrestricted Damerau–Levenshtein function to calculate the edit distance between each candidate and the observed filename. We are also going to collect the device name and folder path as additional context.

kusto

let filenames_to_hunt = dynamic([
    "svchost.exe",
    "powershell.exe",
    "notepad.exe"
]);
DeviceProcessEvents
| where TimeGenerated >= ago(7d)
| where ActionType == "ProcessCreated"
| extend filenames_to_hunt
| mv-expand filenames_to_hunt
| extend normalized_filename = tolower(FileName)
| invoke DamerauLevenshteinUnrestricted(ColumnA="filenames_to_hunt", ColumnB="normalized_filename", CtxColumnC="DeviceName", CtxColumnD="FolderPath")

Threat hunt results for masqueraded process names

Threat hunt results for masqueraded process names

We can further refine our hunt by filtering out legitimate execution locations, such as System32 and Program Files, to reduce noise from expected process activity. Applying these filters before invoking the function also improves performance, as there are fewer word pairs to evaluate.

We can then apply a distance threshold of less than or equal to 2, while excluding matches with a distance of 0, which indicates that the filenames are the same. These additional filters help narrow down the results, reduce noise, and bring potentially suspicious processes to the surface.

kusto

let filenames_to_hunt = dynamic([
    "svchost.exe",
    "powershell.exe",
    "notepad.exe"
]);
DeviceProcessEvents
| where TimeGenerated >= ago(7d)
| where ActionType == "ProcessCreated"
| extend filenames_to_hunt
| mv-expand filenames_to_hunt
| extend normalized_filename = tolower(FileName)
| where not (FolderPath has_any ("System32", "Program Files"))
| invoke DamerauLevenshteinUnrestricted(ColumnA="filenames_to_hunt", ColumnB="normalized_filename", CtxColumnC="DeviceName", CtxColumnD="FolderPath")
| where Distance <= 2 and Distance != 0

Finetuned threat hunt results for masqueraded process names

Finetuned threat hunt results for masqueraded process names

Similarly, let’s say we want to hunt for domains that impersonate well-known vendors such as Microsoft, Google, Apple, and Amazon. We’ll start by retrieving successful network connections from DeviceNetworkEvents. We’ll then parse the SLD and TLD of each request and compare the resulting domains against our predefined list of vendor domains using the unrestricted Damerau–Levenshtein function. For context we will retain the device name and account so we can investigate where these connections originated and which users were involved.

kusto

let vendor_domains = dynamic([
    "microsoft.com",
    "google.com",
    "apple.com",
    "amazon.com",
    "amazonaws.com",
    "facebook.com",
    "adobe.com"
]);
DeviceNetworkEvents
| where TimeGenerated >= ago(7d)
| where ActionType == "ConnectionSuccess"
| where isnotempty(RemoteUrl)
| extend ParsedDomain = tostring(
    parse_url(
        iff(RemoteUrl startswith "http://"
            or RemoteUrl startswith "https://",
            RemoteUrl,
            strcat("https://", RemoteUrl)
        )
    ).Host
)
| extend DomainParts = split(ParsedDomain, ".")
| extend SLD_TLD = strcat(tostring(DomainParts[-2]), ".", tostring(DomainParts[-1]))
| extend vendor_domains = vendor_domains
| mv-expand vendor_domains
| invoke DamerauLevenshteinUnrestricted(ColumnA="vendor_domains", ColumnB="SLD_TLD", CtxColumnC="DeviceName", CtxColumnD="InitiatingProcessAccountName")

Threat hunt results for typosquatted domains

Threat hunt results for typosquatted domains

By applying a distance filter to the results we can again limit the results to a minimum and identify potentially impersonating domains.

kusto

| where Distance == 1

Finetuned threat hunt results for typosquatted domains

Finetuned threat hunt results for typosquatted domains

While distance algorithms can be extremely useful for identifying suspicious variations, there are certain attack techniques and edge cases that they may not handle well.

This approach is not particularly effective against homoglyph attacks, where attackers replace characters with visually similar characters from different alphabets or character sets (e.g., replacing the Latin letter a with the Cyrillic letter а). Although the resulting strings may look identical or nearly identical to a human eye, the underlying characters are different. As a result, the Damerau–Levenshtein function may calculate a relatively large edit distance, even when the filenames or domains appear visually indistinguishable.

The screenshot below illustrates just that for a homoglyphed filename with 3 of each characters replaced.

Distance calculation for a homoglyph version of the svchost.exe process

Distance calculation for a homoglyph version of the svchost.exe process

This concludes our Levenshtein Distance mini-series. I particularly enjoyed writing this series.

Throughout this series, we’ve explored how Levenshtein distance, Optimal String Alignment (OSA), and unrestricted Damerau–Levenshtein distance can be implemented in KQL and applied to practical threat-hunting scenarios.

Of course, string distance alone is not enough to establish malicious intent. Ordinary typing mistakes and legitimate naming variations can also trigger suspicious matches. Distance thresholds should therefore be treated as an initial filtering mechanism rather than a verdict. Combining these findings with additional contextual information, such as execution paths, device names, user accounts, and prevalence, can help distinguish legitimate activity from genuinely suspicious behavior.

Hopefully, these functions will prove to be a useful addition to your detection and threat hunting capabilities.

Related Content