I try to avoid keeping passwords etc. in memory or in plain text anywhere. But I am on a huge time crunch and this will only be used internally this week then probably won't get touched again. I just want to make sure this is secure and if not, what the risk is.
I'm mostly concerned about the password sitting in memory. I'm not sanitizing data but for this particular case it isn't needed.
My specific questions are:
From a security perspective, would this code be acceptable in a SQL Importer?
Besides data sanitation, is there a best practice somewhere that I'm missing in this?
Console.WriteLine("Enter the Server Name. Ex: SQLMASTER"); //Gets the server to connect to, an IP address is also acceptable.
ServerName = Console.ReadLine();
Console.WriteLine("Enter the Database. Ex: Accounts"); //The actual database to use.
DatabaseName = Console.ReadLine();
Console.WriteLine("Use Windows authentication? Y/N"); //you will usually use this.
YesNo = Console.ReadLine();
if (YesNo.ToLower() != "y")
{
Console.WriteLine("Enter your Username (Domain name may be required). Ex: MyName");
UserName = Console.ReadLine();
Console.WriteLine("Enter your Password. Ex: ********");
Password = ReadPassword();
//Builds the connection string with the data we collected above. We're going to send this to the SQL Connection. (Username and Password)
ConnectionString = "Data Source = " + ServerName + "; Initial Catalog = " + DatabaseName + "; User ID = " + UserName + "; Password = " + Password;
Password = ""; //We do this to clear the password from memory
UserName = ""; //Clearing username from memory
}
else
{
//Builds the connection string with the data we collected above. We're going to send this to the SQL Connection. (Windows Authentication)
ConnectionString = "Data Source = " + ServerName + "; Initial Catalog = " + DatabaseName + "; Integrated Security=SSPI"; //User ID = " + UserName + "; Password = " + Password;
}
//Create a new connection with above connection string
SQLCon = new SqlConnection(ConnectionString);
ConnectionString = ""; //Again, doing this to purge the credentials from memory
try
{
SQLCon.Open();
Console.WriteLine("\nConnected!\n");
Console.WriteLine("Working...\n");
.... etc
}
catch (Exception ex)
{
MessageBox.Show("Failed! See console for details");
Console.WriteLine(ex.Message);
}
Password
property -- it doesn't actually remove that string from memory. Storing it as a char array and overwriting each index might be better in that regard but you still have to turn it into a string anyway. Long story short: focus on actually important things, this is pointless. – Jeroen Vannevel 17 hours ago