|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Diagnostics.CodeAnalysis; |
| 5 | +using System.IO; |
| 6 | +using System.Runtime.InteropServices; |
| 7 | + |
| 8 | +namespace Microsoft.SemanticKernel; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Provides utility methods for secure path resolution, including symbolic link handling. |
| 12 | +/// </summary> |
| 13 | +[ExcludeFromCodeCoverage] |
| 14 | +internal static class PathUtilities |
| 15 | +{ |
| 16 | + internal static StringComparison PathComparison { get; } = |
| 17 | + RuntimeInformation.IsOSPlatform(OSPlatform.Windows) |
| 18 | + ? StringComparison.OrdinalIgnoreCase |
| 19 | + : StringComparison.Ordinal; |
| 20 | + |
| 21 | + /// <summary> |
| 22 | + /// Returns the canonical full path for <paramref name="path"/> with symbolic links handled safely. |
| 23 | + /// On .NET 6 and later, symbolic links are resolved to their final target. On older frameworks, |
| 24 | + /// where links cannot be resolved safely, any path containing a symbolic link is rejected. |
| 25 | + /// </summary> |
| 26 | + /// <param name="path">The path to canonicalize.</param> |
| 27 | + /// <returns>The fully resolved canonical path.</returns> |
| 28 | + /// <exception cref="InvalidOperationException"> |
| 29 | + /// On frameworks older than .NET 6, thrown if the path contains a symbolic link. |
| 30 | + /// </exception> |
| 31 | + internal static string GetSafeFullPath(string path) |
| 32 | + { |
| 33 | + var fullPath = Path.GetFullPath(path); |
| 34 | + |
| 35 | +#if NET6_0_OR_GREATER |
| 36 | + return ResolveExistingSegments(fullPath); |
| 37 | +#else |
| 38 | + ThrowIfPathContainsReparsePoint(fullPath); |
| 39 | + return fullPath; |
| 40 | +#endif |
| 41 | + } |
| 42 | + |
| 43 | +#if NET6_0_OR_GREATER |
| 44 | + private static string ResolveExistingSegments(string fullPath) |
| 45 | + { |
| 46 | + var root = Path.GetPathRoot(fullPath) ?? string.Empty; |
| 47 | + return ResolveSegments(root, GetSegmentsAfterRoot(fullPath, root)); |
| 48 | + } |
| 49 | + |
| 50 | + private static string ResolveSegments(string basePath, string[] segments) |
| 51 | + { |
| 52 | + var resolvedPath = basePath; |
| 53 | + for (var i = 0; i < segments.Length; i++) |
| 54 | + { |
| 55 | + var candidatePath = CombinePath(resolvedPath, segments[i]); |
| 56 | + |
| 57 | + if (!TryGetFileSystemInfo(candidatePath, out var fileSystemInfo)) |
| 58 | + { |
| 59 | + return CombineRemainingPath(candidatePath, segments, i + 1); |
| 60 | + } |
| 61 | + |
| 62 | + var linkTarget = ResolveLinkTarget(fileSystemInfo); |
| 63 | + if (linkTarget is not null) |
| 64 | + { |
| 65 | + // The link target may itself contain unresolved symbolic links, |
| 66 | + // so canonicalize it before continuing with the remaining segments. |
| 67 | + resolvedPath = ResolveExistingSegments(linkTarget); |
| 68 | + } |
| 69 | + else |
| 70 | + { |
| 71 | + resolvedPath = candidatePath; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return resolvedPath; |
| 76 | + } |
| 77 | + |
| 78 | + private static bool TryGetFileSystemInfo(string path, [NotNullWhen(true)] out FileSystemInfo? fileSystemInfo) |
| 79 | + { |
| 80 | + if (!TryGetAttributes(path, out var attributes)) |
| 81 | + { |
| 82 | + fileSystemInfo = null; |
| 83 | + return false; |
| 84 | + } |
| 85 | + |
| 86 | + fileSystemInfo = (attributes & FileAttributes.Directory) != 0 |
| 87 | + ? new DirectoryInfo(path) |
| 88 | + : new FileInfo(path); |
| 89 | + return true; |
| 90 | + } |
| 91 | + |
| 92 | + private static string? ResolveLinkTarget(FileSystemInfo fileSystemInfo) |
| 93 | + { |
| 94 | + if ((fileSystemInfo.Attributes & FileAttributes.ReparsePoint) == 0) |
| 95 | + { |
| 96 | + return null; |
| 97 | + } |
| 98 | + |
| 99 | + try |
| 100 | + { |
| 101 | + var target = fileSystemInfo.ResolveLinkTarget(returnFinalTarget: true); |
| 102 | + return target?.FullName |
| 103 | + ?? throw new InvalidOperationException( |
| 104 | + $"Access denied: path contains a symbolic link that cannot be resolved at '{fileSystemInfo.FullName}'."); |
| 105 | + } |
| 106 | + catch (IOException) |
| 107 | + { |
| 108 | + throw new InvalidOperationException( |
| 109 | + $"Access denied: path contains a symbolic link that cannot be resolved at '{fileSystemInfo.FullName}'."); |
| 110 | + } |
| 111 | + } |
| 112 | +#endif |
| 113 | + |
| 114 | +#if !NET6_0_OR_GREATER |
| 115 | + private static void ThrowIfPathContainsReparsePoint(string fullPath) |
| 116 | + { |
| 117 | + var root = Path.GetPathRoot(fullPath) ?? string.Empty; |
| 118 | + var segments = GetSegmentsAfterRoot(fullPath, root); |
| 119 | + |
| 120 | + var currentPath = root; |
| 121 | + foreach (var segment in segments) |
| 122 | + { |
| 123 | + currentPath = CombinePath(currentPath, segment); |
| 124 | + |
| 125 | + if (TryGetAttributes(currentPath, out var attributes) && |
| 126 | + (attributes & FileAttributes.ReparsePoint) != 0) |
| 127 | + { |
| 128 | + throw new InvalidOperationException( |
| 129 | + $"Access denied: path contains a symbolic link at '{currentPath}'."); |
| 130 | + } |
| 131 | + } |
| 132 | + } |
| 133 | +#endif |
| 134 | + |
| 135 | + private static string[] GetSegmentsAfterRoot(string fullPath, string root) |
| 136 | + { |
| 137 | + return fullPath.Substring(root.Length) |
| 138 | + .Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, |
| 139 | + StringSplitOptions.RemoveEmptyEntries); |
| 140 | + } |
| 141 | + |
| 142 | + private static bool TryGetAttributes(string path, out FileAttributes attributes) |
| 143 | + { |
| 144 | + try |
| 145 | + { |
| 146 | + attributes = File.GetAttributes(path); |
| 147 | + return true; |
| 148 | + } |
| 149 | + catch (FileNotFoundException) |
| 150 | + { |
| 151 | + } |
| 152 | + catch (DirectoryNotFoundException) |
| 153 | + { |
| 154 | + } |
| 155 | + |
| 156 | + attributes = default; |
| 157 | + return false; |
| 158 | + } |
| 159 | + |
| 160 | + private static string CombinePath(string basePath, string segment) |
| 161 | + { |
| 162 | + return string.IsNullOrEmpty(basePath) ? segment : Path.Combine(basePath, segment); |
| 163 | + } |
| 164 | + |
| 165 | + private static string CombineRemainingPath(string basePath, string[] segments, int startIndex) |
| 166 | + { |
| 167 | + var result = basePath; |
| 168 | + for (var i = startIndex; i < segments.Length; i++) |
| 169 | + { |
| 170 | + result = Path.Combine(result, segments[i]); |
| 171 | + } |
| 172 | + |
| 173 | + return result; |
| 174 | + } |
| 175 | +} |
0 commit comments