Escaping non special characters in string for LDAP

2019-05-03 17:33发布

问题:

I hope that I have titled this question appropriately. Bit of a mixed subject here.

I have created a function in C# that creates an Active Directory User. Using an LDAP string that needs to look like this:

userinfo.displayName = "Surname, Firstname"

CN=" + userinfo.displayName, "user"

The following exception message is passed back, because of the comma being in the string.

An invalid dn syntax has been specified.

The full dn after the string has been applied is as following

"CN=Surname**,** Lastname,OU=Users,DC="Foo",DC="net"

The comma in the common name CN= is the problem...

Is there a way that C# can ignore the comma out of the string? Effectively escaping it.

回答1:

Escape invalid characters in a distinguished name is done with a leading slash ('\'). For example, the distinguished name above should be:

"CN=Surname\, Lastname,OU=Users,DC=Foo,DC=net"

According to section 2.4 of RFC 4514: Lightweight Directory Access Protocol (LDAP): String Representation of Distinguished Names, the characters , ", #, +, ,, ;, <, =, >, and \ can be escaped by a leading slash. Other non-alphanumeric characters should be shown in the form of \XX where XX are the hex digits of the UTF8 character encoding. See section 4 for examples.

Note that the X500DistinguishedName class (in System.Security Cryptography) does not appear to have a Parse or Escape method to help in this situation.



回答2:

Certain characters must be escaped with a backslash (\) followed by two hex digits, not a single backslash according to RFC4514. Many directory directory server support the \,, but since it is not standardized, LDAP clients must not use this notation - it would work on some servers but not others and clients must not assume they are communicating with a particular servers' software.