-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathPlaintextCredentialStore.cs
More file actions
248 lines (208 loc) · 9.39 KB
/
Copy pathPlaintextCredentialStore.cs
File metadata and controls
248 lines (208 loc) · 9.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace GitCredentialManager
{
public class PlaintextCredentialStore : ICredentialStore
{
public PlaintextCredentialStore(IFileSystem fileSystem, string storeRoot, string @namespace = null)
{
EnsureArgument.NotNull(fileSystem, nameof(fileSystem));
EnsureArgument.NotNullOrWhiteSpace(storeRoot, nameof(storeRoot));
FileSystem = fileSystem;
StoreRoot = storeRoot;
Namespace = @namespace;
}
protected IFileSystem FileSystem { get; }
protected string StoreRoot { get; }
protected string Namespace { get; }
protected virtual string CredentialFileExtension => ".credential";
public IList<string> GetAccounts(string service)
{
return Enumerate(service, null).Select(x => x.Account).Distinct().ToList();
}
public ICredential Get(string service, string account)
{
return Enumerate(service, account).FirstOrDefault();
}
public void AddOrUpdate(string service, string account, string secret)
{
// Ensure the store root exists and permissions are set
EnsureStoreRoot();
FileCredential existingCredential = Enumerate(service, account).FirstOrDefault();
// No need to update existing credential if nothing has changed
if (existingCredential != null &&
StringComparer.Ordinal.Equals(account, existingCredential.Account) &&
StringComparer.Ordinal.Equals(secret, existingCredential.Password))
{
return;
}
string serviceSlug = CreateServiceSlug(service);
string servicePath = Path.Combine(StoreRoot, serviceSlug);
if (!FileSystem.DirectoryExists(servicePath))
{
FileSystem.CreateDirectory(servicePath);
}
// Sanitize account name to prevent path traversal attacks
string safeAccount = GetSafeAccountFileName(account);
string fullPath = Path.Combine(servicePath, $"{safeAccount}{CredentialFileExtension}");
var credential = new FileCredential(fullPath, service, account, secret);
SerializeCredential(credential);
}
public bool Remove(string service, string account)
{
foreach (FileCredential credential in Enumerate(service, account))
{
// Only delete the first match
FileSystem.DeleteFile(credential.FullPath);
return true;
}
return false;
}
protected virtual bool TryDeserializeCredential(string path, out FileCredential credential)
{
string text;
using (var stream = FileSystem.OpenFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var reader = new StreamReader(stream))
{
text = reader.ReadToEnd();
}
int line1Idx = text.IndexOf(Environment.NewLine, StringComparison.OrdinalIgnoreCase);
if (line1Idx > 0)
{
// Password is the first line
string password = text.Substring(0, line1Idx);
// All subsequent lines are metadata/attributes
string attrText = text.Substring(line1Idx + Environment.NewLine.Length);
using var attrReader = new StringReader(attrText);
IDictionary<string, string> attrs = attrReader.ReadDictionary(StringComparer.OrdinalIgnoreCase);
// Account is optional
attrs.TryGetValue("account", out string account);
// Service is required
if (attrs.TryGetValue("service", out string service))
{
credential = new FileCredential(path, service, account, password);
return true;
}
}
credential = null;
return false;
}
protected virtual void SerializeCredential(FileCredential credential)
{
// Ensure the parent directory exists
string parentDir = Path.GetDirectoryName(credential.FullPath);
if (!FileSystem.DirectoryExists(parentDir))
{
FileSystem.CreateDirectory(parentDir);
}
using (var stream = FileSystem.OpenFileStream(credential.FullPath, FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new StreamWriter(stream))
{
writer.WriteLine(credential.Password);
writer.WriteLine("service={0}", credential.Service);
writer.WriteLine("account={0}", credential.Account);
writer.Flush();
}
}
private IEnumerable<FileCredential> Enumerate(string service, string account)
{
string serviceSlug = CreateServiceSlug(service);
string searchPath = Path.Combine(StoreRoot, serviceSlug);
bool anyAccount = string.IsNullOrWhiteSpace(account);
if (!FileSystem.DirectoryExists(searchPath))
{
yield break;
}
IEnumerable<string> allFiles = FileSystem.EnumerateFiles(searchPath, $"*{CredentialFileExtension}");
foreach (string fullPath in allFiles)
{
string accountFile = Path.GetFileNameWithoutExtension(fullPath);
// Compare using the sanitized account name to match how files are named
if (anyAccount || StringComparer.OrdinalIgnoreCase.Equals(GetSafeAccountFileName(account), accountFile))
{
// Validate the credential metadata also matches our search
if (TryDeserializeCredential(fullPath, out FileCredential credential) &&
StringComparer.OrdinalIgnoreCase.Equals(service, credential.Service) &&
(anyAccount || StringComparer.OrdinalIgnoreCase.Equals(account, credential.Account)))
{
yield return credential;
}
}
}
}
/// <summary>
/// Ensure the store root directory exists. If it does not, create a new directory with
/// permissions that only permit the owner to read/write/execute. Permissions on an existing
/// directory are not modified.
/// </summary>
private void EnsureStoreRoot()
{
if (FileSystem.DirectoryExists(StoreRoot))
{
// Don't touch the permissions on the existing directory
return;
}
FileSystem.CreateDirectory(StoreRoot);
// We only set file system permissions on POSIX platforms
if (!PlatformUtils.IsPosix())
{
return;
}
// Set store root permissions such that only the owner can read/write/execute
var mode = Interop.Posix.Native.NativeFileMode.S_IRUSR |
Interop.Posix.Native.NativeFileMode.S_IWUSR |
Interop.Posix.Native.NativeFileMode.S_IXUSR;
// Ignore the return code.. this is a best effort only
Interop.Posix.Native.Stat.chmod(StoreRoot, mode);
}
/// <summary>
/// Sanitize an account name for safe use as a file name by replacing path-separator characters,
/// null bytes, and rejecting reserved path components such as "." and "..".
/// This prevents path traversal attacks where a malicious account name like "../../etc/malicious"
/// could be used to write files outside the intended credential store directory.
/// </summary>
private static string GetSafeAccountFileName(string account)
{
if (string.IsNullOrEmpty(account))
{
throw new ArgumentException("Account name must not be null or empty.", nameof(account));
}
// Replace path separator characters (both Unix '/' and Windows '\') and null bytes.
string safe = account.Replace('/', '_').Replace('\\', '_').Replace('\0', '_');
// Reject reserved path components that could still traverse directories.
if (safe == "." || safe == "..")
{
safe = safe.Replace('.', '_');
}
return safe;
}
private string CreateServiceSlug(string service)
{
var sb = new StringBuilder();
char sep = Path.DirectorySeparatorChar;
if (!string.IsNullOrWhiteSpace(Namespace))
{
sb.AppendFormat("{0}{1}", Namespace, sep);
}
if (Uri.TryCreate(service, UriKind.Absolute, out Uri serviceUri))
{
sb.AppendFormat("{0}{1}", serviceUri.Scheme, sep);
sb.AppendFormat("{0}", serviceUri.Host);
if (!serviceUri.IsDefaultPort)
{
sb.Append(PlatformUtils.IsWindows() ? '-' : ':');
sb.Append(serviceUri.Port);
}
sb.Append(serviceUri.AbsolutePath.Replace('/', sep));
}
else
{
sb.Append(service);
}
return sb.ToString();
}
}
}