-
Notifications
You must be signed in to change notification settings - Fork 4
/
Program.cs
518 lines (462 loc) · 19.3 KB
/
Program.cs
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
using CommandLine;
using CommandLine.Text;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
namespace SSH_Agent_Helper
{
class Program
{
static string SSH_AUTH_SOCK = "SSH_AUTH_SOCK";
static string SSH_AGENT_PID = "SSH_AGENT_PID";
static string AgentSock;
static string AgentPID;
static void Main(string[] args)
{
AgentSock = Environment.GetEnvironmentVariable(SSH_AUTH_SOCK, EnvironmentVariableTarget.Process);
AgentPID = Environment.GetEnvironmentVariable(SSH_AGENT_PID, EnvironmentVariableTarget.Process);
if (String.IsNullOrEmpty(AgentSock))
{
AgentSock = Environment.GetEnvironmentVariable(SSH_AUTH_SOCK, EnvironmentVariableTarget.User);
}
Process existingProcess = null;
try
{
existingProcess = Process.GetProcessById(Convert.ToInt32(AgentPID));
} catch (Exception) {}
if (String.IsNullOrEmpty(AgentPID) || existingProcess == null || existingProcess.Id < 1)
{
AgentPID = Environment.GetEnvironmentVariable(SSH_AGENT_PID, EnvironmentVariableTarget.User);
}
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options) && args.Length > 0)
{
if (options.Test)
{
bool alive = TestSSHAgent();
if (alive)
{
Console.WriteLine(alive);
}
else
{
Console.Error.WriteLine(alive);
}
}
else if (options.Kill)
{
KillSSHAgent();
}
else if (options.RegisterStartup)
{
if (options.Add && options.Others.Count > 0)
{
options.Others.Add("-a");
options.Others.Add("-s");
RegisterStartup(options.Others);
}
else
{
RegisterStartup(new List<string>() { });
}
}
else if (options.UnregisterRestartup)
{
UnregisterStartup();
}
else if (options.Startup && options.Add)
{
RunSSHAgent();
AddSSHKeys(options.Others, true);
}
else if (options.Add)
{
AddSSHKeys(options.Others);
}
else
{
Console.Write(options.GetUsage());
Environment.Exit(1);
}
Environment.Exit(0);
} else if (args.Length == 0)
{
RunSSHAgent();
}
}
static void RunSSHAgent()
{
try
{
Process existingProcess = Process.GetProcessById(Convert.ToInt32(AgentPID));
if (!existingProcess.Responding || Convert.ToInt32(AgentPID) < 1)
{
throw new Exception("There is no process running or the previous ssh-agent is not responding.");
}
Console.Error.WriteLine("Another ssh-agent (PID: " + AgentPID + ") is already running healthily");
} catch (Exception)
{
string SSHAgentPath = FindProgram("ssh-agent.exe");
Process SSHAgent = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = SSHAgentPath,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
try
{
SSHAgent.Start();
Process parent = FindParent.ParentProcess(Process.GetCurrentProcess());
if (!SSHAgent.StandardError.EndOfStream)
{
while (!SSHAgent.StandardError.EndOfStream)
{
Console.Error.WriteLine(SSHAgent.StandardError.ReadLine());
}
}
while (!SSHAgent.StandardOutput.EndOfStream)
{
var line = SSHAgent.StandardOutput.ReadLine();
string[] splits = line.Split(';');
string[] command = splits[0].Split('=');
if (command[0] == SSH_AUTH_SOCK && command.Length > 1)
{
AgentSock = command[1];
Environment.SetEnvironmentVariable(SSH_AUTH_SOCK, command[1], EnvironmentVariableTarget.User);
}
else if (command[0] == SSH_AGENT_PID && command.Length > 1)
{
AgentPID = command[1];
Environment.SetEnvironmentVariable(SSH_AGENT_PID, command[1], EnvironmentVariableTarget.User);
}
if (parent.ProcessName != "cmd" && parent.ProcessName != "powershell")
{
Console.WriteLine(line);
}
}
if (parent.ProcessName == "powershell")
{
Console.WriteLine("$env:" + SSH_AUTH_SOCK + "=\"" + AgentSock + "\"");
Console.WriteLine("$env:" + SSH_AGENT_PID + "=\"" + AgentPID + "\"");
Console.WriteLine("# Your environment has been configured. " +
"Run these commands to configure current terminal or open a new one.");
}
else if (parent.ProcessName == "cmd")
{
Console.WriteLine("set " + SSH_AUTH_SOCK + "=" + AgentSock);
Console.WriteLine("set " + SSH_AGENT_PID + "=" + AgentPID);
Console.WriteLine("rem Your environment has been configured. " +
"Run these commands to configure current terminal or open a new one.");
} else
{
Console.WriteLine("# Your environment has been configured. " +
"Run these commands to configure current terminal or open a new one.");
}
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Environment.Exit(1);
}
}
}
static void KillSSHAgent()
{
Process existingProcess = null;
try
{
existingProcess = Process.GetProcessById(Convert.ToInt32(AgentPID));
}
catch (Exception) { }
if (String.IsNullOrEmpty(AgentPID) || existingProcess == null || existingProcess.Id < 1)
{
Console.Error.WriteLine("Either the environment is currently not configured for ssh-agent or it " +
"has already been killed.");
Environment.Exit(1);
}
string SSHAgentPath = FindProgram("ssh-agent.exe");
Process SSHAgent = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = SSHAgentPath,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
Arguments = "-k",
}
};
SSHAgent.StartInfo.EnvironmentVariables[SSH_AGENT_PID] = AgentPID;
try
{
SSHAgent.Start();
Environment.SetEnvironmentVariable(SSH_AGENT_PID, null, EnvironmentVariableTarget.User);
Environment.SetEnvironmentVariable(SSH_AUTH_SOCK, null, EnvironmentVariableTarget.User);
Process parent = FindParent.ParentProcess(Process.GetCurrentProcess());
if (!SSHAgent.StandardError.EndOfStream)
{
while (!SSHAgent.StandardError.EndOfStream)
{
Console.Error.WriteLine(SSHAgent.StandardError.ReadLine());
}
}
if (parent.ProcessName == "powershell")
{
Console.WriteLine("Remove-Item env:" + SSH_AUTH_SOCK);
Console.WriteLine("Remove-Item env:" + SSH_AGENT_PID);
Console.WriteLine("# ssh-agent has been killed and your environment has been configured. " +
"Run these commands to configure current terminal or open a new one.");
}
else if (parent.ProcessName == "cmd")
{
Console.WriteLine("set " + SSH_AUTH_SOCK + "=");
Console.WriteLine("set " + SSH_AGENT_PID + "=");
Console.WriteLine("rem ssh-agent has been killed and your environment has been configured. " +
"Run these commands to configure current terminal or open a new one.");
} else
{
while (!SSHAgent.StandardOutput.EndOfStream)
{
Console.WriteLine(SSHAgent.StandardOutput.ReadLine());
}
{
Console.WriteLine("# ssh-agent has been killed and your environment has been configured. " +
"Run these commands to configure current terminal or open a new one.");
}
}
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Environment.Exit(1);
}
}
static bool TestSSHAgent()
{
Process existingProcess = null;
try
{
existingProcess = Process.GetProcessById(Convert.ToInt32(AgentPID));
}
catch (Exception) { }
return !(String.IsNullOrEmpty(AgentPID) || existingProcess == null || existingProcess.Id < 1);
}
static string FindProgram(string name)
{
Process Where = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = @"C:\Windows\System32\where.exe",
Arguments = name,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
try
{
Where.Start();
while (!Where.StandardOutput.EndOfStream)
{
return (string)Where.StandardOutput.ReadLine();
}
throw new Exception(name + " was not found in %PATH%");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Environment.Exit(1);
return "";
}
}
static void RegisterStartup(IList<string> args)
{
manageStartup(args);
}
static void UnregisterStartup()
{
manageStartup(new List<string>() { }, true);
}
private static void manageStartup(IList<string> args, bool remove = false)
{
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (!remove)
{
string parameters = (new Uri(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)).LocalPath;
parameters = parameters + " " + String.Join(" ", args);
registryKey.SetValue("SSH Agent Helper", parameters);
Console.WriteLine("SSH Agent Helper has been register to run at Startup with these parameters: " +
String.Join(" ", parameters));
} else if (registryKey.GetValue("SSH Agent Helper") != null)
{
registryKey.DeleteValue("SSH Agent Helper");
Console.WriteLine("SSH Agent Helper registery for Startup has been removed.");
}
else
{
Console.WriteLine("SSH Agent Helper registery has already been removed.");
}
}
static void AddSSHKeys(IList<string> paths, bool customENV = false)
{
string SSHAddPath = FindProgram("ssh-add.exe");
Process SSHAdd = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = SSHAddPath,
UseShellExecute = false,
Arguments = String.Join(" ", paths)
}
};
if (customENV)
{
SSHAdd.StartInfo.EnvironmentVariables[SSH_AGENT_PID] = AgentPID;
SSHAdd.StartInfo.EnvironmentVariables[SSH_AUTH_SOCK] = AgentSock;
}
try
{
SSHAdd.Start();
SSHAdd.WaitForExit();
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Environment.Exit(1);
}
}
}
static class FindParent {
public static Process ParentProcess(this Process process)
{
return Process.GetProcessById(ParentProcessId(process.Id));
}
public static int ParentProcessId(this Process process)
{
return ParentProcessId(process.Id);
}
public static int ParentProcessId(int Id)
{
PROCESSENTRY32 pe32 = new PROCESSENTRY32 { };
pe32.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32));
using (var hSnapshot = CreateToolhelp32Snapshot(SnapshotFlags.Process, (uint)Id))
{
if (hSnapshot.IsInvalid)
throw new Win32Exception();
if (!Process32First(hSnapshot, ref pe32))
{
int errno = Marshal.GetLastWin32Error();
if (errno == ERROR_NO_MORE_FILES)
return -1;
throw new Win32Exception(errno);
}
do
{
if (pe32.th32ProcessID == (uint)Id)
return (int)pe32.th32ParentProcessID;
} while (Process32Next(hSnapshot, ref pe32));
}
return -1;
}
private const int ERROR_NO_MORE_FILES = 0x12;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern SafeSnapshotHandle CreateToolhelp32Snapshot(SnapshotFlags flags, uint id);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool Process32First(SafeSnapshotHandle hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool Process32Next(SafeSnapshotHandle hSnapshot, ref PROCESSENTRY32 lppe);
[Flags]
private enum SnapshotFlags : uint
{
HeapList = 0x00000001,
Process = 0x00000002,
Thread = 0x00000004,
Module = 0x00000008,
Module32 = 0x00000010,
All = (HeapList | Process | Thread | Module),
Inherit = 0x80000000,
NoHeaps = 0x40000000
}
[StructLayout(LayoutKind.Sequential)]
private struct PROCESSENTRY32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szExeFile;
};
[SuppressUnmanagedCodeSecurity, HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
internal sealed class SafeSnapshotHandle : SafeHandleMinusOneIsInvalid
{
internal SafeSnapshotHandle() : base(true)
{
}
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
internal SafeSnapshotHandle(IntPtr handle) : base(true)
{
base.SetHandle(handle);
}
protected override bool ReleaseHandle()
{
return CloseHandle(base.handle);
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
private static extern bool CloseHandle(IntPtr handle);
}
}
class Options
{
[Option('r', "register-startup", Required = false,
HelpText = "Register this program to run at Windows Startup. Parameters for startup are optional. " +
"E.g.: ssh-agent-helper -r -a %USERPROFILE%\\.ssh\\id_rsa")]
public bool RegisterStartup { get; set; }
[Option('u', "unregister-startup", Required = false,
HelpText = "Disable run at Windows Startup behaviour.")]
public bool UnregisterRestartup { get; set; }
[Option('t', "test", Required = false,
HelpText = "Test if configured ssh-agent is alive and responding. Useful for checking programatically.")]
public bool Test { get; set; }
[Option('k', "kill", Required = false,
HelpText = "Kill the current ssh-agent process and unset environment variables.")]
public bool Kill { get; set; }
[Option('s', "startup", Required = false,
HelpText = "Used to incdicate startup, so that, ssh-agent can be started before adding keys.")]
public bool Startup { get; set; }
[Option('a', "add", Required = false,
HelpText = "Adds key to ssh-agent. Useful for startup configuration.")]
public bool Add { get; set; }
[ValueList(typeof(List<string>))]
public IList<string> Others { get; set; }
[ParserState]
public IParserState LastParserState { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this,
(HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
}