Code Monkey home page Code Monkey logo

s.ds.p's People

Contributors

jformacek avatar mmascolino avatar stevevillardi avatar thomaswurtz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

s.ds.p's Issues

"The syntax is invalid."

$Group=Find-LdapObject -LdapConnection:$conn -searchfilter "$($filter)" -SearchBase "$baseDN" -SearchScope "$searchScope" -PropertiesToLoad $attributes -PageSize 0 -RangeSize 0

$newmember = $($Group.member -join "','")

$TargetGroup='cn=testgroupNiLon,ou=groups,o=world'

$groupcontent = "'"+$newmember+"'"+","+"'"+$TargetGroup+"'"
#$GContent=get-content c:\temp\Group.txt
#properties to Modify
$Props = @{distinguishedName='cn=AAA-Test,ou=Groups,o=world';"member"=$null}
$obj = new-object PSObject -Property $Props
#Target UID
$obj.member = $($groupcontent)
#,'uid=1,ou=loadtest,ou=test,o=world','uid=lon3897,ou=people,ou=test,o=world'

#Function to Add new attribute

 $Ldap = Get-LdapConnection -LdapServer "$hostName" -EncryptionType Kerberos   
               edit-LdapObject -LdapConnection $conn -Object $obj

transform in guid.ps1 incorrectly contains rightsGuid

Describe the bug
rightsGUID stored in configuration context in Active Directory is stored as string not binary.

Register-LdapAttributeTransform -Name guid includes rightsGUID and tries to read string as binary and fails.

To Reproduce
Steps to reproduce the behavior:

$LDAPCon = Get-LdapConnection
$RootDSE = Get-RootDSE -LdapConnection $LDAPCon

# Reading rightsGuid straight without transform works:
Find-LdapObject -LdapConnection $LDAPCon -searchBase $RootDSE.configurationNamingContext -searchFilter "(ObjectClass=ControlAccessRight)" -PropertiesToLoad rightsGuid | Select -First 1

distinguishedName                                                             rightsGuid
-----------------                                                             ----------
CN=Domain-Administer-Server,CN=Extended-Rights,CN=Configuration,DC=<ForestDN> ab721a52-1e2f-11d0-9819-00aa0040529b

# fails when using transform
Register-LdapAttributeTransform -Name guid

 Find-LdapObject -LdapConnection $LDAPCon -searchBase $RootDSE.configurationNamingContext -searchFilter "(ObjectClass=ControlAccessRight)" -PropertiesToLoad rightsGuid | Select -First 1
New-Object : Exception calling ".ctor" with "1" argument(s): "Byte array for GUID must be exactly 16 bytes long."
At C:\Users\sczeppa1\OneDrive - Novartis Pharma
AG\Documents\WindowsPowerShell\Modules\S.DS.P\2.1.4\Transforms\guid.ps1:26 char:13
+             New-Object System.Guid(,$Value)
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand


distinguishedName                                                             rightsGuid
-----------------                                                             ----------
CN=Domain-Administer-Server,CN=Extended-Rights,CN=Configuration,DC=<ForestDN>

Expected behavior
Registering 'guid' transform should not not throw an error when reading rightsGuid

Environment (please complete the following information):

  • OS: Windows 10
  • PowerShell version 7.2, 5.1, ...
  • S.DS.P Module version 2.1.4

Proposed Solution
in .\Transforms\guid.ps1 remove rightsGuid SupportedAttributes.

Thank you for your support.

TypeNotFound

When I try to run the get-ldapconnection command I get an error

Unable to find type [System.DirectoryServices.Protocols.AuthType].
At line:795 char:9

  •     [System.DirectoryServices.Protocols.AuthType]
    
  •     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidOperation: (System.Director...tocols.AuthType:TypeName) [], RuntimeException
    • FullyQualifiedErrorId : TypeNotFound

I must of somehow got it working before as my current script I can use the powershell IDE but any new powershell windows get this error.

A request

Please contact me as I have a request I would like to discuss by mail. Thanks!

Support Linux and Mac

Is your feature request related to a problem? Please describe.
When trying to use this module on Linux or Mac, the following error message is always observed:
MethodInvocationException: Exception calling "SendRequest" with "2" argument(s): "The feature is not supported. "

Describe the solution you'd like
I'd like to either know how to make this module work on Mac and Linux or help make this module work on Mac and Linux. If this is a limitation of PowerShell on Mac and Linux, I would like to know that, so that I can close this issue, and file an issue on that repository.

Describe alternatives you've considered
The Azure AD module doesn't work and the ActiveDirectory module isn't available on Mac or Linux

Unable to supply credentials for eDirectory

I am trying to get the module to work against eDirectory. When I do the get-credential -credential and use my user name of cn=myuser,o=admorg I get the popup for supplying the password, but then it complains about the username format and won't let me continue.

I have used the s.ds.p module against AD and it works fine (wonderfully in fact). But I also need to use against other ldap directories that don't use the same credential format. I have just started with eDirectory because it is the most pressing.

[FeatureRequest] SizeLimit Option for Find-LDAPObject

Is your feature request related to a problem? Please describe.
The ability to set the SizeLimit when searching when using Find-LDAPObject

Describe the solution you'd like
A parameter for the function or if it is currently possible, help updated with an example.

Describe alternatives you've considered
I tried the AdditionalControls pamameter but it seems limited to System.DirectoryServices.Protocols.DirectoryControl

Additional context
This is useful when testing queries that will return large sets of data, but would like a quick, limited set of data returned to validate.

Support * wildcard in PropertiesToLoad so that all attributes should be included in matching entries.

It is a common requirement that one might not know the attribute names to be returned in advance.

This is supported by the LDAP standard in that you can send a wildcard character and the server will return all attributes on the object. This is well known and supported by other LDAP query tools.

Would like to see the ability to specify * (and also + for operational attributes) in PropertiesToLoad parameter. That this will then return all attributes and operational attributes from the matched objects.

Have investigated and verified that the underlying API has support for returning the list of all attributes on an object.

Unsure whether this will conflict with the existing ranged attribute code.
Seems like this will require changes to the template for output object code. That these optimizations in object initialization would need to be disabled if this mode is chosen.

non AD add-ldapobject

Describe the bug
Trying to add a user to edir and I'm required to add distinguished name, which is an invalid attribute. I can add it to ignoredprops but then I get a: An object class violation occurred. Any help would be great.

Ranged retrieval of msds-replvaluemetadata fails

Describe the bug
Ranged retrieval of msds-replvaluemetadata fails because the initial query in GetResultsIndirectlyRangedInternal returns both a ranged and non-ranged version of the attribute.

[DBG]: PS C:\>> $sr.Attributes.AttributeNames
msds-replvaluemetadata
msds-replvaluemetadata;range=0-999

The non-ranged version enters the foreach loop and completes correctly. Then the ranged version of the attribute enters the loop and fails due to a double specification of the range:

msds-replvaluemetadata;range=0-999;range=0-99

This problem does not manifest with LVR attribute like "member".

If the ranged version of the attribute is skipped, the data is returned correctly.

To Reproduce
Steps to reproduce the behavior:
Search for replication metadata on a large group, using a ranged query

Find-LdapObject -LdapConnection $ldp -searchscope Base -searchBase "cn=biggroup,ou=groups,dc=domain,dc=local" -searchFilter "(objectclass=*)" -PropertiesToLoad "msds-replvaluemetadata" -RangeSize 100

Expected behavior
Attribute requested is returned without error.

Environment (please complete the following information):

  • OS: Windows Server 2016

  • PowerShell version
    PSVersion 5.1.14393.3866
    PSEdition Desktop
    PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
    BuildVersion 10.0.14393.3866
    CLRVersion 4.0.30319.42000
    WSManStackVersion 3.0
    PSRemotingProtocolVersion 2.3
    SerializationVersion 1.1.0.1

  • S.DS.P Module version
    2.12-beta

Additional context
Add any other context about the problem here.

Authenticating Using A Certificate

I would like to use a certificate to authenticate when using S.DS.P in both of the following ways
[1]
$creds = Get-Credential -Message 'Select Certificate/SC'

[2]
$cert = ChildItem Cert:\LocalMachine\My<Thumbprint>

Is that possible?

Performing Query With Additional Control(s)

I was wondering how to specify the additional control with Find-LDAPObject when you got the OID (https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/3c5e87db-4728-4f29-b164-01dd7d7391ea)

LDAPCONTROLOID = "xyz"

Find-LdapObject -LdapConnection:$xyz -SearchBase:"$abc" -SearchScope:Subtree -SearchFilter:$def -propertiesToLoad:@("something") -BinaryProperties:@("something") -RangeSize:0 -AdditionalControls $XXX

How to define $XXX if you have got the OID?

Cannot process argument transformation on parameter 'Credential'. userName

Hello, I've seen that I'm not the first to struggle with the credentials to use in your script, but it actually works if I try to connect as Anonymous so that's good.
Altough I need to be able to log as admin to edit the LDAP later on.
Problem is that I can't seem to get it working.
I've tried these two ways of writing down my $creds var :
$credentials = new-object System.Net.NetworkCredential -ArgumentList $user,$pwd
$credentials=new-object System.Net.NetworkCredential("cn-admin,dc=ym,dc=com","xxxxx","")
or with and without calling string variables but I still have the following error :

Get-LdapConnection : Cannot process argument transformation on parameter 'Credential'. userName
At C:\sys\scripts\testSDSP.ps1:28 char:129
+ ... -AuthType Basic -EncryptionType None -Credential $credentials  ...
+                                                      ~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-LdapConnection], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-LdapConnection

I even went on trying to edit hte module code to allow me to pass the string values then transform them into creds once in the module but it wasn't happy that I moved lines to the point where the code would trow me errors about functions I didn't touch 🌊

#

$pwd = "XXXXXXX"
$user = "cn=admin,dc=XXXXX,dc=com"
$credentials = new-object System.Net.NetworkCredential -ArgumentList $user,$pwd

$MyConnection=Get-LdapConnection -LdapServer:XXXX.frymghq.XXXX.com -Port 389 -AuthType Basic -EncryptionType None -Credential $credentials

This is what I wrote for testing purpose and that's what fails, hope you can help :)
BTW I'm on powershell 5.1 installed on a Windows Server 2008R2 wich has full network access to the remote server

SecurityDescriptor transform

The transform definition for securityDescriptor.ps1, ms-DS-GroupMSAMembership is not correct. It should be using the Ldap-Display-Name entry as descripted in the Microsoft documentation. The correct value is msDS-GroupMSAMembership.

https://docs.microsoft.com/en-us/windows/win32/adschema/a-msds-groupmsamembership

To Reproduce
It's possible to reproduce with the following code if there is any gMSA or MSA in the domain.
The code will show that the value for ms-DS-GroupMSAMembership is empty and binary data is shown for msDS-GroupMSAMembership.

Register-LdapAttributeTransform -Name SecurityDescriptor
$LDAP = Get-LdapConnection -EncryptionType Kerberos -AuthType Kerberos
$DSE = Get-RootDSE -LdapConnection $LDAP
$LdapObjects = Find-LdapObject -LdapConnection $LDAP -searchBase $DSE.defaultNamingContext -searchFilter "(|(objectClass=msDS-ManagedServiceAccount)(objectClass=msDS-GroupManagedServiceAccount))" -PropertiesToLoad Name,msDS-GroupMSAMembership,ms-DS-GroupMSAMembership
$LdapObjects | Select-Object Name,msDS-GroupMSAMembership,ms-DS-GroupMSAMembership

Expected behavior
It should be expected that the value would be transformed using the transform definition in securityDescriptor.ps1.

Environment:

  • OS: Windows Server 2019
  • PowerShell version 7.2 or 5.1
  • S.DS.P Module version 2.1.3

Huge difference in query time compared to other methods

QUERYING FOR OBJECTS:
"computer"
"inetOrgPerson"
"msDS-GroupManagedServiceAccount"
"user"
"group"
"container"
"organizationalUnit"
"domainDNS"
QUERYING FOR ATTRIBUTES:
"accountExpires"
"canonicalName"
"carLicense"
"cn"
"displayName"
"distinguishedName"
"lastLogonTimestamp"
"lockoutTime"
"mail"
"msDS-AllowedToActOnBehalfOfOtherIdentity"
"msDS-AllowedToDelegateTo"
"msDS-SupportedEncryptionTypes"
"msDS-UserPasswordExpiryTimeComputed"
"name"
"nTSecurityDescriptor"
"objectClass"
"ObjectGUID"
"pwdLastSet"
"sAMAccountName"
"servicePrincipalName"
"userAccountControl"
"UserPrincipalName"
"whenCreated"

Number of Objects: 100341

S.DS.P ==> Time Elapsed....: '49.2810517766667' Minutes
ADSI ==> Time Elapsed....: '1.46958625833333' Minutes
AD POSH==> Time Elapsed....: '4.44061052333333' Minutes
ADFIND ==> Time Elapsed....: '2.25115640833333' Minutes

I seriously do not understand why that S.DS.P posh module is so slow

If you need more info, feel free to ask

Display all attribute of specific user

Hi team,
How can i get the passwordneverexpired of the user? Or display all yhe attribute properotes of the user?

`find-ldapobject -ldapconnection:$conn -searchfilter "extshortname=testuser" -searchbase "ou=domain,ou=com" -searchscope "sub" -propertiestoload "*" -pagesize 0 -rangesize 0'

Hwoing error taht exception setting..etc.
But the passwordneverexpiered is not display?
1599733158818281242831379336440

Thanks.

Unable to login, throws error as Strong authentication is required for this operation

Hi, We are trying to login our Domain Controller using the domain account, but its returning us the below error, can someone please help understand why this error and what should be the resolution ? any changes / pre-requisites on Domain Controller local security policies required ?

Exception calling "SendRequest" with "1" argument(s): "Strong authentication is required for
this operation."
At C:\owen\PID Enumeration - AD\S.DS.P.psm1:360 char:13

  •         $rsp=$LdapConnection.SendRequest($rq)
    
  •         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
    • FullyQualifiedErrorId : DirectoryOperationException

List all user objects

Hi.

Im using the find-ldapobject. What parameters do i need to add to list all users without limit.

My ad users are morethan 700,000 plus.

Is theres away to pull the users object in just one query.

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment (please complete the following information):

  • OS: [e.g. Win8]
  • PowerShell version [$psVersionTable]
  • S.DS.P Module version [e.g. 1.9.1]

Additional context
Add any other context about the problem here.

Blank values returned against LDAP

First, thanks a ton for putting this together. Saved me a lot of time in writing a module like this.

I'm running the Find-LdapObject against NetIQ based eDirectory LDAP server on SSL. The returned results contains only DNs but does not contain any attributes that I may specify in -PropertiesToLoad. However, the filter specified in -searchFilter does indeed work. I've verified the results against a Perl based extract and the results are spot on.

The property -PropertiesToLoad itself doesn't appear to accept a wildcard value. I'm going through the script to see if there needs to be anything modified. This "issue" is raised only to make you aware of the problem.

I'm currently currently experimenting with the module to see what changes would achieve the results I expect and if I find anything, I'll make a Pull request to submit my changes. But if you are aware of the problem, save me the searching please :)

How to grab nTSecurityDescriptor attribute via S.DS.P

Hello,

I am trying to grab the nTSecurityDescriptor attribute, specifically nTSecurityDescriptor.Owner (at least in PowerShell via AD module its like that) to get who created the user object. How would I do this via Find-LdapObject?

I have tried -PropertiesToLoad:@(‘nTSecurityDescriptor’)
with BinaryProps:@(‘nTSecurityDescriptor.Owner’) but they don't load the attribute or at least even the object, the field is blank.

How would I go about doing this?

Thank you for this module though, it is fantastic.

Best,

Chris

Getting size limit is exceed ,im trying to count first the user object in my ldap server and i have a more than 1k users. but when i execute the script it gives me error

Load the required modules.

Import-Module S.DS.P

Pass in a valid username and password to get privileged directory access.

For continued use in an application, get a serice account vs personal t#

$userName = ""
$password = ""

Provide the directory domain name and port.

$hostName = "test.com"
$port = 636

Provide the LDAP search parameters.

$filter = "(uid=*)"
$baseDN = "ou=people,ou=test,o=World"
$searchScope = "Sub"
$attributesToReturn = @("uid")

Establish a connection to the directory and authenticate.

$directoryIdentifier = New-Object System.DirectoryServices.Protocols.LdapDirectoryIdentifier($hostName, $Port)
$conn = New-Object System.DirectoryServices.Protocols.LdapConnection($directoryIdentifier)
$conn.SessionOptions.SecureSocketLayer=$true
$conn.AuthType = "Basic"
$cred = New-Object System.Net.NetworkCredential($userName, $password)
$conn.Credential = $cred
$conn.Bind()

Execute the search and display the entries.

$test = Find-LdapObject -LdapConnection:$conn -SearchFilter "$filter" -SearchBase "$baseDN" -SearchScope "$searchScope" `
-PropertiesToLoad $attributesToReturn -PageSize 0 -RangeSize 0

"$($test.count)"

Paged search "streaming"/"looping" (iterator function)

Is your feature request related to a problem? Please describe.
I have to dump the (custom parsed) entries of a huge (>100k entries) non-AD LDAP directory into a CSV file for further processing in a reporting DB. While the paged query is working I did not find a way to prevent that Find-LDAPObject is fetching/storing the entire result set before continuing ->with this data size RAM limitations lead to issues.

Describe the solution you'd like
I would like to be able to loop over each paged result set (e.g. 1000 records) returned from the directory then parse it, write it to the CSV file and then continue to the next paged result set so that at any time no more than one page size count of entries have to be stored in memory before flushing it to the CSV file.

Describe alternatives you've considered
There are not that many alternatives when it comes to using Powershell with non-AD LDAP queries (that is why I am here) unless I want to code everything from scratch with .NET assemblies.

Additional context

Implement support for System.DirectoryServices.Protocols.DirSyncRequestControl

I'm currently implementing a little tool to automatically update group memberships in one domain as soon as possible after it has been changed in another domain. This is to support special migration scenario.
To do so I would like retrieve only those groups that have been changed since last checked. Asserting the correct permissions (CA;Replicating Directory Changes) this can be achieved by using the System.DirectoryServices.Protocols.DirSyncRequestControl as described here: https://dloder.blogspot.com/2012/01/powershell-dirsync-sample.html

Although the referenced code works quite nicely, I would be happy if I could use s.ds.p for this as this would avoid all sorts of other custom code.
Thank you very much for thinking about implementing this feature request.

Memberof does not display

Hi jiri,
I tried to export all the attributes properties of the user using export-csv but the only properties that im noy able to fetch is memberof.it leaves blank.
Im using 1.7. Version.
I used new-object -type psobject -properties to export the
Please advise on how to achieve the memberof display on csv file.
See command below.
Thanks.

here is the command that i used $user=find-ldapobject....

Memberof=$($user.emberof -join "`n")|export-csv c:\temp\res.csv -append

No error display

Intried to input wrong value but no error appear.
I used tty catch and add -erroraction stop at the end of the command but still no error appears

find-ldapobject -ldapconnection:$conn -searchfilter "$filter" -searchbase $basedn" -searchscope "$searchscope" -propertiestoload "$attrib" `

Attributes being presented as objects/arrays

Hi,

With Find-LdapObject trying to list of objects and list of properties. In my script I have code processing the data.
It looks as if when there is no value in the attribute it presents it as { }, which is an object or array, while the attribute in AD in reality is single valued (string, integer)

So if it has a value ==> x: 123
So if it has no value ==> x: { }

Why is that? Is that a bug?

Thanks
Best regards,
jorge

Getting objectexits

Hi Team,
Im trying to add new attribute to my user using below script but im getting 'The object is already exist"
see below script. what would be wrong
#properties to Modify
$Props = @{"distinguishedName"=$null;"mailAlternateAddress"=$null} #;"sAMAccountName"=$null;"unicodePwd"=$null;"userAccountControl"=0}

$obj = new-object PSObject -Property $Props
#Target UID
$obj.DistinguishedName ="UID=DS7765,ou=testtao,ou=test,o=world"
#$obj.extNtDomain="NA"
$obj.mailAlternateAddress="[email protected]"

 
#Function to Add new attribute
 $Ldap = Get-LdapConnection -LdapServer "$hostName" -EncryptionType Kerberos 
         Add-LdapObject -LdapConnection $conn -Object $obj

Error encounter:
Exception calling "SendRequest" with "2" argument(s): "The object exists."
At C:\Program Files\WindowsPowerShell\Modules\S.DS.P\2.0.6\S.DS.P.psm1:857 char:13

"The LDAP server is unavailable." error when connecting to a LDAP server not hosted on standard port 636

Describe the bug
We have an Forgerock DS server hosted on a non-standard port (5636 for eg.,) which is also published via a load balancer on standard port 636. Trying to run a Find-LdapObject throws an error of "The LDAP server is unavailable". The command successfully completes on non-standard unencrypted port 4389 and on standard ports via load balancer (389 & 636).

This is all that is on the error message

PSMessageDetails :
Exception : System.Management.Automation.MethodInvocationException: Exception calling "SendRequest" with
"1" argument(s): "The LDAP server is unavailable." --->
System.DirectoryServices.Protocols.LdapException: The LDAP server is unavailable.
at System.DirectoryServices.Protocols.LdapConnection.Connect()
at System.DirectoryServices.Protocols.LdapConnection.SendRequestHelper(DirectoryRequest
request, Int32& messageID)
at System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest request,
TimeSpan requestTimeout)
at CallSite.Target(Closure , CallSite , LdapConnection , SearchRequest )
--- End of inner exception stack trace ---
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext
funcContext, Exception exception)
at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame
frame)
at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
TargetObject :
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : LdapException
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at GetResultsDirectlyInternal, C:\Program
Files\WindowsPowerShell\Modules\S.DS.P\2.1.6\S.DS.P.psm1: line 2000
at Find-LdapObject, C:\Program
Files\WindowsPowerShell\Modules\S.DS.P\2.1.6\S.DS.P.psm1: line 416
at , : line 1
PipelineIterationInfo : {}

When I look at the LDAP server logs, I can see a connection being initiated but that's about it.

[29/Nov/2023:04:18:03 +0400] CONNECT conn=2414127 from=10.1.10.111:52746 to=10.225.0.120:5636 protocol=LDAPS

There are nothing else on the logs. Usually, there are lines indicating a BIND, SEARCH/MODIFY/COMPARE, UNBIND and DISCONNECT operations. And eventually at about 90 seconds mark, I see a DISCONNECT due to timeout.

I thought it could be something to do with Certificates, so I added -CertificateValidationFlags AllFlag and this time, the command takes a while thinking about it yet returns nothing. However on the logs, I see a CONNECT, BIND, SEARCH, UNBIND & DISCONNECT operations with SEARCH returning 2 results. I don't see these two entries returned as a response on the console.

To clarify, the certificates are trusted on the local machine (in fact SSL offloading is not enabled on load balancer so connecting via load balancer presents the same certificate as the server) and all DNS names are present as SAN. I'm not quite sure what the issue is here.

Environment (please complete the following information):

  • OS: WIN11/Server 2019
  • PowerShell version [$psVersionTable]: 5.1.17763.4974 & 7.2.1 on server side & 7.2.16 on client side
  • S.DS.P Module version [e.g. 1.9.1]: 2.1.6

Not posting the correct ports/IP addresses/server names/logs because this is a production server but if required, can share these info on direct message.

Base Scoped Query for non-AD LDAP unexpectedly returns all attributes

If I do a base scoped search like this:

$dn = "uid=myaccountname,ou=people,ou=example,o=world"
Find-LdapObject `
-LdapConnection (Get-LdapConnection -LdapServer ldap.example.com -Port 636 -AuthType Basic) `
-searchFilter "(objectclass=*)" `
-searchBase $dn `
-searchScope Base `
-PageSize 0 `
-AdditionalProperties @('cn','mail') `
-RangeSize 0

The underlying LDAP directory appears to be returning all the attributes for the entry and thus throws errors like this when it is trying to set the values into the PSObject

Exception setting "extfunction": "The property 'extfunction' cannot be found on this object. Verify that the property exists and can be set."
At C:\Program Files\WindowsPowerShell\Modules\S.DS.P\1.8.2\S.DS.P.psm1:305 char:29
+                             $data.$attrName=FlattenArray($vals)
+                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationException
    + FullyQualifiedErrorId : ExceptionWhenSetting

Exception setting "extionkey": "The property 'extionkey' cannot be found on this object. Verify that the property exists and can be set."
At C:\Program Files\WindowsPowerShell\Modules\S.DS.P\1.8.2\S.DS.P.psm1:305 char:29
+                             $data.$attrName=FlattenArray($vals)
+                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationException
    + FullyQualifiedErrorId : ExceptionWhenSetting

Account Expires attritbute filetransform

Describe the bug
when querying ActiveDirectory, the accountexpires attribute is returned with type int64 (at least with get-ADObject)
The transform filetime.ps1 fails on converting, when account expires is set to "never expire". The possible values are
9223372036854775807 or 0.

Steps to reproduce the behavior:

  1. set an AD account to any expire date with ADUC
  2. change this AD account back to "never expire"
  3. query accountexpires with the filetime.ps1 transform
  4. no expire date is returned for this account

Expected behavior
file transform should return 0 or $null (it would be even better, if it returns for both never expire values a $null)

See as reference:
https://docs.microsoft.com/en-us/windows/win32/adschema/a-accountexpires

quick solution:
change:
[DateTime]::FromFileTimeUtc([long]$Value)
to:
[DateTime]::FromFileTimeUtc([int64]$Value)

Moving object from one OU to another

First of all : thanks for your job :) That's really amazing !

Maybe i didn't find it ... But is there a way to move an user from one OU to another ?

Thanks !

Error: Exception calling "AddRange" with "1" argument(s): "Value cannot be null. Parameter name: values"

Hello,

I'm trying to use the Add-LdapObject but I keep bumping over this same error :
Exception calling "AddRange" with "1" argument(s): "Value cannot be null. Parameter name: values"

Here's the part of the code I'm doing
`$Props = @{"distinguishedName"=$null;"sambaPwdLastSet"=$null;"objectClass"=$null;"sAMAccountName"=$null;"sambaSID"=$null;"sambaNTPassword"=$null;"userAccountControl"=0;"gidNumber"=$null;"cn"=$null;"sn"=$null;"givenname"=$null;"Userpassword"=$null;"company"=$null;"displayName"=$null;"employeeType"=$null;"mail"=$null;"homeDirectory"=$null;"extensionAttribute5"=$null;"mailhost"=$null;"loginShell"=$null;"uidNumber"=$null;"extensionAttribute15"=$null;"extensionAttribute4"=$null;"gecos"=$null;"title"=$null;"extensionAttribute1"=$null;"mailForwardingAddress"=$null}
$obj = new-object PSObject -Property $Props
$obj.DistinguishedName = ("uid="+$ReceivedObject.user_username+","+$ldap_OU)
$obj.sAMAccountName = $ReceivedObject.user_username
#$obj.objectClass = @("top","sambaPwdLastSet","organizationalPerson","loginShell","displayName","mailHost","gidNumber","person","inetorgperson","inetuser","mailrecipient","pwmuser","sambaSID","uidNumber","posixAccount","shadowAccount","sambaSamAccount","YmagisPrivate")
$obj.objectClass = "person"
$obj.cn = ($ReceivedObject.user_firstname+" "+$ReceivedObject.user_lastname)
$obj.displayName = ($ReceivedObject.user_lastname+" "+$ReceivedObject.user_firstname)
$obj.sn = $ReceivedObject.user_lastname
$obj.givenName = $ReceivedObject.user_firstname
$obj.company = $ReceivedObject.user_company
$obj.employeeType="employee"
$obj.homeDirectory=("/opt/Shares/Homes/"+$ReceivedObject.user_username)
$obj.extensionAttribute5="nomail" #$ReceivedObject.user_domain
$obj.extensionAttribute15="ActiveUser"
$obj.extensionAttribute4=$ReceivedObject.user_division
$obj.gecos = ($ReceivedObject.user_firstname+" "+$ReceivedObject.user_lastname)
$obj.title = $ReceivedObject.user_title
$obj.extensionAttribute1=$user_site
$obj.mail = "nomail"
$obj.gidNumber = 2000
$obj.loginShell = "/bin/false"
$obj.mailHost = "mail-0602.frynoc2.ymagis.com"

            $obj.mailForwardingAddress=($ReceivedObject.user_username+"@ymagisgroup.mail.onmicrosoft.com")
            $obj.uidNumber = Get-Random -Minimum 13500 -Maximum 20000
            $obj.sambaSID = "S-1-5-21-$($obj.uidNumber)"
            $textfilename = -join ((65..90) + (97..122) | Get-Random -Count 8 | % {[char]$_})
            Start-Process -FilePath "C:\python27\python.exe" -verb runas "C:/sys/syncsystem/openldappwd.py","$($ReceivedObject.user_pwd)","$($textfilename)"
            $int = 0
            do
            {
            Sleep(1)
            $int++
            }while(-not(Test-Path -Path "C:\sys\syncsystem\$textfilename.txt") -and $int -lt 10)
            $int=0
            Sleep(1)
            if(Test-Path -Path "C:\sys\syncsystem\$textfilename.txt")
            {
                foreach($line in Get-Content "C:\sys\syncsystem\$textfilename.txt" -Raw) {
                    if($line -ne $null -and $int -eq 0){
                        # Work here
                        $sha_pwd = $line
                    }
                    if($line -ne $null -and $int -eq 1){
                        # Work here
                        $nt_pwd = $line
                    }
                    $int++
                }
                Remove-Item "C:\sys\syncsystem\$textfilename.txt" -Force
                $epoch = (Get-Date -Date ((Get-Date).DateTime) -UFormat %s)
                $obj.sambaPwdLastSet = $epoch
                $obj.Userpassword = $sha_pwd
                $obj.sambaNTPassword = $nt_pwd
                Write-Log "DEBUG" $obj
                try{
                    Write-Log "INFO" "Trying to create the user..."
                    Add-LdapObject -LdapConnection $global:MyConnection -Object $obj
                    return 0
                    }
                    catch{
                        
                        Write-Log "ERROR" $_
                        
                        return -1
                    }

`
Can you help me identify what's wrong in my code?
Also I'd like to send multiple ObjectClass for the same obj, how can I do that ?

Base scoped search of Active Directory doesn't return property values

If I perform a base scoped search of Active Directory like this:

Find-LdapObject -LdapConnection (Get-LdapConnection)`
    -searchBase "CN=theuser,CN=Users,DC=na,DC=example,DC=com" `
    -searchScope Base -AdditionalProperties @('displayname', 'mail', ) `
    -searchFilter '(objectclass=*)'

I get no result values for displayname and mail like this:

mail distinguishedName                      displayname 
---- -----------------                      ----------- 
     CN=ajjan.r,CN=Users,DC=na,DC=example,DC=com

If I repeat the query above with -RangeSize 0, it returns all attributes (like my non-AD example) and thus the setting of non-existent properties exception occurs.

Ranged AD query for msDS-ReplValueMetaData throws errors

Query Active Directory using the property msDS-ReplValueMetaData returns unexpected value if more than 1000 objects are stored in the attribute resulting in errors and an infinite loop:

Find-LdapObject -LdapConnection $LDAPServer -searchBase "CN=group,OU=Org,DC=domain,DC=net"  -searchScope base -searchFilter "(objectclass=*)" -PropertiesToLoad "msDS-ReplValueMetaData" -RangeSize 1000

Index operation failed; the array index evaluated to null.
At C:\Program Files\WindowsPowerShell\Modules\s.ds.p\2.1.6\S.DS.P.psm1:2460
char:33
+ ...             $data[$attrName] += $srAttr.Attributes[$returnedAttrName] ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArrayIndex

You cannot call a method on a null-valued expression.
At C:\Program Files\WindowsPowerShell\Modules\s.ds.p\2.1.6\S.DS.P.psm1:2462
char:32
+ ...          if($returnedAttrName.EndsWith("-*") -or $returnedAttrName -e ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

The same does not happen retrieving member attribute.

This happens as AD returns for whatever reason the original asked attribute as well as the ranged value attritbute:

$rsp.Entries

DistinguishedName                          Attributes Controls
-----------------                           ---------- --------
CN=group,OU=Org,DC=domain,DC=net {member}   {}      


$rsp.Entries

DistinguishedName                          Attributes Controls
-----------------                           ---------- --------
CN=group,OU=Org,DC=domain,DC=net {msds-replvaluemetadata, msds-replvaluemetadata;range=0-999} {}      

msds-replvaluemetadata;range=0-999 is not expected in the initial query.

The foreach($attrName in $AttributeNames) will fail when getting to the second, invalid, entry.

I solved this using an ugly workaround, slightly changing the loop

$AttributeNames = $sr.Attributes.AttributeNames | Where-Object {'' -eq $PropertiesToLoad -or ( $PropertiesToLoad -contains $_ ) -or ( $AdditionalProperties -contains $_ ) }
 foreach($attrName in $AttributeNames) {

This should allow for no entries (like propertiesToLoad '') or a set of properties or even a manual ranged search (like propertiesToLoad "msDS-ReplValueMetaData;range=1000-1999") .
Though I don't know if I can expect $PropertiesToLoad to either contain nothing (
) or the full list of attributes that might ever be returned in the first search.

Find-LdapObject

Hi!

using: S.DS.P-Version 1.9.9

This short script code

$LDAPCONNECT = Get-LdapConnection -LdapServer myServer.myDomain.de -Port 636 -EncryptionType SSL
$SEARCHBASE = "OU=Windows10,OU=Benutzer,DC=mast,DC=country,DC=com"

$ADUSERs = Find-LdapObject -LdapConnection $LDAPCONNECT -SearchFilter "(&(objectClass=user)(objectCategory=organizationalPerson))" -SearchBase $SEARCHBASE -PropertiesToLoad "Name","telephoneNumber","mail" |
Sort-Object -Property Name

produces the following messages per record found in addition to the correct results

Der Typ [Flattener] wurde nicht gefunden.
In C:\Program Files\WindowsPowerShell\Modules\S.DS.P\1.9.9\S.DS.P.psm1:340 Zeichen:43
+                         $data.$attrName = [Flattener]::FlattenArray($ ...
+                                           ~~~~~~~~~~~
	+ CategoryInfo          : InvalidOperation: (Flattener:TypeName) [], RuntimeException
	+ FullyQualifiedErrorId : TypeNotFound

The results are as far as correct but the messages seem to be irrelevant and at least not nice.

Regards Frank

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.