I have path Manipulation problem. The following code is placed in Page_load method of ASPx page.
String rName = Request.QueryString["reportName"];
string path = "C:\\hari" + rName;
if (File.Exists(path))
{
File.Delete(path);
}
But Fortify scan report for the above sample code shows ‘Path Manipulation’ issue as high
Need help to modify above code so that it can pass fortify scan
Jackson is right, this is a direct File Path Manipulation vulnerability that can be fixed through indirect selection.
From your known directory, list all the files. Use the value coming from your own directory list, not the user-supplied value.
String rName = Request.QueryString["reportName"];
String knownPath = "C:\\hari";
DirectoryInfo di = new DirectoryInfo(knownPath);
FileInfo[] files = di.GetFiles(rName);
if (files.length > 0)
{
files[0].Delete();
}
I think the problem is that someone could spoof a request with reportName = "..\\Windows\\Something important" which is clearly a security flaw. You need to change your code so that it doesn't read a partial filename from the request query string.
Related
I am trying to obtain the name of a file (JSON format but saved without an extension) within the last directory of a given path. Each file is saved with its own unique subpath inside the app's data container.
I also need to get the full path of the file, including the filename.
From what I've read, I believe it is better to use URLs to do this rather than using string paths.
I have tried the following code:
do {
let enumerator = FileManager.default.enumerator(at: filePath, includingPropertiesForKeys: nil)
while let element = enumerator?.nextObject() as? URL {
var nexObject = element.lastPathComponent
print(nextObject)
}
} catch let error {
print(error.localizedDescription)
}
This does seem to iterate through each level of the path until the end. Great, but what is the best way to get the full path, including the filename, other than concatenation of each object from the above?
All advice gratiously received. Thanks!
As element is an URL, if you're interested in the full path name rather than the last component, just go for:
var nextObject = element.absoluteURL // instead of .lastPathComponent
or just
var nextObject = element.path // or even relativePath
Thank you, #Christophe (+1)
I've also since spotted that the documentation for enumerator(at:includingPropertiesForKeys:options:errorHandler:) provides a nice example, which can be modifed for my purposes by using additional resource keys (e.g. name, path, etc.).
I'm doing some custom infrastructure for auto-generating specific bundles for individual views, and have a case where I need to get the Layout value for each view while iterating them as files.
I've tried var view = new RazorView(new ControllerContext(), actionView.FullName, null, true, null); but this is taking the LayoutPath as an input, and it is indeed resulting in an empty string on the LayoutPath property of the RazorView if I give null for that parameter, so it's not parsing the file for the value.
Could there be any other way to solve this in a similar manner, or would my best/only option be to just parse the text of the raw file (and _ViewStart)?
This is only done once at application start, so the performance is currently not an issue.
Alright, after a lot of source debugging and an epic battle with the internal access modifier, I have a working solution without having to render the whole page. I don't expect anyone else ever having the need for this, but anyway:
var httpContext = new HttpContextWrapper(new HttpContext(new HttpRequest("", "http://dummyurl", ""), new HttpResponse(new StreamWriter(new MemoryStream()))));
var page = Activator.CreateInstance(BuildManager.GetCompiledType(ReverseMapPath(actionView.FullName))) as WebViewPage;
page.Context = httpContext;
page.PushContext(new WebPageContext(), new StreamWriter(new MemoryStream()));
page.Execute();
var layoutFileFullName = page.Layout;
// If page does not have a Layout defined, search for _ViewStart
if (string.IsNullOrEmpty(layoutFileFullName))
{
page.VirtualPath = ReverseMapPath(actionView.FullName);
var startpage = StartPage.GetStartPage(page, "_ViewStart", new string[] {"cshtml"});
startpage.Execute();
layoutFileFullName = startpage.Layout;
}
Tada!
Ps. ReverseMapPath is a any arbitrary function to resolve the relative path of a full file name, see for example Getting relative virtual path from physical path
I am using
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = res.getPath();
String path2 = path.substring(1);
because the output of the method getPath() returns sth like this:
/C:/Users/......
and I need this
C:/Users....
I really need the below address because some external library refuses to work with the slash at the beginning or with file:/ at the beginning or anything else.
I tried pretty much all the methods in URL like toString() toExternalPath() etc. and done the same with URI and none of it returns it like I need it. (I totally don't understand, why it keeps the slash at the beginning).
It is okay to do it on my machine with just erasing the first char. But a friend tried to run it on linux and since the addresses are different there, it does not work...
What should with such problem?
Convert the URL to a URI and use that in the File constructor:
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
File file = new File(res.toURI());
String fileName = file.getPath();
As long as UNIX paths are not supposed to contain drive letters, you may try this:
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = res.getPath();
char a_char = text.charAt(2);
if (a_char==':') path = path.substring(1);
Convert to a URI, then use Paths.get().
URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = Paths.get(res.toURI()).toString();
You could probably just format the string once you get it.
something like this:
path2= path2[1:];
I was searching for one-line solution, so the best what i came up with was deleting it manually like this:
String url = this.getClass().getClassLoader().getResource(dictionaryPath).getPath().replaceFirst("/","");
In case if someone also needs to have it on different OS, you can make IF statement with
System.getProperty("os.name");
I have an XML as input to a Java function that parses it and produces an output. Somewhere in the XML there is the word "stratégie". The output is "stratgie". How should I parse the XML as to get the "é" character as well?
The XML is not produced by myself, I get it as a response from a web service and I am positive that "stratégie" is included in it as "stratégie".
In the parser, I have:
public List<Item> GetItems(InputStream stream) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("item");
List<Item> items = new ArrayList<Item>();
Item currentItem = new Item();
Node node = nodeLst.item(0);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element item = (Element) node;
if(node.getChildNodes().getLength()==0){
return null;
}
NodeList title = item.getElementsByTagName("title");
Element titleElmnt = (Element) title.item(0);
if (null != titleElmnt)
currentItem.setTitle(titleElmnt.getChildNodes().item(0).getNodeValue());
....
Using the debugger, I can see that titleElmnt.getChildNodes().item(0).getNodeValue() is "stratgie" (without the é).
Thank you for your help.
I strongly suspect that either you're parsing it incorrectly or (rather more likely) it's just not being displayed properly. You haven't really told us anything about the code or how you're using the result, which makes it hard to give very concrete advice.
As ever with encoding issues, the first thing to do is work out exactly where data is getting lost. Lots of logging tends to be the way forward: create a small test case that demonstrates the problem (as small as you can get away with) and log everything about the data. Don't just try to log it as raw text: log the Unicode value of each character. That way your log will have all the information even if there are problems with the font or encoding you use to view the log.
The answer was here: http://www.yagudaev.com/programming/java/7-jsp-escaping-html
You can either use utf-8 and have the 'é' char in your document instead of é, or you need to have a parser that understand this entity which exists in HTML and XHTML and maybe other XML dialects but not in pure XML : in pure XML there's "only" ", <, > and maybe ' I don't remember.
Maybe you can need to specify those special-char entities in your DTD or XML Schema (I don't know which one you use) and tell your parser about it.
I have a database file that I beleive was created with Clipper but can't say for sure (I have .ntx files for indexes which I understand is what Clipper uses). I am trying to create a C# application that will read this database using the System.Data.OleDB namespace.
For the most part I can sucessfully read the contents of the tables there is one field that I cannot. This field called CTRLNUMS that is defined as a CHAR(750). I have read various articles found through Google searches that suggest field larger than 255 chars have to be read through a different process than the normal assignment to a string variable. So far I have not been successful in an approach that I have found.
The following is a sample code snippet I am using to read the table and includes two options I used to read the CTRLNUMS field. Both options resulted in 238 characters being returned even though there is 750 characters stored in the field.
Here is my connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\datadir;Extended Properties=DBASE IV;
Can anyone tell me the secret to reading larger fields from a DBF file?
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = string.Format("SELECT ITEM,CTRLNUMS FROM STUFF WHERE ITEM = '{0}'", stuffId);
using (OleDbDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
stuff.StuffId = dr["ITEM"].ToString();
// OPTION 1
string ctrlNums = dr["CTRLNUMS"].ToString();
// OPTION 2
char[] buffer = new char[750];
int index = 0;
int readSize = 5;
while (index < 750)
{
long charsRead = dr.GetChars(dr.GetOrdinal("CTRLNUMS"), index, buffer, index, readSize);
index += (int)charsRead;
if (charsRead < readSize)
{
break;
}
}
}
}
}
}
You can find a description of the DBF structure here: http://www.dbf2002.com/dbf-file-format.html
What I think Clipper used to do was modify the Field structure so that, in Character fields, the Decimal Places held the high-order byte of the size, so Character field sizes were really 256*Decimals+Size.
I may have a C# class that reads dbfs (natively, not ADO/DAO), it could be modified to handle this case. Let me know if you're interested.
Are you still looking for an answer? Is this a one-off job or something that needs doing regularly?
I have a Python module that is primarily intended to extract data from all kinds of DBF files ... it doesn't yet handle the length_high_byte = decimal_places hack, but it's a trivial change. I'd be quite happy to (a) share this with you and/or (b) get a copy of such a DBF file for testing.
Added later: Extended-length feature added, and tested against files I've created myself. Offer to share code with anyone who would like to test it still stands. Still interested in getting some "real" files myself for testing.
3 suggestions that might be worth a shot...
1 - use Access to create a linked table to the DBF file, then use .Net to hit the table in the access database instead of going direct to the DBF.
2 - try the FoxPro OLEDB provider
3 - parse the DBF file by hand. Example is here.
My guess is that #1 should work the easiest, and #3 will give you the opportunity to fine tune your cussing skills. :)