I'm using configuration manager in the simplest way:
Read:
ConfigurationManager.AppSettings["Foo"]
Write:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Foo"].Value = value;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
The problem is that after installing the application on different machines - some are looking for the file: "My.Application.exe.config"
while others look for "My.Application.config" (same, w/o the ".exe")
Another interesting detail is that after installing VS on the problematic machines - it works ok.
And my question is: Ah?!!?
Any ideas?
Thanks for the responses, your links were very helpful.
Since this is a .NET issue (as described in the links above), I tackled it from a different angle than suggested:
Since my configuration file is vast and demands both read and write operations, i'm using a special class to handle it - configurationFileHelper.
What I did was adding a static constructor to this class, in which i'm inquiring the expected name for the file, and, if necessary, renaming the existing file to match it:
static configurationFileHelper()
{
try
{
string fullFilename = Application.ProductName + ".exe.config";
string expectedFilename = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath;
if (!File.Exists(expectedFilename) && (File.Exists(fullFilename))
File.Move(fullFilename, expectedFilename);
}
catch { ; }
}
Hope this is helpful to someone...
Related
I have been problem to solve an appointment of Veracode Scanner in my project. I created a function to validate a file but it did not pass in veracode scanner;
Here is the code of my function:
public static string GetSafeFileName(string fileNameToValidate)
{
fileNameToValidate= fileNameToValidate.Replace("'", "''").Replace(#"../", "").Replace(#"..\", "");
char[] blackListChars = System.IO.Path.GetInvalidPathChars();
char[] blackListFilename = System.IO.Path.GetInvalidFileNameChars();
foreach (var invalidChar in blackListChars)
{
if (fileNameToValidate.Contains(invalidChar))
{
fileNameToValidate = fileNameToValidate.Replace(invalidChar, ' ').Trim();
}
}
string fullPath = Path.GetFullPath(fileNameToValidate);
string directoryName = Path.GetDirectoryName(fullPath);
string fileName = Path.GetFileName(fullPath);
foreach (var invalidChar in blackListFilename)
{
if (fileName.Contains(invalidChar))
{
fileName = fileName.Replace(invalidChar, ' ').Trim();
}
}
string finalPath = Path.Combine(directoryName, fileName);
return finalPath;
}
What are the changes i have to fix the cwe 73 appointment in Veracode scanner? Anybody can help me?
My project is a windows forms running on .net 4.0
Thanks,
Bruno
Your problem is that Veracode doesn't actually detect what your code is doing, it detects what cleanser function is (or is not) being called. If you login to Veracode and search for help on "Supported Cleansing Functions" you'll find the list that are detected in your language.
Unfortunately, the list for .Net doesn't include anything for a CWE-73.
So, your solution is to specifically label your function as a cleanser for CWE-73 using a custom cleanser annotation. Search Veracode help for "Annotating Custom Cleansers".
using Veracode.Attributes;
[FilePathCleanser]
public static string GetSafeFileName(string fileNameToValidate)
{
...
That said, your implementation is not secure. Try passing in "C:\Windows\System32\notepad.exe" as a filename to be written to and you'll see the problem.
Blacklisting can only deal with what you expect. Whitelisting is a much stronger approach. Your approach should be based on a whitelist of directories, a whitelist of characters for filenames, and a whitelist of file extensions.
I have tried to solve similar problem but in java context. We used ESAPI as external library. You can review esapi project (for ideas how to realise a better solution in your project):https://github.com/ESAPI/esapi-java-legacy
Actually using esapi validator didn't solve the problem with veracode, but in my opinion reduce the risk for attack. With such a library you can enshure that user can't read file out of parent folder(you must hardcode such a directory) and that the user can't read a file with unproper extension -> you can add such a list with file extensions. But this library cant garantee that you can't manipulate files in the parent directory with allowed extensions.
So if you think that all needed verifications of filepaths are done you must ask for mitigation by design or develope a Map with all needed file resources in the project to enshure that there is no way the user to manipulate external files.
Also if you think that you have created a good filepath verification you can use cleanser annotation to mark your method. Here you can read more about custom cleansers
https://help.veracode.com/reader/DGHxSJy3Gn3gtuSIN2jkRQ/xrEjru~XmUHpO6~0FSae2Q
On Windows, I have a C# assembly that is COM visible. It references other assemblies to control an application in the machine. It works fine.
However, under Apache Web Server and using CGI, it doesn't work. After doing some debuging, I found out that the problem is that, while running under Apache's CGI, the environment variables SYSTEMROOT and SYSTEMDRIVE, which aparently are needed by the referenced assemblies, are not loaded.
I can configure Apache to pass those environemtn variables too, but before doing so, I'd really like to know if there's some command I can put on my C# COM visible assembly to make it load environment variables as if it was, let's say, the SYSTEM user or something like that, so it doesn't have to relay on the environment passed by the starting application.
How do you force loading an existent system environment variable in C#, when IT IS NOT SET in the current process (or it was process-deleted by the launching process)?
Thanks in advance for any suggestions!
EDIT 1 - ADDED INFO: Just to make it more clear (as I see in the current answers it's not so clear): Apache intendedly deletes a lot of environment variables for CGI processes. It's not that Apache cannot see them, it can, but it won't pass them to CGI processes.
This should do the trick:
Environment.GetEnvironmentVariable("variable", EnvironmentVariableTarget.Machine);
I did a small test and it is working:
//has the value
string a = Environment.GetEnvironmentVariable("TMP");
Environment.SetEnvironmentVariable("TMP", null);
//does not have has the value
a = Environment.GetEnvironmentVariable("TMP");
//has the value
a = Environment.GetEnvironmentVariable("TMP", EnvironmentVariableTarget.Machine);
SOLUTION: Marco's answer was great and technically answered my question - except that I found out that the environment variables SYSTEMROOT and SYSTEMDRIVE are not really set in the registry where all environment variables are set, so, the chosen answer works for all variables except those two, which I specified in the OP.
SYSTEMROOT is defined on the registry in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRoot, and apparently (after more research), SYSTEMDRIVE is generated as a substring of SYSTEMDRIVE.
So, to get SYSTEMDRIVE and SYSTEMROOT from registry and load them into the environment:
using Microsoft.Win32;
namespace MySpace
{
public class Setup
{
public Setup()
{
SetUpEnvironment();
}
private void SetUpEnvironment()
{
string test_a = Environment.GetEnvironmentVariable("SYSTEMDRIVE", EnvironmentVariableTarget.Process);
string test_b = Environment.GetEnvironmentVariable("SYSTEMROOT", EnvironmentVariableTarget.Process);
if (test_a == null || test_a.Length == 0 || test_b == null || test_b.Length == 0)
{
string RegistryPath = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
string SYSTEMROOT = (string) Registry.GetValue(RegistryPath, "SystemRoot", null);
if (SYSTEMROOT == null)
{
throw new System.ApplicationException("Cannot access registry key " + RegistryPath);
}
string SYSTEMDRIVE = SYSTEMROOT.Substring(0, SYSTEMROOT.IndexOf(':') + 1);
Environment.SetEnvironmentVariable("SYSTEMROOT", SYSTEMROOT, EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("SYSTEMDRIVE", SYSTEMDRIVE, EnvironmentVariableTarget.Process);
}
}
}
}
Then you can just call Setup setup = new Setup(); from other classes. And that's it. :-)
Environment.GetEnvironmentVariable
see reference here.
e.g.
Environment.CurrentDirectory = Environment.GetEnvironmentVariable("windir");
DirectoryInfo info = new DirectoryInfo(".");
lock(info)
{
Console.WriteLine("Directory Info: "+info.FullName);
}
Are the variables set as system wide?
If they are not, that is what you need to do, otherwise create user variables for the user the COM is running under.
Thank you. I cannot state with any certainty that this has once and for all driven a stake through the heart of the vampire, but amazingly enough, the error has disappeared (for now). The odd thing is that access to the statement
Environment.GetEnvironmentVariable("variable", EnvironmentVariableTarget.Machine);
is a real oddity in the debugger. It does not show up in Intellisense and does not even appear to fire, which leads me to suspect, which you all knew already, that this is some sort of magic runtime object Environment that has no instantiation in the debugger but also can be benignly jumped over. Oh well.
Oh and I should mention that after you see that error, you will note oddities in your Windows OS, which is worrisome. In particular, you will see, if you try to use the Control Panel /System/Advanced Properties (whatever) that it cannot load the dialog for the environment variables any more, indicating that %windir% has been seriously hosed (compromised) across all applications. Bad bad bad....
I have spent quite a while trying to solve this problem, but to no avail. I have searched stackoverflow as well as Google and have not been able to resolve my (seemingly) simple problem.
I am getting a FileNotFoundException in the following line:
Image.FromFile("\\Resources\\Icons\\key-icon.png");
The folders and image are really there, and I can't see what the problem is.
You should consider that it is started from "yourproject/bin/Release" so you need to go up 2 directories. Do this:
Image.FromFile("..\\..\\Resources\\Icons\\key-icon.png");
Try using an absolute path not a relative one... i.e.
Image.FromFile(Server.MapPath(#"~\Resources\Icons\key-icon.png"));
Image.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
#"Resources\\Icons\\key-icon.png"))
Base-directory Combine your file-name
You may be missing a leading ".":
Image.FromFile(".\\Resources\\Icons\\key-icon.png");
Internally, Image.FromFile uses File.Exists to check whether the file exists. This method returns false when:
the file does not exist (makes sense)
the current process identity does not have permission to read the file
It may be that the second option is your problem.
And another possibility: is Resources a network share? In that case you should use the following:
Image.FromFile("\\\\Resources\\Icons\\key-icon.png");
For this case I discovered that sikuli does not automatically detect the root folder of the project. What you should do for this case is specify the folder using the command System.getProperty("user.dir");
import org.sikuli.script.*;
public class Test {
public static void main(String[] args) {
Screen s = new Screen();
try{
String pathYourSystem = System.getProperty("user.dir") + "\\";
s.click(pathYourSystem + "imgs/spotlight.png");
//s.wait(pathYourSystem + "imgs/spotlight-input.png");
//s.click();
s.write("hello world#ENTER.");
}
catch(FindFailed e){
e.printStackTrace();
}
}
}
I want to get the path and version number of a ClickOnce application, provided the name of the ClickOnce application.
When I manually searched for it, I found it at the path as follows:
'C:\Users\krishnaim\AppData\Local\Apps\2.0\1HCG3KL0.K41\VO5BM4JR.RPO\head..tion_7446cb71d1187222_0005.0037_37dfcf0728461a82\HeadCount.exe'
But this keeps on changing, and it will become a hard-coded path. Is there another way to get a ClickOnce application (for example, HeadCount.exe which is already installed) path and version number using C#/.NET code?
It seems a little bizarre, but getting the current directory of the executing assembly is a bit tricky so my code below may be doing more than you think it should, but I assure you it is mitigating some issues where others may attempt to use Assembly.GetExecutingAssembly.Location property.
static public string AssemblyDirectory
{
get
{
//Don't use Assembly.GetExecutingAssembly().Location, instead use the CodeBase property
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return System.IO.Path.GetDirectoryName(path);
}
}
static public string AssemblyVersion
{
get
{
var asm = Assembly.GetExecutingAssembly();
//If you want the full four-part version number:
return asm.GetName().Version.ToString(4);
//You can reference asm.GetName().Version to get Major, Minor, MajorRevision, MinorRevision
//components individually and do with them as you please.
}
}
In order to do a ClickOnce application update you do not have to do so manually as long as you are using the standard deployment manifests (which I don't know how to ClickOnce unless you do use them).
The MSDN article Choosing a ClickOnce Update Strategy describes the different options for application updates.
I've got the function for changing the values in web.config
but my problem is it is not getting the path of web.config correctly and throwing
"Could not find file 'C:\Users\maxnet25\Web.config'"
It was giving error on xmlDoc.Load() function.
My code:
public void UpdateConfigKey(string strKey, string newValue)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Web.config");
if (!ConfigKeyExists(strKey))
{
throw new ArgumentNullException("Key", "<" + strKey + "> not find in the configuration.");
}
XmlNode appSettingsNode = xmlDoc.SelectSingleNode("configuration/appSettings");
foreach (XmlNode childNode in appSettingsNode)
{
if (childNode.Attributes["key"].Value == strKey)
childNode.Attributes["value"].Value = newValue;
}
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Web.config");
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
Label1 .Text ="Key Upated Successfullly";
}
What error messsage is being given?
Either way, you're not really going about modifying web.config in the right way. You should probably take a look at the System.Configuration.ConfigurationManager class as this provides programmatic access to the web.config file in a structured manner. Note that to access this class you need to add a reference to System.Configuration.dll to your project to bring the ConfigurationManager into scope.
If you look at the example code for the GetSection method, it shows how to create/add settings in the appSettings section of a .net config file, so that example should be enough to get you where you want to go.
If you definately want to use this approach to manipulate your web.config file, I suspect that:
AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Web.config")
is incorrect, based on the path that you've shown in the error message. Try removing the ..\..\ and seeing if that works. AppDomain.CurrentDomain.BaseDirectory should be pointing at the location of your web.config file without modification.
Assuming this is indeed an ASP.NET website, instead of this:
AppDomain.CurrentDomain.BaseDirectory + "..\\..\\Web.config"
Use this:
HttpContext.Current.Server.MapPath("~/Web.config")
On a side note, please be aware that anytime you make a change to web.config, your web application restarts. You might not need to worry about that depending on what your web app does though.
Try using Server.MapPath() to resolve the location of your web.config. If you're in a page, Server is one of the page properties. If not, you can find it in HttpContext.Current.
As an example...
HttpContext.Current.Server.MapPath("~/web.config")
...should return the physical path to the web.config at the top of your web application.
Now, you're probably much better off using the WebConfigurationManager, as shown in this post. The approach is much cleaner, but requires a reference to System.Configuration.
Have you added a web.config to your web site?
You should use either:
System.Configuration.ConfigurationManager
for app.config files, or:
System.Web.Configuration.WebConfigurationManager
for web.config files.
You can actually use System.Configuration.ConfigurationManager with web.config files as well, and to be honest, I'm not actually sure if there's any benefit for using one over the other.
But either way, you should not be using the Xml namespaces and writing/modifying the raw XML.