Skip to content

Commit

Permalink
Fixed locations for directories
Browse files Browse the repository at this point in the history
Set the location for created directories to be relative to the chroot directory instead of the home directory.
The user is now set as an owner on the first parent of directories relative to the chroot. (Ex: for "sftp/subdirectory" the user is now the owner of "sftp" recursively).
  • Loading branch information
winromulus committed Feb 19, 2020
1 parent b2d8448 commit 04cf3ba
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions ES.SFTP.Host/Orchestrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -348,26 +348,43 @@ private async Task PrepareUserForSftp(string username)
await ProcessUtil.QuickRun("chmod", $"700 {homeDirPath}");

var chroot = user.Chroot ?? _config.Global.Chroot;

//Parse chroot path by replacing markers
var chrootPath = string.Join("%%h",
chroot.Directory.Split("%%h").Select(s => s.Replace("%h", homeDirPath)).ToList());
chrootPath = string.Join("%%u",
chrootPath.Split("%%u").Select(s => s.Replace("%u", username)).ToList());

//Create chroot directory and set owner to root and correct permissions
if (!Directory.Exists(chrootPath)) Directory.CreateDirectory(chrootPath);
await ProcessUtil.QuickRun("chown", $"root:root {chrootPath}");
await ProcessUtil.QuickRun("chmod", $"755 {chrootPath}");

var chrootDirectory = new DirectoryInfo(chrootPath);

var directories = new List<string>();
directories.AddRange(_config.Global.Directories);
directories.AddRange(user.Directories);
foreach (var directory in directories.Distinct().OrderBy(s => s).ToList())
{
var dirPath = Path.Combine(homeDirPath, directory);
var dirPath = Path.Combine(chrootDirectory.FullName, directory);
if (!Directory.Exists(dirPath))
{
_logger.LogDebug("Creating directory '{dir}' for user '{user}'", dirPath, username);
Directory.CreateDirectory(dirPath);
}

await ProcessUtil.QuickRun("chown", $"-R {username}:{SftpUserInventoryGroup} {dirPath}");
var directoryInfo = new DirectoryInfo(dirPath);

var firstParentInChroot = directoryInfo.Parent ?? chrootDirectory;
while ((firstParentInChroot.Parent ??
throw new InvalidOperationException("Cannot find first parent in chroot")).FullName !=
chrootDirectory.FullName)
{
firstParentInChroot = firstParentInChroot.Parent;
}

await ProcessUtil.QuickRun("chown", $"-R {username}:{SftpUserInventoryGroup} {firstParentInChroot.FullName}");
}

var sshDir = Path.Combine(homeDirPath, ".ssh");
Expand Down

0 comments on commit 04cf3ba

Please sign in to comment.