Alexis Peters
Alexis Peters

Reputation: 1631

Check if directory is a subdirectory of specific directory

I'm currently developing a Web-App with an SSH-Connection.

One Task is that I need to validate if a directory is below the htdocs-dir of the current user.

Until now, what I did is checking the directory-string for having the htdocs-part at the beginning of the string. Like

"/var/users/user/htdocs" is in front of "/var/users/user/htdocs/testDir"

Now i was penetration-testing this and inputted

"/var/users/user/htdocs/testDir/../../../".

Here's the problem. how can i Check if a Directory is a subdirectory of n-th level of the other directory

Upvotes: 2

Views: 102

Answers (3)

Peter Andreus
Peter Andreus

Reputation: 98

I would use

find /var/users/user/htdocs -path $(readlink -m /var/users/user/htdocs/testDir/../../../)

Upvotes: 2

Julien Lopez
Julien Lopez

Reputation: 1854

You can use realpath:

find /var/users -path `realpath /var/users/user/htdocs/testDir/../..`

Plus, it will work with relative paths as well:

find `realpath dir` -path `realpath dir/htdocs/testDir/..`

Upvotes: 1

unconditional
unconditional

Reputation: 7666

You can use readlink to get the actual resulting path:

mybox\> readlink -m /var/users/user/htdocs/testDir/../../../    
/var/users

Upvotes: 1

Related Questions