forked from kenjiuno/Npgsql
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathKerberosUsernameProvider.cs
More file actions
93 lines (82 loc) · 3.01 KB
/
KerberosUsernameProvider.cs
File metadata and controls
93 lines (82 loc) · 3.01 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
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Npgsql.Logging;
namespace Npgsql
{
/// <summary>
/// Launches MIT Kerberos klist and parses out the default principal from it.
/// Caches the result.
/// </summary>
class KerberosUsernameProvider
{
static bool _performedDetection;
static string? _principalWithRealm;
static string? _principalWithoutRealm;
static readonly NpgsqlLogger Log = NpgsqlLogManager.CreateLogger(nameof(KerberosUsernameProvider));
internal static string? GetUsername(bool includeRealm)
{
if (!_performedDetection)
{
DetectUsername();
_performedDetection = true;
}
return includeRealm ? _principalWithRealm : _principalWithoutRealm;
}
static void DetectUsername()
{
var klistPath = FindInPath("klist");
if (klistPath == null)
{
Log.Debug("klist not found in PATH, skipping Kerberos username detection");
return;
}
var processStartInfo = new ProcessStartInfo
{
FileName = klistPath,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
var process = Process.Start(processStartInfo);
if (process is null)
{
Log.Debug($"klist process could not be started");
return;
}
process.WaitForExit();
if (process.ExitCode != 0)
{
Log.Debug($"klist exited with code {process.ExitCode}: {process.StandardError.ReadToEnd()}");
return;
}
var line = default(string);
for (var i = 0; i < 2; i++)
if ((line = process.StandardOutput.ReadLine()) == null)
{
Log.Debug("Unexpected output from klist, aborting Kerberos username detection");
return;
}
var components = line!.Split(':');
if (components.Length != 2)
{
Log.Debug("Unexpected output from klist, aborting Kerberos username detection");
return;
}
var principalWithRealm = components[1].Trim();
components = principalWithRealm.Split('@');
if (components.Length != 2)
{
Log.Debug($"Badly-formed default principal {principalWithRealm} from klist, aborting Kerberos username detection");
return;
}
_principalWithRealm = principalWithRealm;
_principalWithoutRealm = components[0];
}
static string? FindInPath(string name) => Environment.GetEnvironmentVariable("PATH")
?.Split(Path.PathSeparator)
.Select(p => Path.Combine(p, name))
.FirstOrDefault(File.Exists);
}
}