Input_Path_Not_Canonicalized - PathTravesal Vulnerability in checkmarx - path

I am facing path traversal vulnerability while analyzing code through checkmarx. I am fetching path with below code:
String path = System.getenv(variableName);
and "path" variable value is traversing through many functions and finally used in one function with below code snippet:
File file = new File(path);
Checkmarx is marking it as medium severity vulnerability.
Please help.
How to resolve it to make it compatible with checkmarx?

Other answers that I believe Checkmarx will accept as sanitizers include Path.normalize:
import java.nio.file.*;
String path = System.getenv(variableName);
Path p = Paths.get(path);
Path normalizedPath = p.normalize();
path = new File(normalizedPath.toString());
or the FilenameUtils.normalize method:
import org.apache.commons.io.FilenameUtils;
String path = System.getenv(variableName);
File file = new File(FilenameUtils.normalize(path));

You can generate canonicalized path by calling File.getCanonicalPath().
In your case:
String path = System.getenv(variableName);
path = new File(path).getCanonicalPath();
For more information read Java Doc

Related

How to read a file in src/main/resources in grails

This has been asked before, and I have tried each proposed solution, but all fail.
I have put a javascript file (hl.js) in myapp/src/main/resources
I have tried to read it with the following code taken from the "solutions":
1 - getRsourcesAsStream. returns null inputstream.
InputStream is = this.class.classLoader.getResourceAsStream("hl.js")
2 - getResource - returns null
File myFile = grailsApplication.mainContext.getResource("hl.js").file
3 - getResourceAsStream with classloader - returns null.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = classLoader.getResourceAsStream("hl.js");
Interestingly, if I do the following:
String fileNameAndPath = this.class.classLoader.getResource("hl.js").getFile()
System.out.println(fileNameAndPath);
File file = new File(fileNameAndPath)
InputStream is = file.newInputStream();
This prints out:
/Users/me/dev/grails_projects/myapp/src/main/resources/hl.js
But "is" is always null.
I an trying to get an input stream so I can evaluate the javascript via nashorn:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(is)
Grails 3.3.8
Any ideas?
Get the resource and open a stream on it.
def resource = this.class.classLoader.getResource('conf.json')
def path = resource.file // absolute file path
return resource.openStream() // input stream for the file
Source: https://www.damirscorner.com/blog/posts/20160313-AccessingApplicationFilesFromCodeInGrails.html
Well, I dont know why the solutions 1, 2 and 3 do not work, but I found a more long winded way which does work. The main issue is that there are lots of different implementations of eval(), and netbeans "go to declaration" has never worked (presumably some configuration issue in netbeans).
It turns out that the eval() version i happen to be using is expecting a Reader, where as the default documentation shows it needs in InputStream. Also, reader is not the same as InputStreamReader.
This is the solution I found:
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import org.grails.core.io.ResourceLocator
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String fileNameAndPath = this.class.classLoader.getResource("hl.js").getFile()
System.out.println(fileNameAndPath);
File file = new File(fileNameAndPath)
System.out.println("exists: " + file.exists())
Reader reader = file.newReader();
engine.eval(reader)

Absolute path on Xtext project

I wanted to know how I can get the absolute path of a file which is inside my project not in the application running.
For example this one:
C:\Users\Mr\Documents\Example\org.xtext.example.mydsl\src\example.txt
I have tried with paths like:
val file = new File("relative path");
val absolutePathString = file.getAbsolutePath();
or
System.getProperty("user.dir");
But all of them retrieves me Eclipse's path and not my project's path.
Thanks for the help!
There does not need to be a file. Assuming you have a default eclipse with default filesystem and talk about a file in a project you may have a look a at these
public void doit(Resource r) {
URI uri = r.getURI();
if (uri.isPlatformResource()) {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uri.toPlatformString(true)));
file.getLocation();
file.getLocationURI();
file.getRawLocation();
file.getRawLocationURI();
}
}

How do I copy DOORS modules between folders/projects using DXL?

I am new to both DOORS and DXL. I've been trying to copy a module in a project template to any given project folder using DXL, but my approaches haven't been working. Here's the part of my script where the copy and paste operations are attempted:
// Where string originalModule is the path to the module being copied.
// Where string targetPath is the path to where the copied module should be pasted.
ModName_ originalMMP = module(originalModule)
string originalMMPdesc = description(originalMMP)
clipCopy(originalMMP)
clipPaste(targetPath)
clipClear()
Whenever I run my script in the DOORS' DXL editor, I get an error indicating that the functions clipCopy() and clipPaste() have invalid arguments. In the DXL reference manual, it indicates that the type of the arguments should be of Item type, but I'm not totally sure I'm understanding that.
I have tried this other approach as well:
// The same conventions as above are used for the originalModule and targetPath
// string type variables.
// The variable string targetPathTemp contains the path to the replicated
// file New Module Temp
ModName_ originalMMP = module(originalModule)
string originalMMPdesc = description(originalMMP)
bool OK = copy(originalMMP,"New Module Temp", originalMMPdesc)
ModName_ newMMP = module(targetPathTemp)
// Moving and Renaming:
ErrMess = move(newMMP, targetPath)
ErrMess = rename(copiedMMP,newModuleName, originalMMPdesc)
I get the same errors as clipCopy() and clipPaste() for the functions: copy() and move().
Does anyone have any idea of what am I doing wrong, and what exactly am I not understanding?
Thanks in advance!
I think clipCopy and its brethren only work with Items. Use Item originalMMP = item(originalModule) instead of ModName_...

How to read file from an imported library

I have two packages: webserver and utils which provides assets to webserver.
The webserver needs access to static files inside utils. So I have this setup:
utils/
lib/
static.html
How can I access the static.html file in one of my dart scripts in webserver?
EDIT: What I tried so far, is to use mirrors to get the path of the library, and read it from there. The problem with that approach is, that if utils is included with package:, the url returned by currentMirrorSystem().findLibrary(#utils).uri is a package uri, that can't be transformed to an actual file entity.
Use the Resource class, a new class in Dart SDK 1.12.
Usage example:
var resource = new Resource('package:myapp/myfile.txt');
var contents = await resource.loadAsString();
print(contents);
This works on the VM, as of 1.12.
However, this doesn't directly address your need to get to the actual File entity, from a package: URI. Given the Resource class today, you'd have to route the bytes from loadAsString() into the HTTP server's Response object.
I tend to use Platform.script or mirrors to find the main package top folder (i.e. where pubspec.yaml is present) and find imported packages exported assets. I agree this is not a perfect solution but it works
import 'dart:io';
import 'package:path/path.dart';
String getProjectTopPath(String resolverPath) {
String dirPath = normalize(absolute(resolverPath));
while (true) {
// Find the project root path
if (new File(join(dirPath, "pubspec.yaml")).existsSync()) {
return dirPath;
}
String newDirPath = dirname(dirPath);
if (newDirPath == dirPath) {
throw new Exception("No project found for path '$resolverPath");
}
dirPath = newDirPath;
}
}
String getPackagesPath(String resolverPath) {
return join(getProjectTopPath(resolverPath), 'packages');
}
class _TestUtils {}
main(List<String> arguments) {
// User Platform.script - does not work in unit test
String currentScriptPath = Platform.script.toFilePath();
String packagesPath = getPackagesPath(currentScriptPath);
// Get your file using the package name and its relative path from the lib folder
String filePath = join(packagesPath, "utils", "static.html");
print(filePath);
// use mirror to find this file path
String thisFilePath = (reflectClass(_TestUtils).owner as LibraryMirror).uri.toString();
packagesPath = getPackagesPath(thisFilePath);
filePath = join(packagesPath, "utils", "static.html");
print(filePath);
}
To note that since recently Platform.script is not reliable in unit test when using the new test package so you might use the mirror tricks that I propose above and explained here: https://github.com/dart-lang/test/issues/110

resource file error no culture found

i have created a resource file "Resource.resx" in my project and added some values against some keys(string values) now when i try to access the value i get the following error...
Could not find any resources appropriate for the specified culture (or the neutral culture) on disk. baseName: Resource locationInfo: fileName: Resource.resources
im accessing the resource.resx by following code
string key = "Home";
string resourceValue = string.Empty;
string resourceFile = "Resource";//name of my resource file Resource.resx
string filePath =System.AppDomain.CurrentDomain.BaseDirectory.ToString();
ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
resourceValue = resourceManager.GetString(key);
im using mvc.net...
plz help
Why don't you use the class automatically generated by Visual Studio when you added the Resource.resx file (Resource.Designer.cs). This way you don't need to write all the code you wrote.
// assuming you've added a Home key in the resource file
string resourceValue = Resource.Home;

Resources