dn.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. // File contains DN parsing functionality
  2. //
  3. // https://tools.ietf.org/html/rfc4514
  4. //
  5. // distinguishedName = [ relativeDistinguishedName
  6. // *( COMMA relativeDistinguishedName ) ]
  7. // relativeDistinguishedName = attributeTypeAndValue
  8. // *( PLUS attributeTypeAndValue )
  9. // attributeTypeAndValue = attributeType EQUALS attributeValue
  10. // attributeType = descr / numericoid
  11. // attributeValue = string / hexstring
  12. //
  13. // ; The following characters are to be escaped when they appear
  14. // ; in the value to be encoded: ESC, one of <escaped>, leading
  15. // ; SHARP or SPACE, trailing SPACE, and NULL.
  16. // string = [ ( leadchar / pair ) [ *( stringchar / pair )
  17. // ( trailchar / pair ) ] ]
  18. //
  19. // leadchar = LUTF1 / UTFMB
  20. // LUTF1 = %x01-1F / %x21 / %x24-2A / %x2D-3A /
  21. // %x3D / %x3F-5B / %x5D-7F
  22. //
  23. // trailchar = TUTF1 / UTFMB
  24. // TUTF1 = %x01-1F / %x21 / %x23-2A / %x2D-3A /
  25. // %x3D / %x3F-5B / %x5D-7F
  26. //
  27. // stringchar = SUTF1 / UTFMB
  28. // SUTF1 = %x01-21 / %x23-2A / %x2D-3A /
  29. // %x3D / %x3F-5B / %x5D-7F
  30. //
  31. // pair = ESC ( ESC / special / hexpair )
  32. // special = escaped / SPACE / SHARP / EQUALS
  33. // escaped = DQUOTE / PLUS / COMMA / SEMI / LANGLE / RANGLE
  34. // hexstring = SHARP 1*hexpair
  35. // hexpair = HEX HEX
  36. //
  37. // where the productions <descr>, <numericoid>, <COMMA>, <DQUOTE>,
  38. // <EQUALS>, <ESC>, <HEX>, <LANGLE>, <NULL>, <PLUS>, <RANGLE>, <SEMI>,
  39. // <SPACE>, <SHARP>, and <UTFMB> are defined in [RFC4512].
  40. //
  41. package ldap
  42. import (
  43. "bytes"
  44. enchex "encoding/hex"
  45. "errors"
  46. "fmt"
  47. "strings"
  48. "gopkg.in/asn1-ber.v1"
  49. )
  50. // AttributeTypeAndValue represents an attributeTypeAndValue from https://tools.ietf.org/html/rfc4514
  51. type AttributeTypeAndValue struct {
  52. // Type is the attribute type
  53. Type string
  54. // Value is the attribute value
  55. Value string
  56. }
  57. // RelativeDN represents a relativeDistinguishedName from https://tools.ietf.org/html/rfc4514
  58. type RelativeDN struct {
  59. Attributes []*AttributeTypeAndValue
  60. }
  61. // DN represents a distinguishedName from https://tools.ietf.org/html/rfc4514
  62. type DN struct {
  63. RDNs []*RelativeDN
  64. }
  65. // ParseDN returns a distinguishedName or an error
  66. func ParseDN(str string) (*DN, error) {
  67. dn := new(DN)
  68. dn.RDNs = make([]*RelativeDN, 0)
  69. rdn := new(RelativeDN)
  70. rdn.Attributes = make([]*AttributeTypeAndValue, 0)
  71. buffer := bytes.Buffer{}
  72. attribute := new(AttributeTypeAndValue)
  73. escaping := false
  74. unescapedTrailingSpaces := 0
  75. stringFromBuffer := func() string {
  76. s := buffer.String()
  77. s = s[0 : len(s)-unescapedTrailingSpaces]
  78. buffer.Reset()
  79. unescapedTrailingSpaces = 0
  80. return s
  81. }
  82. for i := 0; i < len(str); i++ {
  83. char := str[i]
  84. if escaping {
  85. unescapedTrailingSpaces = 0
  86. escaping = false
  87. switch char {
  88. case ' ', '"', '#', '+', ',', ';', '<', '=', '>', '\\':
  89. buffer.WriteByte(char)
  90. continue
  91. }
  92. // Not a special character, assume hex encoded octet
  93. if len(str) == i+1 {
  94. return nil, errors.New("got corrupted escaped character")
  95. }
  96. dst := []byte{0}
  97. n, err := enchex.Decode([]byte(dst), []byte(str[i:i+2]))
  98. if err != nil {
  99. return nil, fmt.Errorf("failed to decode escaped character: %s", err)
  100. } else if n != 1 {
  101. return nil, fmt.Errorf("expected 1 byte when un-escaping, got %d", n)
  102. }
  103. buffer.WriteByte(dst[0])
  104. i++
  105. } else if char == '\\' {
  106. unescapedTrailingSpaces = 0
  107. escaping = true
  108. } else if char == '=' {
  109. attribute.Type = stringFromBuffer()
  110. // Special case: If the first character in the value is # the
  111. // following data is BER encoded so we can just fast forward
  112. // and decode.
  113. if len(str) > i+1 && str[i+1] == '#' {
  114. i += 2
  115. index := strings.IndexAny(str[i:], ",+")
  116. data := str
  117. if index > 0 {
  118. data = str[i : i+index]
  119. } else {
  120. data = str[i:]
  121. }
  122. rawBER, err := enchex.DecodeString(data)
  123. if err != nil {
  124. return nil, fmt.Errorf("failed to decode BER encoding: %s", err)
  125. }
  126. packet, err := ber.DecodePacketErr(rawBER)
  127. if err != nil {
  128. return nil, fmt.Errorf("failed to decode BER packet: %s", err)
  129. }
  130. buffer.WriteString(packet.Data.String())
  131. i += len(data) - 1
  132. }
  133. } else if char == ',' || char == '+' {
  134. // We're done with this RDN or value, push it
  135. if len(attribute.Type) == 0 {
  136. return nil, errors.New("incomplete type, value pair")
  137. }
  138. attribute.Value = stringFromBuffer()
  139. rdn.Attributes = append(rdn.Attributes, attribute)
  140. attribute = new(AttributeTypeAndValue)
  141. if char == ',' {
  142. dn.RDNs = append(dn.RDNs, rdn)
  143. rdn = new(RelativeDN)
  144. rdn.Attributes = make([]*AttributeTypeAndValue, 0)
  145. }
  146. } else if char == ' ' && buffer.Len() == 0 {
  147. // ignore unescaped leading spaces
  148. continue
  149. } else {
  150. if char == ' ' {
  151. // Track unescaped spaces in case they are trailing and we need to remove them
  152. unescapedTrailingSpaces++
  153. } else {
  154. // Reset if we see a non-space char
  155. unescapedTrailingSpaces = 0
  156. }
  157. buffer.WriteByte(char)
  158. }
  159. }
  160. if buffer.Len() > 0 {
  161. if len(attribute.Type) == 0 {
  162. return nil, errors.New("DN ended with incomplete type, value pair")
  163. }
  164. attribute.Value = stringFromBuffer()
  165. rdn.Attributes = append(rdn.Attributes, attribute)
  166. dn.RDNs = append(dn.RDNs, rdn)
  167. }
  168. return dn, nil
  169. }
  170. // Equal returns true if the DNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch).
  171. // Returns true if they have the same number of relative distinguished names
  172. // and corresponding relative distinguished names (by position) are the same.
  173. func (d *DN) Equal(other *DN) bool {
  174. if len(d.RDNs) != len(other.RDNs) {
  175. return false
  176. }
  177. for i := range d.RDNs {
  178. if !d.RDNs[i].Equal(other.RDNs[i]) {
  179. return false
  180. }
  181. }
  182. return true
  183. }
  184. // AncestorOf returns true if the other DN consists of at least one RDN followed by all the RDNs of the current DN.
  185. // "ou=widgets,o=acme.com" is an ancestor of "ou=sprockets,ou=widgets,o=acme.com"
  186. // "ou=widgets,o=acme.com" is not an ancestor of "ou=sprockets,ou=widgets,o=foo.com"
  187. // "ou=widgets,o=acme.com" is not an ancestor of "ou=widgets,o=acme.com"
  188. func (d *DN) AncestorOf(other *DN) bool {
  189. if len(d.RDNs) >= len(other.RDNs) {
  190. return false
  191. }
  192. // Take the last `len(d.RDNs)` RDNs from the other DN to compare against
  193. otherRDNs := other.RDNs[len(other.RDNs)-len(d.RDNs):]
  194. for i := range d.RDNs {
  195. if !d.RDNs[i].Equal(otherRDNs[i]) {
  196. return false
  197. }
  198. }
  199. return true
  200. }
  201. // Equal returns true if the RelativeDNs are equal as defined by rfc4517 4.2.15 (distinguishedNameMatch).
  202. // Relative distinguished names are the same if and only if they have the same number of AttributeTypeAndValues
  203. // and each attribute of the first RDN is the same as the attribute of the second RDN with the same attribute type.
  204. // The order of attributes is not significant.
  205. // Case of attribute types is not significant.
  206. func (r *RelativeDN) Equal(other *RelativeDN) bool {
  207. if len(r.Attributes) != len(other.Attributes) {
  208. return false
  209. }
  210. return r.hasAllAttributes(other.Attributes) && other.hasAllAttributes(r.Attributes)
  211. }
  212. func (r *RelativeDN) hasAllAttributes(attrs []*AttributeTypeAndValue) bool {
  213. for _, attr := range attrs {
  214. found := false
  215. for _, myattr := range r.Attributes {
  216. if myattr.Equal(attr) {
  217. found = true
  218. break
  219. }
  220. }
  221. if !found {
  222. return false
  223. }
  224. }
  225. return true
  226. }
  227. // Equal returns true if the AttributeTypeAndValue is equivalent to the specified AttributeTypeAndValue
  228. // Case of the attribute type is not significant
  229. func (a *AttributeTypeAndValue) Equal(other *AttributeTypeAndValue) bool {
  230. return strings.EqualFold(a.Type, other.Type) && a.Value == other.Value
  231. }