I have a section of code that uses the StreamWriter.WriteLine method to write a message to a file. When checking for Vulnerabilities I am informed that system data information by calling WriteLine() could leak information to an attacker. What I did was attempted to use a regular expression to validate the text being written in hopes that it might prevent this from happening. My code is below which protects nothing. If anyone can help that would be great.

    public void WriteErrorLog(Exception ex)
    {
        FileStream fs;
        StringBuilder errorMessage = new StringBuilder();
        string currentYear = DateTime.Now.Year.ToString();
        string currentMonth = DateTime.Now.Month.ToString();
        string rootPath = HttpContext.Current.Server.MapPath("~");
        string logPath = rootPath + @"logs" + Convert.ToString(Path.DirectorySeparatorChar);
        string fileName = "Error_" + currentYear + "-" + currentMonth + ".log";
        string filePath = logPath + fileName;
        errorMessage.AppendLine(DateTime.Now.ToString());
        errorMessage.AppendLine(GetErrorMessage(ex));

        if (!Directory.Exists(logPath)) { DirectoryInfo di = Directory.CreateDirectory(logPath); }
        if (!File.Exists(filePath)) { fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); fs.Close(); }
        fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
        using (StreamWriter sw = new StreamWriter(fs))
        {
            if (!Regex.IsMatch(errorMessage.ToString(),
               @"^[\w\s+/-/./:/-]+$"))
            {
                sw.WriteLine(errorMessage.ToString());
            }
        }
    }

Related posts

Recent Viewed