dn.go 7.4 KB

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