-
Notifications
You must be signed in to change notification settings - Fork 0
/
LDAPUtils.cs
323 lines (290 loc) · 12 KB
/
LDAPUtils.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
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Claims;
using System.Text.RegularExpressions;
using System.Net;
using Novell.Directory.Ldap;
using Novell.Directory.Ldap.Rfc2251;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
namespace eshc_diradmin
{
public class LDAPUtils
{
private readonly ILogger logger;
public Parameters Params;
public LdapConnection Connection;
public LDAPUtils()
{
logger = new Microsoft.Extensions.Logging.Console.ConsoleLogger("ldap", (x, y) => true, true);
}
public class Parameters
{
public string Host { get; set; } = "localhost";
public int Port { get; set; } = 389;
public string RootDN { get; set; } = "dc=directory,dc=eshc,dc=coop";
public string ManagerDN { get; set; } = "cn=Manager";
public string ManagerPW { get; set; } = "";
public string DN(string subdn)
{
return subdn + "," + RootDN;
}
public string TrimGroupName(string groupDN)
{
if (groupDN.StartsWith("cn="))
{
groupDN = groupDN.Substring("cn=".Length);
}
string sfx = ",ou=Groups," + RootDN;
if (groupDN.EndsWith(sfx))
{
groupDN = groupDN.Substring(0, groupDN.Length - sfx.Length);
}
return groupDN;
}
public string GroupNameToDN(string groupName)
{
return String.Format("cn={0},ou=Groups,{1}", groupName, RootDN);
}
}
public void ValidateParametersAndConnect(Parameters prams)
{
Params = prams;
Connection = new LdapConnection { SecureSocketLayer = false };
EnsureConnection();
}
public void EnsureConnection()
{
if (!Connection.Connected)
{
Connection.Connect(Params.Host, Params.Port);
if (!Connection.Connected)
{
throw new System.Exception("Could not connect to the LDAP server at " + Params.Host + ":" + Params.Port);
}
Connection.Bind(Params.DN(Params.ManagerDN), Params.ManagerPW);
if (!Connection.Bound)
{
throw new System.Exception("Could not bind to the LDAP server with username " + Params.DN(Params.ManagerDN));
}
}
}
static string GetOptAttr(LdapEntry e, string name)
{
if (e == null)
{
return "";
}
var a = e.GetAttribute(name);
if (a == null)
{
return "";
}
return a.StringValue ?? "";
}
public class MemberInfo
{
public string DN;
public string[] Groups;
public string FullName; // cn
public string FirstName; // givenName
public string Surname; // sn
public string UID;
public string DisplayName;
public string Mail;
public string Address; // postalAddress
public string Flat; // roomNumber
public string TelephoneNumber;
public string Password;
public int DjangoAccount;
public static string[] LdapAttrList = {
"cn", "givenName", "sn", "uid", "displayName", "mail", "postalAddress", "telephoneNumber", "employeeNumber", "userPassword", "memberOf", "roomNumber" };
public MemberInfo(LdapEntry e, LDAPUtils ldap)
{
ldap.logger.LogInformation("Reading user info for " + e.Dn);
DN = e.Dn;
FullName = GetOptAttr(e, "cn");
FirstName = GetOptAttr(e, "givenName");
Surname = GetOptAttr(e, "sn");
UID = GetOptAttr(e, "uid");
DisplayName = GetOptAttr(e, "displayName");
Mail = GetOptAttr(e, "mail");
Address = GetOptAttr(e, "postalAddress");
Flat = GetOptAttr(e, "roomNumber");
TelephoneNumber = GetOptAttr(e, "telephoneNumber");
Password = GetOptAttr(e, "userPassword");
if (!Int32.TryParse(GetOptAttr(e, "employeeNumber"), out DjangoAccount))
{
DjangoAccount = -1;
}
var memof = e.GetAttribute("memberOf");
if (memof != null)
{
Groups = memof.StringValueArray;
}
else
{
Groups = new string[] { };
}
}
}
public MemberInfo FetchMemberInfo(ClaimsPrincipal user, HttpContext httpContext)
{
var DN = user.FindFirstValue(ClaimTypes.NameIdentifier);
if (DN == null)
{
httpContext.SignOutAsync().Wait();
return null;
}
var Entry = Startup.ldap.Connection.Read(DN, LDAPUtils.MemberInfo.LdapAttrList);
return new LDAPUtils.MemberInfo(Entry, Startup.ldap);
}
public List<MemberInfo> FetchAllMembersInfo()
{
var mems = new List<MemberInfo>();
var entries = Connection.Search(Params.DN("ou=Members"),
LdapConnection.ScopeOne, "(objectClass=inetOrgPerson)", MemberInfo.LdapAttrList, false);
foreach (var entry in entries)
{
mems.Add(new MemberInfo(entry, this));
}
mems.Sort((a, b) => a.Surname.CompareTo(b.Surname));
return mems;
}
/// <summary>
/// </summary>
/// <returns>A dictionary of pairs: (ldapName, displayName)</returns>
public SortedDictionary<string, string> FetchAllGroups()
{
var result = new SortedDictionary<string, string>();
var entries = Connection.Search(Params.DN("ou=Groups"),
LdapConnection.ScopeOne, "(objectClass=groupOfNames)", new string[] { "description" }, false);
foreach (var entry in entries)
{
string dn = entry.Dn;
string dsc = GetOptAttr(entry, "description");
if (dsc.Length < 1)
dsc = dn;
result.Add(dn, dsc);
}
return result;
}
public struct AuthResult
{
public bool ValidCredentrials;
public bool Active;
public bool SuperAdmin;
public string DN;
public string DisplayName;
}
static Regex ldapFieldRegex = new Regex(@"[ a-zA-Z0-9@_-]*");
public static bool ValidateLDAPField(string field)
{
return ldapFieldRegex.IsMatch(field);
}
public LdapSearchQueue Search(string @base, int scope, RfcFilter filter, string[] attrs, bool namesOnly = false)
{
LdapMessage m = new LdapSearchRequest(@base, scope, filter, attrs,
LdapSearchConstraints.DerefAlways, 512, 1, namesOnly, null);
return (LdapSearchQueue)Connection.SendRequest(m, null);
}
public AuthResult Authenticate(string username, string password)
{
if (!ValidateLDAPField(username))
{
logger.LogWarning("Tried LDAP injection: " + username);
return new AuthResult { ValidCredentrials = false, Active = false };
}
RfcFilter query = new RfcFilter();
var UTF8 = System.Text.Encoding.UTF8;
query.StartNestedFilter(RfcFilter.And);
query.AddAttributeValueAssertion(RfcFilter.EqualityMatch, "objectClass", UTF8.GetBytes("inetOrgPerson"));
query.StartNestedFilter(RfcFilter.Or);
var usernameBytes = UTF8.GetBytes(username);
query.AddAttributeValueAssertion(RfcFilter.EqualityMatch, "mailPrimaryAddress", usernameBytes);
query.AddAttributeValueAssertion(RfcFilter.EqualityMatch, "mail", usernameBytes);
query.AddAttributeValueAssertion(RfcFilter.EqualityMatch, "uid", usernameBytes);
query.EndNestedFilter(RfcFilter.Or);
query.EndNestedFilter(RfcFilter.And);
var resmq = Search(Params.DN("ou=Members"),
LdapConnection.ScopeOne, query, new string[] { "displayName", "memberOf" });
LdapEntry res = null;
AuthResult ar = new AuthResult();
LdapMessage msg;
while ((msg = resmq.GetResponse()) != null)
{
if (msg is LdapSearchResult)
{
LdapEntry r = ((LdapSearchResult)msg).Entry;
if (res != null)
{
logger.LogError("LDAP login returned multiple results: " + username);
return new AuthResult { ValidCredentrials = false, Active = false };
}
res = r;
logger.LogInformation("LDAP login found user DN: " + res.Dn);
}
}
if (res == null)
{
logger.LogError("LDAP login failed to find account: " + username);
return new AuthResult { ValidCredentrials = false, Active = false };
}
ar.ValidCredentrials = false;
ar.Active = false;
ar.SuperAdmin = false;
ar.DN = res.Dn;
ar.DisplayName = res.GetAttribute("displayName").StringValue ?? res.Dn;
// try login
using (LdapConnection userConn = new LdapConnection { SecureSocketLayer = false })
{
userConn.Connect(Params.Host, Params.Port);
if (!userConn.Connected)
{
throw new System.Exception("Could not connect to the LDAP server at " + Params.Host + ":" + Params.Port);
}
try
{
userConn.Bind(ar.DN, password);
}
catch (LdapException)
{
logger.LogError("LDAP login: wrong password for account: " + ar.DN);
return new AuthResult { ValidCredentrials = false, Active = false };
}
if (!userConn.Bound)
{
logger.LogError("LDAP login: could not bind account: " + ar.DN);
return new AuthResult { ValidCredentrials = false, Active = false };
}
}
ar.ValidCredentrials = true;
var groups = res.GetAttribute("memberOf").StringValueArray;
ar.Active = groups.Contains(Params.DN("cn=AllMembers,ou=Groups"));
ar.SuperAdmin = groups.Contains(Params.DN("cn=InternetSpecialists,ou=Groups")) || groups.Contains(Params.DN("cn=DirectoryEditors,ou=Groups"));
foreach (var group in groups)
{
logger.LogDebug("Group: " + group);
}
return ar.Active ? ar : new AuthResult { ValidCredentrials = true, Active = false };
}
private static RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
public static string EncodeSSHA(string password)
{
byte[] salt = new byte[16];
rngCsp.GetNonZeroBytes(salt);
byte[] pwd = System.Text.Encoding.UTF8.GetBytes(password);
byte[] saltedPwd = pwd.Concat(salt).ToArray();
byte[] sha = SHA256.Create().ComputeHash(saltedPwd);
return "{SSHA256}" + Convert.ToBase64String(sha.Concat(salt).ToArray());
}
}
}