Ajay
Ajay

Reputation: 18411

How to hide password in logging

I'm printing command line arguments this way:

static void LogParameters(string[] args)
{
    Console.WriteLine("Command line parameters: {0}", string.Join(" ", args);
}

Which will print -username=Scott -password=cafebabe -nofail. But I would like to print it as:

-username=Scott -password=******* -nofail

How do I make that anything appears after password= for this argument is printed with asterisks?

Upvotes: 3

Views: 4543

Answers (3)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

I see two obvious ways to do this:

  1. Iterate through your args array, find password argument manually and mask password
  2. Combine arguments into a string and replace password using regular expressions

I would prefer the first one, using LINQ:

var argsForLogging = args
    .Select(arg => arg.StartsWith("-password=") ? "-password=(entered)" : arg);

Console.WriteLine("Command line parameters: {0}", string.Join(" ", argsForLogging));

It may look not that good, but it is easily readable, and there are no regular expressions :)

P.S. It is possible to make the code output not (entered), but as many asterisks as there are letters in a password. However, it would still disclose very sensitive information.

Update: If arguments format is not strict, then you need to take this into account.
For example, if it should be case-insensitive, then you may want to use this approach:

var argsForLogging = args
    .Select(arg => arg.Trim().StartsWith("-password=", true, CultureInfo.InvariantCulture) 
        ? "-password=(entered)" 
        : arg);

Console.WriteLine("Command line parameters: {0}", string.Join(" ", argsForLogging));

Upvotes: 3

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26199

static void LogParameters(string[] args)
{
    string msg = string.Empty;
    foreach(var item in args)
    {
        var subParts = item.Split(new[] { '=' },  
                       StringSplitOptions.RemoveEmptyEntries);
        if (subParts[0] != "-password")
            msg += item + " ";
        else
            msg += subParts[0] + "****** ";
    }
   Console.WriteLine("Command line parameters: {0}",msg.TrimEnd());
}

Upvotes: 1

Alper Şaldırak
Alper Şaldırak

Reputation: 1054

Normally

String maskString = String.Empty;
    String replaceString = "-password=";
    foreach (var item in args)
    {
        if (item.IndexOf(replaceString) >= 0)
        {
            maskString += replaceString + "********* ";
        }
        else
        {
            maskString += item+" ";
        }
    }
    Console.WriteLine("Command line parameters: {0}", maskString.TrimEnd());

Or LinQ

var argsForLogging = args
 .Select(arg => arg.StartsWith("-password=") ? "-password=*********" : arg);

 Console.WriteLine("Command line parameters: {0}", string.Join(" ", argsForLogging));

Upvotes: 2

Related Questions