public static Dictionary <string, object> ReadOUProperties(SearchResultEntry entry) { var props = new Dictionary <string, object> { { "description", entry.GetProperty("description") } }; return(props); }
internal MX(SearchResultEntry Entry, int Index = 0) { base.UpdateProperties(Entry, Index); Preference = base.RecordReader.ReadUInt16(true); TargetName = base.ReadName(); base.RecordData = String.Format("{0} {1}", Preference, TargetName); }
/// <summary> /// Executes implementation for this rule /// </summary> /// <param name="parent">The composed rule containing this rule</param> /// <param name="entry">The search result we are checking</param> /// <param name="attributeValue">The current attribute value as pass through the chain</param> /// <returns>Either a success or error result</returns> public override RuleResult Execute(ComposedRule parent, SearchResultEntry entry, string attributeValue) { if (entry.Attributes.Contains(StringLiterals.UserPrincipalName)) { return(this.GetSuccessResult()); } return(base.Execute(parent, entry, attributeValue)); }
internal static void GetProps(SearchResultEntry entry, ResolvedEntry resolved, ref Ou obj) { if (!Utils.IsMethodSet(ResolvedCollectionMethod.ObjectProps)) { return; } obj.Properties.Add("description", entry.GetProp("description")); }
public SearchResultEntryWrapper(SearchResultEntry searchResultEntry) { if (searchResultEntry == null) { throw new ArgumentNullException("searchResultEntry"); } this._searchResultEntry = searchResultEntry; }
private void ParseAttributes(SearchResultEntry entry) { Attributes = new Dictionary <String, AdAttribute>(); foreach (var attribute in entry.Attributes.Values) { var attr = (DirectoryAttribute)attribute; Attributes.Add(attr.Name, new AdAttribute(attr)); } }
public static string GetProp(this SearchResultEntry result, string prop) { if (!result.Attributes.Contains(prop)) { return(null); } return(result.Attributes[prop][0].ToString()); }
/// <summary> /// Helper function to print attributes of a SearchResultEntry. Not used currently /// </summary> /// <param name="searchResultEntry"></param> public static void PrintEntry(this SearchResultEntry searchResultEntry) { foreach (var propertyName in searchResultEntry.Attributes.AttributeNames) { var property = propertyName.ToString(); Console.WriteLine(property); Console.WriteLine(searchResultEntry.GetProperty(property)); } }
public static byte[] GetPropBytes(this SearchResultEntry result, string prop) { if (!result.Attributes.Contains(prop)) { return(null); } return(result.Attributes[prop][0] as byte[]); }
public static string GetSid(this SearchResultEntry result) { if (!result.Attributes.Contains("objectsid")) { return(null); } return(new SecurityIdentifier(result.Attributes["objectsid"][0] as byte[], 0).ToString()); }
/// <summary> /// Executes implementation for this rule /// </summary> /// <param name="parent">The composed rule containing this rule</param> /// <param name="entry">The search result we are checking</param> /// <param name="attributeValue">The current attribute value as pass through the chain</param> /// <returns>Either a success or error result</returns> public override RuleResult Execute(ComposedRule parent, SearchResultEntry entry, string attributeValue) { if (Constants.PeriodsRegex.IsMatch(attributeValue)) { this.GetErrorResult(ErrorType.Format, this.Fixer(entry, attributeValue)); } return(this.GetSuccessResult()); }
[Fact]// [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestMoveAndRenameUser() { using (LdapConnection connection = GetConnection()) { string ouName1 = "ProtocolsGroup7.1"; string dn1 = "ou=" + ouName1; string ouName2 = "ProtocolsGroup7.2"; string dn2 = "ou=" + ouName2; string userDn1 = "cn=protocolUser7.1" + "," + dn1; string userDn2 = "cn=protocolUser7.2" + "," + dn2; DeleteEntry(connection, userDn1); DeleteEntry(connection, userDn2); DeleteEntry(connection, dn1); DeleteEntry(connection, dn2); try { AddOrganizationalUnit(connection, dn1); SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName1); Assert.NotNull(sre); AddOrganizationalUnit(connection, dn2); sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.Domain, ouName2); Assert.NotNull(sre); AddOrganizationalRole(connection, userDn1); string user1Root = dn1 + "," + LdapConfiguration.Configuration.Domain; string user2Root = dn2 + "," + LdapConfiguration.Configuration.Domain; sre = SearchUser(connection, user1Root, "protocolUser7.1"); Assert.NotNull(sre); ModifyDNRequest modDnRequest = new ModifyDNRequest(userDn1 + "," + LdapConfiguration.Configuration.Domain, dn2 + "," + LdapConfiguration.Configuration.Domain, "cn=protocolUser7.2"); ModifyDNResponse modDnResponse = (ModifyDNResponse)connection.SendRequest(modDnRequest); Assert.Equal(ResultCode.Success, modDnResponse.ResultCode); sre = SearchUser(connection, user1Root, "protocolUser7.1"); Assert.Null(sre); sre = SearchUser(connection, user2Root, "protocolUser7.2"); Assert.NotNull(sre); } finally { DeleteEntry(connection, userDn1); DeleteEntry(connection, userDn2); DeleteEntry(connection, dn1); DeleteEntry(connection, dn2); } } }
public void GivenASearchResult_WhenCreateSearchBundle_ThenCorrectBundleShouldBeReturned() { _urlResolver.ResolveResourceWrapperUrl(Arg.Any <ResourceWrapper>()).Returns(x => new Uri(string.Format(_resourceUrlFormat, x.ArgAt <ResourceWrapper>(0).ResourceId))); _urlResolver.ResolveRouteUrl(_unsupportedSearchParameters).Returns(_selfUrl); ResourceElement observation1 = Samples.GetDefaultObservation().UpdateId("123"); ResourceElement observation2 = Samples.GetDefaultObservation().UpdateId("abc"); var resourceWrappers = new SearchResultEntry[] { new SearchResultEntry(CreateResourceWrapper(observation1, HttpMethod.Post)), new SearchResultEntry(CreateResourceWrapper(observation2, HttpMethod.Post)), }; var searchResult = new SearchResult(resourceWrappers, continuationToken: null, sortOrder: null, unsupportedSearchParameters: _unsupportedSearchParameters); ResourceElement actual = null; using (Mock.Property(() => ClockResolver.UtcNowFunc, () => _dateTime)) { actual = _bundleFactory.CreateSearchBundle(searchResult); } // Since there is no continuation token, there should not be next link. Assert.Null(actual.Scalar <string>("Bundle.link.where(relation='next').url")); Assert.Collection( actual.ToPoco <Bundle>().Entry, async e => await ValidateEntry(observation1.ToPoco <Observation>(), e), async e => await ValidateEntry(observation2.ToPoco <Observation>(), e)); async Task ValidateEntry(Observation expected, Bundle.EntryComponent actualEntry) { Assert.NotNull(actualEntry); var raw = actualEntry as RawBundleEntryComponent; using (var ms = new MemoryStream()) using (var sr = new StreamReader(ms)) { await raw?.ResourceElement?.SerializeToStreamAsUtf8Json(ms); ms.Seek(0, SeekOrigin.Begin); var resourceData = await sr.ReadToEndAsync(); Assert.NotNull(resourceData); Resource resource; resource = new FhirJsonParser().Parse(resourceData) as Resource; Assert.Equal(expected.Id, resource.Id); Assert.Equal(string.Format(_resourceUrlFormat, expected.Id), raw.FullUrl); Assert.NotNull(raw.Search); Assert.Equal(Bundle.SearchEntryMode.Match, raw.Search.Mode); } } }
public override PasswordExpiryInfo GetPasswordExpiryInfo(string username) { // at any point if we cannot determine if the password has expired or not // we assume the password has not expired PasswordExpiryInfo pei = null; LdapConnection ldap = null; try { ldap = GetLdapConnection(LdapUsername, LdapPassword); // assume not expired if (ldap == null) { return(null); } SearchResultEntry sre = GetUserSearchResultEntry(ldap, username); if (sre == null) { // assume not expired return(null); } string passwordExpirationTime = GetSearchResultEntryValue(sre, "passwordExpirationTime"); if (!string.IsNullOrEmpty(passwordExpirationTime)) { DateTime passwordExpiration = DateTime.MinValue; if (DateTime.TryParseExact(passwordExpirationTime, "yyyyMMddHHmmssZ", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.None, out passwordExpiration)) { pei = new PasswordExpiryInfo(passwordExpiration); return(pei); } } // assume not expired return(null); } catch (Exception ex) { _logger.Warn(ex, "Password expiration check failed. Assume password has not expired and continue authentication. {0}"); // assume not expired return(null); } finally { if (ldap != null) { ldap.Dispose(); ldap = null; } } }
/// <summary> /// Extension method to determine the type of a SearchResultEntry. /// Requires objectsid, samaccounttype, objectclass /// </summary> /// <param name="searchResultEntry"></param> /// <returns></returns> public static LdapTypeEnum GetLdapType(this SearchResultEntry searchResultEntry) { var objectId = searchResultEntry.GetObjectIdentifier(); if (objectId == null) { return(LdapTypeEnum.Unknown); } if (searchResultEntry.GetPropertyAsBytes("msds-groupmsamembership") != null) { return(LdapTypeEnum.User); } var objectType = LdapTypeEnum.Unknown; var samAccountType = searchResultEntry.GetProperty("samaccounttype"); //Its not a common principal. Lets use properties to figure out what it actually is if (samAccountType != null) { if (samAccountType == "805306370") { return(LdapTypeEnum.Unknown); } objectType = Helpers.SamAccountTypeToType(samAccountType); } else { var objectClasses = searchResultEntry.GetPropertyAsArray("objectClass"); if (objectClasses == null) { objectType = LdapTypeEnum.Unknown; } else if (objectClasses.Contains("groupPolicyContainer")) { objectType = LdapTypeEnum.GPO; } else if (objectClasses.Contains("organizationalUnit")) { objectType = LdapTypeEnum.OU; } else if (objectClasses.Contains("domain")) { objectType = LdapTypeEnum.Domain; } } //Override GMSA object type if (searchResultEntry.GetPropertyAsBytes("msds-groupmsamembership") != null) { objectType = LdapTypeEnum.User; } return(objectType); }
/// <summary> /// Processes the "member" property of groups and converts the resulting list of distinguishednames to TypedPrincipals /// </summary> /// <param name="entry"></param> /// <returns></returns> public static async IAsyncEnumerable <TypedPrincipal> ReadGroupMembers(SearchResultEntry entry) { var groupSid = entry.GetSid(); Cache.AddConvertedValue(entry.DistinguishedName, groupSid); Cache.AddType(groupSid, Label.Group); var members = entry.GetPropertyAsArray("member"); // If our returned array has a length of 0, one of two things is happening // The first possibility we'll look at is we need to use ranged retrieval, because AD will not return // more than a certain number of items. If we get nothing back from this, then the group is empty if (members.Length == 0) { foreach (var member in LDAPUtils.DoRangedRetrieval(entry.DistinguishedName, "member")) { var res = await LDAPUtils.ResolveDistinguishedName(member); if (res == null) { yield return new TypedPrincipal { ObjectIdentifier = member, ObjectType = Label.Unknown } } ; else { yield return(res); } } } else { //If we're here, we just read the data directly and life is good foreach (var member in members) { var res = await LDAPUtils.ResolveDistinguishedName(member); if (res == null) { yield return new TypedPrincipal { ObjectIdentifier = member, ObjectType = Label.Unknown } } ; else { yield return(res); } } } }
public static Dictionary <string, object> ReadGPOProperties(SearchResultEntry entry) { var props = new Dictionary <string, object> { { "description", entry.GetProperty("description") }, { "gpcpath", entry.GetProperty("gpcfilesyspath") } }; return(props); }
public string GetLdapUid(SearchResultEntry ldapEntity) { if (ldapEntity == null) { throw new ArgumentNullException("ldapEntity"); } return(ldapEntity.Attributes[Common.LdapUID] != null ? ldapEntity.Attributes[Common.LdapUID][0].ToString() : null); }
/// <summary> /// Executes implementation for this rule /// </summary> /// <param name="parent">The composed rule containing this rule</param> /// <param name="entry">The search result we are checking</param> /// <param name="attributeValue">The current attribute value as pass through the chain</param> /// <returns>Either a success or error result</returns> public override RuleResult Execute(ComposedRule parent, SearchResultEntry entry, string attributeValue) { if (string.IsNullOrEmpty(attributeValue)) { var updatedValue = this.Fixer(entry, attributeValue); return(this.GetErrorResult(ErrorType.Blank, updatedValue)); } return(this.GetSuccessResult()); }
private string GetEntryAttributeStringValue(SearchResultEntry entry, string attributeName, string defValue) { DirectoryAttribute attribute = entry.Attributes[attributeName]; if (attribute == null) { return(defValue); } return(attribute[0].ToString()); }
private LdapGroup CreateLdapGroup(SearchResultEntry entry) { LdapGroup ldapGroup = new LdapGroup(); ldapGroup.Id = GetEntryIdentityAttribute(entry, _ldapGroupIdentityAttribute); ldapGroup.Name = GetEntryRequiredAttributeStringValue(entry, _ldapGroupNameAttribute); ldapGroup.Dn = entry.DistinguishedName; ldapGroup.ModifiedOn = GetEntryDateTimeAttributeValue(entry, _ldapEntryModifiedOnAttribute); return(ldapGroup); }
public void GivenResults_WhenInitialized_ThenCorrectResultsShouldBeSet() { var expectedResourceWrapper = new SearchResultEntry[0]; var expectedUnsupportedSearchParameters = new List <Tuple <string, string> >(); var searchResult = new SearchResult(expectedResourceWrapper, null, null, expectedUnsupportedSearchParameters); Assert.Same(expectedResourceWrapper, searchResult.Results); Assert.Same(expectedUnsupportedSearchParameters, searchResult.UnsupportedSearchParameters); }
public byte[] GetObjectSid(SearchResultEntry ldapEntity) { if (ldapEntity == null) { throw new ArgumentNullException("ldapEntity"); } return(ldapEntity.Attributes[Common.LdapObjectSid] != null ? (byte[])ldapEntity.Attributes[Common.LdapObjectSid][0] : null); }
internal static void GetProps(SearchResultEntry entry, ResolvedEntry resolved, ref Domain obj) { if (!Utils.IsMethodSet(ResolvedCollectionMethod.ObjectProps)) { return; } obj.Properties.Add("description", entry.GetProp("description")); if (!int.TryParse(entry.GetProp("msds-behavior-version"), out var level)) { level = -1; } string func; switch (level) { case 0: func = "2000 Mixed/Native"; break; case 1: func = "2003 Interim"; break; case 2: func = "2003"; break; case 3: func = "2008"; break; case 4: func = "2008 R2"; break; case 5: func = "2012"; break; case 6: func = "2012 R2"; break; case 7: func = "2016"; break; default: func = "Unknown"; break; } obj.Properties.Add("functionallevel", func); }
public LdapUserEntity(SearchResultEntry ldapUser) { if (ldapUser != null) { DistinguishedName = GetDistinguishedName(ldapUser); SFqdnLdapUser = GetFullyQualifiedDomainName(DistinguishedName.Replace(',', '.')); SamaccountName = GetSamaccountName(ldapUser); LdapUid = GetLdapUid(ldapUser); LdapCommonName = GetCommonName(ldapUser); } }
public async Task GivenAResourceWithIncorrectId_WhenUpsertingConditionallyWithOneMatch_TheServerShouldFail() { var mockResultEntry = new SearchResultEntry(CreateMockResourceWrapper(Samples.GetDefaultObservation().UpdateId(Guid.NewGuid().ToString()), false)); ConditionalUpsertResourceRequest message = SetupConditionalUpdate( SaveOutcomeType.Updated, Samples.GetDefaultObservation().UpdateId(Guid.NewGuid().ToString()), mockResultEntry); await Assert.ThrowsAsync <BadRequestException>(() => _mediator.Send <UpsertResourceResponse>(message)); }
public bool LDAPSAuthenticate(String username, String pwd) { LdapConnection con = CreateConnection(); username = username.Trim(); try { con.Bind(); } catch (LdapException ex) { throw new LdapException(ex.Message); } catch (DirectoryOperationException ex) { throw new DirectoryOperationException(ex.Message); } try { string UsersDN = null; SearchRequest request = new SearchRequest( UsersDN, "(&(objectClass=person)(SAMAccountName=" + username + "))", System.DirectoryServices.Protocols.SearchScope.Subtree ); SearchResponse response = (SearchResponse)con.SendRequest(request); if (response.Entries.Count == 0) { return(false); } else { SearchResultEntry entry = response.Entries[0]; string dn = entry.DistinguishedName; con.Credential = new NetworkCredential(dn, pwd); con.Bind(); return(true); } } catch (DirectoryOperationException ex) { throw new DirectoryOperationException(ex.Message); } catch (LdapException ex) { throw new LdapException(ex.Message); } catch (Exception ex) { throw new LdapException(ex.Message); } }
/// <summary> /// Executes implementation for this rule /// </summary> /// <param name="parent">The composed rule containing this rule</param> /// <param name="entry">The search result we are checking</param> /// <param name="attributeValue">The current attribute value as pass through the chain</param> /// <returns>Either a success or error result</returns> public override RuleResult Execute(ComposedRule parent, SearchResultEntry entry, string attributeValue) { string objectType = this.GetObjectType(entry); if (objectType.Equals("group", StringComparison.CurrentCultureIgnoreCase)) { return(base.Execute(parent, entry, attributeValue)); } return(this.GetSuccessResult()); }
public ISDN(SearchResultEntry Entry, int Index = 0) { base.UpdateProperties(Entry, Index); this.ISDNAddressLength = base.RecordReader.ReadByte(); this.ISDNAddress = new String(base.RecordReader.ReadChars(this.ISDNAddressLength)); this.SubAddressLength = base.RecordReader.ReadByte(); this.SubAddress = new String(base.RecordReader.ReadChars(this.SubAddressLength)); base.RecordData = String.Format("\"{0}\" \"{1}\"", this.ISDNAddress, this.SubAddress); }
public HINFO(SearchResultEntry Entry, int Index = 0) { base.UpdateProperties(Entry, Index); this.CPULength = base.RecordReader.ReadByte(); this.CPU = new String(base.RecordReader.ReadChars(this.CPULength)); this.OSLength = base.RecordReader.ReadByte(); this.OS = new String(base.RecordReader.ReadChars(this.OSLength)); base.RecordData = String.Format("\"{0}\" \"{1}\"", this.CPU, this.OS); }
/// <summary> /// Creates a SearchResultEntry packet. /// </summary> /// <param name="context">The user context which contains message ID.</param> /// <param name="matchedDn">Matched DN.</param> /// <param name="attributes">The attributes and values that are contained in the entry.</param> /// <returns>The packet that contains the response.</returns> internal override AdtsSearchResultEntryPacket CreateSearchedResultEntry( AdtsLdapContext context, string matchedDn, params KeyValuePair<string, string[]>[] attributes) { int length = (attributes != null) ? attributes.Length : 0; PartialAttributeList_element[] partialAttributeElementArray = new PartialAttributeList_element[length]; for (int i = 0; i < length; i++) { partialAttributeElementArray[i] = new PartialAttributeList_element( new AttributeDescription(attributes[i].Key), CreateAttributeValueSet(attributes[i].Value)); } PartialAttributeList attributeList = new PartialAttributeList(partialAttributeElementArray); SearchResultEntry entry = new SearchResultEntry( new LDAPDN(matchedDn ?? string.Empty), attributeList); LDAPMessage_protocolOp operation = new LDAPMessage_protocolOp(); operation.SetData(LDAPMessage_protocolOp.searchResEntry, entry); LDAPMessage message = new LDAPMessage(new MessageID(context.MessageId), operation, null); AdtsSearchResultEntryPacket packet = new AdtsSearchResultEntryPacket(); packet.ldapMessagev3 = message; packet.messageId = context.MessageId; return packet; }
public int IndexOf(SearchResultEntry value) { }
public void CopyTo(SearchResultEntry[] values, int index) { }
// Methods public bool Contains(SearchResultEntry value) { }