forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowsUsernameProvider.cs
More file actions
128 lines (111 loc) · 4.78 KB
/
WindowsUsernameProvider.cs
File metadata and controls
128 lines (111 loc) · 4.78 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
#if NET45 || NET451
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Npgsql
{
internal static class WindowsUsernameProvider
{
class CachedUpn
{
public string Upn;
public DateTime ExpiryTimeUtc;
}
static readonly Dictionary<SecurityIdentifier, CachedUpn> CachedUpns = new Dictionary<SecurityIdentifier, CachedUpn>();
[CanBeNull]
internal static string GetUserName(bool includeRealm)
{
// Side note: This maintains the hack fix mentioned before for https://github.com/npgsql/Npgsql/issues/133.
// In a nutshell, starting with .NET 4.5 WindowsIdentity inherits from ClaimsIdentity
// which doesn't exist in mono, and calling a WindowsIdentity method bombs.
// The workaround is that this function that actually deals with WindowsIdentity never
// gets called on mono, so never gets JITted and the problem goes away.
// Gets the current user's username for integrated security purposes
var identity = WindowsIdentity.GetCurrent();
if (identity?.User == null)
{
return null;
}
CachedUpn cachedUpn;
string upn = null;
// Check to see if we already have this UPN cached
lock (CachedUpns)
{
if (CachedUpns.TryGetValue(identity.User, out cachedUpn))
{
if (cachedUpn.ExpiryTimeUtc > DateTime.UtcNow)
upn = cachedUpn.Upn;
else
CachedUpns.Remove(identity.User);
}
}
try
{
if (upn == null)
{
// Try to get the user's UPN in its correct case; this is what the
// server will need to verify against a Kerberos/SSPI ticket
// If the computer does not belong to a domain, returns Empty.
string domainName = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
if (domainName.Equals(string.Empty))
{
return GetWindowsIdentityUserName(includeRealm);
}
// First, find a domain server we can talk to
string domainHostName;
using (DirectoryEntry rootDse = new DirectoryEntry("LDAP://rootDSE") { AuthenticationType = AuthenticationTypes.Secure })
{
domainHostName = (string)rootDse.Properties["dnsHostName"].Value;
}
// Query the domain server by the current user's SID
using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + domainHostName) { AuthenticationType = AuthenticationTypes.Secure })
{
DirectorySearcher search = new DirectorySearcher(entry,
"(objectSid=" + identity.User.Value + ")", new[] { "userPrincipalName" });
SearchResult result = search.FindOne();
upn = (string)result.Properties["userPrincipalName"][0];
}
}
if (cachedUpn == null)
{
// Save this value
cachedUpn = new CachedUpn() { Upn = upn, ExpiryTimeUtc = DateTime.UtcNow.AddHours(3.0) };
lock (CachedUpns)
{
CachedUpns[identity.User] = cachedUpn;
}
}
string[] upnParts = upn.Split('@');
if (includeRealm)
{
// Make it Kerberos-y by uppercasing the realm part
return upnParts[0] + "@" + upnParts[1].ToUpperInvariant();
}
else
{
return upnParts[0];
}
}
catch
{
// Querying the directory failed, so return the SAM name
// (which probably won't work, but it's better than nothing)
return GetWindowsIdentityUserName(includeRealm);
}
}
static string GetWindowsIdentityUserName(bool includeRealm)
{
var s = WindowsIdentity.GetCurrent()?.Name;
if (s == null)
return string.Empty;
var machineAndUser = s.Split('\\');
return includeRealm ? $"{machineAndUser[1]}@{machineAndUser[0]}" : machineAndUser[1];
}
}
}
#endif