dn.go 6.0 KB

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