Browse Source

Merge pull request #1142 from slingamn/removeldap

remove LDAP support from core
tags/v2.2.0-rc1
Shivaram Lingamneni 4 years ago
parent
commit
7af1f20223
No account linked to committer's email address
45 changed files with 10 additions and 5524 deletions
  1. 4
    0
      .check-gofmt.sh
  2. 4
    1
      Makefile
  3. 0
    35
      conventional.yaml
  4. 0
    35
      default.yaml
  5. 0
    1
      go.mod
  6. 0
    4
      go.sum
  7. 2
    16
      irc/accounts.go
  8. 0
    2
      irc/config.go
  9. 0
    202
      irc/ldap/LICENSE
  10. 0
    62
      irc/ldap/config.go
  11. 0
    267
      irc/ldap/grafana.go
  12. 0
    60
      irc/ldap/helpers.go
  13. 0
    152
      irc/ldap/login.go
  14. 0
    38
      vendor/github.com/go-asn1-ber/asn1-ber/.travis.yml
  15. 0
    22
      vendor/github.com/go-asn1-ber/asn1-ber/LICENSE
  16. 0
    24
      vendor/github.com/go-asn1-ber/asn1-ber/README.md
  17. 0
    512
      vendor/github.com/go-asn1-ber/asn1-ber/ber.go
  18. 0
    25
      vendor/github.com/go-asn1-ber/asn1-ber/content_int.go
  19. 0
    3
      vendor/github.com/go-asn1-ber/asn1-ber/go.mod
  20. 0
    35
      vendor/github.com/go-asn1-ber/asn1-ber/header.go
  21. 0
    112
      vendor/github.com/go-asn1-ber/asn1-ber/identifier.go
  22. 0
    81
      vendor/github.com/go-asn1-ber/asn1-ber/length.go
  23. 0
    24
      vendor/github.com/go-asn1-ber/asn1-ber/util.go
  24. 0
    22
      vendor/github.com/go-ldap/ldap/v3/LICENSE
  25. 0
    91
      vendor/github.com/go-ldap/ldap/v3/add.go
  26. 0
    389
      vendor/github.com/go-ldap/ldap/v3/bind.go
  27. 0
    30
      vendor/github.com/go-ldap/ldap/v3/client.go
  28. 0
    61
      vendor/github.com/go-ldap/ldap/v3/compare.go
  29. 0
    570
      vendor/github.com/go-ldap/ldap/v3/conn.go
  30. 0
    499
      vendor/github.com/go-ldap/ldap/v3/control.go
  31. 0
    30
      vendor/github.com/go-ldap/ldap/v3/debug.go
  32. 0
    59
      vendor/github.com/go-ldap/ldap/v3/del.go
  33. 0
    207
      vendor/github.com/go-ldap/ldap/v3/dn.go
  34. 0
    4
      vendor/github.com/go-ldap/ldap/v3/doc.go
  35. 0
    236
      vendor/github.com/go-ldap/ldap/v3/error.go
  36. 0
    487
      vendor/github.com/go-ldap/ldap/v3/filter.go
  37. 0
    5
      vendor/github.com/go-ldap/ldap/v3/go.mod
  38. 0
    2
      vendor/github.com/go-ldap/ldap/v3/go.sum
  39. 0
    345
      vendor/github.com/go-ldap/ldap/v3/ldap.go
  40. 0
    75
      vendor/github.com/go-ldap/ldap/v3/moddn.go
  41. 0
    132
      vendor/github.com/go-ldap/ldap/v3/modify.go
  42. 0
    126
      vendor/github.com/go-ldap/ldap/v3/passwdmodify.go
  43. 0
    66
      vendor/github.com/go-ldap/ldap/v3/request.go
  44. 0
    370
      vendor/github.com/go-ldap/ldap/v3/search.go
  45. 0
    5
      vendor/modules.txt

+ 4
- 0
.check-gofmt.sh View File

@@ -3,6 +3,10 @@
3 3
 # exclude vendor/
4 4
 SOURCES="./oragono.go ./irc"
5 5
 
6
+if [ "$1" = "--fix" ]; then
7
+	exec gofmt -s -w $SOURCES
8
+fi
9
+
6 10
 if [ -n "$(gofmt -s -l $SOURCES)" ]; then
7 11
     echo "Go code is not formatted correctly with \`gofmt -s\`:"
8 12
     gofmt -s -d $SOURCES

+ 4
- 1
Makefile View File

@@ -1,4 +1,4 @@
1
-.PHONY: all install build release capdefs test smoke
1
+.PHONY: all install build release capdefs test smoke gofmt
2 2
 
3 3
 GIT_COMMIT := $(shell git rev-parse HEAD 2> /dev/null)
4 4
 
@@ -36,3 +36,6 @@ test:
36 36
 smoke:
37 37
 	oragono mkcerts --conf ./default.yaml || true
38 38
 	oragono run --conf ./default.yaml --smoke
39
+
40
+gofmt:
41
+	./.check-gofmt.sh --fix

+ 0
- 35
conventional.yaml View File

@@ -456,41 +456,6 @@ accounts:
456 456
     # see  /QUOTE HELP umodes  for more user modes
457 457
     # default-user-modes: +i
458 458
 
459
-    # support for deferring password checking to an external LDAP server
460
-    # you should probably ignore this section! consult the grafana docs for details:
461
-    # https://grafana.com/docs/grafana/latest/auth/ldap/
462
-    # you will probably want to set require-sasl and disable accounts.registration.enabled
463
-    # ldap:
464
-    #     enabled: true
465
-    #     # should we automatically create users if their LDAP login succeeds?
466
-    #     autocreate: true
467
-    #     # example configuration that works with Forum Systems's testing server:
468
-    #     # https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/
469
-    #     host: "ldap.forumsys.com"
470
-    #     port: 389
471
-    #     timeout: 30s
472
-    #     # example "single-bind" configuration, where we bind directly to the user's entry:
473
-    #     bind-dn: "uid=%s,dc=example,dc=com"
474
-    #     # example "admin bind" configuration, where we bind to an initial admin user,
475
-    #     # then search for the user's entry with a search filter:
476
-    #     #search-base-dns:
477
-    #     #    - "dc=example,dc=com"
478
-    #     #bind-dn: "cn=read-only-admin,dc=example,dc=com"
479
-    #     #bind-password: "password"
480
-    #     #search-filter: "(uid=%s)"
481
-    #     # example of requiring that users be in a particular group
482
-    #     # (note that this is an OR over the listed groups, not an AND):
483
-    #     #require-groups:
484
-    #     #    - "ou=mathematicians,dc=example,dc=com"
485
-    #     #group-search-filter-user-attribute: "dn"
486
-    #     #group-search-filter: "(uniqueMember=%s)"
487
-    #     #group-search-base-dns:
488
-    #     #    - "dc=example,dc=com"
489
-    #     # example of group membership testing via user attributes, as in AD
490
-    #     # or with OpenLDAP's "memberOf overlay" (overrides group-search-filter):
491
-    #     attributes:
492
-    #         member-of: "memberOf"
493
-
494 459
     # pluggable authentication mechanism, via subprocess invocation
495 460
     # see the manual for details on how to write an authentication plugin script
496 461
     auth-script:

+ 0
- 35
default.yaml View File

@@ -482,41 +482,6 @@ accounts:
482 482
     # see  /QUOTE HELP umodes  for more user modes
483 483
     default-user-modes: +i
484 484
 
485
-    # support for deferring password checking to an external LDAP server
486
-    # you should probably ignore this section! consult the grafana docs for details:
487
-    # https://grafana.com/docs/grafana/latest/auth/ldap/
488
-    # you will probably want to set require-sasl and disable accounts.registration.enabled
489
-    # ldap:
490
-    #     enabled: true
491
-    #     # should we automatically create users if their LDAP login succeeds?
492
-    #     autocreate: true
493
-    #     # example configuration that works with Forum Systems's testing server:
494
-    #     # https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/
495
-    #     host: "ldap.forumsys.com"
496
-    #     port: 389
497
-    #     timeout: 30s
498
-    #     # example "single-bind" configuration, where we bind directly to the user's entry:
499
-    #     bind-dn: "uid=%s,dc=example,dc=com"
500
-    #     # example "admin bind" configuration, where we bind to an initial admin user,
501
-    #     # then search for the user's entry with a search filter:
502
-    #     #search-base-dns:
503
-    #     #    - "dc=example,dc=com"
504
-    #     #bind-dn: "cn=read-only-admin,dc=example,dc=com"
505
-    #     #bind-password: "password"
506
-    #     #search-filter: "(uid=%s)"
507
-    #     # example of requiring that users be in a particular group
508
-    #     # (note that this is an OR over the listed groups, not an AND):
509
-    #     #require-groups:
510
-    #     #    - "ou=mathematicians,dc=example,dc=com"
511
-    #     #group-search-filter-user-attribute: "dn"
512
-    #     #group-search-filter: "(uniqueMember=%s)"
513
-    #     #group-search-base-dns:
514
-    #     #    - "dc=example,dc=com"
515
-    #     # example of group membership testing via user attributes, as in AD
516
-    #     # or with OpenLDAP's "memberOf overlay" (overrides group-search-filter):
517
-    #     attributes:
518
-    #         member-of: "memberOf"
519
-
520 485
     # pluggable authentication mechanism, via subprocess invocation
521 486
     # see the manual for details on how to write an authentication plugin script
522 487
     auth-script:

+ 0
- 1
go.mod View File

@@ -6,7 +6,6 @@ require (
6 6
 	code.cloudfoundry.org/bytefmt v0.0.0-20200131002437-cf55d5288a48
7 7
 	github.com/dgrijalva/jwt-go v3.2.0+incompatible
8 8
 	github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815
9
-	github.com/go-ldap/ldap/v3 v3.1.10
10 9
 	github.com/go-sql-driver/mysql v1.5.0
11 10
 	github.com/go-test/deep v1.0.6 // indirect
12 11
 	github.com/gorilla/websocket v1.4.2

+ 0
- 4
go.sum View File

@@ -9,10 +9,6 @@ github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815 h1:bWDMxwH3px2JBh
9 9
 github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE=
10 10
 github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
11 11
 github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
12
-github.com/go-asn1-ber/asn1-ber v1.3.1 h1:gvPdv/Hr++TRFCl0UbPFHC54P9N9jgsRPnmnr419Uck=
13
-github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
14
-github.com/go-ldap/ldap/v3 v3.1.10 h1:7WsKqasmPThNvdl0Q5GPpbTDD/ZD98CfuawrMIuh7qQ=
15
-github.com/go-ldap/ldap/v3 v3.1.10/go.mod h1:5Zun81jBTabRaI8lzN7E1JjyEl1g6zI6u9pd8luAK4Q=
16 12
 github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
17 13
 github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
18 14
 github.com/go-test/deep v1.0.6 h1:UHSEyLZUwX9Qoi99vVwvewiMC8mM2bf7XEM2nqvzEn8=

+ 2
- 16
irc/accounts.go View File

@@ -17,7 +17,6 @@ import (
17 17
 
18 18
 	"github.com/oragono/oragono/irc/connection_limits"
19 19
 	"github.com/oragono/oragono/irc/email"
20
-	"github.com/oragono/oragono/irc/ldap"
21 20
 	"github.com/oragono/oragono/irc/modes"
22 21
 	"github.com/oragono/oragono/irc/passwd"
23 22
 	"github.com/oragono/oragono/irc/utils"
@@ -1065,24 +1064,13 @@ func (am *AccountManager) AuthenticateByPassphrase(client *Client, accountName s
1065 1064
 	}()
1066 1065
 
1067 1066
 	config := am.server.Config()
1068
-	if config.Accounts.LDAP.Enabled {
1069
-		ldapConf := am.server.Config().Accounts.LDAP
1070
-		err = ldap.CheckLDAPPassphrase(ldapConf, accountName, passphrase, am.server.logger)
1071
-		if err != nil {
1072
-			account, err = am.loadWithAutocreation(accountName, ldapConf.Autocreate)
1073
-			return
1074
-		}
1075
-	}
1076
-
1077 1067
 	if config.Accounts.AuthScript.Enabled {
1078 1068
 		var output AuthScriptOutput
1079 1069
 		output, err = CheckAuthScript(config.Accounts.AuthScript,
1080 1070
 			AuthScriptInput{AccountName: accountName, Passphrase: passphrase, IP: client.IP().String()})
1081 1071
 		if err != nil {
1082 1072
 			am.server.logger.Error("internal", "failed shell auth invocation", err.Error())
1083
-			return err
1084
-		}
1085
-		if output.Success {
1073
+		} else if output.Success {
1086 1074
 			if output.AccountName != "" {
1087 1075
 				accountName = output.AccountName
1088 1076
 			}
@@ -1419,9 +1407,7 @@ func (am *AccountManager) AuthenticateByCertFP(client *Client, certfp, authzid s
1419 1407
 			AuthScriptInput{Certfp: certfp, IP: client.IP().String()})
1420 1408
 		if err != nil {
1421 1409
 			am.server.logger.Error("internal", "failed shell auth invocation", err.Error())
1422
-			return err
1423
-		}
1424
-		if output.Success && output.AccountName != "" {
1410
+		} else if output.Success && output.AccountName != "" {
1425 1411
 			clientAccount, err = am.loadWithAutocreation(output.AccountName, config.Accounts.AuthScript.Autocreate)
1426 1412
 			return
1427 1413
 		}

+ 0
- 2
irc/config.go View File

@@ -29,7 +29,6 @@ import (
29 29
 	"github.com/oragono/oragono/irc/isupport"
30 30
 	"github.com/oragono/oragono/irc/jwt"
31 31
 	"github.com/oragono/oragono/irc/languages"
32
-	"github.com/oragono/oragono/irc/ldap"
33 32
 	"github.com/oragono/oragono/irc/logger"
34 33
 	"github.com/oragono/oragono/irc/modes"
35 34
 	"github.com/oragono/oragono/irc/mysql"
@@ -258,7 +257,6 @@ type AccountConfig struct {
258 257
 	} `yaml:"require-sasl"`
259 258
 	DefaultUserModes    *string `yaml:"default-user-modes"`
260 259
 	defaultUserModes    modes.Modes
261
-	LDAP                ldap.ServerConfig
262 260
 	LoginThrottling     ThrottleConfig `yaml:"login-throttling"`
263 261
 	SkipServerPassword  bool           `yaml:"skip-server-password"`
264 262
 	LoginViaPassCommand bool           `yaml:"login-via-pass-command"`

+ 0
- 202
irc/ldap/LICENSE View File

@@ -1,202 +0,0 @@
1
-
2
-                                 Apache License
3
-                           Version 2.0, January 2004
4
-                        http://www.apache.org/licenses/
5
-
6
-   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
-
8
-   1. Definitions.
9
-
10
-      "License" shall mean the terms and conditions for use, reproduction,
11
-      and distribution as defined by Sections 1 through 9 of this document.
12
-
13
-      "Licensor" shall mean the copyright owner or entity authorized by
14
-      the copyright owner that is granting the License.
15
-
16
-      "Legal Entity" shall mean the union of the acting entity and all
17
-      other entities that control, are controlled by, or are under common
18
-      control with that entity. For the purposes of this definition,
19
-      "control" means (i) the power, direct or indirect, to cause the
20
-      direction or management of such entity, whether by contract or
21
-      otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
-      outstanding shares, or (iii) beneficial ownership of such entity.
23
-
24
-      "You" (or "Your") shall mean an individual or Legal Entity
25
-      exercising permissions granted by this License.
26
-
27
-      "Source" form shall mean the preferred form for making modifications,
28
-      including but not limited to software source code, documentation
29
-      source, and configuration files.
30
-
31
-      "Object" form shall mean any form resulting from mechanical
32
-      transformation or translation of a Source form, including but
33
-      not limited to compiled object code, generated documentation,
34
-      and conversions to other media types.
35
-
36
-      "Work" shall mean the work of authorship, whether in Source or
37
-      Object form, made available under the License, as indicated by a
38
-      copyright notice that is included in or attached to the work
39
-      (an example is provided in the Appendix below).
40
-
41
-      "Derivative Works" shall mean any work, whether in Source or Object
42
-      form, that is based on (or derived from) the Work and for which the
43
-      editorial revisions, annotations, elaborations, or other modifications
44
-      represent, as a whole, an original work of authorship. For the purposes
45
-      of this License, Derivative Works shall not include works that remain
46
-      separable from, or merely link (or bind by name) to the interfaces of,
47
-      the Work and Derivative Works thereof.
48
-
49
-      "Contribution" shall mean any work of authorship, including
50
-      the original version of the Work and any modifications or additions
51
-      to that Work or Derivative Works thereof, that is intentionally
52
-      submitted to Licensor for inclusion in the Work by the copyright owner
53
-      or by an individual or Legal Entity authorized to submit on behalf of
54
-      the copyright owner. For the purposes of this definition, "submitted"
55
-      means any form of electronic, verbal, or written communication sent
56
-      to the Licensor or its representatives, including but not limited to
57
-      communication on electronic mailing lists, source code control systems,
58
-      and issue tracking systems that are managed by, or on behalf of, the
59
-      Licensor for the purpose of discussing and improving the Work, but
60
-      excluding communication that is conspicuously marked or otherwise
61
-      designated in writing by the copyright owner as "Not a Contribution."
62
-
63
-      "Contributor" shall mean Licensor and any individual or Legal Entity
64
-      on behalf of whom a Contribution has been received by Licensor and
65
-      subsequently incorporated within the Work.
66
-
67
-   2. Grant of Copyright License. Subject to the terms and conditions of
68
-      this License, each Contributor hereby grants to You a perpetual,
69
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
-      copyright license to reproduce, prepare Derivative Works of,
71
-      publicly display, publicly perform, sublicense, and distribute the
72
-      Work and such Derivative Works in Source or Object form.
73
-
74
-   3. Grant of Patent License. Subject to the terms and conditions of
75
-      this License, each Contributor hereby grants to You a perpetual,
76
-      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
-      (except as stated in this section) patent license to make, have made,
78
-      use, offer to sell, sell, import, and otherwise transfer the Work,
79
-      where such license applies only to those patent claims licensable
80
-      by such Contributor that are necessarily infringed by their
81
-      Contribution(s) alone or by combination of their Contribution(s)
82
-      with the Work to which such Contribution(s) was submitted. If You
83
-      institute patent litigation against any entity (including a
84
-      cross-claim or counterclaim in a lawsuit) alleging that the Work
85
-      or a Contribution incorporated within the Work constitutes direct
86
-      or contributory patent infringement, then any patent licenses
87
-      granted to You under this License for that Work shall terminate
88
-      as of the date such litigation is filed.
89
-
90
-   4. Redistribution. You may reproduce and distribute copies of the
91
-      Work or Derivative Works thereof in any medium, with or without
92
-      modifications, and in Source or Object form, provided that You
93
-      meet the following conditions:
94
-
95
-      (a) You must give any other recipients of the Work or
96
-          Derivative Works a copy of this License; and
97
-
98
-      (b) You must cause any modified files to carry prominent notices
99
-          stating that You changed the files; and
100
-
101
-      (c) You must retain, in the Source form of any Derivative Works
102
-          that You distribute, all copyright, patent, trademark, and
103
-          attribution notices from the Source form of the Work,
104
-          excluding those notices that do not pertain to any part of
105
-          the Derivative Works; and
106
-
107
-      (d) If the Work includes a "NOTICE" text file as part of its
108
-          distribution, then any Derivative Works that You distribute must
109
-          include a readable copy of the attribution notices contained
110
-          within such NOTICE file, excluding those notices that do not
111
-          pertain to any part of the Derivative Works, in at least one
112
-          of the following places: within a NOTICE text file distributed
113
-          as part of the Derivative Works; within the Source form or
114
-          documentation, if provided along with the Derivative Works; or,
115
-          within a display generated by the Derivative Works, if and
116
-          wherever such third-party notices normally appear. The contents
117
-          of the NOTICE file are for informational purposes only and
118
-          do not modify the License. You may add Your own attribution
119
-          notices within Derivative Works that You distribute, alongside
120
-          or as an addendum to the NOTICE text from the Work, provided
121
-          that such additional attribution notices cannot be construed
122
-          as modifying the License.
123
-
124
-      You may add Your own copyright statement to Your modifications and
125
-      may provide additional or different license terms and conditions
126
-      for use, reproduction, or distribution of Your modifications, or
127
-      for any such Derivative Works as a whole, provided Your use,
128
-      reproduction, and distribution of the Work otherwise complies with
129
-      the conditions stated in this License.
130
-
131
-   5. Submission of Contributions. Unless You explicitly state otherwise,
132
-      any Contribution intentionally submitted for inclusion in the Work
133
-      by You to the Licensor shall be under the terms and conditions of
134
-      this License, without any additional terms or conditions.
135
-      Notwithstanding the above, nothing herein shall supersede or modify
136
-      the terms of any separate license agreement you may have executed
137
-      with Licensor regarding such Contributions.
138
-
139
-   6. Trademarks. This License does not grant permission to use the trade
140
-      names, trademarks, service marks, or product names of the Licensor,
141
-      except as required for reasonable and customary use in describing the
142
-      origin of the Work and reproducing the content of the NOTICE file.
143
-
144
-   7. Disclaimer of Warranty. Unless required by applicable law or
145
-      agreed to in writing, Licensor provides the Work (and each
146
-      Contributor provides its Contributions) on an "AS IS" BASIS,
147
-      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
-      implied, including, without limitation, any warranties or conditions
149
-      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
-      PARTICULAR PURPOSE. You are solely responsible for determining the
151
-      appropriateness of using or redistributing the Work and assume any
152
-      risks associated with Your exercise of permissions under this License.
153
-
154
-   8. Limitation of Liability. In no event and under no legal theory,
155
-      whether in tort (including negligence), contract, or otherwise,
156
-      unless required by applicable law (such as deliberate and grossly
157
-      negligent acts) or agreed to in writing, shall any Contributor be
158
-      liable to You for damages, including any direct, indirect, special,
159
-      incidental, or consequential damages of any character arising as a
160
-      result of this License or out of the use or inability to use the
161
-      Work (including but not limited to damages for loss of goodwill,
162
-      work stoppage, computer failure or malfunction, or any and all
163
-      other commercial damages or losses), even if such Contributor
164
-      has been advised of the possibility of such damages.
165
-
166
-   9. Accepting Warranty or Additional Liability. While redistributing
167
-      the Work or Derivative Works thereof, You may choose to offer,
168
-      and charge a fee for, acceptance of support, warranty, indemnity,
169
-      or other liability obligations and/or rights consistent with this
170
-      License. However, in accepting such obligations, You may act only
171
-      on Your own behalf and on Your sole responsibility, not on behalf
172
-      of any other Contributor, and only if You agree to indemnify,
173
-      defend, and hold each Contributor harmless for any liability
174
-      incurred by, or claims asserted against, such Contributor by reason
175
-      of your accepting any such warranty or additional liability.
176
-
177
-   END OF TERMS AND CONDITIONS
178
-
179
-   APPENDIX: How to apply the Apache License to your work.
180
-
181
-      To apply the Apache License to your work, attach the following
182
-      boilerplate notice, with the fields enclosed by brackets "[]"
183
-      replaced with your own identifying information. (Don't include
184
-      the brackets!)  The text should be enclosed in the appropriate
185
-      comment syntax for the file format. We also recommend that a
186
-      file or class name and description of purpose be included on the
187
-      same "printed page" as the copyright notice for easier
188
-      identification within third-party archives.
189
-
190
-   Copyright 2015 Grafana Labs
191
-
192
-   Licensed under the Apache License, Version 2.0 (the "License");
193
-   you may not use this file except in compliance with the License.
194
-   You may obtain a copy of the License at
195
-
196
-       http://www.apache.org/licenses/LICENSE-2.0
197
-
198
-   Unless required by applicable law or agreed to in writing, software
199
-   distributed under the License is distributed on an "AS IS" BASIS,
200
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
-   See the License for the specific language governing permissions and
202
-   limitations under the License.

+ 0
- 62
irc/ldap/config.go View File

@@ -1,62 +0,0 @@
1
-// Copyright 2014-2018 Grafana Labs
2
-// Released under the Apache 2.0 license
3
-
4
-// Modification notice:
5
-// 1. All field names were changed from toml and snake case to yaml and kebab case,
6
-//    matching the Oragono project conventions
7
-// 2. Four fields were added:
8
-//    2.1 `Enabled`
9
-//    2.2 `Autocreate`
10
-//    2.3 `Timeout`
11
-//    2.4 `RequireGroups`
12
-
13
-// XXX: none of AttributeMap does anything in oragono, except MemberOf,
14
-// which can be used to retrieve group memberships
15
-
16
-package ldap
17
-
18
-import (
19
-	"time"
20
-)
21
-
22
-type ServerConfig struct {
23
-	Enabled    bool
24
-	Autocreate bool
25
-
26
-	Host          string
27
-	Port          int
28
-	Timeout       time.Duration
29
-	UseSSL        bool   `yaml:"use-ssl"`
30
-	StartTLS      bool   `yaml:"start-tls"`
31
-	SkipVerifySSL bool   `yaml:"ssl-skip-verify"`
32
-	RootCACert    string `yaml:"root-ca-cert"`
33
-	ClientCert    string `yaml:"client-cert"`
34
-	ClientKey     string `yaml:"client-key"`
35
-
36
-	BindDN        string   `yaml:"bind-dn"`
37
-	BindPassword  string   `yaml:"bind-password"`
38
-	SearchFilter  string   `yaml:"search-filter"`
39
-	SearchBaseDNs []string `yaml:"search-base-dns"`
40
-
41
-	// user validation: require them to be in any one of these groups
42
-	RequireGroups []string `yaml:"require-groups"`
43
-
44
-	// two ways of testing group membership:
45
-	// either by searching for groups that match the user's DN
46
-	// and testing their names:
47
-	GroupSearchFilter              string   `yaml:"group-search-filter"`
48
-	GroupSearchFilterUserAttribute string   `yaml:"group-search-filter-user-attribute"`
49
-	GroupSearchBaseDNs             []string `yaml:"group-search-base-dns"`
50
-
51
-	// or by an attribute on the user's DN, typically named 'memberOf', but customizable:
52
-	Attr AttributeMap `yaml:"attributes"`
53
-}
54
-
55
-// AttributeMap is a struct representation for LDAP "attributes" setting
56
-type AttributeMap struct {
57
-	Username string
58
-	Name     string
59
-	Surname  string
60
-	Email    string
61
-	MemberOf string `yaml:"member-of"`
62
-}

+ 0
- 267
irc/ldap/grafana.go View File

@@ -1,267 +0,0 @@
1
-// Copyright 2014-2018 Grafana Labs
2
-// Released under the Apache 2.0 license
3
-
4
-// Modification notice:
5
-// 1. `serverConn` was substituted for `Server` as the type of the server object
6
-// 2. Debug loglines were altered to work with Oragono's logging system
7
-
8
-package ldap
9
-
10
-import (
11
-	"crypto/tls"
12
-	"crypto/x509"
13
-	"errors"
14
-	"fmt"
15
-	"io/ioutil"
16
-	"strings"
17
-
18
-	ldap "github.com/go-ldap/ldap/v3"
19
-)
20
-
21
-var (
22
-	// ErrInvalidCredentials is returned if username and password do not match
23
-	ErrInvalidCredentials = errors.New("Invalid Username or Password")
24
-
25
-	// ErrCouldNotFindUser is returned when username hasn't been found (not username+password)
26
-	ErrCouldNotFindUser = errors.New("Can't find user in LDAP")
27
-)
28
-
29
-// shouldAdminBind checks if we should use
30
-// admin username & password for LDAP bind
31
-func (server *serverConn) shouldAdminBind() bool {
32
-	return server.Config.BindPassword != ""
33
-}
34
-
35
-// singleBindDN combines the bind with the username
36
-// in order to get the proper path
37
-func (server *serverConn) singleBindDN(username string) string {
38
-	return fmt.Sprintf(server.Config.BindDN, username)
39
-}
40
-
41
-// shouldSingleBind checks if we can use "single bind" approach
42
-func (server *serverConn) shouldSingleBind() bool {
43
-	return strings.Contains(server.Config.BindDN, "%s")
44
-}
45
-
46
-// Dial dials in the LDAP
47
-// TODO: decrease cyclomatic complexity
48
-func (server *serverConn) Dial() error {
49
-	var err error
50
-	var certPool *x509.CertPool
51
-	if server.Config.RootCACert != "" {
52
-		certPool = x509.NewCertPool()
53
-		for _, caCertFile := range strings.Split(server.Config.RootCACert, " ") {
54
-			pem, err := ioutil.ReadFile(caCertFile)
55
-			if err != nil {
56
-				return err
57
-			}
58
-			if !certPool.AppendCertsFromPEM(pem) {
59
-				return errors.New("Failed to append CA certificate " + caCertFile)
60
-			}
61
-		}
62
-	}
63
-	var clientCert tls.Certificate
64
-	if server.Config.ClientCert != "" && server.Config.ClientKey != "" {
65
-		clientCert, err = tls.LoadX509KeyPair(server.Config.ClientCert, server.Config.ClientKey)
66
-		if err != nil {
67
-			return err
68
-		}
69
-	}
70
-	for _, host := range strings.Split(server.Config.Host, " ") {
71
-		address := fmt.Sprintf("%s:%d", host, server.Config.Port)
72
-		if server.Config.UseSSL {
73
-			tlsCfg := &tls.Config{
74
-				InsecureSkipVerify: server.Config.SkipVerifySSL,
75
-				ServerName:         host,
76
-				RootCAs:            certPool,
77
-			}
78
-			if len(clientCert.Certificate) > 0 {
79
-				tlsCfg.Certificates = append(tlsCfg.Certificates, clientCert)
80
-			}
81
-			if server.Config.StartTLS {
82
-				server.Connection, err = ldap.Dial("tcp", address)
83
-				if err == nil {
84
-					if err = server.Connection.StartTLS(tlsCfg); err == nil {
85
-						return nil
86
-					}
87
-				}
88
-			} else {
89
-				server.Connection, err = ldap.DialTLS("tcp", address, tlsCfg)
90
-			}
91
-		} else {
92
-			server.Connection, err = ldap.Dial("tcp", address)
93
-		}
94
-
95
-		if err == nil {
96
-			return nil
97
-		}
98
-	}
99
-	return err
100
-}
101
-
102
-// Close closes the LDAP connection
103
-// Dial() sets the connection with the server for this Struct. Therefore, we require a
104
-// call to Dial() before being able to execute this function.
105
-func (server *serverConn) Close() {
106
-	server.Connection.Close()
107
-}
108
-
109
-// userBind binds the user with the LDAP server
110
-func (server *serverConn) userBind(path, password string) error {
111
-	err := server.Connection.Bind(path, password)
112
-	if err != nil {
113
-		if ldapErr, ok := err.(*ldap.Error); ok {
114
-			if ldapErr.ResultCode == 49 {
115
-				return ErrInvalidCredentials
116
-			}
117
-		}
118
-		return err
119
-	}
120
-
121
-	return nil
122
-}
123
-
124
-// users is helper method for the Users()
125
-func (server *serverConn) users(logins []string) (
126
-	[]*ldap.Entry,
127
-	error,
128
-) {
129
-	var result *ldap.SearchResult
130
-	var Config = server.Config
131
-	var err error
132
-
133
-	for _, base := range Config.SearchBaseDNs {
134
-		result, err = server.Connection.Search(
135
-			server.getSearchRequest(base, logins),
136
-		)
137
-		if err != nil {
138
-			return nil, err
139
-		}
140
-
141
-		if len(result.Entries) > 0 {
142
-			break
143
-		}
144
-	}
145
-
146
-	return result.Entries, nil
147
-}
148
-
149
-// getSearchRequest returns LDAP search request for users
150
-func (server *serverConn) getSearchRequest(
151
-	base string,
152
-	logins []string,
153
-) *ldap.SearchRequest {
154
-	attributes := []string{}
155
-
156
-	inputs := server.Config.Attr
157
-	attributes = appendIfNotEmpty(
158
-		attributes,
159
-		inputs.Username,
160
-		inputs.Surname,
161
-		inputs.Email,
162
-		inputs.Name,
163
-		inputs.MemberOf,
164
-
165
-		// In case for the POSIX LDAP schema server
166
-		server.Config.GroupSearchFilterUserAttribute,
167
-	)
168
-
169
-	search := ""
170
-	for _, login := range logins {
171
-		query := strings.Replace(
172
-			server.Config.SearchFilter,
173
-			"%s", ldap.EscapeFilter(login),
174
-			-1,
175
-		)
176
-
177
-		search = search + query
178
-	}
179
-
180
-	filter := fmt.Sprintf("(|%s)", search)
181
-
182
-	return &ldap.SearchRequest{
183
-		BaseDN:       base,
184
-		Scope:        ldap.ScopeWholeSubtree,
185
-		DerefAliases: ldap.NeverDerefAliases,
186
-		Attributes:   attributes,
187
-		Filter:       filter,
188
-	}
189
-}
190
-
191
-// requestMemberOf use this function when POSIX LDAP
192
-// schema does not support memberOf, so it manually search the groups
193
-func (server *serverConn) requestMemberOf(entry *ldap.Entry) ([]string, error) {
194
-	var memberOf []string
195
-	var config = server.Config
196
-
197
-	for _, groupSearchBase := range config.GroupSearchBaseDNs {
198
-		var filterReplace string
199
-		if config.GroupSearchFilterUserAttribute == "" {
200
-			filterReplace = getAttribute(config.Attr.Username, entry)
201
-		} else {
202
-			filterReplace = getAttribute(
203
-				config.GroupSearchFilterUserAttribute,
204
-				entry,
205
-			)
206
-		}
207
-
208
-		filter := strings.Replace(
209
-			config.GroupSearchFilter, "%s",
210
-			ldap.EscapeFilter(filterReplace),
211
-			-1,
212
-		)
213
-
214
-		server.logger.Debug("ldap", "Searching for groups with filter", filter)
215
-
216
-		// support old way of reading settings
217
-		groupIDAttribute := config.Attr.MemberOf
218
-		// but prefer dn attribute if default settings are used
219
-		if groupIDAttribute == "" || groupIDAttribute == "memberOf" {
220
-			groupIDAttribute = "dn"
221
-		}
222
-
223
-		groupSearchReq := ldap.SearchRequest{
224
-			BaseDN:       groupSearchBase,
225
-			Scope:        ldap.ScopeWholeSubtree,
226
-			DerefAliases: ldap.NeverDerefAliases,
227
-			Attributes:   []string{groupIDAttribute},
228
-			Filter:       filter,
229
-		}
230
-
231
-		groupSearchResult, err := server.Connection.Search(&groupSearchReq)
232
-		if err != nil {
233
-			return nil, err
234
-		}
235
-
236
-		if len(groupSearchResult.Entries) > 0 {
237
-			for _, group := range groupSearchResult.Entries {
238
-
239
-				memberOf = append(
240
-					memberOf,
241
-					getAttribute(groupIDAttribute, group),
242
-				)
243
-			}
244
-			break
245
-		}
246
-	}
247
-
248
-	return memberOf, nil
249
-}
250
-
251
-// getMemberOf finds memberOf property or request it
252
-func (server *serverConn) getMemberOf(result *ldap.Entry) (
253
-	[]string, error,
254
-) {
255
-	if server.Config.GroupSearchFilter == "" {
256
-		memberOf := getArrayAttribute(server.Config.Attr.MemberOf, result)
257
-
258
-		return memberOf, nil
259
-	}
260
-
261
-	memberOf, err := server.requestMemberOf(result)
262
-	if err != nil {
263
-		return nil, err
264
-	}
265
-
266
-	return memberOf, nil
267
-}

+ 0
- 60
irc/ldap/helpers.go View File

@@ -1,60 +0,0 @@
1
-// Copyright 2014-2018 Grafana Labs
2
-// Released under the Apache 2.0 license
3
-
4
-package ldap
5
-
6
-import (
7
-	"strings"
8
-
9
-	ldap "github.com/go-ldap/ldap/v3"
10
-)
11
-
12
-func isMemberOf(memberOf []string, group string) bool {
13
-	if group == "*" {
14
-		return true
15
-	}
16
-
17
-	for _, member := range memberOf {
18
-		if strings.EqualFold(member, group) {
19
-			return true
20
-		}
21
-	}
22
-	return false
23
-}
24
-
25
-func getArrayAttribute(name string, entry *ldap.Entry) []string {
26
-	if strings.ToLower(name) == "dn" {
27
-		return []string{entry.DN}
28
-	}
29
-
30
-	for _, attr := range entry.Attributes {
31
-		if attr.Name == name && len(attr.Values) > 0 {
32
-			return attr.Values
33
-		}
34
-	}
35
-	return []string{}
36
-}
37
-
38
-func getAttribute(name string, entry *ldap.Entry) string {
39
-	if strings.ToLower(name) == "dn" {
40
-		return entry.DN
41
-	}
42
-
43
-	for _, attr := range entry.Attributes {
44
-		if attr.Name == name {
45
-			if len(attr.Values) > 0 {
46
-				return attr.Values[0]
47
-			}
48
-		}
49
-	}
50
-	return ""
51
-}
52
-
53
-func appendIfNotEmpty(slice []string, values ...string) []string {
54
-	for _, v := range values {
55
-		if v != "" {
56
-			slice = append(slice, v)
57
-		}
58
-	}
59
-	return slice
60
-}

+ 0
- 152
irc/ldap/login.go View File

@@ -1,152 +0,0 @@
1
-// Copyright (c) 2020 Matt Ouille
2
-// Copyright (c) 2020 Shivaram Lingamneni
3
-// released under the MIT license
4
-
5
-// Portions of this code copyright Grafana Labs and contributors
6
-// and released under the Apache 2.0 license
7
-
8
-// Copying Grafana's original comment on the different cases for LDAP:
9
-// There are several cases -
10
-// 1. "admin" user
11
-// Bind the "admin" user (defined in Grafana config file) which has the search privileges
12
-// in LDAP server, then we search the targeted user through that bind, then the second
13
-// perform the bind via passed login/password.
14
-// 2. Single bind
15
-// // If all the users meant to be used with Grafana have the ability to search in LDAP server
16
-// then we bind with LDAP server with targeted login/password
17
-// and then search for the said user in order to retrive all the information about them
18
-// 3. Unauthenticated bind
19
-// For some LDAP configurations it is allowed to search the
20
-// user without login/password binding with LDAP server, in such case
21
-// we will perform "unauthenticated bind", then search for the
22
-// targeted user and then perform the bind with passed login/password.
23
-
24
-// Note: the only validation we do on users is to check RequiredGroups.
25
-// If RequiredGroups is not set and we can do a single bind, we don't
26
-// even need to search. So our case 2 is not restricted
27
-// to setups where all the users have search privileges: we only need to
28
-// be able to do DN resolution via pure string substitution.
29
-
30
-package ldap
31
-
32
-import (
33
-	"errors"
34
-	"fmt"
35
-
36
-	ldap "github.com/go-ldap/ldap/v3"
37
-
38
-	"github.com/oragono/oragono/irc/logger"
39
-)
40
-
41
-var (
42
-	ErrUserNotInRequiredGroup = errors.New("User is not a member of any required groups")
43
-)
44
-
45
-// equivalent of Grafana's `Server`, but unexported
46
-// also, `log` was renamed to `logger`, since the APIs are slightly different
47
-// and this way the compiler will catch any unchanged references to Grafana's `Server.log`
48
-type serverConn struct {
49
-	Config     *ServerConfig
50
-	Connection *ldap.Conn
51
-	logger     *logger.Manager
52
-}
53
-
54
-func CheckLDAPPassphrase(config ServerConfig, accountName, passphrase string, log *logger.Manager) (err error) {
55
-	defer func() {
56
-		if err != nil {
57
-			log.Debug("ldap", "failed passphrase check", err.Error())
58
-		}
59
-	}()
60
-
61
-	server := serverConn{
62
-		Config: &config,
63
-		logger: log,
64
-	}
65
-
66
-	err = server.Dial()
67
-	if err != nil {
68
-		return
69
-	}
70
-	defer server.Close()
71
-
72
-	server.Connection.SetTimeout(config.Timeout)
73
-
74
-	passphraseChecked := false
75
-
76
-	if server.shouldSingleBind() {
77
-		log.Debug("ldap", "attempting single bind to", accountName)
78
-		err = server.userBind(server.singleBindDN(accountName), passphrase)
79
-		passphraseChecked = (err == nil)
80
-	} else if server.shouldAdminBind() {
81
-		log.Debug("ldap", "attempting admin bind to", config.BindDN)
82
-		err = server.userBind(config.BindDN, config.BindPassword)
83
-	} else {
84
-		log.Debug("ldap", "attempting unauthenticated bind")
85
-		err = server.Connection.UnauthenticatedBind(config.BindDN)
86
-	}
87
-
88
-	if err != nil {
89
-		return
90
-	}
91
-
92
-	if passphraseChecked && len(config.RequireGroups) == 0 {
93
-		return nil
94
-	}
95
-
96
-	users, err := server.users([]string{accountName})
97
-	if err != nil {
98
-		log.Debug("ldap", "failed user lookup")
99
-		return err
100
-	}
101
-
102
-	if len(users) == 0 {
103
-		return ErrCouldNotFindUser
104
-	}
105
-
106
-	user := users[0]
107
-
108
-	log.Debug("ldap", "looked up user", user.DN)
109
-
110
-	err = server.validateGroupMembership(user)
111
-	if err != nil {
112
-		return err
113
-	}
114
-
115
-	if !passphraseChecked {
116
-		log.Debug("ldap", "rebinding", user.DN)
117
-		err = server.userBind(user.DN, passphrase)
118
-	}
119
-
120
-	return err
121
-}
122
-
123
-func (server *serverConn) validateGroupMembership(user *ldap.Entry) (err error) {
124
-	if len(server.Config.RequireGroups) == 0 {
125
-		return
126
-	}
127
-
128
-	var memberOf []string
129
-	memberOf, err = server.getMemberOf(user)
130
-	if err != nil {
131
-		server.logger.Debug("ldap", "could not retrieve group memberships", err.Error())
132
-		return
133
-	}
134
-	server.logger.Debug("ldap", fmt.Sprintf("found group memberships: %v", memberOf))
135
-	foundGroup := false
136
-	for _, inGroup := range memberOf {
137
-		for _, acceptableGroup := range server.Config.RequireGroups {
138
-			if inGroup == acceptableGroup {
139
-				foundGroup = true
140
-				break
141
-			}
142
-		}
143
-		if foundGroup {
144
-			break
145
-		}
146
-	}
147
-	if foundGroup {
148
-		return nil
149
-	} else {
150
-		return ErrUserNotInRequiredGroup
151
-	}
152
-}

+ 0
- 38
vendor/github.com/go-asn1-ber/asn1-ber/.travis.yml View File

@@ -1,38 +0,0 @@
1
-language: go
2
-matrix:
3
-    include:
4
-        - go: 1.2.x
5
-          env: GOOS=linux GOARCH=amd64
6
-        - go: 1.2.x
7
-          env: GOOS=linux GOARCH=386
8
-        - go: 1.2.x
9
-          env: GOOS=windows GOARCH=amd64
10
-        - go: 1.2.x
11
-          env: GOOS=windows GOARCH=386
12
-        - go: 1.3.x
13
-        - go: 1.4.x
14
-        - go: 1.5.x
15
-        - go: 1.6.x
16
-        - go: 1.7.x
17
-        - go: 1.8.x
18
-        - go: 1.9.x
19
-        - go: 1.10.x
20
-        - go: 1.11.x
21
-        - go: 1.12.x
22
-        - go: 1.13.x
23
-          env: GOOS=linux GOARCH=amd64
24
-        - go: 1.13.x
25
-          env: GOOS=linux GOARCH=386
26
-        - go: 1.13.x
27
-          env: GOOS=windows GOARCH=amd64
28
-        - go: 1.13.x
29
-          env: GOOS=windows GOARCH=386
30
-        - go: tip
31
-go_import_path: gopkg.in/asn-ber.v1
32
-install:
33
-    - go list -f '{{range .Imports}}{{.}} {{end}}' ./... | xargs go get -v
34
-    - go list -f '{{range .TestImports}}{{.}} {{end}}' ./... | xargs go get -v
35
-    - go get code.google.com/p/go.tools/cmd/cover || go get golang.org/x/tools/cmd/cover
36
-    - go build -v ./...
37
-script:
38
-    - go test -v -cover ./... || go test -v ./...

+ 0
- 22
vendor/github.com/go-asn1-ber/asn1-ber/LICENSE View File

@@ -1,22 +0,0 @@
1
-The MIT License (MIT)
2
-
3
-Copyright (c) 2011-2015 Michael Mitton (mmitton@gmail.com)
4
-Portions copyright (c) 2015-2016 go-asn1-ber Authors
5
-
6
-Permission is hereby granted, free of charge, to any person obtaining a copy
7
-of this software and associated documentation files (the "Software"), to deal
8
-in the Software without restriction, including without limitation the rights
9
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
-copies of the Software, and to permit persons to whom the Software is
11
-furnished to do so, subject to the following conditions:
12
-
13
-The above copyright notice and this permission notice shall be included in all
14
-copies or substantial portions of the Software.
15
-
16
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
-SOFTWARE.

+ 0
- 24
vendor/github.com/go-asn1-ber/asn1-ber/README.md View File

@@ -1,24 +0,0 @@
1
-[![GoDoc](https://godoc.org/gopkg.in/asn1-ber.v1?status.svg)](https://godoc.org/gopkg.in/asn1-ber.v1) [![Build Status](https://travis-ci.org/go-asn1-ber/asn1-ber.svg)](https://travis-ci.org/go-asn1-ber/asn1-ber)
2
-
3
-
4
-ASN1 BER Encoding / Decoding Library for the GO programming language.
5
----------------------------------------------------------------------
6
-
7
-Required libraries: 
8
-   None
9
-
10
-Working:
11
-   Very basic encoding / decoding needed for LDAP protocol
12
-
13
-Tests Implemented:
14
-   A few
15
-
16
-TODO:
17
-   Fix all encoding / decoding to conform to ASN1 BER spec
18
-   Implement Tests / Benchmarks
19
-
20
----
21
-
22
-The Go gopher was designed by Renee French. (http://reneefrench.blogspot.com/)
23
-The design is licensed under the Creative Commons 3.0 Attributions license.
24
-Read this article for more details: http://blog.golang.org/gopher

+ 0
- 512
vendor/github.com/go-asn1-ber/asn1-ber/ber.go View File

@@ -1,512 +0,0 @@
1
-package ber
2
-
3
-import (
4
-	"bytes"
5
-	"errors"
6
-	"fmt"
7
-	"io"
8
-	"math"
9
-	"os"
10
-	"reflect"
11
-)
12
-
13
-// MaxPacketLengthBytes specifies the maximum allowed packet size when calling ReadPacket or DecodePacket. Set to 0 for
14
-// no limit.
15
-var MaxPacketLengthBytes int64 = math.MaxInt32
16
-
17
-type Packet struct {
18
-	Identifier
19
-	Value       interface{}
20
-	ByteValue   []byte
21
-	Data        *bytes.Buffer
22
-	Children    []*Packet
23
-	Description string
24
-}
25
-
26
-type Identifier struct {
27
-	ClassType Class
28
-	TagType   Type
29
-	Tag       Tag
30
-}
31
-
32
-type Tag uint64
33
-
34
-const (
35
-	TagEOC              Tag = 0x00
36
-	TagBoolean          Tag = 0x01
37
-	TagInteger          Tag = 0x02
38
-	TagBitString        Tag = 0x03
39
-	TagOctetString      Tag = 0x04
40
-	TagNULL             Tag = 0x05
41
-	TagObjectIdentifier Tag = 0x06
42
-	TagObjectDescriptor Tag = 0x07
43
-	TagExternal         Tag = 0x08
44
-	TagRealFloat        Tag = 0x09
45
-	TagEnumerated       Tag = 0x0a
46
-	TagEmbeddedPDV      Tag = 0x0b
47
-	TagUTF8String       Tag = 0x0c
48
-	TagRelativeOID      Tag = 0x0d
49
-	TagSequence         Tag = 0x10
50
-	TagSet              Tag = 0x11
51
-	TagNumericString    Tag = 0x12
52
-	TagPrintableString  Tag = 0x13
53
-	TagT61String        Tag = 0x14
54
-	TagVideotexString   Tag = 0x15
55
-	TagIA5String        Tag = 0x16
56
-	TagUTCTime          Tag = 0x17
57
-	TagGeneralizedTime  Tag = 0x18
58
-	TagGraphicString    Tag = 0x19
59
-	TagVisibleString    Tag = 0x1a
60
-	TagGeneralString    Tag = 0x1b
61
-	TagUniversalString  Tag = 0x1c
62
-	TagCharacterString  Tag = 0x1d
63
-	TagBMPString        Tag = 0x1e
64
-	TagBitmask          Tag = 0x1f // xxx11111b
65
-
66
-	// HighTag indicates the start of a high-tag byte sequence
67
-	HighTag Tag = 0x1f // xxx11111b
68
-	// HighTagContinueBitmask indicates the high-tag byte sequence should continue
69
-	HighTagContinueBitmask Tag = 0x80 // 10000000b
70
-	// HighTagValueBitmask obtains the tag value from a high-tag byte sequence byte
71
-	HighTagValueBitmask Tag = 0x7f // 01111111b
72
-)
73
-
74
-const (
75
-	// LengthLongFormBitmask is the mask to apply to the length byte to see if a long-form byte sequence is used
76
-	LengthLongFormBitmask = 0x80
77
-	// LengthValueBitmask is the mask to apply to the length byte to get the number of bytes in the long-form byte sequence
78
-	LengthValueBitmask = 0x7f
79
-
80
-	// LengthIndefinite is returned from readLength to indicate an indefinite length
81
-	LengthIndefinite = -1
82
-)
83
-
84
-var tagMap = map[Tag]string{
85
-	TagEOC:              "EOC (End-of-Content)",
86
-	TagBoolean:          "Boolean",
87
-	TagInteger:          "Integer",
88
-	TagBitString:        "Bit String",
89
-	TagOctetString:      "Octet String",
90
-	TagNULL:             "NULL",
91
-	TagObjectIdentifier: "Object Identifier",
92
-	TagObjectDescriptor: "Object Descriptor",
93
-	TagExternal:         "External",
94
-	TagRealFloat:        "Real (float)",
95
-	TagEnumerated:       "Enumerated",
96
-	TagEmbeddedPDV:      "Embedded PDV",
97
-	TagUTF8String:       "UTF8 String",
98
-	TagRelativeOID:      "Relative-OID",
99
-	TagSequence:         "Sequence and Sequence of",
100
-	TagSet:              "Set and Set OF",
101
-	TagNumericString:    "Numeric String",
102
-	TagPrintableString:  "Printable String",
103
-	TagT61String:        "T61 String",
104
-	TagVideotexString:   "Videotex String",
105
-	TagIA5String:        "IA5 String",
106
-	TagUTCTime:          "UTC Time",
107
-	TagGeneralizedTime:  "Generalized Time",
108
-	TagGraphicString:    "Graphic String",
109
-	TagVisibleString:    "Visible String",
110
-	TagGeneralString:    "General String",
111
-	TagUniversalString:  "Universal String",
112
-	TagCharacterString:  "Character String",
113
-	TagBMPString:        "BMP String",
114
-}
115
-
116
-type Class uint8
117
-
118
-const (
119
-	ClassUniversal   Class = 0   // 00xxxxxxb
120
-	ClassApplication Class = 64  // 01xxxxxxb
121
-	ClassContext     Class = 128 // 10xxxxxxb
122
-	ClassPrivate     Class = 192 // 11xxxxxxb
123
-	ClassBitmask     Class = 192 // 11xxxxxxb
124
-)
125
-
126
-var ClassMap = map[Class]string{
127
-	ClassUniversal:   "Universal",
128
-	ClassApplication: "Application",
129
-	ClassContext:     "Context",
130
-	ClassPrivate:     "Private",
131
-}
132
-
133
-type Type uint8
134
-
135
-const (
136
-	TypePrimitive   Type = 0  // xx0xxxxxb
137
-	TypeConstructed Type = 32 // xx1xxxxxb
138
-	TypeBitmask     Type = 32 // xx1xxxxxb
139
-)
140
-
141
-var TypeMap = map[Type]string{
142
-	TypePrimitive:   "Primitive",
143
-	TypeConstructed: "Constructed",
144
-}
145
-
146
-var Debug bool = false
147
-
148
-func PrintBytes(out io.Writer, buf []byte, indent string) {
149
-	data_lines := make([]string, (len(buf)/30)+1)
150
-	num_lines := make([]string, (len(buf)/30)+1)
151
-
152
-	for i, b := range buf {
153
-		data_lines[i/30] += fmt.Sprintf("%02x ", b)
154
-		num_lines[i/30] += fmt.Sprintf("%02d ", (i+1)%100)
155
-	}
156
-
157
-	for i := 0; i < len(data_lines); i++ {
158
-		out.Write([]byte(indent + data_lines[i] + "\n"))
159
-		out.Write([]byte(indent + num_lines[i] + "\n\n"))
160
-	}
161
-}
162
-
163
-func PrintPacket(p *Packet) {
164
-	printPacket(os.Stdout, p, 0, false)
165
-}
166
-
167
-func printPacket(out io.Writer, p *Packet, indent int, printBytes bool) {
168
-	indent_str := ""
169
-
170
-	for len(indent_str) != indent {
171
-		indent_str += " "
172
-	}
173
-
174
-	class_str := ClassMap[p.ClassType]
175
-
176
-	tagtype_str := TypeMap[p.TagType]
177
-
178
-	tag_str := fmt.Sprintf("0x%02X", p.Tag)
179
-
180
-	if p.ClassType == ClassUniversal {
181
-		tag_str = tagMap[p.Tag]
182
-	}
183
-
184
-	value := fmt.Sprint(p.Value)
185
-	description := ""
186
-
187
-	if p.Description != "" {
188
-		description = p.Description + ": "
189
-	}
190
-
191
-	fmt.Fprintf(out, "%s%s(%s, %s, %s) Len=%d %q\n", indent_str, description, class_str, tagtype_str, tag_str, p.Data.Len(), value)
192
-
193
-	if printBytes {
194
-		PrintBytes(out, p.Bytes(), indent_str)
195
-	}
196
-
197
-	for _, child := range p.Children {
198
-		printPacket(out, child, indent+1, printBytes)
199
-	}
200
-}
201
-
202
-// ReadPacket reads a single Packet from the reader
203
-func ReadPacket(reader io.Reader) (*Packet, error) {
204
-	p, _, err := readPacket(reader)
205
-	if err != nil {
206
-		return nil, err
207
-	}
208
-	return p, nil
209
-}
210
-
211
-func DecodeString(data []byte) string {
212
-	return string(data)
213
-}
214
-
215
-func ParseInt64(bytes []byte) (ret int64, err error) {
216
-	if len(bytes) > 8 {
217
-		// We'll overflow an int64 in this case.
218
-		err = fmt.Errorf("integer too large")
219
-		return
220
-	}
221
-	for bytesRead := 0; bytesRead < len(bytes); bytesRead++ {
222
-		ret <<= 8
223
-		ret |= int64(bytes[bytesRead])
224
-	}
225
-
226
-	// Shift up and down in order to sign extend the result.
227
-	ret <<= 64 - uint8(len(bytes))*8
228
-	ret >>= 64 - uint8(len(bytes))*8
229
-	return
230
-}
231
-
232
-func encodeInteger(i int64) []byte {
233
-	n := int64Length(i)
234
-	out := make([]byte, n)
235
-
236
-	var j int
237
-	for ; n > 0; n-- {
238
-		out[j] = (byte(i >> uint((n-1)*8)))
239
-		j++
240
-	}
241
-
242
-	return out
243
-}
244
-
245
-func int64Length(i int64) (numBytes int) {
246
-	numBytes = 1
247
-
248
-	for i > 127 {
249
-		numBytes++
250
-		i >>= 8
251
-	}
252
-
253
-	for i < -128 {
254
-		numBytes++
255
-		i >>= 8
256
-	}
257
-
258
-	return
259
-}
260
-
261
-// DecodePacket decodes the given bytes into a single Packet
262
-// If a decode error is encountered, nil is returned.
263
-func DecodePacket(data []byte) *Packet {
264
-	p, _, _ := readPacket(bytes.NewBuffer(data))
265
-
266
-	return p
267
-}
268
-
269
-// DecodePacketErr decodes the given bytes into a single Packet
270
-// If a decode error is encountered, nil is returned
271
-func DecodePacketErr(data []byte) (*Packet, error) {
272
-	p, _, err := readPacket(bytes.NewBuffer(data))
273
-	if err != nil {
274
-		return nil, err
275
-	}
276
-	return p, nil
277
-}
278
-
279
-// readPacket reads a single Packet from the reader, returning the number of bytes read
280
-func readPacket(reader io.Reader) (*Packet, int, error) {
281
-	identifier, length, read, err := readHeader(reader)
282
-	if err != nil {
283
-		return nil, read, err
284
-	}
285
-
286
-	p := &Packet{
287
-		Identifier: identifier,
288
-	}
289
-
290
-	p.Data = new(bytes.Buffer)
291
-	p.Children = make([]*Packet, 0, 2)
292
-	p.Value = nil
293
-
294
-	if p.TagType == TypeConstructed {
295
-		// TODO: if universal, ensure tag type is allowed to be constructed
296
-
297
-		// Track how much content we've read
298
-		contentRead := 0
299
-		for {
300
-			if length != LengthIndefinite {
301
-				// End if we've read what we've been told to
302
-				if contentRead == length {
303
-					break
304
-				}
305
-				// Detect if a packet boundary didn't fall on the expected length
306
-				if contentRead > length {
307
-					return nil, read, fmt.Errorf("expected to read %d bytes, read %d", length, contentRead)
308
-				}
309
-			}
310
-
311
-			// Read the next packet
312
-			child, r, err := readPacket(reader)
313
-			if err != nil {
314
-				return nil, read, err
315
-			}
316
-			contentRead += r
317
-			read += r
318
-
319
-			// Test is this is the EOC marker for our packet
320
-			if isEOCPacket(child) {
321
-				if length == LengthIndefinite {
322
-					break
323
-				}
324
-				return nil, read, errors.New("eoc child not allowed with definite length")
325
-			}
326
-
327
-			// Append and continue
328
-			p.AppendChild(child)
329
-		}
330
-		return p, read, nil
331
-	}
332
-
333
-	if length == LengthIndefinite {
334
-		return nil, read, errors.New("indefinite length used with primitive type")
335
-	}
336
-
337
-	// Read definite-length content
338
-	if MaxPacketLengthBytes > 0 && int64(length) > MaxPacketLengthBytes {
339
-		return nil, read, fmt.Errorf("length %d greater than maximum %d", length, MaxPacketLengthBytes)
340
-	}
341
-	content := make([]byte, length, length)
342
-	if length > 0 {
343
-		_, err := io.ReadFull(reader, content)
344
-		if err != nil {
345
-			if err == io.EOF {
346
-				return nil, read, io.ErrUnexpectedEOF
347
-			}
348
-			return nil, read, err
349
-		}
350
-		read += length
351
-	}
352
-
353
-	if p.ClassType == ClassUniversal {
354
-		p.Data.Write(content)
355
-		p.ByteValue = content
356
-
357
-		switch p.Tag {
358
-		case TagEOC:
359
-		case TagBoolean:
360
-			val, _ := ParseInt64(content)
361
-
362
-			p.Value = val != 0
363
-		case TagInteger:
364
-			p.Value, _ = ParseInt64(content)
365
-		case TagBitString:
366
-		case TagOctetString:
367
-			// the actual string encoding is not known here
368
-			// (e.g. for LDAP content is already an UTF8-encoded
369
-			// string). Return the data without further processing
370
-			p.Value = DecodeString(content)
371
-		case TagNULL:
372
-		case TagObjectIdentifier:
373
-		case TagObjectDescriptor:
374
-		case TagExternal:
375
-		case TagRealFloat:
376
-		case TagEnumerated:
377
-			p.Value, _ = ParseInt64(content)
378
-		case TagEmbeddedPDV:
379
-		case TagUTF8String:
380
-			p.Value = DecodeString(content)
381
-		case TagRelativeOID:
382
-		case TagSequence:
383
-		case TagSet:
384
-		case TagNumericString:
385
-		case TagPrintableString:
386
-			p.Value = DecodeString(content)
387
-		case TagT61String:
388
-		case TagVideotexString:
389
-		case TagIA5String:
390
-		case TagUTCTime:
391
-		case TagGeneralizedTime:
392
-		case TagGraphicString:
393
-		case TagVisibleString:
394
-		case TagGeneralString:
395
-		case TagUniversalString:
396
-		case TagCharacterString:
397
-		case TagBMPString:
398
-		}
399
-	} else {
400
-		p.Data.Write(content)
401
-	}
402
-
403
-	return p, read, nil
404
-}
405
-
406
-func (p *Packet) Bytes() []byte {
407
-	var out bytes.Buffer
408
-
409
-	out.Write(encodeIdentifier(p.Identifier))
410
-	out.Write(encodeLength(p.Data.Len()))
411
-	out.Write(p.Data.Bytes())
412
-
413
-	return out.Bytes()
414
-}
415
-
416
-func (p *Packet) AppendChild(child *Packet) {
417
-	p.Data.Write(child.Bytes())
418
-	p.Children = append(p.Children, child)
419
-}
420
-
421
-func Encode(ClassType Class, TagType Type, Tag Tag, Value interface{}, Description string) *Packet {
422
-	p := new(Packet)
423
-
424
-	p.ClassType = ClassType
425
-	p.TagType = TagType
426
-	p.Tag = Tag
427
-	p.Data = new(bytes.Buffer)
428
-
429
-	p.Children = make([]*Packet, 0, 2)
430
-
431
-	p.Value = Value
432
-	p.Description = Description
433
-
434
-	if Value != nil {
435
-		v := reflect.ValueOf(Value)
436
-
437
-		if ClassType == ClassUniversal {
438
-			switch Tag {
439
-			case TagOctetString:
440
-				sv, ok := v.Interface().(string)
441
-
442
-				if ok {
443
-					p.Data.Write([]byte(sv))
444
-				}
445
-			}
446
-		}
447
-	}
448
-
449
-	return p
450
-}
451
-
452
-func NewSequence(Description string) *Packet {
453
-	return Encode(ClassUniversal, TypeConstructed, TagSequence, nil, Description)
454
-}
455
-
456
-func NewBoolean(ClassType Class, TagType Type, Tag Tag, Value bool, Description string) *Packet {
457
-	intValue := int64(0)
458
-
459
-	if Value {
460
-		intValue = 1
461
-	}
462
-
463
-	p := Encode(ClassType, TagType, Tag, nil, Description)
464
-
465
-	p.Value = Value
466
-	p.Data.Write(encodeInteger(intValue))
467
-
468
-	return p
469
-}
470
-
471
-func NewInteger(ClassType Class, TagType Type, Tag Tag, Value interface{}, Description string) *Packet {
472
-	p := Encode(ClassType, TagType, Tag, nil, Description)
473
-
474
-	p.Value = Value
475
-	switch v := Value.(type) {
476
-	case int:
477
-		p.Data.Write(encodeInteger(int64(v)))
478
-	case uint:
479
-		p.Data.Write(encodeInteger(int64(v)))
480
-	case int64:
481
-		p.Data.Write(encodeInteger(v))
482
-	case uint64:
483
-		// TODO : check range or add encodeUInt...
484
-		p.Data.Write(encodeInteger(int64(v)))
485
-	case int32:
486
-		p.Data.Write(encodeInteger(int64(v)))
487
-	case uint32:
488
-		p.Data.Write(encodeInteger(int64(v)))
489
-	case int16:
490
-		p.Data.Write(encodeInteger(int64(v)))
491
-	case uint16:
492
-		p.Data.Write(encodeInteger(int64(v)))
493
-	case int8:
494
-		p.Data.Write(encodeInteger(int64(v)))
495
-	case uint8:
496
-		p.Data.Write(encodeInteger(int64(v)))
497
-	default:
498
-		// TODO : add support for big.Int ?
499
-		panic(fmt.Sprintf("Invalid type %T, expected {u|}int{64|32|16|8}", v))
500
-	}
501
-
502
-	return p
503
-}
504
-
505
-func NewString(ClassType Class, TagType Type, Tag Tag, Value, Description string) *Packet {
506
-	p := Encode(ClassType, TagType, Tag, nil, Description)
507
-
508
-	p.Value = Value
509
-	p.Data.Write([]byte(Value))
510
-
511
-	return p
512
-}

+ 0
- 25
vendor/github.com/go-asn1-ber/asn1-ber/content_int.go View File

@@ -1,25 +0,0 @@
1
-package ber
2
-
3
-func encodeUnsignedInteger(i uint64) []byte {
4
-	n := uint64Length(i)
5
-	out := make([]byte, n)
6
-
7
-	var j int
8
-	for ; n > 0; n-- {
9
-		out[j] = (byte(i >> uint((n-1)*8)))
10
-		j++
11
-	}
12
-
13
-	return out
14
-}
15
-
16
-func uint64Length(i uint64) (numBytes int) {
17
-	numBytes = 1
18
-
19
-	for i > 255 {
20
-		numBytes++
21
-		i >>= 8
22
-	}
23
-
24
-	return
25
-}

+ 0
- 3
vendor/github.com/go-asn1-ber/asn1-ber/go.mod View File

@@ -1,3 +0,0 @@
1
-module github.com/go-asn1-ber/asn1-ber
2
-
3
-go 1.13

+ 0
- 35
vendor/github.com/go-asn1-ber/asn1-ber/header.go View File

@@ -1,35 +0,0 @@
1
-package ber
2
-
3
-import (
4
-	"errors"
5
-	"fmt"
6
-	"io"
7
-)
8
-
9
-func readHeader(reader io.Reader) (identifier Identifier, length int, read int, err error) {
10
-	if i, c, err := readIdentifier(reader); err != nil {
11
-		return Identifier{}, 0, read, err
12
-	} else {
13
-		identifier = i
14
-		read += c
15
-	}
16
-
17
-	if l, c, err := readLength(reader); err != nil {
18
-		return Identifier{}, 0, read, err
19
-	} else {
20
-		length = l
21
-		read += c
22
-	}
23
-
24
-	// Validate length type with identifier (x.600, 8.1.3.2.a)
25
-	if length == LengthIndefinite && identifier.TagType == TypePrimitive {
26
-		return Identifier{}, 0, read, errors.New("indefinite length used with primitive type")
27
-	}
28
-
29
-	if length < LengthIndefinite {
30
-		err = fmt.Errorf("length cannot be less than %d", LengthIndefinite)
31
-		return
32
-	}
33
-
34
-	return identifier, length, read, nil
35
-}

+ 0
- 112
vendor/github.com/go-asn1-ber/asn1-ber/identifier.go View File

@@ -1,112 +0,0 @@
1
-package ber
2
-
3
-import (
4
-	"errors"
5
-	"fmt"
6
-	"io"
7
-)
8
-
9
-func readIdentifier(reader io.Reader) (Identifier, int, error) {
10
-	identifier := Identifier{}
11
-	read := 0
12
-
13
-	// identifier byte
14
-	b, err := readByte(reader)
15
-	if err != nil {
16
-		if Debug {
17
-			fmt.Printf("error reading identifier byte: %v\n", err)
18
-		}
19
-		return Identifier{}, read, err
20
-	}
21
-	read++
22
-
23
-	identifier.ClassType = Class(b) & ClassBitmask
24
-	identifier.TagType = Type(b) & TypeBitmask
25
-
26
-	if tag := Tag(b) & TagBitmask; tag != HighTag {
27
-		// short-form tag
28
-		identifier.Tag = tag
29
-		return identifier, read, nil
30
-	}
31
-
32
-	// high-tag-number tag
33
-	tagBytes := 0
34
-	for {
35
-		b, err := readByte(reader)
36
-		if err != nil {
37
-			if Debug {
38
-				fmt.Printf("error reading high-tag-number tag byte %d: %v\n", tagBytes, err)
39
-			}
40
-			return Identifier{}, read, err
41
-		}
42
-		tagBytes++
43
-		read++
44
-
45
-		// Lowest 7 bits get appended to the tag value (x.690, 8.1.2.4.2.b)
46
-		identifier.Tag <<= 7
47
-		identifier.Tag |= Tag(b) & HighTagValueBitmask
48
-
49
-		// First byte may not be all zeros (x.690, 8.1.2.4.2.c)
50
-		if tagBytes == 1 && identifier.Tag == 0 {
51
-			return Identifier{}, read, errors.New("invalid first high-tag-number tag byte")
52
-		}
53
-		// Overflow of int64
54
-		// TODO: support big int tags?
55
-		if tagBytes > 9 {
56
-			return Identifier{}, read, errors.New("high-tag-number tag overflow")
57
-		}
58
-
59
-		// Top bit of 0 means this is the last byte in the high-tag-number tag (x.690, 8.1.2.4.2.a)
60
-		if Tag(b)&HighTagContinueBitmask == 0 {
61
-			break
62
-		}
63
-	}
64
-
65
-	return identifier, read, nil
66
-}
67
-
68
-func encodeIdentifier(identifier Identifier) []byte {
69
-	b := []byte{0x0}
70
-	b[0] |= byte(identifier.ClassType)
71
-	b[0] |= byte(identifier.TagType)
72
-
73
-	if identifier.Tag < HighTag {
74
-		// Short-form
75
-		b[0] |= byte(identifier.Tag)
76
-	} else {
77
-		// high-tag-number
78
-		b[0] |= byte(HighTag)
79
-
80
-		tag := identifier.Tag
81
-
82
-		b = append(b, encodeHighTag(tag)...)
83
-	}
84
-	return b
85
-}
86
-
87
-func encodeHighTag(tag Tag) []byte {
88
-	// set cap=4 to hopefully avoid additional allocations
89
-	b := make([]byte, 0, 4)
90
-	for tag != 0 {
91
-		// t := last 7 bits of tag (HighTagValueBitmask = 0x7F)
92
-		t := tag & HighTagValueBitmask
93
-
94
-		// right shift tag 7 to remove what was just pulled off
95
-		tag >>= 7
96
-
97
-		// if b already has entries this entry needs a continuation bit (0x80)
98
-		if len(b) != 0 {
99
-			t |= HighTagContinueBitmask
100
-		}
101
-
102
-		b = append(b, byte(t))
103
-	}
104
-	// reverse
105
-	// since bits were pulled off 'tag' small to high the byte slice is in reverse order.
106
-	// example: tag = 0xFF results in {0x7F, 0x01 + 0x80 (continuation bit)}
107
-	// this needs to be reversed into 0x81 0x7F
108
-	for i, j := 0, len(b)-1; i < len(b)/2; i++ {
109
-		b[i], b[j-i] = b[j-i], b[i]
110
-	}
111
-	return b
112
-}

+ 0
- 81
vendor/github.com/go-asn1-ber/asn1-ber/length.go View File

@@ -1,81 +0,0 @@
1
-package ber
2
-
3
-import (
4
-	"errors"
5
-	"fmt"
6
-	"io"
7
-)
8
-
9
-func readLength(reader io.Reader) (length int, read int, err error) {
10
-	// length byte
11
-	b, err := readByte(reader)
12
-	if err != nil {
13
-		if Debug {
14
-			fmt.Printf("error reading length byte: %v\n", err)
15
-		}
16
-		return 0, 0, err
17
-	}
18
-	read++
19
-
20
-	switch {
21
-	case b == 0xFF:
22
-		// Invalid 0xFF (x.600, 8.1.3.5.c)
23
-		return 0, read, errors.New("invalid length byte 0xff")
24
-
25
-	case b == LengthLongFormBitmask:
26
-		// Indefinite form, we have to decode packets until we encounter an EOC packet (x.600, 8.1.3.6)
27
-		length = LengthIndefinite
28
-
29
-	case b&LengthLongFormBitmask == 0:
30
-		// Short definite form, extract the length from the bottom 7 bits (x.600, 8.1.3.4)
31
-		length = int(b) & LengthValueBitmask
32
-
33
-	case b&LengthLongFormBitmask != 0:
34
-		// Long definite form, extract the number of length bytes to follow from the bottom 7 bits (x.600, 8.1.3.5.b)
35
-		lengthBytes := int(b) & LengthValueBitmask
36
-		// Protect against overflow
37
-		// TODO: support big int length?
38
-		if lengthBytes > 8 {
39
-			return 0, read, errors.New("long-form length overflow")
40
-		}
41
-
42
-		// Accumulate into a 64-bit variable
43
-		var length64 int64
44
-		for i := 0; i < lengthBytes; i++ {
45
-			b, err = readByte(reader)
46
-			if err != nil {
47
-				if Debug {
48
-					fmt.Printf("error reading long-form length byte %d: %v\n", i, err)
49
-				}
50
-				return 0, read, err
51
-			}
52
-			read++
53
-
54
-			// x.600, 8.1.3.5
55
-			length64 <<= 8
56
-			length64 |= int64(b)
57
-		}
58
-
59
-		// Cast to a platform-specific integer
60
-		length = int(length64)
61
-		// Ensure we didn't overflow
62
-		if int64(length) != length64 {
63
-			return 0, read, errors.New("long-form length overflow")
64
-		}
65
-
66
-	default:
67
-		return 0, read, errors.New("invalid length byte")
68
-	}
69
-
70
-	return length, read, nil
71
-}
72
-
73
-func encodeLength(length int) []byte {
74
-	length_bytes := encodeUnsignedInteger(uint64(length))
75
-	if length > 127 || len(length_bytes) > 1 {
76
-		longFormBytes := []byte{(LengthLongFormBitmask | byte(len(length_bytes)))}
77
-		longFormBytes = append(longFormBytes, length_bytes...)
78
-		length_bytes = longFormBytes
79
-	}
80
-	return length_bytes
81
-}

+ 0
- 24
vendor/github.com/go-asn1-ber/asn1-ber/util.go View File

@@ -1,24 +0,0 @@
1
-package ber
2
-
3
-import "io"
4
-
5
-func readByte(reader io.Reader) (byte, error) {
6
-	bytes := make([]byte, 1, 1)
7
-	_, err := io.ReadFull(reader, bytes)
8
-	if err != nil {
9
-		if err == io.EOF {
10
-			return 0, io.ErrUnexpectedEOF
11
-		}
12
-		return 0, err
13
-	}
14
-	return bytes[0], nil
15
-}
16
-
17
-func isEOCPacket(p *Packet) bool {
18
-	return p != nil &&
19
-		p.Tag == TagEOC &&
20
-		p.ClassType == ClassUniversal &&
21
-		p.TagType == TypePrimitive &&
22
-		len(p.ByteValue) == 0 &&
23
-		len(p.Children) == 0
24
-}

+ 0
- 22
vendor/github.com/go-ldap/ldap/v3/LICENSE View File

@@ -1,22 +0,0 @@
1
-The MIT License (MIT)
2
-
3
-Copyright (c) 2011-2015 Michael Mitton (mmitton@gmail.com)
4
-Portions copyright (c) 2015-2016 go-ldap Authors
5
-
6
-Permission is hereby granted, free of charge, to any person obtaining a copy
7
-of this software and associated documentation files (the "Software"), to deal
8
-in the Software without restriction, including without limitation the rights
9
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
-copies of the Software, and to permit persons to whom the Software is
11
-furnished to do so, subject to the following conditions:
12
-
13
-The above copyright notice and this permission notice shall be included in all
14
-copies or substantial portions of the Software.
15
-
16
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
-SOFTWARE.

+ 0
- 91
vendor/github.com/go-ldap/ldap/v3/add.go View File

@@ -1,91 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"log"
5
-
6
-	ber "github.com/go-asn1-ber/asn1-ber"
7
-)
8
-
9
-// Attribute represents an LDAP attribute
10
-type Attribute struct {
11
-	// Type is the name of the LDAP attribute
12
-	Type string
13
-	// Vals are the LDAP attribute values
14
-	Vals []string
15
-}
16
-
17
-func (a *Attribute) encode() *ber.Packet {
18
-	seq := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Attribute")
19
-	seq.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, a.Type, "Type"))
20
-	set := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSet, nil, "AttributeValue")
21
-	for _, value := range a.Vals {
22
-		set.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, value, "Vals"))
23
-	}
24
-	seq.AppendChild(set)
25
-	return seq
26
-}
27
-
28
-// AddRequest represents an LDAP AddRequest operation
29
-type AddRequest struct {
30
-	// DN identifies the entry being added
31
-	DN string
32
-	// Attributes list the attributes of the new entry
33
-	Attributes []Attribute
34
-	// Controls hold optional controls to send with the request
35
-	Controls []Control
36
-}
37
-
38
-func (req *AddRequest) appendTo(envelope *ber.Packet) error {
39
-	pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationAddRequest, nil, "Add Request")
40
-	pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.DN, "DN"))
41
-	attributes := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Attributes")
42
-	for _, attribute := range req.Attributes {
43
-		attributes.AppendChild(attribute.encode())
44
-	}
45
-	pkt.AppendChild(attributes)
46
-
47
-	envelope.AppendChild(pkt)
48
-	if len(req.Controls) > 0 {
49
-		envelope.AppendChild(encodeControls(req.Controls))
50
-	}
51
-
52
-	return nil
53
-}
54
-
55
-// Attribute adds an attribute with the given type and values
56
-func (req *AddRequest) Attribute(attrType string, attrVals []string) {
57
-	req.Attributes = append(req.Attributes, Attribute{Type: attrType, Vals: attrVals})
58
-}
59
-
60
-// NewAddRequest returns an AddRequest for the given DN, with no attributes
61
-func NewAddRequest(dn string, controls []Control) *AddRequest {
62
-	return &AddRequest{
63
-		DN:       dn,
64
-		Controls: controls,
65
-	}
66
-
67
-}
68
-
69
-// Add performs the given AddRequest
70
-func (l *Conn) Add(addRequest *AddRequest) error {
71
-	msgCtx, err := l.doRequest(addRequest)
72
-	if err != nil {
73
-		return err
74
-	}
75
-	defer l.finishMessage(msgCtx)
76
-
77
-	packet, err := l.readPacket(msgCtx)
78
-	if err != nil {
79
-		return err
80
-	}
81
-
82
-	if packet.Children[1].Tag == ApplicationAddResponse {
83
-		err := GetLDAPError(packet)
84
-		if err != nil {
85
-			return err
86
-		}
87
-	} else {
88
-		log.Printf("Unexpected Response: %d", packet.Children[1].Tag)
89
-	}
90
-	return nil
91
-}

+ 0
- 389
vendor/github.com/go-ldap/ldap/v3/bind.go View File

@@ -1,389 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"bytes"
5
-	"crypto/md5"
6
-	enchex "encoding/hex"
7
-	"errors"
8
-	"fmt"
9
-	"io/ioutil"
10
-	"math/rand"
11
-	"strings"
12
-
13
-	ber "github.com/go-asn1-ber/asn1-ber"
14
-)
15
-
16
-// SimpleBindRequest represents a username/password bind operation
17
-type SimpleBindRequest struct {
18
-	// Username is the name of the Directory object that the client wishes to bind as
19
-	Username string
20
-	// Password is the credentials to bind with
21
-	Password string
22
-	// Controls are optional controls to send with the bind request
23
-	Controls []Control
24
-	// AllowEmptyPassword sets whether the client allows binding with an empty password
25
-	// (normally used for unauthenticated bind).
26
-	AllowEmptyPassword bool
27
-}
28
-
29
-// SimpleBindResult contains the response from the server
30
-type SimpleBindResult struct {
31
-	Controls []Control
32
-}
33
-
34
-// NewSimpleBindRequest returns a bind request
35
-func NewSimpleBindRequest(username string, password string, controls []Control) *SimpleBindRequest {
36
-	return &SimpleBindRequest{
37
-		Username:           username,
38
-		Password:           password,
39
-		Controls:           controls,
40
-		AllowEmptyPassword: false,
41
-	}
42
-}
43
-
44
-func (req *SimpleBindRequest) appendTo(envelope *ber.Packet) error {
45
-	pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request")
46
-	pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version"))
47
-	pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.Username, "User Name"))
48
-	pkt.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, req.Password, "Password"))
49
-
50
-	envelope.AppendChild(pkt)
51
-	if len(req.Controls) > 0 {
52
-		envelope.AppendChild(encodeControls(req.Controls))
53
-	}
54
-
55
-	return nil
56
-}
57
-
58
-// SimpleBind performs the simple bind operation defined in the given request
59
-func (l *Conn) SimpleBind(simpleBindRequest *SimpleBindRequest) (*SimpleBindResult, error) {
60
-	if simpleBindRequest.Password == "" && !simpleBindRequest.AllowEmptyPassword {
61
-		return nil, NewError(ErrorEmptyPassword, errors.New("ldap: empty password not allowed by the client"))
62
-	}
63
-
64
-	msgCtx, err := l.doRequest(simpleBindRequest)
65
-	if err != nil {
66
-		return nil, err
67
-	}
68
-	defer l.finishMessage(msgCtx)
69
-
70
-	packet, err := l.readPacket(msgCtx)
71
-	if err != nil {
72
-		return nil, err
73
-	}
74
-
75
-	result := &SimpleBindResult{
76
-		Controls: make([]Control, 0),
77
-	}
78
-
79
-	if len(packet.Children) == 3 {
80
-		for _, child := range packet.Children[2].Children {
81
-			decodedChild, decodeErr := DecodeControl(child)
82
-			if decodeErr != nil {
83
-				return nil, fmt.Errorf("failed to decode child control: %s", decodeErr)
84
-			}
85
-			result.Controls = append(result.Controls, decodedChild)
86
-		}
87
-	}
88
-
89
-	err = GetLDAPError(packet)
90
-	return result, err
91
-}
92
-
93
-// Bind performs a bind with the given username and password.
94
-//
95
-// It does not allow unauthenticated bind (i.e. empty password). Use the UnauthenticatedBind method
96
-// for that.
97
-func (l *Conn) Bind(username, password string) error {
98
-	req := &SimpleBindRequest{
99
-		Username:           username,
100
-		Password:           password,
101
-		AllowEmptyPassword: false,
102
-	}
103
-	_, err := l.SimpleBind(req)
104
-	return err
105
-}
106
-
107
-// UnauthenticatedBind performs an unauthenticated bind.
108
-//
109
-// A username may be provided for trace (e.g. logging) purpose only, but it is normally not
110
-// authenticated or otherwise validated by the LDAP server.
111
-//
112
-// See https://tools.ietf.org/html/rfc4513#section-5.1.2 .
113
-// See https://tools.ietf.org/html/rfc4513#section-6.3.1 .
114
-func (l *Conn) UnauthenticatedBind(username string) error {
115
-	req := &SimpleBindRequest{
116
-		Username:           username,
117
-		Password:           "",
118
-		AllowEmptyPassword: true,
119
-	}
120
-	_, err := l.SimpleBind(req)
121
-	return err
122
-}
123
-
124
-// DigestMD5BindRequest represents a digest-md5 bind operation
125
-type DigestMD5BindRequest struct {
126
-	Host string
127
-	// Username is the name of the Directory object that the client wishes to bind as
128
-	Username string
129
-	// Password is the credentials to bind with
130
-	Password string
131
-	// Controls are optional controls to send with the bind request
132
-	Controls []Control
133
-}
134
-
135
-func (req *DigestMD5BindRequest) appendTo(envelope *ber.Packet) error {
136
-	request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request")
137
-	request.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version"))
138
-	request.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "", "User Name"))
139
-
140
-	auth := ber.Encode(ber.ClassContext, ber.TypeConstructed, 3, "", "authentication")
141
-	auth.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "DIGEST-MD5", "SASL Mech"))
142
-	request.AppendChild(auth)
143
-	envelope.AppendChild(request)
144
-	if len(req.Controls) > 0 {
145
-		envelope.AppendChild(encodeControls(req.Controls))
146
-	}
147
-	return nil
148
-}
149
-
150
-// DigestMD5BindResult contains the response from the server
151
-type DigestMD5BindResult struct {
152
-	Controls []Control
153
-}
154
-
155
-// MD5Bind performs a digest-md5 bind with the given host, username and password.
156
-func (l *Conn) MD5Bind(host, username, password string) error {
157
-	req := &DigestMD5BindRequest{
158
-		Host:     host,
159
-		Username: username,
160
-		Password: password,
161
-	}
162
-	_, err := l.DigestMD5Bind(req)
163
-	return err
164
-}
165
-
166
-// DigestMD5Bind performs the digest-md5 bind operation defined in the given request
167
-func (l *Conn) DigestMD5Bind(digestMD5BindRequest *DigestMD5BindRequest) (*DigestMD5BindResult, error) {
168
-	if digestMD5BindRequest.Password == "" {
169
-		return nil, NewError(ErrorEmptyPassword, errors.New("ldap: empty password not allowed by the client"))
170
-	}
171
-
172
-	msgCtx, err := l.doRequest(digestMD5BindRequest)
173
-	if err != nil {
174
-		return nil, err
175
-	}
176
-	defer l.finishMessage(msgCtx)
177
-
178
-	packet, err := l.readPacket(msgCtx)
179
-	if err != nil {
180
-		return nil, err
181
-	}
182
-	l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
183
-	if l.Debug {
184
-		if err = addLDAPDescriptions(packet); err != nil {
185
-			return nil, err
186
-		}
187
-		ber.PrintPacket(packet)
188
-	}
189
-
190
-	result := &DigestMD5BindResult{
191
-		Controls: make([]Control, 0),
192
-	}
193
-	var params map[string]string
194
-	if len(packet.Children) == 2 {
195
-		if len(packet.Children[1].Children) == 4 {
196
-			child := packet.Children[1].Children[0]
197
-			if child.Tag != ber.TagEnumerated {
198
-				return result, GetLDAPError(packet)
199
-			}
200
-			if child.Value.(int64) != 14 {
201
-				return result, GetLDAPError(packet)
202
-			}
203
-			child = packet.Children[1].Children[3]
204
-			if child.Tag != ber.TagObjectDescriptor {
205
-				return result, GetLDAPError(packet)
206
-			}
207
-			if child.Data == nil {
208
-				return result, GetLDAPError(packet)
209
-			}
210
-			data, _ := ioutil.ReadAll(child.Data)
211
-			params, err = parseParams(string(data))
212
-			if err != nil {
213
-				return result, fmt.Errorf("parsing digest-challenge: %s", err)
214
-			}
215
-		}
216
-	}
217
-
218
-	if params != nil {
219
-		resp := computeResponse(
220
-			params,
221
-			"ldap/"+strings.ToLower(digestMD5BindRequest.Host),
222
-			digestMD5BindRequest.Username,
223
-			digestMD5BindRequest.Password,
224
-		)
225
-		packet = ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request")
226
-		packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID"))
227
-
228
-		request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request")
229
-		request.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version"))
230
-		request.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "", "User Name"))
231
-
232
-		auth := ber.Encode(ber.ClassContext, ber.TypeConstructed, 3, "", "authentication")
233
-		auth.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "DIGEST-MD5", "SASL Mech"))
234
-		auth.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, resp, "Credentials"))
235
-		request.AppendChild(auth)
236
-		packet.AppendChild(request)
237
-		msgCtx, err = l.sendMessage(packet)
238
-		if err != nil {
239
-			return nil, fmt.Errorf("send message: %s", err)
240
-		}
241
-		defer l.finishMessage(msgCtx)
242
-		packetResponse, ok := <-msgCtx.responses
243
-		if !ok {
244
-			return nil, NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
245
-		}
246
-		packet, err = packetResponse.ReadPacket()
247
-		l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
248
-		if err != nil {
249
-			return nil, fmt.Errorf("read packet: %s", err)
250
-		}
251
-	}
252
-
253
-	err = GetLDAPError(packet)
254
-	return result, err
255
-}
256
-
257
-func parseParams(str string) (map[string]string, error) {
258
-	m := make(map[string]string)
259
-	var key, value string
260
-	var state int
261
-	for i := 0; i <= len(str); i++ {
262
-		switch state {
263
-		case 0: //reading key
264
-			if i == len(str) {
265
-				return nil, fmt.Errorf("syntax error on %d", i)
266
-			}
267
-			if str[i] != '=' {
268
-				key += string(str[i])
269
-				continue
270
-			}
271
-			state = 1
272
-		case 1: //reading value
273
-			if i == len(str) {
274
-				m[key] = value
275
-				break
276
-			}
277
-			switch str[i] {
278
-			case ',':
279
-				m[key] = value
280
-				state = 0
281
-				key = ""
282
-				value = ""
283
-			case '"':
284
-				if value != "" {
285
-					return nil, fmt.Errorf("syntax error on %d", i)
286
-				}
287
-				state = 2
288
-			default:
289
-				value += string(str[i])
290
-			}
291
-		case 2: //inside quotes
292
-			if i == len(str) {
293
-				return nil, fmt.Errorf("syntax error on %d", i)
294
-			}
295
-			if str[i] != '"' {
296
-				value += string(str[i])
297
-			} else {
298
-				state = 1
299
-			}
300
-		}
301
-	}
302
-	return m, nil
303
-}
304
-
305
-func computeResponse(params map[string]string, uri, username, password string) string {
306
-	nc := "00000001"
307
-	qop := "auth"
308
-	cnonce := enchex.EncodeToString(randomBytes(16))
309
-	x := username + ":" + params["realm"] + ":" + password
310
-	y := md5Hash([]byte(x))
311
-
312
-	a1 := bytes.NewBuffer(y)
313
-	a1.WriteString(":" + params["nonce"] + ":" + cnonce)
314
-	if len(params["authzid"]) > 0 {
315
-		a1.WriteString(":" + params["authzid"])
316
-	}
317
-	a2 := bytes.NewBuffer([]byte("AUTHENTICATE"))
318
-	a2.WriteString(":" + uri)
319
-	ha1 := enchex.EncodeToString(md5Hash(a1.Bytes()))
320
-	ha2 := enchex.EncodeToString(md5Hash(a2.Bytes()))
321
-
322
-	kd := ha1
323
-	kd += ":" + params["nonce"]
324
-	kd += ":" + nc
325
-	kd += ":" + cnonce
326
-	kd += ":" + qop
327
-	kd += ":" + ha2
328
-	resp := enchex.EncodeToString(md5Hash([]byte(kd)))
329
-	return fmt.Sprintf(
330
-		`username="%s",realm="%s",nonce="%s",cnonce="%s",nc=00000001,qop=%s,digest-uri="%s",response=%s`,
331
-		username,
332
-		params["realm"],
333
-		params["nonce"],
334
-		cnonce,
335
-		qop,
336
-		uri,
337
-		resp,
338
-	)
339
-}
340
-
341
-func md5Hash(b []byte) []byte {
342
-	hasher := md5.New()
343
-	hasher.Write(b)
344
-	return hasher.Sum(nil)
345
-}
346
-
347
-func randomBytes(len int) []byte {
348
-	b := make([]byte, len)
349
-	for i := 0; i < len; i++ {
350
-		b[i] = byte(rand.Intn(256))
351
-	}
352
-	return b
353
-}
354
-
355
-var externalBindRequest = requestFunc(func(envelope *ber.Packet) error {
356
-	pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindRequest, nil, "Bind Request")
357
-	pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, 3, "Version"))
358
-	pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "", "User Name"))
359
-
360
-	saslAuth := ber.Encode(ber.ClassContext, ber.TypeConstructed, 3, "", "authentication")
361
-	saslAuth.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "EXTERNAL", "SASL Mech"))
362
-	saslAuth.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, "", "SASL Cred"))
363
-
364
-	pkt.AppendChild(saslAuth)
365
-
366
-	envelope.AppendChild(pkt)
367
-
368
-	return nil
369
-})
370
-
371
-// ExternalBind performs SASL/EXTERNAL authentication.
372
-//
373
-// Use ldap.DialURL("ldapi://") to connect to the Unix socket before ExternalBind.
374
-//
375
-// See https://tools.ietf.org/html/rfc4422#appendix-A
376
-func (l *Conn) ExternalBind() error {
377
-	msgCtx, err := l.doRequest(externalBindRequest)
378
-	if err != nil {
379
-		return err
380
-	}
381
-	defer l.finishMessage(msgCtx)
382
-
383
-	packet, err := l.readPacket(msgCtx)
384
-	if err != nil {
385
-		return err
386
-	}
387
-
388
-	return GetLDAPError(packet)
389
-}

+ 0
- 30
vendor/github.com/go-ldap/ldap/v3/client.go View File

@@ -1,30 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"crypto/tls"
5
-	"time"
6
-)
7
-
8
-// Client knows how to interact with an LDAP server
9
-type Client interface {
10
-	Start()
11
-	StartTLS(*tls.Config) error
12
-	Close()
13
-	SetTimeout(time.Duration)
14
-
15
-	Bind(username, password string) error
16
-	UnauthenticatedBind(username string) error
17
-	SimpleBind(*SimpleBindRequest) (*SimpleBindResult, error)
18
-	ExternalBind() error
19
-
20
-	Add(*AddRequest) error
21
-	Del(*DelRequest) error
22
-	Modify(*ModifyRequest) error
23
-	ModifyDN(*ModifyDNRequest) error
24
-
25
-	Compare(dn, attribute, value string) (bool, error)
26
-	PasswordModify(*PasswordModifyRequest) (*PasswordModifyResult, error)
27
-
28
-	Search(*SearchRequest) (*SearchResult, error)
29
-	SearchWithPaging(searchRequest *SearchRequest, pagingSize uint32) (*SearchResult, error)
30
-}

+ 0
- 61
vendor/github.com/go-ldap/ldap/v3/compare.go View File

@@ -1,61 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"fmt"
5
-
6
-	ber "github.com/go-asn1-ber/asn1-ber"
7
-)
8
-
9
-// CompareRequest represents an LDAP CompareRequest operation.
10
-type CompareRequest struct {
11
-	DN        string
12
-	Attribute string
13
-	Value     string
14
-}
15
-
16
-func (req *CompareRequest) appendTo(envelope *ber.Packet) error {
17
-	pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationCompareRequest, nil, "Compare Request")
18
-	pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.DN, "DN"))
19
-
20
-	ava := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "AttributeValueAssertion")
21
-	ava.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.Attribute, "AttributeDesc"))
22
-	ava.AppendChild(ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.Value, "AssertionValue"))
23
-
24
-	pkt.AppendChild(ava)
25
-
26
-	envelope.AppendChild(pkt)
27
-
28
-	return nil
29
-}
30
-
31
-// Compare checks to see if the attribute of the dn matches value. Returns true if it does otherwise
32
-// false with any error that occurs if any.
33
-func (l *Conn) Compare(dn, attribute, value string) (bool, error) {
34
-	msgCtx, err := l.doRequest(&CompareRequest{
35
-		DN:        dn,
36
-		Attribute: attribute,
37
-		Value:     value})
38
-	if err != nil {
39
-		return false, err
40
-	}
41
-	defer l.finishMessage(msgCtx)
42
-
43
-	packet, err := l.readPacket(msgCtx)
44
-	if err != nil {
45
-		return false, err
46
-	}
47
-
48
-	if packet.Children[1].Tag == ApplicationCompareResponse {
49
-		err := GetLDAPError(packet)
50
-
51
-		switch {
52
-		case IsErrorWithCode(err, LDAPResultCompareTrue):
53
-			return true, nil
54
-		case IsErrorWithCode(err, LDAPResultCompareFalse):
55
-			return false, nil
56
-		default:
57
-			return false, err
58
-		}
59
-	}
60
-	return false, fmt.Errorf("unexpected Response: %d", packet.Children[1].Tag)
61
-}

+ 0
- 570
vendor/github.com/go-ldap/ldap/v3/conn.go View File

@@ -1,570 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"crypto/tls"
5
-	"errors"
6
-	"fmt"
7
-	"log"
8
-	"net"
9
-	"net/url"
10
-	"sync"
11
-	"sync/atomic"
12
-	"time"
13
-
14
-	ber "github.com/go-asn1-ber/asn1-ber"
15
-)
16
-
17
-const (
18
-	// MessageQuit causes the processMessages loop to exit
19
-	MessageQuit = 0
20
-	// MessageRequest sends a request to the server
21
-	MessageRequest = 1
22
-	// MessageResponse receives a response from the server
23
-	MessageResponse = 2
24
-	// MessageFinish indicates the client considers a particular message ID to be finished
25
-	MessageFinish = 3
26
-	// MessageTimeout indicates the client-specified timeout for a particular message ID has been reached
27
-	MessageTimeout = 4
28
-)
29
-
30
-const (
31
-	// DefaultLdapPort default ldap port for pure TCP connection
32
-	DefaultLdapPort = "389"
33
-	// DefaultLdapsPort default ldap port for SSL connection
34
-	DefaultLdapsPort = "636"
35
-)
36
-
37
-// PacketResponse contains the packet or error encountered reading a response
38
-type PacketResponse struct {
39
-	// Packet is the packet read from the server
40
-	Packet *ber.Packet
41
-	// Error is an error encountered while reading
42
-	Error error
43
-}
44
-
45
-// ReadPacket returns the packet or an error
46
-func (pr *PacketResponse) ReadPacket() (*ber.Packet, error) {
47
-	if (pr == nil) || (pr.Packet == nil && pr.Error == nil) {
48
-		return nil, NewError(ErrorNetwork, errors.New("ldap: could not retrieve response"))
49
-	}
50
-	return pr.Packet, pr.Error
51
-}
52
-
53
-type messageContext struct {
54
-	id int64
55
-	// close(done) should only be called from finishMessage()
56
-	done chan struct{}
57
-	// close(responses) should only be called from processMessages(), and only sent to from sendResponse()
58
-	responses chan *PacketResponse
59
-}
60
-
61
-// sendResponse should only be called within the processMessages() loop which
62
-// is also responsible for closing the responses channel.
63
-func (msgCtx *messageContext) sendResponse(packet *PacketResponse) {
64
-	select {
65
-	case msgCtx.responses <- packet:
66
-		// Successfully sent packet to message handler.
67
-	case <-msgCtx.done:
68
-		// The request handler is done and will not receive more
69
-		// packets.
70
-	}
71
-}
72
-
73
-type messagePacket struct {
74
-	Op        int
75
-	MessageID int64
76
-	Packet    *ber.Packet
77
-	Context   *messageContext
78
-}
79
-
80
-type sendMessageFlags uint
81
-
82
-const (
83
-	startTLS sendMessageFlags = 1 << iota
84
-)
85
-
86
-// Conn represents an LDAP Connection
87
-type Conn struct {
88
-	// requestTimeout is loaded atomically
89
-	// so we need to ensure 64-bit alignment on 32-bit platforms.
90
-	requestTimeout      int64
91
-	conn                net.Conn
92
-	isTLS               bool
93
-	closing             uint32
94
-	closeErr            atomic.Value
95
-	isStartingTLS       bool
96
-	Debug               debugging
97
-	chanConfirm         chan struct{}
98
-	messageContexts     map[int64]*messageContext
99
-	chanMessage         chan *messagePacket
100
-	chanMessageID       chan int64
101
-	wgClose             sync.WaitGroup
102
-	outstandingRequests uint
103
-	messageMutex        sync.Mutex
104
-}
105
-
106
-var _ Client = &Conn{}
107
-
108
-// DefaultTimeout is a package-level variable that sets the timeout value
109
-// used for the Dial and DialTLS methods.
110
-//
111
-// WARNING: since this is a package-level variable, setting this value from
112
-// multiple places will probably result in undesired behaviour.
113
-var DefaultTimeout = 60 * time.Second
114
-
115
-// DialOpt configures DialContext.
116
-type DialOpt func(*DialContext)
117
-
118
-// DialWithDialer updates net.Dialer in DialContext.
119
-func DialWithDialer(d *net.Dialer) DialOpt {
120
-	return func(dc *DialContext) {
121
-		dc.d = d
122
-	}
123
-}
124
-
125
-// DialWithTLSConfig updates tls.Config in DialContext.
126
-func DialWithTLSConfig(tc *tls.Config) DialOpt {
127
-	return func(dc *DialContext) {
128
-		dc.tc = tc
129
-	}
130
-}
131
-
132
-// DialContext contains necessary parameters to dial the given ldap URL.
133
-type DialContext struct {
134
-	d  *net.Dialer
135
-	tc *tls.Config
136
-}
137
-
138
-func (dc *DialContext) dial(u *url.URL) (net.Conn, error) {
139
-	if u.Scheme == "ldapi" {
140
-		if u.Path == "" || u.Path == "/" {
141
-			u.Path = "/var/run/slapd/ldapi"
142
-		}
143
-		return dc.d.Dial("unix", u.Path)
144
-	}
145
-
146
-	host, port, err := net.SplitHostPort(u.Host)
147
-	if err != nil {
148
-		// we asume that error is due to missing port
149
-		host = u.Host
150
-		port = ""
151
-	}
152
-
153
-	switch u.Scheme {
154
-	case "ldap":
155
-		if port == "" {
156
-			port = DefaultLdapPort
157
-		}
158
-		return dc.d.Dial("tcp", net.JoinHostPort(host, port))
159
-	case "ldaps":
160
-		if port == "" {
161
-			port = DefaultLdapsPort
162
-		}
163
-		return tls.DialWithDialer(dc.d, "tcp", net.JoinHostPort(host, port), dc.tc)
164
-	}
165
-
166
-	return nil, fmt.Errorf("Unknown scheme '%s'", u.Scheme)
167
-}
168
-
169
-// Dial connects to the given address on the given network using net.Dial
170
-// and then returns a new Conn for the connection.
171
-// @deprecated Use DialURL instead.
172
-func Dial(network, addr string) (*Conn, error) {
173
-	c, err := net.DialTimeout(network, addr, DefaultTimeout)
174
-	if err != nil {
175
-		return nil, NewError(ErrorNetwork, err)
176
-	}
177
-	conn := NewConn(c, false)
178
-	conn.Start()
179
-	return conn, nil
180
-}
181
-
182
-// DialTLS connects to the given address on the given network using tls.Dial
183
-// and then returns a new Conn for the connection.
184
-// @deprecated Use DialURL instead.
185
-func DialTLS(network, addr string, config *tls.Config) (*Conn, error) {
186
-	c, err := tls.DialWithDialer(&net.Dialer{Timeout: DefaultTimeout}, network, addr, config)
187
-	if err != nil {
188
-		return nil, NewError(ErrorNetwork, err)
189
-	}
190
-	conn := NewConn(c, true)
191
-	conn.Start()
192
-	return conn, nil
193
-}
194
-
195
-// DialURL connects to the given ldap URL.
196
-// The following schemas are supported: ldap://, ldaps://, ldapi://.
197
-// On success a new Conn for the connection is returned.
198
-func DialURL(addr string, opts ...DialOpt) (*Conn, error) {
199
-	u, err := url.Parse(addr)
200
-	if err != nil {
201
-		return nil, NewError(ErrorNetwork, err)
202
-	}
203
-
204
-	var dc DialContext
205
-	for _, opt := range opts {
206
-		opt(&dc)
207
-	}
208
-	if dc.d == nil {
209
-		dc.d = &net.Dialer{Timeout: DefaultTimeout}
210
-	}
211
-
212
-	c, err := dc.dial(u)
213
-	if err != nil {
214
-		return nil, NewError(ErrorNetwork, err)
215
-	}
216
-
217
-	conn := NewConn(c, u.Scheme == "ldaps")
218
-	conn.Start()
219
-	return conn, nil
220
-}
221
-
222
-// NewConn returns a new Conn using conn for network I/O.
223
-func NewConn(conn net.Conn, isTLS bool) *Conn {
224
-	return &Conn{
225
-		conn:            conn,
226
-		chanConfirm:     make(chan struct{}),
227
-		chanMessageID:   make(chan int64),
228
-		chanMessage:     make(chan *messagePacket, 10),
229
-		messageContexts: map[int64]*messageContext{},
230
-		requestTimeout:  0,
231
-		isTLS:           isTLS,
232
-	}
233
-}
234
-
235
-// Start initializes goroutines to read responses and process messages
236
-func (l *Conn) Start() {
237
-	l.wgClose.Add(1)
238
-	go l.reader()
239
-	go l.processMessages()
240
-}
241
-
242
-// IsClosing returns whether or not we're currently closing.
243
-func (l *Conn) IsClosing() bool {
244
-	return atomic.LoadUint32(&l.closing) == 1
245
-}
246
-
247
-// setClosing sets the closing value to true
248
-func (l *Conn) setClosing() bool {
249
-	return atomic.CompareAndSwapUint32(&l.closing, 0, 1)
250
-}
251
-
252
-// Close closes the connection.
253
-func (l *Conn) Close() {
254
-	l.messageMutex.Lock()
255
-	defer l.messageMutex.Unlock()
256
-
257
-	if l.setClosing() {
258
-		l.Debug.Printf("Sending quit message and waiting for confirmation")
259
-		l.chanMessage <- &messagePacket{Op: MessageQuit}
260
-		<-l.chanConfirm
261
-		close(l.chanMessage)
262
-
263
-		l.Debug.Printf("Closing network connection")
264
-		if err := l.conn.Close(); err != nil {
265
-			log.Println(err)
266
-		}
267
-
268
-		l.wgClose.Done()
269
-	}
270
-	l.wgClose.Wait()
271
-}
272
-
273
-// SetTimeout sets the time after a request is sent that a MessageTimeout triggers
274
-func (l *Conn) SetTimeout(timeout time.Duration) {
275
-	if timeout > 0 {
276
-		atomic.StoreInt64(&l.requestTimeout, int64(timeout))
277
-	}
278
-}
279
-
280
-// Returns the next available messageID
281
-func (l *Conn) nextMessageID() int64 {
282
-	if messageID, ok := <-l.chanMessageID; ok {
283
-		return messageID
284
-	}
285
-	return 0
286
-}
287
-
288
-// StartTLS sends the command to start a TLS session and then creates a new TLS Client
289
-func (l *Conn) StartTLS(config *tls.Config) error {
290
-	if l.isTLS {
291
-		return NewError(ErrorNetwork, errors.New("ldap: already encrypted"))
292
-	}
293
-
294
-	packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request")
295
-	packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID"))
296
-	request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationExtendedRequest, nil, "Start TLS")
297
-	request.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, "1.3.6.1.4.1.1466.20037", "TLS Extended Command"))
298
-	packet.AppendChild(request)
299
-	l.Debug.PrintPacket(packet)
300
-
301
-	msgCtx, err := l.sendMessageWithFlags(packet, startTLS)
302
-	if err != nil {
303
-		return err
304
-	}
305
-	defer l.finishMessage(msgCtx)
306
-
307
-	l.Debug.Printf("%d: waiting for response", msgCtx.id)
308
-
309
-	packetResponse, ok := <-msgCtx.responses
310
-	if !ok {
311
-		return NewError(ErrorNetwork, errors.New("ldap: response channel closed"))
312
-	}
313
-	packet, err = packetResponse.ReadPacket()
314
-	l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
315
-	if err != nil {
316
-		return err
317
-	}
318
-
319
-	if l.Debug {
320
-		if err := addLDAPDescriptions(packet); err != nil {
321
-			l.Close()
322
-			return err
323
-		}
324
-		l.Debug.PrintPacket(packet)
325
-	}
326
-
327
-	if err := GetLDAPError(packet); err == nil {
328
-		conn := tls.Client(l.conn, config)
329
-
330
-		if connErr := conn.Handshake(); connErr != nil {
331
-			l.Close()
332
-			return NewError(ErrorNetwork, fmt.Errorf("TLS handshake failed (%v)", connErr))
333
-		}
334
-
335
-		l.isTLS = true
336
-		l.conn = conn
337
-	} else {
338
-		return err
339
-	}
340
-	go l.reader()
341
-
342
-	return nil
343
-}
344
-
345
-// TLSConnectionState returns the client's TLS connection state.
346
-// The return values are their zero values if StartTLS did
347
-// not succeed.
348
-func (l *Conn) TLSConnectionState() (state tls.ConnectionState, ok bool) {
349
-	tc, ok := l.conn.(*tls.Conn)
350
-	if !ok {
351
-		return
352
-	}
353
-	return tc.ConnectionState(), true
354
-}
355
-
356
-func (l *Conn) sendMessage(packet *ber.Packet) (*messageContext, error) {
357
-	return l.sendMessageWithFlags(packet, 0)
358
-}
359
-
360
-func (l *Conn) sendMessageWithFlags(packet *ber.Packet, flags sendMessageFlags) (*messageContext, error) {
361
-	if l.IsClosing() {
362
-		return nil, NewError(ErrorNetwork, errors.New("ldap: connection closed"))
363
-	}
364
-	l.messageMutex.Lock()
365
-	l.Debug.Printf("flags&startTLS = %d", flags&startTLS)
366
-	if l.isStartingTLS {
367
-		l.messageMutex.Unlock()
368
-		return nil, NewError(ErrorNetwork, errors.New("ldap: connection is in startls phase"))
369
-	}
370
-	if flags&startTLS != 0 {
371
-		if l.outstandingRequests != 0 {
372
-			l.messageMutex.Unlock()
373
-			return nil, NewError(ErrorNetwork, errors.New("ldap: cannot StartTLS with outstanding requests"))
374
-		}
375
-		l.isStartingTLS = true
376
-	}
377
-	l.outstandingRequests++
378
-
379
-	l.messageMutex.Unlock()
380
-
381
-	responses := make(chan *PacketResponse)
382
-	messageID := packet.Children[0].Value.(int64)
383
-	message := &messagePacket{
384
-		Op:        MessageRequest,
385
-		MessageID: messageID,
386
-		Packet:    packet,
387
-		Context: &messageContext{
388
-			id:        messageID,
389
-			done:      make(chan struct{}),
390
-			responses: responses,
391
-		},
392
-	}
393
-	if !l.sendProcessMessage(message) {
394
-		if l.IsClosing() {
395
-			return nil, NewError(ErrorNetwork, errors.New("ldap: connection closed"))
396
-		}
397
-		return nil, NewError(ErrorNetwork, errors.New("ldap: could not send message for unknown reason"))
398
-	}
399
-	return message.Context, nil
400
-}
401
-
402
-func (l *Conn) finishMessage(msgCtx *messageContext) {
403
-	close(msgCtx.done)
404
-
405
-	if l.IsClosing() {
406
-		return
407
-	}
408
-
409
-	l.messageMutex.Lock()
410
-	l.outstandingRequests--
411
-	if l.isStartingTLS {
412
-		l.isStartingTLS = false
413
-	}
414
-	l.messageMutex.Unlock()
415
-
416
-	message := &messagePacket{
417
-		Op:        MessageFinish,
418
-		MessageID: msgCtx.id,
419
-	}
420
-	l.sendProcessMessage(message)
421
-}
422
-
423
-func (l *Conn) sendProcessMessage(message *messagePacket) bool {
424
-	l.messageMutex.Lock()
425
-	defer l.messageMutex.Unlock()
426
-	if l.IsClosing() {
427
-		return false
428
-	}
429
-	l.chanMessage <- message
430
-	return true
431
-}
432
-
433
-func (l *Conn) processMessages() {
434
-	defer func() {
435
-		if err := recover(); err != nil {
436
-			log.Printf("ldap: recovered panic in processMessages: %v", err)
437
-		}
438
-		for messageID, msgCtx := range l.messageContexts {
439
-			// If we are closing due to an error, inform anyone who
440
-			// is waiting about the error.
441
-			if l.IsClosing() && l.closeErr.Load() != nil {
442
-				msgCtx.sendResponse(&PacketResponse{Error: l.closeErr.Load().(error)})
443
-			}
444
-			l.Debug.Printf("Closing channel for MessageID %d", messageID)
445
-			close(msgCtx.responses)
446
-			delete(l.messageContexts, messageID)
447
-		}
448
-		close(l.chanMessageID)
449
-		close(l.chanConfirm)
450
-	}()
451
-
452
-	var messageID int64 = 1
453
-	for {
454
-		select {
455
-		case l.chanMessageID <- messageID:
456
-			messageID++
457
-		case message := <-l.chanMessage:
458
-			switch message.Op {
459
-			case MessageQuit:
460
-				l.Debug.Printf("Shutting down - quit message received")
461
-				return
462
-			case MessageRequest:
463
-				// Add to message list and write to network
464
-				l.Debug.Printf("Sending message %d", message.MessageID)
465
-
466
-				buf := message.Packet.Bytes()
467
-				_, err := l.conn.Write(buf)
468
-				if err != nil {
469
-					l.Debug.Printf("Error Sending Message: %s", err.Error())
470
-					message.Context.sendResponse(&PacketResponse{Error: fmt.Errorf("unable to send request: %s", err)})
471
-					close(message.Context.responses)
472
-					break
473
-				}
474
-
475
-				// Only add to messageContexts if we were able to
476
-				// successfully write the message.
477
-				l.messageContexts[message.MessageID] = message.Context
478
-
479
-				// Add timeout if defined
480
-				requestTimeout := time.Duration(atomic.LoadInt64(&l.requestTimeout))
481
-				if requestTimeout > 0 {
482
-					go func() {
483
-						defer func() {
484
-							if err := recover(); err != nil {
485
-								log.Printf("ldap: recovered panic in RequestTimeout: %v", err)
486
-							}
487
-						}()
488
-						time.Sleep(requestTimeout)
489
-						timeoutMessage := &messagePacket{
490
-							Op:        MessageTimeout,
491
-							MessageID: message.MessageID,
492
-						}
493
-						l.sendProcessMessage(timeoutMessage)
494
-					}()
495
-				}
496
-			case MessageResponse:
497
-				l.Debug.Printf("Receiving message %d", message.MessageID)
498
-				if msgCtx, ok := l.messageContexts[message.MessageID]; ok {
499
-					msgCtx.sendResponse(&PacketResponse{message.Packet, nil})
500
-				} else {
501
-					log.Printf("Received unexpected message %d, %v", message.MessageID, l.IsClosing())
502
-					l.Debug.PrintPacket(message.Packet)
503
-				}
504
-			case MessageTimeout:
505
-				// Handle the timeout by closing the channel
506
-				// All reads will return immediately
507
-				if msgCtx, ok := l.messageContexts[message.MessageID]; ok {
508
-					l.Debug.Printf("Receiving message timeout for %d", message.MessageID)
509
-					msgCtx.sendResponse(&PacketResponse{message.Packet, errors.New("ldap: connection timed out")})
510
-					delete(l.messageContexts, message.MessageID)
511
-					close(msgCtx.responses)
512
-				}
513
-			case MessageFinish:
514
-				l.Debug.Printf("Finished message %d", message.MessageID)
515
-				if msgCtx, ok := l.messageContexts[message.MessageID]; ok {
516
-					delete(l.messageContexts, message.MessageID)
517
-					close(msgCtx.responses)
518
-				}
519
-			}
520
-		}
521
-	}
522
-}
523
-
524
-func (l *Conn) reader() {
525
-	cleanstop := false
526
-	defer func() {
527
-		if err := recover(); err != nil {
528
-			log.Printf("ldap: recovered panic in reader: %v", err)
529
-		}
530
-		if !cleanstop {
531
-			l.Close()
532
-		}
533
-	}()
534
-
535
-	for {
536
-		if cleanstop {
537
-			l.Debug.Printf("reader clean stopping (without closing the connection)")
538
-			return
539
-		}
540
-		packet, err := ber.ReadPacket(l.conn)
541
-		if err != nil {
542
-			// A read error is expected here if we are closing the connection...
543
-			if !l.IsClosing() {
544
-				l.closeErr.Store(fmt.Errorf("unable to read LDAP response packet: %s", err))
545
-				l.Debug.Printf("reader error: %s", err)
546
-			}
547
-			return
548
-		}
549
-		if err := addLDAPDescriptions(packet); err != nil {
550
-			l.Debug.Printf("descriptions error: %s", err)
551
-		}
552
-		if len(packet.Children) == 0 {
553
-			l.Debug.Printf("Received bad ldap packet")
554
-			continue
555
-		}
556
-		l.messageMutex.Lock()
557
-		if l.isStartingTLS {
558
-			cleanstop = true
559
-		}
560
-		l.messageMutex.Unlock()
561
-		message := &messagePacket{
562
-			Op:        MessageResponse,
563
-			MessageID: packet.Children[0].Value.(int64),
564
-			Packet:    packet,
565
-		}
566
-		if !l.sendProcessMessage(message) {
567
-			return
568
-		}
569
-	}
570
-}

+ 0
- 499
vendor/github.com/go-ldap/ldap/v3/control.go View File

@@ -1,499 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"fmt"
5
-	"strconv"
6
-
7
-	"github.com/go-asn1-ber/asn1-ber"
8
-)
9
-
10
-const (
11
-	// ControlTypePaging - https://www.ietf.org/rfc/rfc2696.txt
12
-	ControlTypePaging = "1.2.840.113556.1.4.319"
13
-	// ControlTypeBeheraPasswordPolicy - https://tools.ietf.org/html/draft-behera-ldap-password-policy-10
14
-	ControlTypeBeheraPasswordPolicy = "1.3.6.1.4.1.42.2.27.8.5.1"
15
-	// ControlTypeVChuPasswordMustChange - https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00
16
-	ControlTypeVChuPasswordMustChange = "2.16.840.1.113730.3.4.4"
17
-	// ControlTypeVChuPasswordWarning - https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00
18
-	ControlTypeVChuPasswordWarning = "2.16.840.1.113730.3.4.5"
19
-	// ControlTypeManageDsaIT - https://tools.ietf.org/html/rfc3296
20
-	ControlTypeManageDsaIT = "2.16.840.1.113730.3.4.2"
21
-
22
-	// ControlTypeMicrosoftNotification - https://msdn.microsoft.com/en-us/library/aa366983(v=vs.85).aspx
23
-	ControlTypeMicrosoftNotification = "1.2.840.113556.1.4.528"
24
-	// ControlTypeMicrosoftShowDeleted - https://msdn.microsoft.com/en-us/library/aa366989(v=vs.85).aspx
25
-	ControlTypeMicrosoftShowDeleted = "1.2.840.113556.1.4.417"
26
-)
27
-
28
-// ControlTypeMap maps controls to text descriptions
29
-var ControlTypeMap = map[string]string{
30
-	ControlTypePaging:                "Paging",
31
-	ControlTypeBeheraPasswordPolicy:  "Password Policy - Behera Draft",
32
-	ControlTypeManageDsaIT:           "Manage DSA IT",
33
-	ControlTypeMicrosoftNotification: "Change Notification - Microsoft",
34
-	ControlTypeMicrosoftShowDeleted:  "Show Deleted Objects - Microsoft",
35
-}
36
-
37
-// Control defines an interface controls provide to encode and describe themselves
38
-type Control interface {
39
-	// GetControlType returns the OID
40
-	GetControlType() string
41
-	// Encode returns the ber packet representation
42
-	Encode() *ber.Packet
43
-	// String returns a human-readable description
44
-	String() string
45
-}
46
-
47
-// ControlString implements the Control interface for simple controls
48
-type ControlString struct {
49
-	ControlType  string
50
-	Criticality  bool
51
-	ControlValue string
52
-}
53
-
54
-// GetControlType returns the OID
55
-func (c *ControlString) GetControlType() string {
56
-	return c.ControlType
57
-}
58
-
59
-// Encode returns the ber packet representation
60
-func (c *ControlString) Encode() *ber.Packet {
61
-	packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control")
62
-	packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, c.ControlType, "Control Type ("+ControlTypeMap[c.ControlType]+")"))
63
-	if c.Criticality {
64
-		packet.AppendChild(ber.NewBoolean(ber.ClassUniversal, ber.TypePrimitive, ber.TagBoolean, c.Criticality, "Criticality"))
65
-	}
66
-	if c.ControlValue != "" {
67
-		packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, string(c.ControlValue), "Control Value"))
68
-	}
69
-	return packet
70
-}
71
-
72
-// String returns a human-readable description
73
-func (c *ControlString) String() string {
74
-	return fmt.Sprintf("Control Type: %s (%q)  Criticality: %t  Control Value: %s", ControlTypeMap[c.ControlType], c.ControlType, c.Criticality, c.ControlValue)
75
-}
76
-
77
-// ControlPaging implements the paging control described in https://www.ietf.org/rfc/rfc2696.txt
78
-type ControlPaging struct {
79
-	// PagingSize indicates the page size
80
-	PagingSize uint32
81
-	// Cookie is an opaque value returned by the server to track a paging cursor
82
-	Cookie []byte
83
-}
84
-
85
-// GetControlType returns the OID
86
-func (c *ControlPaging) GetControlType() string {
87
-	return ControlTypePaging
88
-}
89
-
90
-// Encode returns the ber packet representation
91
-func (c *ControlPaging) Encode() *ber.Packet {
92
-	packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control")
93
-	packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypePaging, "Control Type ("+ControlTypeMap[ControlTypePaging]+")"))
94
-
95
-	p2 := ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, nil, "Control Value (Paging)")
96
-	seq := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Search Control Value")
97
-	seq.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, int64(c.PagingSize), "Paging Size"))
98
-	cookie := ber.Encode(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, nil, "Cookie")
99
-	cookie.Value = c.Cookie
100
-	cookie.Data.Write(c.Cookie)
101
-	seq.AppendChild(cookie)
102
-	p2.AppendChild(seq)
103
-
104
-	packet.AppendChild(p2)
105
-	return packet
106
-}
107
-
108
-// String returns a human-readable description
109
-func (c *ControlPaging) String() string {
110
-	return fmt.Sprintf(
111
-		"Control Type: %s (%q)  Criticality: %t  PagingSize: %d  Cookie: %q",
112
-		ControlTypeMap[ControlTypePaging],
113
-		ControlTypePaging,
114
-		false,
115
-		c.PagingSize,
116
-		c.Cookie)
117
-}
118
-
119
-// SetCookie stores the given cookie in the paging control
120
-func (c *ControlPaging) SetCookie(cookie []byte) {
121
-	c.Cookie = cookie
122
-}
123
-
124
-// ControlBeheraPasswordPolicy implements the control described in https://tools.ietf.org/html/draft-behera-ldap-password-policy-10
125
-type ControlBeheraPasswordPolicy struct {
126
-	// Expire contains the number of seconds before a password will expire
127
-	Expire int64
128
-	// Grace indicates the remaining number of times a user will be allowed to authenticate with an expired password
129
-	Grace int64
130
-	// Error indicates the error code
131
-	Error int8
132
-	// ErrorString is a human readable error
133
-	ErrorString string
134
-}
135
-
136
-// GetControlType returns the OID
137
-func (c *ControlBeheraPasswordPolicy) GetControlType() string {
138
-	return ControlTypeBeheraPasswordPolicy
139
-}
140
-
141
-// Encode returns the ber packet representation
142
-func (c *ControlBeheraPasswordPolicy) Encode() *ber.Packet {
143
-	packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control")
144
-	packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypeBeheraPasswordPolicy, "Control Type ("+ControlTypeMap[ControlTypeBeheraPasswordPolicy]+")"))
145
-
146
-	return packet
147
-}
148
-
149
-// String returns a human-readable description
150
-func (c *ControlBeheraPasswordPolicy) String() string {
151
-	return fmt.Sprintf(
152
-		"Control Type: %s (%q)  Criticality: %t  Expire: %d  Grace: %d  Error: %d, ErrorString: %s",
153
-		ControlTypeMap[ControlTypeBeheraPasswordPolicy],
154
-		ControlTypeBeheraPasswordPolicy,
155
-		false,
156
-		c.Expire,
157
-		c.Grace,
158
-		c.Error,
159
-		c.ErrorString)
160
-}
161
-
162
-// ControlVChuPasswordMustChange implements the control described in https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00
163
-type ControlVChuPasswordMustChange struct {
164
-	// MustChange indicates if the password is required to be changed
165
-	MustChange bool
166
-}
167
-
168
-// GetControlType returns the OID
169
-func (c *ControlVChuPasswordMustChange) GetControlType() string {
170
-	return ControlTypeVChuPasswordMustChange
171
-}
172
-
173
-// Encode returns the ber packet representation
174
-func (c *ControlVChuPasswordMustChange) Encode() *ber.Packet {
175
-	return nil
176
-}
177
-
178
-// String returns a human-readable description
179
-func (c *ControlVChuPasswordMustChange) String() string {
180
-	return fmt.Sprintf(
181
-		"Control Type: %s (%q)  Criticality: %t  MustChange: %v",
182
-		ControlTypeMap[ControlTypeVChuPasswordMustChange],
183
-		ControlTypeVChuPasswordMustChange,
184
-		false,
185
-		c.MustChange)
186
-}
187
-
188
-// ControlVChuPasswordWarning implements the control described in https://tools.ietf.org/html/draft-vchu-ldap-pwd-policy-00
189
-type ControlVChuPasswordWarning struct {
190
-	// Expire indicates the time in seconds until the password expires
191
-	Expire int64
192
-}
193
-
194
-// GetControlType returns the OID
195
-func (c *ControlVChuPasswordWarning) GetControlType() string {
196
-	return ControlTypeVChuPasswordWarning
197
-}
198
-
199
-// Encode returns the ber packet representation
200
-func (c *ControlVChuPasswordWarning) Encode() *ber.Packet {
201
-	return nil
202
-}
203
-
204
-// String returns a human-readable description
205
-func (c *ControlVChuPasswordWarning) String() string {
206
-	return fmt.Sprintf(
207
-		"Control Type: %s (%q)  Criticality: %t  Expire: %b",
208
-		ControlTypeMap[ControlTypeVChuPasswordWarning],
209
-		ControlTypeVChuPasswordWarning,
210
-		false,
211
-		c.Expire)
212
-}
213
-
214
-// ControlManageDsaIT implements the control described in https://tools.ietf.org/html/rfc3296
215
-type ControlManageDsaIT struct {
216
-	// Criticality indicates if this control is required
217
-	Criticality bool
218
-}
219
-
220
-// GetControlType returns the OID
221
-func (c *ControlManageDsaIT) GetControlType() string {
222
-	return ControlTypeManageDsaIT
223
-}
224
-
225
-// Encode returns the ber packet representation
226
-func (c *ControlManageDsaIT) Encode() *ber.Packet {
227
-	//FIXME
228
-	packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control")
229
-	packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypeManageDsaIT, "Control Type ("+ControlTypeMap[ControlTypeManageDsaIT]+")"))
230
-	if c.Criticality {
231
-		packet.AppendChild(ber.NewBoolean(ber.ClassUniversal, ber.TypePrimitive, ber.TagBoolean, c.Criticality, "Criticality"))
232
-	}
233
-	return packet
234
-}
235
-
236
-// String returns a human-readable description
237
-func (c *ControlManageDsaIT) String() string {
238
-	return fmt.Sprintf(
239
-		"Control Type: %s (%q)  Criticality: %t",
240
-		ControlTypeMap[ControlTypeManageDsaIT],
241
-		ControlTypeManageDsaIT,
242
-		c.Criticality)
243
-}
244
-
245
-// NewControlManageDsaIT returns a ControlManageDsaIT control
246
-func NewControlManageDsaIT(Criticality bool) *ControlManageDsaIT {
247
-	return &ControlManageDsaIT{Criticality: Criticality}
248
-}
249
-
250
-// ControlMicrosoftNotification implements the control described in https://msdn.microsoft.com/en-us/library/aa366983(v=vs.85).aspx
251
-type ControlMicrosoftNotification struct{}
252
-
253
-// GetControlType returns the OID
254
-func (c *ControlMicrosoftNotification) GetControlType() string {
255
-	return ControlTypeMicrosoftNotification
256
-}
257
-
258
-// Encode returns the ber packet representation
259
-func (c *ControlMicrosoftNotification) Encode() *ber.Packet {
260
-	packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control")
261
-	packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypeMicrosoftNotification, "Control Type ("+ControlTypeMap[ControlTypeMicrosoftNotification]+")"))
262
-
263
-	return packet
264
-}
265
-
266
-// String returns a human-readable description
267
-func (c *ControlMicrosoftNotification) String() string {
268
-	return fmt.Sprintf(
269
-		"Control Type: %s (%q)",
270
-		ControlTypeMap[ControlTypeMicrosoftNotification],
271
-		ControlTypeMicrosoftNotification)
272
-}
273
-
274
-// NewControlMicrosoftNotification returns a ControlMicrosoftNotification control
275
-func NewControlMicrosoftNotification() *ControlMicrosoftNotification {
276
-	return &ControlMicrosoftNotification{}
277
-}
278
-
279
-// ControlMicrosoftShowDeleted implements the control described in https://msdn.microsoft.com/en-us/library/aa366989(v=vs.85).aspx
280
-type ControlMicrosoftShowDeleted struct{}
281
-
282
-// GetControlType returns the OID
283
-func (c *ControlMicrosoftShowDeleted) GetControlType() string {
284
-	return ControlTypeMicrosoftShowDeleted
285
-}
286
-
287
-// Encode returns the ber packet representation
288
-func (c *ControlMicrosoftShowDeleted) Encode() *ber.Packet {
289
-	packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Control")
290
-	packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, ControlTypeMicrosoftShowDeleted, "Control Type ("+ControlTypeMap[ControlTypeMicrosoftShowDeleted]+")"))
291
-
292
-	return packet
293
-}
294
-
295
-// String returns a human-readable description
296
-func (c *ControlMicrosoftShowDeleted) String() string {
297
-	return fmt.Sprintf(
298
-		"Control Type: %s (%q)",
299
-		ControlTypeMap[ControlTypeMicrosoftShowDeleted],
300
-		ControlTypeMicrosoftShowDeleted)
301
-}
302
-
303
-// NewControlMicrosoftShowDeleted returns a ControlMicrosoftShowDeleted control
304
-func NewControlMicrosoftShowDeleted() *ControlMicrosoftShowDeleted {
305
-	return &ControlMicrosoftShowDeleted{}
306
-}
307
-
308
-// FindControl returns the first control of the given type in the list, or nil
309
-func FindControl(controls []Control, controlType string) Control {
310
-	for _, c := range controls {
311
-		if c.GetControlType() == controlType {
312
-			return c
313
-		}
314
-	}
315
-	return nil
316
-}
317
-
318
-// DecodeControl returns a control read from the given packet, or nil if no recognized control can be made
319
-func DecodeControl(packet *ber.Packet) (Control, error) {
320
-	var (
321
-		ControlType = ""
322
-		Criticality = false
323
-		value       *ber.Packet
324
-	)
325
-
326
-	switch len(packet.Children) {
327
-	case 0:
328
-		// at least one child is required for control type
329
-		return nil, fmt.Errorf("at least one child is required for control type")
330
-
331
-	case 1:
332
-		// just type, no criticality or value
333
-		packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
334
-		ControlType = packet.Children[0].Value.(string)
335
-
336
-	case 2:
337
-		packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
338
-		ControlType = packet.Children[0].Value.(string)
339
-
340
-		// Children[1] could be criticality or value (both are optional)
341
-		// duck-type on whether this is a boolean
342
-		if _, ok := packet.Children[1].Value.(bool); ok {
343
-			packet.Children[1].Description = "Criticality"
344
-			Criticality = packet.Children[1].Value.(bool)
345
-		} else {
346
-			packet.Children[1].Description = "Control Value"
347
-			value = packet.Children[1]
348
-		}
349
-
350
-	case 3:
351
-		packet.Children[0].Description = "Control Type (" + ControlTypeMap[ControlType] + ")"
352
-		ControlType = packet.Children[0].Value.(string)
353
-
354
-		packet.Children[1].Description = "Criticality"
355
-		Criticality = packet.Children[1].Value.(bool)
356
-
357
-		packet.Children[2].Description = "Control Value"
358
-		value = packet.Children[2]
359
-
360
-	default:
361
-		// more than 3 children is invalid
362
-		return nil, fmt.Errorf("more than 3 children is invalid for controls")
363
-	}
364
-
365
-	switch ControlType {
366
-	case ControlTypeManageDsaIT:
367
-		return NewControlManageDsaIT(Criticality), nil
368
-	case ControlTypePaging:
369
-		value.Description += " (Paging)"
370
-		c := new(ControlPaging)
371
-		if value.Value != nil {
372
-			valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
373
-			if err != nil {
374
-				return nil, fmt.Errorf("failed to decode data bytes: %s", err)
375
-			}
376
-			value.Data.Truncate(0)
377
-			value.Value = nil
378
-			value.AppendChild(valueChildren)
379
-		}
380
-		value = value.Children[0]
381
-		value.Description = "Search Control Value"
382
-		value.Children[0].Description = "Paging Size"
383
-		value.Children[1].Description = "Cookie"
384
-		c.PagingSize = uint32(value.Children[0].Value.(int64))
385
-		c.Cookie = value.Children[1].Data.Bytes()
386
-		value.Children[1].Value = c.Cookie
387
-		return c, nil
388
-	case ControlTypeBeheraPasswordPolicy:
389
-		value.Description += " (Password Policy - Behera)"
390
-		c := NewControlBeheraPasswordPolicy()
391
-		if value.Value != nil {
392
-			valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
393
-			if err != nil {
394
-				return nil, fmt.Errorf("failed to decode data bytes: %s", err)
395
-			}
396
-			value.Data.Truncate(0)
397
-			value.Value = nil
398
-			value.AppendChild(valueChildren)
399
-		}
400
-
401
-		sequence := value.Children[0]
402
-
403
-		for _, child := range sequence.Children {
404
-			if child.Tag == 0 {
405
-				//Warning
406
-				warningPacket := child.Children[0]
407
-				packet, err := ber.DecodePacketErr(warningPacket.Data.Bytes())
408
-				if err != nil {
409
-					return nil, fmt.Errorf("failed to decode data bytes: %s", err)
410
-				}
411
-				val, ok := packet.Value.(int64)
412
-				if ok {
413
-					if warningPacket.Tag == 0 {
414
-						//timeBeforeExpiration
415
-						c.Expire = val
416
-						warningPacket.Value = c.Expire
417
-					} else if warningPacket.Tag == 1 {
418
-						//graceAuthNsRemaining
419
-						c.Grace = val
420
-						warningPacket.Value = c.Grace
421
-					}
422
-				}
423
-			} else if child.Tag == 1 {
424
-				// Error
425
-				packet, err := ber.DecodePacketErr(child.Data.Bytes())
426
-				if err != nil {
427
-					return nil, fmt.Errorf("failed to decode data bytes: %s", err)
428
-				}
429
-				val, ok := packet.Value.(int8)
430
-				if !ok {
431
-					// what to do?
432
-					val = -1
433
-				}
434
-				c.Error = val
435
-				child.Value = c.Error
436
-				c.ErrorString = BeheraPasswordPolicyErrorMap[c.Error]
437
-			}
438
-		}
439
-		return c, nil
440
-	case ControlTypeVChuPasswordMustChange:
441
-		c := &ControlVChuPasswordMustChange{MustChange: true}
442
-		return c, nil
443
-	case ControlTypeVChuPasswordWarning:
444
-		c := &ControlVChuPasswordWarning{Expire: -1}
445
-		expireStr := ber.DecodeString(value.Data.Bytes())
446
-
447
-		expire, err := strconv.ParseInt(expireStr, 10, 64)
448
-		if err != nil {
449
-			return nil, fmt.Errorf("failed to parse value as int: %s", err)
450
-		}
451
-		c.Expire = expire
452
-		value.Value = c.Expire
453
-
454
-		return c, nil
455
-	case ControlTypeMicrosoftNotification:
456
-		return NewControlMicrosoftNotification(), nil
457
-	case ControlTypeMicrosoftShowDeleted:
458
-		return NewControlMicrosoftShowDeleted(), nil
459
-	default:
460
-		c := new(ControlString)
461
-		c.ControlType = ControlType
462
-		c.Criticality = Criticality
463
-		if value != nil {
464
-			c.ControlValue = value.Value.(string)
465
-		}
466
-		return c, nil
467
-	}
468
-}
469
-
470
-// NewControlString returns a generic control
471
-func NewControlString(controlType string, criticality bool, controlValue string) *ControlString {
472
-	return &ControlString{
473
-		ControlType:  controlType,
474
-		Criticality:  criticality,
475
-		ControlValue: controlValue,
476
-	}
477
-}
478
-
479
-// NewControlPaging returns a paging control
480
-func NewControlPaging(pagingSize uint32) *ControlPaging {
481
-	return &ControlPaging{PagingSize: pagingSize}
482
-}
483
-
484
-// NewControlBeheraPasswordPolicy returns a ControlBeheraPasswordPolicy
485
-func NewControlBeheraPasswordPolicy() *ControlBeheraPasswordPolicy {
486
-	return &ControlBeheraPasswordPolicy{
487
-		Expire: -1,
488
-		Grace:  -1,
489
-		Error:  -1,
490
-	}
491
-}
492
-
493
-func encodeControls(controls []Control) *ber.Packet {
494
-	packet := ber.Encode(ber.ClassContext, ber.TypeConstructed, 0, nil, "Controls")
495
-	for _, control := range controls {
496
-		packet.AppendChild(control.Encode())
497
-	}
498
-	return packet
499
-}

+ 0
- 30
vendor/github.com/go-ldap/ldap/v3/debug.go View File

@@ -1,30 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"log"
5
-
6
-	ber "github.com/go-asn1-ber/asn1-ber"
7
-)
8
-
9
-// debugging type
10
-//     - has a Printf method to write the debug output
11
-type debugging bool
12
-
13
-// Enable controls debugging mode.
14
-func (debug *debugging) Enable(b bool) {
15
-	*debug = debugging(b)
16
-}
17
-
18
-// Printf writes debug output.
19
-func (debug debugging) Printf(format string, args ...interface{}) {
20
-	if debug {
21
-		log.Printf(format, args...)
22
-	}
23
-}
24
-
25
-// PrintPacket dumps a packet.
26
-func (debug debugging) PrintPacket(packet *ber.Packet) {
27
-	if debug {
28
-		ber.PrintPacket(packet)
29
-	}
30
-}

+ 0
- 59
vendor/github.com/go-ldap/ldap/v3/del.go View File

@@ -1,59 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"log"
5
-
6
-	ber "github.com/go-asn1-ber/asn1-ber"
7
-)
8
-
9
-// DelRequest implements an LDAP deletion request
10
-type DelRequest struct {
11
-	// DN is the name of the directory entry to delete
12
-	DN string
13
-	// Controls hold optional controls to send with the request
14
-	Controls []Control
15
-}
16
-
17
-func (req *DelRequest) appendTo(envelope *ber.Packet) error {
18
-	pkt := ber.Encode(ber.ClassApplication, ber.TypePrimitive, ApplicationDelRequest, req.DN, "Del Request")
19
-	pkt.Data.Write([]byte(req.DN))
20
-
21
-	envelope.AppendChild(pkt)
22
-	if len(req.Controls) > 0 {
23
-		envelope.AppendChild(encodeControls(req.Controls))
24
-	}
25
-
26
-	return nil
27
-}
28
-
29
-// NewDelRequest creates a delete request for the given DN and controls
30
-func NewDelRequest(DN string, Controls []Control) *DelRequest {
31
-	return &DelRequest{
32
-		DN:       DN,
33
-		Controls: Controls,
34
-	}
35
-}
36
-
37
-// Del executes the given delete request
38
-func (l *Conn) Del(delRequest *DelRequest) error {
39
-	msgCtx, err := l.doRequest(delRequest)
40
-	if err != nil {
41
-		return err
42
-	}
43
-	defer l.finishMessage(msgCtx)
44
-
45
-	packet, err := l.readPacket(msgCtx)
46
-	if err != nil {
47
-		return err
48
-	}
49
-
50
-	if packet.Children[1].Tag == ApplicationDelResponse {
51
-		err := GetLDAPError(packet)
52
-		if err != nil {
53
-			return err
54
-		}
55
-	} else {
56
-		log.Printf("Unexpected Response: %d", packet.Children[1].Tag)
57
-	}
58
-	return nil
59
-}

+ 0
- 207
vendor/github.com/go-ldap/ldap/v3/dn.go View File

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

+ 0
- 4
vendor/github.com/go-ldap/ldap/v3/doc.go View File

@@ -1,4 +0,0 @@
1
-/*
2
-Package ldap provides basic LDAP v3 functionality.
3
-*/
4
-package ldap

+ 0
- 236
vendor/github.com/go-ldap/ldap/v3/error.go View File

@@ -1,236 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"fmt"
5
-
6
-	ber "github.com/go-asn1-ber/asn1-ber"
7
-)
8
-
9
-// LDAP Result Codes
10
-const (
11
-	LDAPResultSuccess                            = 0
12
-	LDAPResultOperationsError                    = 1
13
-	LDAPResultProtocolError                      = 2
14
-	LDAPResultTimeLimitExceeded                  = 3
15
-	LDAPResultSizeLimitExceeded                  = 4
16
-	LDAPResultCompareFalse                       = 5
17
-	LDAPResultCompareTrue                        = 6
18
-	LDAPResultAuthMethodNotSupported             = 7
19
-	LDAPResultStrongAuthRequired                 = 8
20
-	LDAPResultReferral                           = 10
21
-	LDAPResultAdminLimitExceeded                 = 11
22
-	LDAPResultUnavailableCriticalExtension       = 12
23
-	LDAPResultConfidentialityRequired            = 13
24
-	LDAPResultSaslBindInProgress                 = 14
25
-	LDAPResultNoSuchAttribute                    = 16
26
-	LDAPResultUndefinedAttributeType             = 17
27
-	LDAPResultInappropriateMatching              = 18
28
-	LDAPResultConstraintViolation                = 19
29
-	LDAPResultAttributeOrValueExists             = 20
30
-	LDAPResultInvalidAttributeSyntax             = 21
31
-	LDAPResultNoSuchObject                       = 32
32
-	LDAPResultAliasProblem                       = 33
33
-	LDAPResultInvalidDNSyntax                    = 34
34
-	LDAPResultIsLeaf                             = 35
35
-	LDAPResultAliasDereferencingProblem          = 36
36
-	LDAPResultInappropriateAuthentication        = 48
37
-	LDAPResultInvalidCredentials                 = 49
38
-	LDAPResultInsufficientAccessRights           = 50
39
-	LDAPResultBusy                               = 51
40
-	LDAPResultUnavailable                        = 52
41
-	LDAPResultUnwillingToPerform                 = 53
42
-	LDAPResultLoopDetect                         = 54
43
-	LDAPResultSortControlMissing                 = 60
44
-	LDAPResultOffsetRangeError                   = 61
45
-	LDAPResultNamingViolation                    = 64
46
-	LDAPResultObjectClassViolation               = 65
47
-	LDAPResultNotAllowedOnNonLeaf                = 66
48
-	LDAPResultNotAllowedOnRDN                    = 67
49
-	LDAPResultEntryAlreadyExists                 = 68
50
-	LDAPResultObjectClassModsProhibited          = 69
51
-	LDAPResultResultsTooLarge                    = 70
52
-	LDAPResultAffectsMultipleDSAs                = 71
53
-	LDAPResultVirtualListViewErrorOrControlError = 76
54
-	LDAPResultOther                              = 80
55
-	LDAPResultServerDown                         = 81
56
-	LDAPResultLocalError                         = 82
57
-	LDAPResultEncodingError                      = 83
58
-	LDAPResultDecodingError                      = 84
59
-	LDAPResultTimeout                            = 85
60
-	LDAPResultAuthUnknown                        = 86
61
-	LDAPResultFilterError                        = 87
62
-	LDAPResultUserCanceled                       = 88
63
-	LDAPResultParamError                         = 89
64
-	LDAPResultNoMemory                           = 90
65
-	LDAPResultConnectError                       = 91
66
-	LDAPResultNotSupported                       = 92
67
-	LDAPResultControlNotFound                    = 93
68
-	LDAPResultNoResultsReturned                  = 94
69
-	LDAPResultMoreResultsToReturn                = 95
70
-	LDAPResultClientLoop                         = 96
71
-	LDAPResultReferralLimitExceeded              = 97
72
-	LDAPResultInvalidResponse                    = 100
73
-	LDAPResultAmbiguousResponse                  = 101
74
-	LDAPResultTLSNotSupported                    = 112
75
-	LDAPResultIntermediateResponse               = 113
76
-	LDAPResultUnknownType                        = 114
77
-	LDAPResultCanceled                           = 118
78
-	LDAPResultNoSuchOperation                    = 119
79
-	LDAPResultTooLate                            = 120
80
-	LDAPResultCannotCancel                       = 121
81
-	LDAPResultAssertionFailed                    = 122
82
-	LDAPResultAuthorizationDenied                = 123
83
-	LDAPResultSyncRefreshRequired                = 4096
84
-
85
-	ErrorNetwork            = 200
86
-	ErrorFilterCompile      = 201
87
-	ErrorFilterDecompile    = 202
88
-	ErrorDebugging          = 203
89
-	ErrorUnexpectedMessage  = 204
90
-	ErrorUnexpectedResponse = 205
91
-	ErrorEmptyPassword      = 206
92
-)
93
-
94
-// LDAPResultCodeMap contains string descriptions for LDAP error codes
95
-var LDAPResultCodeMap = map[uint16]string{
96
-	LDAPResultSuccess:                            "Success",
97
-	LDAPResultOperationsError:                    "Operations Error",
98
-	LDAPResultProtocolError:                      "Protocol Error",
99
-	LDAPResultTimeLimitExceeded:                  "Time Limit Exceeded",
100
-	LDAPResultSizeLimitExceeded:                  "Size Limit Exceeded",
101
-	LDAPResultCompareFalse:                       "Compare False",
102
-	LDAPResultCompareTrue:                        "Compare True",
103
-	LDAPResultAuthMethodNotSupported:             "Auth Method Not Supported",
104
-	LDAPResultStrongAuthRequired:                 "Strong Auth Required",
105
-	LDAPResultReferral:                           "Referral",
106
-	LDAPResultAdminLimitExceeded:                 "Admin Limit Exceeded",
107
-	LDAPResultUnavailableCriticalExtension:       "Unavailable Critical Extension",
108
-	LDAPResultConfidentialityRequired:            "Confidentiality Required",
109
-	LDAPResultSaslBindInProgress:                 "Sasl Bind In Progress",
110
-	LDAPResultNoSuchAttribute:                    "No Such Attribute",
111
-	LDAPResultUndefinedAttributeType:             "Undefined Attribute Type",
112
-	LDAPResultInappropriateMatching:              "Inappropriate Matching",
113
-	LDAPResultConstraintViolation:                "Constraint Violation",
114
-	LDAPResultAttributeOrValueExists:             "Attribute Or Value Exists",
115
-	LDAPResultInvalidAttributeSyntax:             "Invalid Attribute Syntax",
116
-	LDAPResultNoSuchObject:                       "No Such Object",
117
-	LDAPResultAliasProblem:                       "Alias Problem",
118
-	LDAPResultInvalidDNSyntax:                    "Invalid DN Syntax",
119
-	LDAPResultIsLeaf:                             "Is Leaf",
120
-	LDAPResultAliasDereferencingProblem:          "Alias Dereferencing Problem",
121
-	LDAPResultInappropriateAuthentication:        "Inappropriate Authentication",
122
-	LDAPResultInvalidCredentials:                 "Invalid Credentials",
123
-	LDAPResultInsufficientAccessRights:           "Insufficient Access Rights",
124
-	LDAPResultBusy:                               "Busy",
125
-	LDAPResultUnavailable:                        "Unavailable",
126
-	LDAPResultUnwillingToPerform:                 "Unwilling To Perform",
127
-	LDAPResultLoopDetect:                         "Loop Detect",
128
-	LDAPResultSortControlMissing:                 "Sort Control Missing",
129
-	LDAPResultOffsetRangeError:                   "Result Offset Range Error",
130
-	LDAPResultNamingViolation:                    "Naming Violation",
131
-	LDAPResultObjectClassViolation:               "Object Class Violation",
132
-	LDAPResultResultsTooLarge:                    "Results Too Large",
133
-	LDAPResultNotAllowedOnNonLeaf:                "Not Allowed On Non Leaf",
134
-	LDAPResultNotAllowedOnRDN:                    "Not Allowed On RDN",
135
-	LDAPResultEntryAlreadyExists:                 "Entry Already Exists",
136
-	LDAPResultObjectClassModsProhibited:          "Object Class Mods Prohibited",
137
-	LDAPResultAffectsMultipleDSAs:                "Affects Multiple DSAs",
138
-	LDAPResultVirtualListViewErrorOrControlError: "Failed because of a problem related to the virtual list view",
139
-	LDAPResultOther:                              "Other",
140
-	LDAPResultServerDown:                         "Cannot establish a connection",
141
-	LDAPResultLocalError:                         "An error occurred",
142
-	LDAPResultEncodingError:                      "LDAP encountered an error while encoding",
143
-	LDAPResultDecodingError:                      "LDAP encountered an error while decoding",
144
-	LDAPResultTimeout:                            "LDAP timeout while waiting for a response from the server",
145
-	LDAPResultAuthUnknown:                        "The auth method requested in a bind request is unknown",
146
-	LDAPResultFilterError:                        "An error occurred while encoding the given search filter",
147
-	LDAPResultUserCanceled:                       "The user canceled the operation",
148
-	LDAPResultParamError:                         "An invalid parameter was specified",
149
-	LDAPResultNoMemory:                           "Out of memory error",
150
-	LDAPResultConnectError:                       "A connection to the server could not be established",
151
-	LDAPResultNotSupported:                       "An attempt has been made to use a feature not supported LDAP",
152
-	LDAPResultControlNotFound:                    "The controls required to perform the requested operation were not found",
153
-	LDAPResultNoResultsReturned:                  "No results were returned from the server",
154
-	LDAPResultMoreResultsToReturn:                "There are more results in the chain of results",
155
-	LDAPResultClientLoop:                         "A loop has been detected. For example when following referrals",
156
-	LDAPResultReferralLimitExceeded:              "The referral hop limit has been exceeded",
157
-	LDAPResultCanceled:                           "Operation was canceled",
158
-	LDAPResultNoSuchOperation:                    "Server has no knowledge of the operation requested for cancellation",
159
-	LDAPResultTooLate:                            "Too late to cancel the outstanding operation",
160
-	LDAPResultCannotCancel:                       "The identified operation does not support cancellation or the cancel operation cannot be performed",
161
-	LDAPResultAssertionFailed:                    "An assertion control given in the LDAP operation evaluated to false causing the operation to not be performed",
162
-	LDAPResultSyncRefreshRequired:                "Refresh Required",
163
-	LDAPResultInvalidResponse:                    "Invalid Response",
164
-	LDAPResultAmbiguousResponse:                  "Ambiguous Response",
165
-	LDAPResultTLSNotSupported:                    "Tls Not Supported",
166
-	LDAPResultIntermediateResponse:               "Intermediate Response",
167
-	LDAPResultUnknownType:                        "Unknown Type",
168
-	LDAPResultAuthorizationDenied:                "Authorization Denied",
169
-
170
-	ErrorNetwork:            "Network Error",
171
-	ErrorFilterCompile:      "Filter Compile Error",
172
-	ErrorFilterDecompile:    "Filter Decompile Error",
173
-	ErrorDebugging:          "Debugging Error",
174
-	ErrorUnexpectedMessage:  "Unexpected Message",
175
-	ErrorUnexpectedResponse: "Unexpected Response",
176
-	ErrorEmptyPassword:      "Empty password not allowed by the client",
177
-}
178
-
179
-// Error holds LDAP error information
180
-type Error struct {
181
-	// Err is the underlying error
182
-	Err error
183
-	// ResultCode is the LDAP error code
184
-	ResultCode uint16
185
-	// MatchedDN is the matchedDN returned if any
186
-	MatchedDN string
187
-}
188
-
189
-func (e *Error) Error() string {
190
-	return fmt.Sprintf("LDAP Result Code %d %q: %s", e.ResultCode, LDAPResultCodeMap[e.ResultCode], e.Err.Error())
191
-}
192
-
193
-// GetLDAPError creates an Error out of a BER packet representing a LDAPResult
194
-// The return is an error object. It can be casted to a Error structure.
195
-// This function returns nil if resultCode in the LDAPResult sequence is success(0).
196
-func GetLDAPError(packet *ber.Packet) error {
197
-	if packet == nil {
198
-		return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("Empty packet")}
199
-	}
200
-
201
-	if len(packet.Children) >= 2 {
202
-		response := packet.Children[1]
203
-		if response == nil {
204
-			return &Error{ResultCode: ErrorUnexpectedResponse, Err: fmt.Errorf("Empty response in packet")}
205
-		}
206
-		if response.ClassType == ber.ClassApplication && response.TagType == ber.TypeConstructed && len(response.Children) >= 3 {
207
-			resultCode := uint16(response.Children[0].Value.(int64))
208
-			if resultCode == 0 { // No error
209
-				return nil
210
-			}
211
-			return &Error{ResultCode: resultCode, MatchedDN: response.Children[1].Value.(string),
212
-				Err: fmt.Errorf("%s", response.Children[2].Value.(string))}
213
-		}
214
-	}
215
-
216
-	return &Error{ResultCode: ErrorNetwork, Err: fmt.Errorf("Invalid packet format")}
217
-}
218
-
219
-// NewError creates an LDAP error with the given code and underlying error
220
-func NewError(resultCode uint16, err error) error {
221
-	return &Error{ResultCode: resultCode, Err: err}
222
-}
223
-
224
-// IsErrorWithCode returns true if the given error is an LDAP error with the given result code
225
-func IsErrorWithCode(err error, desiredResultCode uint16) bool {
226
-	if err == nil {
227
-		return false
228
-	}
229
-
230
-	serverError, ok := err.(*Error)
231
-	if !ok {
232
-		return false
233
-	}
234
-
235
-	return serverError.ResultCode == desiredResultCode
236
-}

+ 0
- 487
vendor/github.com/go-ldap/ldap/v3/filter.go View File

@@ -1,487 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"bytes"
5
-	hexpac "encoding/hex"
6
-	"errors"
7
-	"fmt"
8
-	"io"
9
-	"strings"
10
-	"unicode"
11
-	"unicode/utf8"
12
-
13
-	ber "github.com/go-asn1-ber/asn1-ber"
14
-)
15
-
16
-// Filter choices
17
-const (
18
-	FilterAnd             = 0
19
-	FilterOr              = 1
20
-	FilterNot             = 2
21
-	FilterEqualityMatch   = 3
22
-	FilterSubstrings      = 4
23
-	FilterGreaterOrEqual  = 5
24
-	FilterLessOrEqual     = 6
25
-	FilterPresent         = 7
26
-	FilterApproxMatch     = 8
27
-	FilterExtensibleMatch = 9
28
-)
29
-
30
-// FilterMap contains human readable descriptions of Filter choices
31
-var FilterMap = map[uint64]string{
32
-	FilterAnd:             "And",
33
-	FilterOr:              "Or",
34
-	FilterNot:             "Not",
35
-	FilterEqualityMatch:   "Equality Match",
36
-	FilterSubstrings:      "Substrings",
37
-	FilterGreaterOrEqual:  "Greater Or Equal",
38
-	FilterLessOrEqual:     "Less Or Equal",
39
-	FilterPresent:         "Present",
40
-	FilterApproxMatch:     "Approx Match",
41
-	FilterExtensibleMatch: "Extensible Match",
42
-}
43
-
44
-// SubstringFilter options
45
-const (
46
-	FilterSubstringsInitial = 0
47
-	FilterSubstringsAny     = 1
48
-	FilterSubstringsFinal   = 2
49
-)
50
-
51
-// FilterSubstringsMap contains human readable descriptions of SubstringFilter choices
52
-var FilterSubstringsMap = map[uint64]string{
53
-	FilterSubstringsInitial: "Substrings Initial",
54
-	FilterSubstringsAny:     "Substrings Any",
55
-	FilterSubstringsFinal:   "Substrings Final",
56
-}
57
-
58
-// MatchingRuleAssertion choices
59
-const (
60
-	MatchingRuleAssertionMatchingRule = 1
61
-	MatchingRuleAssertionType         = 2
62
-	MatchingRuleAssertionMatchValue   = 3
63
-	MatchingRuleAssertionDNAttributes = 4
64
-)
65
-
66
-// MatchingRuleAssertionMap contains human readable descriptions of MatchingRuleAssertion choices
67
-var MatchingRuleAssertionMap = map[uint64]string{
68
-	MatchingRuleAssertionMatchingRule: "Matching Rule Assertion Matching Rule",
69
-	MatchingRuleAssertionType:         "Matching Rule Assertion Type",
70
-	MatchingRuleAssertionMatchValue:   "Matching Rule Assertion Match Value",
71
-	MatchingRuleAssertionDNAttributes: "Matching Rule Assertion DN Attributes",
72
-}
73
-
74
-var _SymbolAny = []byte{'*'}
75
-
76
-// CompileFilter converts a string representation of a filter into a BER-encoded packet
77
-func CompileFilter(filter string) (*ber.Packet, error) {
78
-	if len(filter) == 0 || filter[0] != '(' {
79
-		return nil, NewError(ErrorFilterCompile, errors.New("ldap: filter does not start with an '('"))
80
-	}
81
-	packet, pos, err := compileFilter(filter, 1)
82
-	if err != nil {
83
-		return nil, err
84
-	}
85
-	switch {
86
-	case pos > len(filter):
87
-		return nil, NewError(ErrorFilterCompile, errors.New("ldap: unexpected end of filter"))
88
-	case pos < len(filter):
89
-		return nil, NewError(ErrorFilterCompile, errors.New("ldap: finished compiling filter with extra at end: "+fmt.Sprint(filter[pos:])))
90
-	}
91
-	return packet, nil
92
-}
93
-
94
-// DecompileFilter converts a packet representation of a filter into a string representation
95
-func DecompileFilter(packet *ber.Packet) (_ string, err error) {
96
-	defer func() {
97
-		if r := recover(); r != nil {
98
-			err = NewError(ErrorFilterDecompile, errors.New("ldap: error decompiling filter"))
99
-		}
100
-	}()
101
-
102
-	buf := bytes.NewBuffer(nil)
103
-	buf.WriteByte('(')
104
-	childStr := ""
105
-
106
-	switch packet.Tag {
107
-	case FilterAnd:
108
-		buf.WriteByte('&')
109
-		for _, child := range packet.Children {
110
-			childStr, err = DecompileFilter(child)
111
-			if err != nil {
112
-				return
113
-			}
114
-			buf.WriteString(childStr)
115
-		}
116
-	case FilterOr:
117
-		buf.WriteByte('|')
118
-		for _, child := range packet.Children {
119
-			childStr, err = DecompileFilter(child)
120
-			if err != nil {
121
-				return
122
-			}
123
-			buf.WriteString(childStr)
124
-		}
125
-	case FilterNot:
126
-		buf.WriteByte('!')
127
-		childStr, err = DecompileFilter(packet.Children[0])
128
-		if err != nil {
129
-			return
130
-		}
131
-		buf.WriteString(childStr)
132
-
133
-	case FilterSubstrings:
134
-		buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
135
-		buf.WriteByte('=')
136
-		for i, child := range packet.Children[1].Children {
137
-			if i == 0 && child.Tag != FilterSubstringsInitial {
138
-				buf.Write(_SymbolAny)
139
-			}
140
-			buf.WriteString(EscapeFilter(ber.DecodeString(child.Data.Bytes())))
141
-			if child.Tag != FilterSubstringsFinal {
142
-				buf.Write(_SymbolAny)
143
-			}
144
-		}
145
-	case FilterEqualityMatch:
146
-		buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
147
-		buf.WriteByte('=')
148
-		buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
149
-	case FilterGreaterOrEqual:
150
-		buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
151
-		buf.WriteString(">=")
152
-		buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
153
-	case FilterLessOrEqual:
154
-		buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
155
-		buf.WriteString("<=")
156
-		buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
157
-	case FilterPresent:
158
-		buf.WriteString(ber.DecodeString(packet.Data.Bytes()))
159
-		buf.WriteString("=*")
160
-	case FilterApproxMatch:
161
-		buf.WriteString(ber.DecodeString(packet.Children[0].Data.Bytes()))
162
-		buf.WriteString("~=")
163
-		buf.WriteString(EscapeFilter(ber.DecodeString(packet.Children[1].Data.Bytes())))
164
-	case FilterExtensibleMatch:
165
-		attr := ""
166
-		dnAttributes := false
167
-		matchingRule := ""
168
-		value := ""
169
-
170
-		for _, child := range packet.Children {
171
-			switch child.Tag {
172
-			case MatchingRuleAssertionMatchingRule:
173
-				matchingRule = ber.DecodeString(child.Data.Bytes())
174
-			case MatchingRuleAssertionType:
175
-				attr = ber.DecodeString(child.Data.Bytes())
176
-			case MatchingRuleAssertionMatchValue:
177
-				value = ber.DecodeString(child.Data.Bytes())
178
-			case MatchingRuleAssertionDNAttributes:
179
-				dnAttributes = child.Value.(bool)
180
-			}
181
-		}
182
-
183
-		if len(attr) > 0 {
184
-			buf.WriteString(attr)
185
-		}
186
-		if dnAttributes {
187
-			buf.WriteString(":dn")
188
-		}
189
-		if len(matchingRule) > 0 {
190
-			buf.WriteString(":")
191
-			buf.WriteString(matchingRule)
192
-		}
193
-		buf.WriteString(":=")
194
-		buf.WriteString(EscapeFilter(value))
195
-	}
196
-
197
-	buf.WriteByte(')')
198
-
199
-	return buf.String(), nil
200
-}
201
-
202
-func compileFilterSet(filter string, pos int, parent *ber.Packet) (int, error) {
203
-	for pos < len(filter) && filter[pos] == '(' {
204
-		child, newPos, err := compileFilter(filter, pos+1)
205
-		if err != nil {
206
-			return pos, err
207
-		}
208
-		pos = newPos
209
-		parent.AppendChild(child)
210
-	}
211
-	if pos == len(filter) {
212
-		return pos, NewError(ErrorFilterCompile, errors.New("ldap: unexpected end of filter"))
213
-	}
214
-
215
-	return pos + 1, nil
216
-}
217
-
218
-func compileFilter(filter string, pos int) (*ber.Packet, int, error) {
219
-	var (
220
-		packet *ber.Packet
221
-		err    error
222
-	)
223
-
224
-	defer func() {
225
-		if r := recover(); r != nil {
226
-			err = NewError(ErrorFilterCompile, errors.New("ldap: error compiling filter"))
227
-		}
228
-	}()
229
-	newPos := pos
230
-
231
-	currentRune, currentWidth := utf8.DecodeRuneInString(filter[newPos:])
232
-
233
-	switch currentRune {
234
-	case utf8.RuneError:
235
-		return nil, 0, NewError(ErrorFilterCompile, fmt.Errorf("ldap: error reading rune at position %d", newPos))
236
-	case '(':
237
-		packet, newPos, err = compileFilter(filter, pos+currentWidth)
238
-		newPos++
239
-		return packet, newPos, err
240
-	case '&':
241
-		packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterAnd, nil, FilterMap[FilterAnd])
242
-		newPos, err = compileFilterSet(filter, pos+currentWidth, packet)
243
-		return packet, newPos, err
244
-	case '|':
245
-		packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterOr, nil, FilterMap[FilterOr])
246
-		newPos, err = compileFilterSet(filter, pos+currentWidth, packet)
247
-		return packet, newPos, err
248
-	case '!':
249
-		packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterNot, nil, FilterMap[FilterNot])
250
-		var child *ber.Packet
251
-		child, newPos, err = compileFilter(filter, pos+currentWidth)
252
-		packet.AppendChild(child)
253
-		return packet, newPos, err
254
-	default:
255
-		const (
256
-			stateReadingAttr                   = 0
257
-			stateReadingExtensibleMatchingRule = 1
258
-			stateReadingCondition              = 2
259
-		)
260
-
261
-		state := stateReadingAttr
262
-		attribute := bytes.NewBuffer(nil)
263
-		extensibleDNAttributes := false
264
-		extensibleMatchingRule := bytes.NewBuffer(nil)
265
-		condition := bytes.NewBuffer(nil)
266
-
267
-		for newPos < len(filter) {
268
-			remainingFilter := filter[newPos:]
269
-			currentRune, currentWidth = utf8.DecodeRuneInString(remainingFilter)
270
-			if currentRune == ')' {
271
-				break
272
-			}
273
-			if currentRune == utf8.RuneError {
274
-				return packet, newPos, NewError(ErrorFilterCompile, fmt.Errorf("ldap: error reading rune at position %d", newPos))
275
-			}
276
-
277
-			switch state {
278
-			case stateReadingAttr:
279
-				switch {
280
-				// Extensible rule, with only DN-matching
281
-				case currentRune == ':' && strings.HasPrefix(remainingFilter, ":dn:="):
282
-					packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterExtensibleMatch, nil, FilterMap[FilterExtensibleMatch])
283
-					extensibleDNAttributes = true
284
-					state = stateReadingCondition
285
-					newPos += 5
286
-
287
-				// Extensible rule, with DN-matching and a matching OID
288
-				case currentRune == ':' && strings.HasPrefix(remainingFilter, ":dn:"):
289
-					packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterExtensibleMatch, nil, FilterMap[FilterExtensibleMatch])
290
-					extensibleDNAttributes = true
291
-					state = stateReadingExtensibleMatchingRule
292
-					newPos += 4
293
-
294
-				// Extensible rule, with attr only
295
-				case currentRune == ':' && strings.HasPrefix(remainingFilter, ":="):
296
-					packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterExtensibleMatch, nil, FilterMap[FilterExtensibleMatch])
297
-					state = stateReadingCondition
298
-					newPos += 2
299
-
300
-				// Extensible rule, with no DN attribute matching
301
-				case currentRune == ':':
302
-					packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterExtensibleMatch, nil, FilterMap[FilterExtensibleMatch])
303
-					state = stateReadingExtensibleMatchingRule
304
-					newPos++
305
-
306
-				// Equality condition
307
-				case currentRune == '=':
308
-					packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterEqualityMatch, nil, FilterMap[FilterEqualityMatch])
309
-					state = stateReadingCondition
310
-					newPos++
311
-
312
-				// Greater-than or equal
313
-				case currentRune == '>' && strings.HasPrefix(remainingFilter, ">="):
314
-					packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterGreaterOrEqual, nil, FilterMap[FilterGreaterOrEqual])
315
-					state = stateReadingCondition
316
-					newPos += 2
317
-
318
-				// Less-than or equal
319
-				case currentRune == '<' && strings.HasPrefix(remainingFilter, "<="):
320
-					packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterLessOrEqual, nil, FilterMap[FilterLessOrEqual])
321
-					state = stateReadingCondition
322
-					newPos += 2
323
-
324
-				// Approx
325
-				case currentRune == '~' && strings.HasPrefix(remainingFilter, "~="):
326
-					packet = ber.Encode(ber.ClassContext, ber.TypeConstructed, FilterApproxMatch, nil, FilterMap[FilterApproxMatch])
327
-					state = stateReadingCondition
328
-					newPos += 2
329
-
330
-				// Still reading the attribute name
331
-				default:
332
-					attribute.WriteRune(currentRune)
333
-					newPos += currentWidth
334
-				}
335
-
336
-			case stateReadingExtensibleMatchingRule:
337
-				switch {
338
-
339
-				// Matching rule OID is done
340
-				case currentRune == ':' && strings.HasPrefix(remainingFilter, ":="):
341
-					state = stateReadingCondition
342
-					newPos += 2
343
-
344
-				// Still reading the matching rule oid
345
-				default:
346
-					extensibleMatchingRule.WriteRune(currentRune)
347
-					newPos += currentWidth
348
-				}
349
-
350
-			case stateReadingCondition:
351
-				// append to the condition
352
-				condition.WriteRune(currentRune)
353
-				newPos += currentWidth
354
-			}
355
-		}
356
-
357
-		if newPos == len(filter) {
358
-			err = NewError(ErrorFilterCompile, errors.New("ldap: unexpected end of filter"))
359
-			return packet, newPos, err
360
-		}
361
-		if packet == nil {
362
-			err = NewError(ErrorFilterCompile, errors.New("ldap: error parsing filter"))
363
-			return packet, newPos, err
364
-		}
365
-
366
-		switch {
367
-		case packet.Tag == FilterExtensibleMatch:
368
-			// MatchingRuleAssertion ::= SEQUENCE {
369
-			//         matchingRule    [1] MatchingRuleID OPTIONAL,
370
-			//         type            [2] AttributeDescription OPTIONAL,
371
-			//         matchValue      [3] AssertionValue,
372
-			//         dnAttributes    [4] BOOLEAN DEFAULT FALSE
373
-			// }
374
-
375
-			// Include the matching rule oid, if specified
376
-			if extensibleMatchingRule.Len() > 0 {
377
-				packet.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, MatchingRuleAssertionMatchingRule, extensibleMatchingRule.String(), MatchingRuleAssertionMap[MatchingRuleAssertionMatchingRule]))
378
-			}
379
-
380
-			// Include the attribute, if specified
381
-			if attribute.Len() > 0 {
382
-				packet.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, MatchingRuleAssertionType, attribute.String(), MatchingRuleAssertionMap[MatchingRuleAssertionType]))
383
-			}
384
-
385
-			// Add the value (only required child)
386
-			encodedString, encodeErr := decodeEscapedSymbols(condition.Bytes())
387
-			if encodeErr != nil {
388
-				return packet, newPos, encodeErr
389
-			}
390
-			packet.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, MatchingRuleAssertionMatchValue, encodedString, MatchingRuleAssertionMap[MatchingRuleAssertionMatchValue]))
391
-
392
-			// Defaults to false, so only include in the sequence if true
393
-			if extensibleDNAttributes {
394
-				packet.AppendChild(ber.NewBoolean(ber.ClassContext, ber.TypePrimitive, MatchingRuleAssertionDNAttributes, extensibleDNAttributes, MatchingRuleAssertionMap[MatchingRuleAssertionDNAttributes]))
395
-			}
396
-
397
-		case packet.Tag == FilterEqualityMatch && bytes.Equal(condition.Bytes(), _SymbolAny):
398
-			packet = ber.NewString(ber.ClassContext, ber.TypePrimitive, FilterPresent, attribute.String(), FilterMap[FilterPresent])
399
-		case packet.Tag == FilterEqualityMatch && bytes.Index(condition.Bytes(), _SymbolAny) > -1:
400
-			packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, attribute.String(), "Attribute"))
401
-			packet.Tag = FilterSubstrings
402
-			packet.Description = FilterMap[uint64(packet.Tag)]
403
-			seq := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Substrings")
404
-			parts := bytes.Split(condition.Bytes(), _SymbolAny)
405
-			for i, part := range parts {
406
-				if len(part) == 0 {
407
-					continue
408
-				}
409
-				var tag ber.Tag
410
-				switch i {
411
-				case 0:
412
-					tag = FilterSubstringsInitial
413
-				case len(parts) - 1:
414
-					tag = FilterSubstringsFinal
415
-				default:
416
-					tag = FilterSubstringsAny
417
-				}
418
-				encodedString, encodeErr := decodeEscapedSymbols(part)
419
-				if encodeErr != nil {
420
-					return packet, newPos, encodeErr
421
-				}
422
-				seq.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, tag, encodedString, FilterSubstringsMap[uint64(tag)]))
423
-			}
424
-			packet.AppendChild(seq)
425
-		default:
426
-			encodedString, encodeErr := decodeEscapedSymbols(condition.Bytes())
427
-			if encodeErr != nil {
428
-				return packet, newPos, encodeErr
429
-			}
430
-			packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, attribute.String(), "Attribute"))
431
-			packet.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, encodedString, "Condition"))
432
-		}
433
-
434
-		newPos += currentWidth
435
-		return packet, newPos, err
436
-	}
437
-}
438
-
439
-// Convert from "ABC\xx\xx\xx" form to literal bytes for transport
440
-func decodeEscapedSymbols(src []byte) (string, error) {
441
-
442
-	var (
443
-		buffer  bytes.Buffer
444
-		offset  int
445
-		reader  = bytes.NewReader(src)
446
-		byteHex []byte
447
-		byteVal []byte
448
-	)
449
-
450
-	for {
451
-		runeVal, runeSize, err := reader.ReadRune()
452
-		if err == io.EOF {
453
-			return buffer.String(), nil
454
-		} else if err != nil {
455
-			return "", NewError(ErrorFilterCompile, fmt.Errorf("ldap: failed to read filter: %v", err))
456
-		} else if runeVal == unicode.ReplacementChar {
457
-			return "", NewError(ErrorFilterCompile, fmt.Errorf("ldap: error reading rune at position %d", offset))
458
-		}
459
-
460
-		if runeVal == '\\' {
461
-			// http://tools.ietf.org/search/rfc4515
462
-			// \ (%x5C) is not a valid character unless it is followed by two HEX characters due to not
463
-			// being a member of UTF1SUBSET.
464
-			if byteHex == nil {
465
-				byteHex = make([]byte, 2)
466
-				byteVal = make([]byte, 1)
467
-			}
468
-
469
-			if _, err := io.ReadFull(reader, byteHex); err != nil {
470
-				if err == io.ErrUnexpectedEOF {
471
-					return "", NewError(ErrorFilterCompile, errors.New("ldap: missing characters for escape in filter"))
472
-				}
473
-				return "", NewError(ErrorFilterCompile, fmt.Errorf("ldap: invalid characters for escape in filter: %v", err))
474
-			}
475
-
476
-			if _, err := hexpac.Decode(byteVal, byteHex); err != nil {
477
-				return "", NewError(ErrorFilterCompile, fmt.Errorf("ldap: invalid characters for escape in filter: %v", err))
478
-			}
479
-
480
-			buffer.Write(byteVal)
481
-		} else {
482
-			buffer.WriteRune(runeVal)
483
-		}
484
-
485
-		offset += runeSize
486
-	}
487
-}

+ 0
- 5
vendor/github.com/go-ldap/ldap/v3/go.mod View File

@@ -1,5 +0,0 @@
1
-module github.com/go-ldap/ldap/v3
2
-
3
-go 1.13
4
-
5
-require github.com/go-asn1-ber/asn1-ber v1.3.1

+ 0
- 2
vendor/github.com/go-ldap/ldap/v3/go.sum View File

@@ -1,2 +0,0 @@
1
-github.com/go-asn1-ber/asn1-ber v1.3.1 h1:gvPdv/Hr++TRFCl0UbPFHC54P9N9jgsRPnmnr419Uck=
2
-github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=

+ 0
- 345
vendor/github.com/go-ldap/ldap/v3/ldap.go View File

@@ -1,345 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"fmt"
5
-	"io/ioutil"
6
-	"os"
7
-
8
-	ber "github.com/go-asn1-ber/asn1-ber"
9
-)
10
-
11
-// LDAP Application Codes
12
-const (
13
-	ApplicationBindRequest           = 0
14
-	ApplicationBindResponse          = 1
15
-	ApplicationUnbindRequest         = 2
16
-	ApplicationSearchRequest         = 3
17
-	ApplicationSearchResultEntry     = 4
18
-	ApplicationSearchResultDone      = 5
19
-	ApplicationModifyRequest         = 6
20
-	ApplicationModifyResponse        = 7
21
-	ApplicationAddRequest            = 8
22
-	ApplicationAddResponse           = 9
23
-	ApplicationDelRequest            = 10
24
-	ApplicationDelResponse           = 11
25
-	ApplicationModifyDNRequest       = 12
26
-	ApplicationModifyDNResponse      = 13
27
-	ApplicationCompareRequest        = 14
28
-	ApplicationCompareResponse       = 15
29
-	ApplicationAbandonRequest        = 16
30
-	ApplicationSearchResultReference = 19
31
-	ApplicationExtendedRequest       = 23
32
-	ApplicationExtendedResponse      = 24
33
-)
34
-
35
-// ApplicationMap contains human readable descriptions of LDAP Application Codes
36
-var ApplicationMap = map[uint8]string{
37
-	ApplicationBindRequest:           "Bind Request",
38
-	ApplicationBindResponse:          "Bind Response",
39
-	ApplicationUnbindRequest:         "Unbind Request",
40
-	ApplicationSearchRequest:         "Search Request",
41
-	ApplicationSearchResultEntry:     "Search Result Entry",
42
-	ApplicationSearchResultDone:      "Search Result Done",
43
-	ApplicationModifyRequest:         "Modify Request",
44
-	ApplicationModifyResponse:        "Modify Response",
45
-	ApplicationAddRequest:            "Add Request",
46
-	ApplicationAddResponse:           "Add Response",
47
-	ApplicationDelRequest:            "Del Request",
48
-	ApplicationDelResponse:           "Del Response",
49
-	ApplicationModifyDNRequest:       "Modify DN Request",
50
-	ApplicationModifyDNResponse:      "Modify DN Response",
51
-	ApplicationCompareRequest:        "Compare Request",
52
-	ApplicationCompareResponse:       "Compare Response",
53
-	ApplicationAbandonRequest:        "Abandon Request",
54
-	ApplicationSearchResultReference: "Search Result Reference",
55
-	ApplicationExtendedRequest:       "Extended Request",
56
-	ApplicationExtendedResponse:      "Extended Response",
57
-}
58
-
59
-// Ldap Behera Password Policy Draft 10 (https://tools.ietf.org/html/draft-behera-ldap-password-policy-10)
60
-const (
61
-	BeheraPasswordExpired             = 0
62
-	BeheraAccountLocked               = 1
63
-	BeheraChangeAfterReset            = 2
64
-	BeheraPasswordModNotAllowed       = 3
65
-	BeheraMustSupplyOldPassword       = 4
66
-	BeheraInsufficientPasswordQuality = 5
67
-	BeheraPasswordTooShort            = 6
68
-	BeheraPasswordTooYoung            = 7
69
-	BeheraPasswordInHistory           = 8
70
-)
71
-
72
-// BeheraPasswordPolicyErrorMap contains human readable descriptions of Behera Password Policy error codes
73
-var BeheraPasswordPolicyErrorMap = map[int8]string{
74
-	BeheraPasswordExpired:             "Password expired",
75
-	BeheraAccountLocked:               "Account locked",
76
-	BeheraChangeAfterReset:            "Password must be changed",
77
-	BeheraPasswordModNotAllowed:       "Policy prevents password modification",
78
-	BeheraMustSupplyOldPassword:       "Policy requires old password in order to change password",
79
-	BeheraInsufficientPasswordQuality: "Password fails quality checks",
80
-	BeheraPasswordTooShort:            "Password is too short for policy",
81
-	BeheraPasswordTooYoung:            "Password has been changed too recently",
82
-	BeheraPasswordInHistory:           "New password is in list of old passwords",
83
-}
84
-
85
-// Adds descriptions to an LDAP Response packet for debugging
86
-func addLDAPDescriptions(packet *ber.Packet) (err error) {
87
-	defer func() {
88
-		if r := recover(); r != nil {
89
-			err = NewError(ErrorDebugging, fmt.Errorf("ldap: cannot process packet to add descriptions: %s", r))
90
-		}
91
-	}()
92
-	packet.Description = "LDAP Response"
93
-	packet.Children[0].Description = "Message ID"
94
-
95
-	application := uint8(packet.Children[1].Tag)
96
-	packet.Children[1].Description = ApplicationMap[application]
97
-
98
-	switch application {
99
-	case ApplicationBindRequest:
100
-		err = addRequestDescriptions(packet)
101
-	case ApplicationBindResponse:
102
-		err = addDefaultLDAPResponseDescriptions(packet)
103
-	case ApplicationUnbindRequest:
104
-		err = addRequestDescriptions(packet)
105
-	case ApplicationSearchRequest:
106
-		err = addRequestDescriptions(packet)
107
-	case ApplicationSearchResultEntry:
108
-		packet.Children[1].Children[0].Description = "Object Name"
109
-		packet.Children[1].Children[1].Description = "Attributes"
110
-		for _, child := range packet.Children[1].Children[1].Children {
111
-			child.Description = "Attribute"
112
-			child.Children[0].Description = "Attribute Name"
113
-			child.Children[1].Description = "Attribute Values"
114
-			for _, grandchild := range child.Children[1].Children {
115
-				grandchild.Description = "Attribute Value"
116
-			}
117
-		}
118
-		if len(packet.Children) == 3 {
119
-			err = addControlDescriptions(packet.Children[2])
120
-		}
121
-	case ApplicationSearchResultDone:
122
-		err = addDefaultLDAPResponseDescriptions(packet)
123
-	case ApplicationModifyRequest:
124
-		err = addRequestDescriptions(packet)
125
-	case ApplicationModifyResponse:
126
-	case ApplicationAddRequest:
127
-		err = addRequestDescriptions(packet)
128
-	case ApplicationAddResponse:
129
-	case ApplicationDelRequest:
130
-		err = addRequestDescriptions(packet)
131
-	case ApplicationDelResponse:
132
-	case ApplicationModifyDNRequest:
133
-		err = addRequestDescriptions(packet)
134
-	case ApplicationModifyDNResponse:
135
-	case ApplicationCompareRequest:
136
-		err = addRequestDescriptions(packet)
137
-	case ApplicationCompareResponse:
138
-	case ApplicationAbandonRequest:
139
-		err = addRequestDescriptions(packet)
140
-	case ApplicationSearchResultReference:
141
-	case ApplicationExtendedRequest:
142
-		err = addRequestDescriptions(packet)
143
-	case ApplicationExtendedResponse:
144
-	}
145
-
146
-	return err
147
-}
148
-
149
-func addControlDescriptions(packet *ber.Packet) error {
150
-	packet.Description = "Controls"
151
-	for _, child := range packet.Children {
152
-		var value *ber.Packet
153
-		controlType := ""
154
-		child.Description = "Control"
155
-		switch len(child.Children) {
156
-		case 0:
157
-			// at least one child is required for control type
158
-			return fmt.Errorf("at least one child is required for control type")
159
-
160
-		case 1:
161
-			// just type, no criticality or value
162
-			controlType = child.Children[0].Value.(string)
163
-			child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")"
164
-
165
-		case 2:
166
-			controlType = child.Children[0].Value.(string)
167
-			child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")"
168
-			// Children[1] could be criticality or value (both are optional)
169
-			// duck-type on whether this is a boolean
170
-			if _, ok := child.Children[1].Value.(bool); ok {
171
-				child.Children[1].Description = "Criticality"
172
-			} else {
173
-				child.Children[1].Description = "Control Value"
174
-				value = child.Children[1]
175
-			}
176
-
177
-		case 3:
178
-			// criticality and value present
179
-			controlType = child.Children[0].Value.(string)
180
-			child.Children[0].Description = "Control Type (" + ControlTypeMap[controlType] + ")"
181
-			child.Children[1].Description = "Criticality"
182
-			child.Children[2].Description = "Control Value"
183
-			value = child.Children[2]
184
-
185
-		default:
186
-			// more than 3 children is invalid
187
-			return fmt.Errorf("more than 3 children for control packet found")
188
-		}
189
-
190
-		if value == nil {
191
-			continue
192
-		}
193
-		switch controlType {
194
-		case ControlTypePaging:
195
-			value.Description += " (Paging)"
196
-			if value.Value != nil {
197
-				valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
198
-				if err != nil {
199
-					return fmt.Errorf("failed to decode data bytes: %s", err)
200
-				}
201
-				value.Data.Truncate(0)
202
-				value.Value = nil
203
-				valueChildren.Children[1].Value = valueChildren.Children[1].Data.Bytes()
204
-				value.AppendChild(valueChildren)
205
-			}
206
-			value.Children[0].Description = "Real Search Control Value"
207
-			value.Children[0].Children[0].Description = "Paging Size"
208
-			value.Children[0].Children[1].Description = "Cookie"
209
-
210
-		case ControlTypeBeheraPasswordPolicy:
211
-			value.Description += " (Password Policy - Behera Draft)"
212
-			if value.Value != nil {
213
-				valueChildren, err := ber.DecodePacketErr(value.Data.Bytes())
214
-				if err != nil {
215
-					return fmt.Errorf("failed to decode data bytes: %s", err)
216
-				}
217
-				value.Data.Truncate(0)
218
-				value.Value = nil
219
-				value.AppendChild(valueChildren)
220
-			}
221
-			sequence := value.Children[0]
222
-			for _, child := range sequence.Children {
223
-				if child.Tag == 0 {
224
-					//Warning
225
-					warningPacket := child.Children[0]
226
-					packet, err := ber.DecodePacketErr(warningPacket.Data.Bytes())
227
-					if err != nil {
228
-						return fmt.Errorf("failed to decode data bytes: %s", err)
229
-					}
230
-					val, ok := packet.Value.(int64)
231
-					if ok {
232
-						if warningPacket.Tag == 0 {
233
-							//timeBeforeExpiration
234
-							value.Description += " (TimeBeforeExpiration)"
235
-							warningPacket.Value = val
236
-						} else if warningPacket.Tag == 1 {
237
-							//graceAuthNsRemaining
238
-							value.Description += " (GraceAuthNsRemaining)"
239
-							warningPacket.Value = val
240
-						}
241
-					}
242
-				} else if child.Tag == 1 {
243
-					// Error
244
-					packet, err := ber.DecodePacketErr(child.Data.Bytes())
245
-					if err != nil {
246
-						return fmt.Errorf("failed to decode data bytes: %s", err)
247
-					}
248
-					val, ok := packet.Value.(int8)
249
-					if !ok {
250
-						val = -1
251
-					}
252
-					child.Description = "Error"
253
-					child.Value = val
254
-				}
255
-			}
256
-		}
257
-	}
258
-	return nil
259
-}
260
-
261
-func addRequestDescriptions(packet *ber.Packet) error {
262
-	packet.Description = "LDAP Request"
263
-	packet.Children[0].Description = "Message ID"
264
-	packet.Children[1].Description = ApplicationMap[uint8(packet.Children[1].Tag)]
265
-	if len(packet.Children) == 3 {
266
-		return addControlDescriptions(packet.Children[2])
267
-	}
268
-	return nil
269
-}
270
-
271
-func addDefaultLDAPResponseDescriptions(packet *ber.Packet) error {
272
-	resultCode := uint16(LDAPResultSuccess)
273
-	matchedDN := ""
274
-	description := "Success"
275
-	if err := GetLDAPError(packet); err != nil {
276
-		resultCode = err.(*Error).ResultCode
277
-		matchedDN = err.(*Error).MatchedDN
278
-		description = "Error Message"
279
-	}
280
-
281
-	packet.Children[1].Children[0].Description = "Result Code (" + LDAPResultCodeMap[resultCode] + ")"
282
-	packet.Children[1].Children[1].Description = "Matched DN (" + matchedDN + ")"
283
-	packet.Children[1].Children[2].Description = description
284
-	if len(packet.Children[1].Children) > 3 {
285
-		packet.Children[1].Children[3].Description = "Referral"
286
-	}
287
-	if len(packet.Children) == 3 {
288
-		return addControlDescriptions(packet.Children[2])
289
-	}
290
-	return nil
291
-}
292
-
293
-// DebugBinaryFile reads and prints packets from the given filename
294
-func DebugBinaryFile(fileName string) error {
295
-	file, err := ioutil.ReadFile(fileName)
296
-	if err != nil {
297
-		return NewError(ErrorDebugging, err)
298
-	}
299
-	ber.PrintBytes(os.Stdout, file, "")
300
-	packet, err := ber.DecodePacketErr(file)
301
-	if err != nil {
302
-		return fmt.Errorf("failed to decode packet: %s", err)
303
-	}
304
-	if err := addLDAPDescriptions(packet); err != nil {
305
-		return err
306
-	}
307
-	ber.PrintPacket(packet)
308
-
309
-	return nil
310
-}
311
-
312
-var hex = "0123456789abcdef"
313
-
314
-func mustEscape(c byte) bool {
315
-	return c > 0x7f || c == '(' || c == ')' || c == '\\' || c == '*' || c == 0
316
-}
317
-
318
-// EscapeFilter escapes from the provided LDAP filter string the special
319
-// characters in the set `()*\` and those out of the range 0 < c < 0x80,
320
-// as defined in RFC4515.
321
-func EscapeFilter(filter string) string {
322
-	escape := 0
323
-	for i := 0; i < len(filter); i++ {
324
-		if mustEscape(filter[i]) {
325
-			escape++
326
-		}
327
-	}
328
-	if escape == 0 {
329
-		return filter
330
-	}
331
-	buf := make([]byte, len(filter)+escape*2)
332
-	for i, j := 0, 0; i < len(filter); i++ {
333
-		c := filter[i]
334
-		if mustEscape(c) {
335
-			buf[j+0] = '\\'
336
-			buf[j+1] = hex[c>>4]
337
-			buf[j+2] = hex[c&0xf]
338
-			j += 3
339
-		} else {
340
-			buf[j] = c
341
-			j++
342
-		}
343
-	}
344
-	return string(buf)
345
-}

+ 0
- 75
vendor/github.com/go-ldap/ldap/v3/moddn.go View File

@@ -1,75 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"log"
5
-
6
-	ber "github.com/go-asn1-ber/asn1-ber"
7
-)
8
-
9
-// ModifyDNRequest holds the request to modify a DN
10
-type ModifyDNRequest struct {
11
-	DN           string
12
-	NewRDN       string
13
-	DeleteOldRDN bool
14
-	NewSuperior  string
15
-}
16
-
17
-// NewModifyDNRequest creates a new request which can be passed to ModifyDN().
18
-//
19
-// To move an object in the tree, set the "newSup" to the new parent entry DN. Use an
20
-// empty string for just changing the object's RDN.
21
-//
22
-// For moving the object without renaming, the "rdn" must be the first
23
-// RDN of the given DN.
24
-//
25
-// A call like
26
-//   mdnReq := NewModifyDNRequest("uid=someone,dc=example,dc=org", "uid=newname", true, "")
27
-// will setup the request to just rename uid=someone,dc=example,dc=org to
28
-// uid=newname,dc=example,dc=org.
29
-func NewModifyDNRequest(dn string, rdn string, delOld bool, newSup string) *ModifyDNRequest {
30
-	return &ModifyDNRequest{
31
-		DN:           dn,
32
-		NewRDN:       rdn,
33
-		DeleteOldRDN: delOld,
34
-		NewSuperior:  newSup,
35
-	}
36
-}
37
-
38
-func (req *ModifyDNRequest) appendTo(envelope *ber.Packet) error {
39
-	pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationModifyDNRequest, nil, "Modify DN Request")
40
-	pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.DN, "DN"))
41
-	pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.NewRDN, "New RDN"))
42
-	pkt.AppendChild(ber.NewBoolean(ber.ClassUniversal, ber.TypePrimitive, ber.TagBoolean, req.DeleteOldRDN, "Delete old RDN"))
43
-	if req.NewSuperior != "" {
44
-		pkt.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, req.NewSuperior, "New Superior"))
45
-	}
46
-
47
-	envelope.AppendChild(pkt)
48
-
49
-	return nil
50
-}
51
-
52
-// ModifyDN renames the given DN and optionally move to another base (when the "newSup" argument
53
-// to NewModifyDNRequest() is not "").
54
-func (l *Conn) ModifyDN(m *ModifyDNRequest) error {
55
-	msgCtx, err := l.doRequest(m)
56
-	if err != nil {
57
-		return err
58
-	}
59
-	defer l.finishMessage(msgCtx)
60
-
61
-	packet, err := l.readPacket(msgCtx)
62
-	if err != nil {
63
-		return err
64
-	}
65
-
66
-	if packet.Children[1].Tag == ApplicationModifyDNResponse {
67
-		err := GetLDAPError(packet)
68
-		if err != nil {
69
-			return err
70
-		}
71
-	} else {
72
-		log.Printf("Unexpected Response: %d", packet.Children[1].Tag)
73
-	}
74
-	return nil
75
-}

+ 0
- 132
vendor/github.com/go-ldap/ldap/v3/modify.go View File

@@ -1,132 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"log"
5
-
6
-	ber "github.com/go-asn1-ber/asn1-ber"
7
-)
8
-
9
-// Change operation choices
10
-const (
11
-	AddAttribute       = 0
12
-	DeleteAttribute    = 1
13
-	ReplaceAttribute   = 2
14
-	IncrementAttribute = 3 // (https://tools.ietf.org/html/rfc4525)
15
-)
16
-
17
-// PartialAttribute for a ModifyRequest as defined in https://tools.ietf.org/html/rfc4511
18
-type PartialAttribute struct {
19
-	// Type is the type of the partial attribute
20
-	Type string
21
-	// Vals are the values of the partial attribute
22
-	Vals []string
23
-}
24
-
25
-func (p *PartialAttribute) encode() *ber.Packet {
26
-	seq := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "PartialAttribute")
27
-	seq.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, p.Type, "Type"))
28
-	set := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSet, nil, "AttributeValue")
29
-	for _, value := range p.Vals {
30
-		set.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, value, "Vals"))
31
-	}
32
-	seq.AppendChild(set)
33
-	return seq
34
-}
35
-
36
-// Change for a ModifyRequest as defined in https://tools.ietf.org/html/rfc4511
37
-type Change struct {
38
-	// Operation is the type of change to be made
39
-	Operation uint
40
-	// Modification is the attribute to be modified
41
-	Modification PartialAttribute
42
-}
43
-
44
-func (c *Change) encode() *ber.Packet {
45
-	change := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Change")
46
-	change.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagEnumerated, uint64(c.Operation), "Operation"))
47
-	change.AppendChild(c.Modification.encode())
48
-	return change
49
-}
50
-
51
-// ModifyRequest as defined in https://tools.ietf.org/html/rfc4511
52
-type ModifyRequest struct {
53
-	// DN is the distinguishedName of the directory entry to modify
54
-	DN string
55
-	// Changes contain the attributes to modify
56
-	Changes []Change
57
-	// Controls hold optional controls to send with the request
58
-	Controls []Control
59
-}
60
-
61
-// Add appends the given attribute to the list of changes to be made
62
-func (req *ModifyRequest) Add(attrType string, attrVals []string) {
63
-	req.appendChange(AddAttribute, attrType, attrVals)
64
-}
65
-
66
-// Delete appends the given attribute to the list of changes to be made
67
-func (req *ModifyRequest) Delete(attrType string, attrVals []string) {
68
-	req.appendChange(DeleteAttribute, attrType, attrVals)
69
-}
70
-
71
-// Replace appends the given attribute to the list of changes to be made
72
-func (req *ModifyRequest) Replace(attrType string, attrVals []string) {
73
-	req.appendChange(ReplaceAttribute, attrType, attrVals)
74
-}
75
-
76
-// Increment appends the given attribute to the list of changes to be made
77
-func (req *ModifyRequest) Increment(attrType string, attrVal string) {
78
-	req.appendChange(IncrementAttribute, attrType, []string{attrVal})
79
-}
80
-
81
-func (req *ModifyRequest) appendChange(operation uint, attrType string, attrVals []string) {
82
-	req.Changes = append(req.Changes, Change{operation, PartialAttribute{Type: attrType, Vals: attrVals}})
83
-}
84
-
85
-func (req *ModifyRequest) appendTo(envelope *ber.Packet) error {
86
-	pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationModifyRequest, nil, "Modify Request")
87
-	pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.DN, "DN"))
88
-	changes := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Changes")
89
-	for _, change := range req.Changes {
90
-		changes.AppendChild(change.encode())
91
-	}
92
-	pkt.AppendChild(changes)
93
-
94
-	envelope.AppendChild(pkt)
95
-	if len(req.Controls) > 0 {
96
-		envelope.AppendChild(encodeControls(req.Controls))
97
-	}
98
-
99
-	return nil
100
-}
101
-
102
-// NewModifyRequest creates a modify request for the given DN
103
-func NewModifyRequest(dn string, controls []Control) *ModifyRequest {
104
-	return &ModifyRequest{
105
-		DN:       dn,
106
-		Controls: controls,
107
-	}
108
-}
109
-
110
-// Modify performs the ModifyRequest
111
-func (l *Conn) Modify(modifyRequest *ModifyRequest) error {
112
-	msgCtx, err := l.doRequest(modifyRequest)
113
-	if err != nil {
114
-		return err
115
-	}
116
-	defer l.finishMessage(msgCtx)
117
-
118
-	packet, err := l.readPacket(msgCtx)
119
-	if err != nil {
120
-		return err
121
-	}
122
-
123
-	if packet.Children[1].Tag == ApplicationModifyResponse {
124
-		err := GetLDAPError(packet)
125
-		if err != nil {
126
-			return err
127
-		}
128
-	} else {
129
-		log.Printf("Unexpected Response: %d", packet.Children[1].Tag)
130
-	}
131
-	return nil
132
-}

+ 0
- 126
vendor/github.com/go-ldap/ldap/v3/passwdmodify.go View File

@@ -1,126 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"fmt"
5
-
6
-	ber "github.com/go-asn1-ber/asn1-ber"
7
-)
8
-
9
-const (
10
-	passwordModifyOID = "1.3.6.1.4.1.4203.1.11.1"
11
-)
12
-
13
-// PasswordModifyRequest implements the Password Modify Extended Operation as defined in https://www.ietf.org/rfc/rfc3062.txt
14
-type PasswordModifyRequest struct {
15
-	// UserIdentity is an optional string representation of the user associated with the request.
16
-	// This string may or may not be an LDAPDN [RFC2253].
17
-	// If no UserIdentity field is present, the request acts up upon the password of the user currently associated with the LDAP session
18
-	UserIdentity string
19
-	// OldPassword, if present, contains the user's current password
20
-	OldPassword string
21
-	// NewPassword, if present, contains the desired password for this user
22
-	NewPassword string
23
-}
24
-
25
-// PasswordModifyResult holds the server response to a PasswordModifyRequest
26
-type PasswordModifyResult struct {
27
-	// GeneratedPassword holds a password generated by the server, if present
28
-	GeneratedPassword string
29
-	// Referral are the returned referral
30
-	Referral string
31
-}
32
-
33
-func (req *PasswordModifyRequest) appendTo(envelope *ber.Packet) error {
34
-	pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationExtendedRequest, nil, "Password Modify Extended Operation")
35
-	pkt.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, passwordModifyOID, "Extended Request Name: Password Modify OID"))
36
-
37
-	extendedRequestValue := ber.Encode(ber.ClassContext, ber.TypePrimitive, 1, nil, "Extended Request Value: Password Modify Request")
38
-	passwordModifyRequestValue := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Password Modify Request")
39
-	if req.UserIdentity != "" {
40
-		passwordModifyRequestValue.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 0, req.UserIdentity, "User Identity"))
41
-	}
42
-	if req.OldPassword != "" {
43
-		passwordModifyRequestValue.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 1, req.OldPassword, "Old Password"))
44
-	}
45
-	if req.NewPassword != "" {
46
-		passwordModifyRequestValue.AppendChild(ber.NewString(ber.ClassContext, ber.TypePrimitive, 2, req.NewPassword, "New Password"))
47
-	}
48
-	extendedRequestValue.AppendChild(passwordModifyRequestValue)
49
-
50
-	pkt.AppendChild(extendedRequestValue)
51
-
52
-	envelope.AppendChild(pkt)
53
-
54
-	return nil
55
-}
56
-
57
-// NewPasswordModifyRequest creates a new PasswordModifyRequest
58
-//
59
-// According to the RFC 3602 (https://tools.ietf.org/html/rfc3062):
60
-// userIdentity is a string representing the user associated with the request.
61
-// This string may or may not be an LDAPDN (RFC 2253).
62
-// If userIdentity is empty then the operation will act on the user associated
63
-// with the session.
64
-//
65
-// oldPassword is the current user's password, it can be empty or it can be
66
-// needed depending on the session user access rights (usually an administrator
67
-// can change a user's password without knowing the current one) and the
68
-// password policy (see pwdSafeModify password policy's attribute)
69
-//
70
-// newPassword is the desired user's password. If empty the server can return
71
-// an error or generate a new password that will be available in the
72
-// PasswordModifyResult.GeneratedPassword
73
-//
74
-func NewPasswordModifyRequest(userIdentity string, oldPassword string, newPassword string) *PasswordModifyRequest {
75
-	return &PasswordModifyRequest{
76
-		UserIdentity: userIdentity,
77
-		OldPassword:  oldPassword,
78
-		NewPassword:  newPassword,
79
-	}
80
-}
81
-
82
-// PasswordModify performs the modification request
83
-func (l *Conn) PasswordModify(passwordModifyRequest *PasswordModifyRequest) (*PasswordModifyResult, error) {
84
-	msgCtx, err := l.doRequest(passwordModifyRequest)
85
-	if err != nil {
86
-		return nil, err
87
-	}
88
-	defer l.finishMessage(msgCtx)
89
-
90
-	packet, err := l.readPacket(msgCtx)
91
-	if err != nil {
92
-		return nil, err
93
-	}
94
-
95
-	result := &PasswordModifyResult{}
96
-
97
-	if packet.Children[1].Tag == ApplicationExtendedResponse {
98
-		err := GetLDAPError(packet)
99
-		if err != nil {
100
-			if IsErrorWithCode(err, LDAPResultReferral) {
101
-				for _, child := range packet.Children[1].Children {
102
-					if child.Tag == 3 {
103
-						result.Referral = child.Children[0].Value.(string)
104
-					}
105
-				}
106
-			}
107
-			return result, err
108
-		}
109
-	} else {
110
-		return nil, NewError(ErrorUnexpectedResponse, fmt.Errorf("unexpected Response: %d", packet.Children[1].Tag))
111
-	}
112
-
113
-	extendedResponse := packet.Children[1]
114
-	for _, child := range extendedResponse.Children {
115
-		if child.Tag == 11 {
116
-			passwordModifyResponseValue := ber.DecodePacket(child.Data.Bytes())
117
-			if len(passwordModifyResponseValue.Children) == 1 {
118
-				if passwordModifyResponseValue.Children[0].Tag == 0 {
119
-					result.GeneratedPassword = ber.DecodeString(passwordModifyResponseValue.Children[0].Data.Bytes())
120
-				}
121
-			}
122
-		}
123
-	}
124
-
125
-	return result, nil
126
-}

+ 0
- 66
vendor/github.com/go-ldap/ldap/v3/request.go View File

@@ -1,66 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"errors"
5
-
6
-	ber "github.com/go-asn1-ber/asn1-ber"
7
-)
8
-
9
-var (
10
-	errRespChanClosed = errors.New("ldap: response channel closed")
11
-	errCouldNotRetMsg = errors.New("ldap: could not retrieve message")
12
-)
13
-
14
-type request interface {
15
-	appendTo(*ber.Packet) error
16
-}
17
-
18
-type requestFunc func(*ber.Packet) error
19
-
20
-func (f requestFunc) appendTo(p *ber.Packet) error {
21
-	return f(p)
22
-}
23
-
24
-func (l *Conn) doRequest(req request) (*messageContext, error) {
25
-	packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request")
26
-	packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, l.nextMessageID(), "MessageID"))
27
-	if err := req.appendTo(packet); err != nil {
28
-		return nil, err
29
-	}
30
-
31
-	if l.Debug {
32
-		l.Debug.PrintPacket(packet)
33
-	}
34
-
35
-	msgCtx, err := l.sendMessage(packet)
36
-	if err != nil {
37
-		return nil, err
38
-	}
39
-	l.Debug.Printf("%d: returning", msgCtx.id)
40
-	return msgCtx, nil
41
-}
42
-
43
-func (l *Conn) readPacket(msgCtx *messageContext) (*ber.Packet, error) {
44
-	l.Debug.Printf("%d: waiting for response", msgCtx.id)
45
-	packetResponse, ok := <-msgCtx.responses
46
-	if !ok {
47
-		return nil, NewError(ErrorNetwork, errRespChanClosed)
48
-	}
49
-	packet, err := packetResponse.ReadPacket()
50
-	l.Debug.Printf("%d: got response %p", msgCtx.id, packet)
51
-	if err != nil {
52
-		return nil, err
53
-	}
54
-
55
-	if packet == nil {
56
-		return nil, NewError(ErrorNetwork, errCouldNotRetMsg)
57
-	}
58
-
59
-	if l.Debug {
60
-		if err = addLDAPDescriptions(packet); err != nil {
61
-			return nil, err
62
-		}
63
-		l.Debug.PrintPacket(packet)
64
-	}
65
-	return packet, nil
66
-}

+ 0
- 370
vendor/github.com/go-ldap/ldap/v3/search.go View File

@@ -1,370 +0,0 @@
1
-package ldap
2
-
3
-import (
4
-	"errors"
5
-	"fmt"
6
-	"sort"
7
-	"strings"
8
-
9
-	ber "github.com/go-asn1-ber/asn1-ber"
10
-)
11
-
12
-// scope choices
13
-const (
14
-	ScopeBaseObject   = 0
15
-	ScopeSingleLevel  = 1
16
-	ScopeWholeSubtree = 2
17
-)
18
-
19
-// ScopeMap contains human readable descriptions of scope choices
20
-var ScopeMap = map[int]string{
21
-	ScopeBaseObject:   "Base Object",
22
-	ScopeSingleLevel:  "Single Level",
23
-	ScopeWholeSubtree: "Whole Subtree",
24
-}
25
-
26
-// derefAliases
27
-const (
28
-	NeverDerefAliases   = 0
29
-	DerefInSearching    = 1
30
-	DerefFindingBaseObj = 2
31
-	DerefAlways         = 3
32
-)
33
-
34
-// DerefMap contains human readable descriptions of derefAliases choices
35
-var DerefMap = map[int]string{
36
-	NeverDerefAliases:   "NeverDerefAliases",
37
-	DerefInSearching:    "DerefInSearching",
38
-	DerefFindingBaseObj: "DerefFindingBaseObj",
39
-	DerefAlways:         "DerefAlways",
40
-}
41
-
42
-// NewEntry returns an Entry object with the specified distinguished name and attribute key-value pairs.
43
-// The map of attributes is accessed in alphabetical order of the keys in order to ensure that, for the
44
-// same input map of attributes, the output entry will contain the same order of attributes
45
-func NewEntry(dn string, attributes map[string][]string) *Entry {
46
-	var attributeNames []string
47
-	for attributeName := range attributes {
48
-		attributeNames = append(attributeNames, attributeName)
49
-	}
50
-	sort.Strings(attributeNames)
51
-
52
-	var encodedAttributes []*EntryAttribute
53
-	for _, attributeName := range attributeNames {
54
-		encodedAttributes = append(encodedAttributes, NewEntryAttribute(attributeName, attributes[attributeName]))
55
-	}
56
-	return &Entry{
57
-		DN:         dn,
58
-		Attributes: encodedAttributes,
59
-	}
60
-}
61
-
62
-// Entry represents a single search result entry
63
-type Entry struct {
64
-	// DN is the distinguished name of the entry
65
-	DN string
66
-	// Attributes are the returned attributes for the entry
67
-	Attributes []*EntryAttribute
68
-}
69
-
70
-// GetAttributeValues returns the values for the named attribute, or an empty list
71
-func (e *Entry) GetAttributeValues(attribute string) []string {
72
-	for _, attr := range e.Attributes {
73
-		if attr.Name == attribute {
74
-			return attr.Values
75
-		}
76
-	}
77
-	return []string{}
78
-}
79
-
80
-// GetRawAttributeValues returns the byte values for the named attribute, or an empty list
81
-func (e *Entry) GetRawAttributeValues(attribute string) [][]byte {
82
-	for _, attr := range e.Attributes {
83
-		if attr.Name == attribute {
84
-			return attr.ByteValues
85
-		}
86
-	}
87
-	return [][]byte{}
88
-}
89
-
90
-// GetAttributeValue returns the first value for the named attribute, or ""
91
-func (e *Entry) GetAttributeValue(attribute string) string {
92
-	values := e.GetAttributeValues(attribute)
93
-	if len(values) == 0 {
94
-		return ""
95
-	}
96
-	return values[0]
97
-}
98
-
99
-// GetRawAttributeValue returns the first value for the named attribute, or an empty slice
100
-func (e *Entry) GetRawAttributeValue(attribute string) []byte {
101
-	values := e.GetRawAttributeValues(attribute)
102
-	if len(values) == 0 {
103
-		return []byte{}
104
-	}
105
-	return values[0]
106
-}
107
-
108
-// Print outputs a human-readable description
109
-func (e *Entry) Print() {
110
-	fmt.Printf("DN: %s\n", e.DN)
111
-	for _, attr := range e.Attributes {
112
-		attr.Print()
113
-	}
114
-}
115
-
116
-// PrettyPrint outputs a human-readable description indenting
117
-func (e *Entry) PrettyPrint(indent int) {
118
-	fmt.Printf("%sDN: %s\n", strings.Repeat(" ", indent), e.DN)
119
-	for _, attr := range e.Attributes {
120
-		attr.PrettyPrint(indent + 2)
121
-	}
122
-}
123
-
124
-// NewEntryAttribute returns a new EntryAttribute with the desired key-value pair
125
-func NewEntryAttribute(name string, values []string) *EntryAttribute {
126
-	var bytes [][]byte
127
-	for _, value := range values {
128
-		bytes = append(bytes, []byte(value))
129
-	}
130
-	return &EntryAttribute{
131
-		Name:       name,
132
-		Values:     values,
133
-		ByteValues: bytes,
134
-	}
135
-}
136
-
137
-// EntryAttribute holds a single attribute
138
-type EntryAttribute struct {
139
-	// Name is the name of the attribute
140
-	Name string
141
-	// Values contain the string values of the attribute
142
-	Values []string
143
-	// ByteValues contain the raw values of the attribute
144
-	ByteValues [][]byte
145
-}
146
-
147
-// Print outputs a human-readable description
148
-func (e *EntryAttribute) Print() {
149
-	fmt.Printf("%s: %s\n", e.Name, e.Values)
150
-}
151
-
152
-// PrettyPrint outputs a human-readable description with indenting
153
-func (e *EntryAttribute) PrettyPrint(indent int) {
154
-	fmt.Printf("%s%s: %s\n", strings.Repeat(" ", indent), e.Name, e.Values)
155
-}
156
-
157
-// SearchResult holds the server's response to a search request
158
-type SearchResult struct {
159
-	// Entries are the returned entries
160
-	Entries []*Entry
161
-	// Referrals are the returned referrals
162
-	Referrals []string
163
-	// Controls are the returned controls
164
-	Controls []Control
165
-}
166
-
167
-// Print outputs a human-readable description
168
-func (s *SearchResult) Print() {
169
-	for _, entry := range s.Entries {
170
-		entry.Print()
171
-	}
172
-}
173
-
174
-// PrettyPrint outputs a human-readable description with indenting
175
-func (s *SearchResult) PrettyPrint(indent int) {
176
-	for _, entry := range s.Entries {
177
-		entry.PrettyPrint(indent)
178
-	}
179
-}
180
-
181
-// SearchRequest represents a search request to send to the server
182
-type SearchRequest struct {
183
-	BaseDN       string
184
-	Scope        int
185
-	DerefAliases int
186
-	SizeLimit    int
187
-	TimeLimit    int
188
-	TypesOnly    bool
189
-	Filter       string
190
-	Attributes   []string
191
-	Controls     []Control
192
-}
193
-
194
-func (req *SearchRequest) appendTo(envelope *ber.Packet) error {
195
-	pkt := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationSearchRequest, nil, "Search Request")
196
-	pkt.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, req.BaseDN, "Base DN"))
197
-	pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagEnumerated, uint64(req.Scope), "Scope"))
198
-	pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagEnumerated, uint64(req.DerefAliases), "Deref Aliases"))
199
-	pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, uint64(req.SizeLimit), "Size Limit"))
200
-	pkt.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, uint64(req.TimeLimit), "Time Limit"))
201
-	pkt.AppendChild(ber.NewBoolean(ber.ClassUniversal, ber.TypePrimitive, ber.TagBoolean, req.TypesOnly, "Types Only"))
202
-	// compile and encode filter
203
-	filterPacket, err := CompileFilter(req.Filter)
204
-	if err != nil {
205
-		return err
206
-	}
207
-	pkt.AppendChild(filterPacket)
208
-	// encode attributes
209
-	attributesPacket := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "Attributes")
210
-	for _, attribute := range req.Attributes {
211
-		attributesPacket.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, attribute, "Attribute"))
212
-	}
213
-	pkt.AppendChild(attributesPacket)
214
-
215
-	envelope.AppendChild(pkt)
216
-	if len(req.Controls) > 0 {
217
-		envelope.AppendChild(encodeControls(req.Controls))
218
-	}
219
-
220
-	return nil
221
-}
222
-
223
-// NewSearchRequest creates a new search request
224
-func NewSearchRequest(
225
-	BaseDN string,
226
-	Scope, DerefAliases, SizeLimit, TimeLimit int,
227
-	TypesOnly bool,
228
-	Filter string,
229
-	Attributes []string,
230
-	Controls []Control,
231
-) *SearchRequest {
232
-	return &SearchRequest{
233
-		BaseDN:       BaseDN,
234
-		Scope:        Scope,
235
-		DerefAliases: DerefAliases,
236
-		SizeLimit:    SizeLimit,
237
-		TimeLimit:    TimeLimit,
238
-		TypesOnly:    TypesOnly,
239
-		Filter:       Filter,
240
-		Attributes:   Attributes,
241
-		Controls:     Controls,
242
-	}
243
-}
244
-
245
-// SearchWithPaging accepts a search request and desired page size in order to execute LDAP queries to fulfill the
246
-// search request. All paged LDAP query responses will be buffered and the final result will be returned atomically.
247
-// The following four cases are possible given the arguments:
248
-//  - given SearchRequest missing a control of type ControlTypePaging: we will add one with the desired paging size
249
-//  - given SearchRequest contains a control of type ControlTypePaging that isn't actually a ControlPaging: fail without issuing any queries
250
-//  - given SearchRequest contains a control of type ControlTypePaging with pagingSize equal to the size requested: no change to the search request
251
-//  - given SearchRequest contains a control of type ControlTypePaging with pagingSize not equal to the size requested: fail without issuing any queries
252
-// A requested pagingSize of 0 is interpreted as no limit by LDAP servers.
253
-func (l *Conn) SearchWithPaging(searchRequest *SearchRequest, pagingSize uint32) (*SearchResult, error) {
254
-	var pagingControl *ControlPaging
255
-
256
-	control := FindControl(searchRequest.Controls, ControlTypePaging)
257
-	if control == nil {
258
-		pagingControl = NewControlPaging(pagingSize)
259
-		searchRequest.Controls = append(searchRequest.Controls, pagingControl)
260
-	} else {
261
-		castControl, ok := control.(*ControlPaging)
262
-		if !ok {
263
-			return nil, fmt.Errorf("expected paging control to be of type *ControlPaging, got %v", control)
264
-		}
265
-		if castControl.PagingSize != pagingSize {
266
-			return nil, fmt.Errorf("paging size given in search request (%d) conflicts with size given in search call (%d)", castControl.PagingSize, pagingSize)
267
-		}
268
-		pagingControl = castControl
269
-	}
270
-
271
-	searchResult := new(SearchResult)
272
-	for {
273
-		result, err := l.Search(searchRequest)
274
-		l.Debug.Printf("Looking for Paging Control...")
275
-		if err != nil {
276
-			return searchResult, err
277
-		}
278
-		if result == nil {
279
-			return searchResult, NewError(ErrorNetwork, errors.New("ldap: packet not received"))
280
-		}
281
-
282
-		for _, entry := range result.Entries {
283
-			searchResult.Entries = append(searchResult.Entries, entry)
284
-		}
285
-		for _, referral := range result.Referrals {
286
-			searchResult.Referrals = append(searchResult.Referrals, referral)
287
-		}
288
-		for _, control := range result.Controls {
289
-			searchResult.Controls = append(searchResult.Controls, control)
290
-		}
291
-
292
-		l.Debug.Printf("Looking for Paging Control...")
293
-		pagingResult := FindControl(result.Controls, ControlTypePaging)
294
-		if pagingResult == nil {
295
-			pagingControl = nil
296
-			l.Debug.Printf("Could not find paging control.  Breaking...")
297
-			break
298
-		}
299
-
300
-		cookie := pagingResult.(*ControlPaging).Cookie
301
-		if len(cookie) == 0 {
302
-			pagingControl = nil
303
-			l.Debug.Printf("Could not find cookie.  Breaking...")
304
-			break
305
-		}
306
-		pagingControl.SetCookie(cookie)
307
-	}
308
-
309
-	if pagingControl != nil {
310
-		l.Debug.Printf("Abandoning Paging...")
311
-		pagingControl.PagingSize = 0
312
-		l.Search(searchRequest)
313
-	}
314
-
315
-	return searchResult, nil
316
-}
317
-
318
-// Search performs the given search request
319
-func (l *Conn) Search(searchRequest *SearchRequest) (*SearchResult, error) {
320
-	msgCtx, err := l.doRequest(searchRequest)
321
-	if err != nil {
322
-		return nil, err
323
-	}
324
-	defer l.finishMessage(msgCtx)
325
-
326
-	result := &SearchResult{
327
-		Entries:   make([]*Entry, 0),
328
-		Referrals: make([]string, 0),
329
-		Controls:  make([]Control, 0)}
330
-
331
-	for {
332
-		packet, err := l.readPacket(msgCtx)
333
-		if err != nil {
334
-			return nil, err
335
-		}
336
-
337
-		switch packet.Children[1].Tag {
338
-		case 4:
339
-			entry := new(Entry)
340
-			entry.DN = packet.Children[1].Children[0].Value.(string)
341
-			for _, child := range packet.Children[1].Children[1].Children {
342
-				attr := new(EntryAttribute)
343
-				attr.Name = child.Children[0].Value.(string)
344
-				for _, value := range child.Children[1].Children {
345
-					attr.Values = append(attr.Values, value.Value.(string))
346
-					attr.ByteValues = append(attr.ByteValues, value.ByteValue)
347
-				}
348
-				entry.Attributes = append(entry.Attributes, attr)
349
-			}
350
-			result.Entries = append(result.Entries, entry)
351
-		case 5:
352
-			err := GetLDAPError(packet)
353
-			if err != nil {
354
-				return nil, err
355
-			}
356
-			if len(packet.Children) == 3 {
357
-				for _, child := range packet.Children[2].Children {
358
-					decodedChild, err := DecodeControl(child)
359
-					if err != nil {
360
-						return nil, fmt.Errorf("failed to decode child control: %s", err)
361
-					}
362
-					result.Controls = append(result.Controls, decodedChild)
363
-				}
364
-			}
365
-			return result, nil
366
-		case 19:
367
-			result.Referrals = append(result.Referrals, packet.Children[1].Children[0].Value.(string))
368
-		}
369
-	}
370
-}

+ 0
- 5
vendor/modules.txt View File

@@ -7,11 +7,6 @@ github.com/dgrijalva/jwt-go
7 7
 # github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815
8 8
 ## explicit
9 9
 github.com/docopt/docopt-go
10
-# github.com/go-asn1-ber/asn1-ber v1.3.1
11
-github.com/go-asn1-ber/asn1-ber
12
-# github.com/go-ldap/ldap/v3 v3.1.10
13
-## explicit
14
-github.com/go-ldap/ldap/v3
15 10
 # github.com/go-sql-driver/mysql v1.5.0
16 11
 ## explicit
17 12
 github.com/go-sql-driver/mysql

Loading…
Cancel
Save