|
| 1 | +/* |
| 2 | + * The MIT License (MIT) |
| 3 | + * |
| 4 | + * Copyright (c) 2018 Tamás Gulácsi |
| 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. |
| 23 | + */ |
| 24 | + |
| 25 | +package ldap |
| 26 | + |
| 27 | +import ( |
| 28 | + "crypto/tls" |
| 29 | + "errors" |
| 30 | + "fmt" |
| 31 | + "net" |
| 32 | + "net/http" |
| 33 | + "strings" |
| 34 | + "time" |
| 35 | + |
| 36 | + "github.com/freman/caddy2-reauth/backends" |
| 37 | + "github.com/freman/caddy2-reauth/jsontypes" |
| 38 | + |
| 39 | + ldp "github.com/go-ldap/ldap/v3" |
| 40 | +) |
| 41 | + |
| 42 | +// Interface guard |
| 43 | +var _ backends.Driver = (*LDAP)(nil) |
| 44 | + |
| 45 | +// BackendName name |
| 46 | +const BackendName = "ldap" |
| 47 | + |
| 48 | +const defaultPoolSize = 10 |
| 49 | +const defaultTimeout = time.Minute |
| 50 | +const defaultFilter = "(&(objectClass=user)(sAMAccountName=%s))" |
| 51 | + |
| 52 | +// LDAP backend provides authentication against LDAP paths, for example for Microsoft AD. |
| 53 | +type LDAP struct { |
| 54 | + URL *jsontypes.URL `json:"url,omitempty"` |
| 55 | + BaseDN string `json:"base_dn,omitempty"` |
| 56 | + FilterDN string `json:"filter_dn,omitempty"` |
| 57 | + PrincipalSuffix string `json:"principal_suffix,omitempty"` |
| 58 | + BindDN string `json:"bind_dn,omitempty"` |
| 59 | + BindPassword string `json:"bind_password,omitempty"` |
| 60 | + TLS bool `json:"tls,omitempty"` |
| 61 | + InsecureSkipVerify bool `json:"insecure_skip_verify,omitempty"` |
| 62 | + Timeout jsontypes.Duration `json:"timeout,omitempty"` |
| 63 | + ConnectionPoolSize int `json:"connection_pool_size,omitempty"` |
| 64 | + |
| 65 | + pool chan ldp.Client |
| 66 | +} |
| 67 | + |
| 68 | +// NewDriver returns a LDAP instance with some defaults |
| 69 | +func NewDriver() *LDAP { |
| 70 | + return &LDAP{ |
| 71 | + Timeout: jsontypes.Duration{Duration: defaultTimeout}, |
| 72 | + ConnectionPoolSize: defaultPoolSize, |
| 73 | + FilterDN: defaultFilter, |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +// Validate that this module is ready to go |
| 78 | +func (h *LDAP) Validate() error { |
| 79 | + var missing []string |
| 80 | + if h.URL == nil { |
| 81 | + missing = append(missing, "URL") |
| 82 | + } |
| 83 | + |
| 84 | + if h.BindDN == "" { |
| 85 | + missing = append(missing, "BindDN") |
| 86 | + } |
| 87 | + |
| 88 | + if h.BindPassword == "" { |
| 89 | + missing = append(missing, "BindPassword") |
| 90 | + } |
| 91 | + |
| 92 | + if h.BaseDN == "" { |
| 93 | + missing = append(missing, "BaseDN") |
| 94 | + } |
| 95 | + |
| 96 | + if n := len(missing); n > 0 { |
| 97 | + var s string |
| 98 | + if n > 1 { |
| 99 | + s = "s" |
| 100 | + } |
| 101 | + return errors.New("missing the following required parameter" + s + ": " + strings.Join(missing, ", ")) |
| 102 | + } |
| 103 | + |
| 104 | + if h.Timeout.Duration <= 0 { |
| 105 | + return errors.New("timeout must be greater than 0") |
| 106 | + } |
| 107 | + |
| 108 | + if h.ConnectionPoolSize <= 0 { |
| 109 | + return errors.New("connection pool size must be greater than 0") |
| 110 | + } |
| 111 | + |
| 112 | + h.pool = make(chan ldp.Client, h.ConnectionPoolSize) |
| 113 | + |
| 114 | + c, err := h.getConnection() |
| 115 | + if err != nil { |
| 116 | + return err |
| 117 | + } |
| 118 | + h.stashConnection(c) |
| 119 | + |
| 120 | + return nil |
| 121 | +} |
| 122 | + |
| 123 | +// Authenticate fulfils the backend interface |
| 124 | +func (h *LDAP) Authenticate(r *http.Request) (string, error) { |
| 125 | + un, pw, k := r.BasicAuth() |
| 126 | + if !k { |
| 127 | + return "", nil |
| 128 | + } |
| 129 | + |
| 130 | + c, err := h.getConnection() |
| 131 | + if err != nil { |
| 132 | + return "", err |
| 133 | + } |
| 134 | + defer h.stashConnection(c) |
| 135 | + |
| 136 | + // Search for the given username |
| 137 | + searchRequest := ldp.NewSearchRequest( |
| 138 | + h.BaseDN, |
| 139 | + ldp.ScopeWholeSubtree, ldp.NeverDerefAliases, 0, int(h.Timeout.Duration/time.Second), false, |
| 140 | + fmt.Sprintf(h.FilterDN, un+h.PrincipalSuffix), |
| 141 | + []string{"dn"}, |
| 142 | + nil, |
| 143 | + ) |
| 144 | + |
| 145 | + sr, err := c.Search(searchRequest) |
| 146 | + if err != nil { |
| 147 | + return "", fmt.Errorf("search under %q for %q: %v", h.BaseDN, fmt.Sprintf(h.FilterDN, un+h.PrincipalSuffix), err) |
| 148 | + } |
| 149 | + |
| 150 | + if len(sr.Entries) == 0 { |
| 151 | + return "", nil |
| 152 | + } |
| 153 | + |
| 154 | + if len(sr.Entries) > 1 { |
| 155 | + return "", errors.New("too many entries returned") |
| 156 | + } |
| 157 | + |
| 158 | + userDN := sr.Entries[0].DN |
| 159 | + |
| 160 | + // Bind as the user to verify their password |
| 161 | + err = c.Bind(userDN, pw) |
| 162 | + if err != nil { |
| 163 | + if ldp.IsErrorWithCode(err, ldp.LDAPResultInvalidCredentials) { |
| 164 | + return "", nil |
| 165 | + } |
| 166 | + return "", fmt.Errorf("bind with %q: %v", userDN, err) |
| 167 | + } |
| 168 | + |
| 169 | + return userDN, nil |
| 170 | +} |
| 171 | + |
| 172 | +func (h *LDAP) getConnection() (ldp.Client, error) { |
| 173 | + var c ldp.Client |
| 174 | + select { |
| 175 | + case c = <-h.pool: |
| 176 | + if err := c.Bind(h.BindDN, h.BindPassword); err == nil { |
| 177 | + return c, nil |
| 178 | + } |
| 179 | + c.Close() |
| 180 | + default: |
| 181 | + } |
| 182 | + |
| 183 | + host, port, _ := net.SplitHostPort(h.URL.Host) |
| 184 | + |
| 185 | + ldaps := port == "636" || port == "3269" || h.URL.Scheme == "ldaps" |
| 186 | + if h.URL.Scheme == "ldap" { |
| 187 | + ldaps = false |
| 188 | + } |
| 189 | + if port == "" || port == "0" { |
| 190 | + port = "389" |
| 191 | + if ldaps { |
| 192 | + port = "636" |
| 193 | + } |
| 194 | + } |
| 195 | + |
| 196 | + hostPort := fmt.Sprintf("%s:%s", host, port) |
| 197 | + |
| 198 | + var err error |
| 199 | + if ldaps { |
| 200 | + c, err = ldp.DialTLS("tcp", hostPort, &tls.Config{InsecureSkipVerify: h.InsecureSkipVerify}) |
| 201 | + } else { |
| 202 | + c, err = ldp.Dial("tcp", hostPort) |
| 203 | + } |
| 204 | + |
| 205 | + if err != nil { |
| 206 | + return nil, fmt.Errorf("connect to %q: %v", hostPort, err) |
| 207 | + } |
| 208 | + |
| 209 | + // Technically it's not impossible to run tls over ssl... just excessive |
| 210 | + if h.TLS { |
| 211 | + if err = c.StartTLS(&tls.Config{InsecureSkipVerify: h.InsecureSkipVerify}); err != nil { |
| 212 | + c.Close() |
| 213 | + return nil, fmt.Errorf("StartTLS: %v", err) |
| 214 | + } |
| 215 | + } |
| 216 | + |
| 217 | + if err := c.Bind(h.BindDN, h.BindPassword); err != nil { |
| 218 | + c.Close() |
| 219 | + return nil, fmt.Errorf("bind with %q: %v", h.BindDN, err) |
| 220 | + } |
| 221 | + |
| 222 | + return c, nil |
| 223 | +} |
| 224 | + |
| 225 | +func (h *LDAP) stashConnection(c ldp.Client) { |
| 226 | + select { |
| 227 | + case h.pool <- c: |
| 228 | + return |
| 229 | + default: |
| 230 | + c.Close() |
| 231 | + return |
| 232 | + } |
| 233 | +} |
0 commit comments