forked from LeakIX/ntlmssp
/
client.go
299 lines (239 loc) · 6.33 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package http
import (
"bytes"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/textproto"
"net/url"
"strings"
"github.com/PIngBZ/ntlmssp"
"github.com/hashicorp/go-cleanhttp"
"github.com/go-logr/logr"
)
var (
httpAuthenticateHeader = textproto.CanonicalMIMEHeaderKey("WWW-Authenticate")
)
type Client struct {
http *http.Client
ntlm *ntlmssp.Client
encryption bool
sendCBT bool
logger logr.Logger
}
type teeReadCloser struct {
io.Reader
io.Closer
}
func NewClient(httpClient *http.Client, ntlmClient *ntlmssp.Client, options ...func(*Client) error) (*Client, error) {
if httpClient == nil {
httpClient = cleanhttp.DefaultClient()
}
if httpClient.Jar == nil {
httpClient.Jar, _ = cookiejar.New(nil)
}
if httpClient.Transport != nil && httpClient.Transport.(*http.Transport).DisableKeepAlives {
return nil, errors.New("NTLM cannot work without keepalives")
}
// FIXME CheckRedirect
if ntlmClient == nil {
domain, err := ntlmssp.DefaultDomain()
if err != nil {
return nil, err
}
workstation, err := ntlmssp.DefaultWorkstation()
if err != nil {
return nil, err
}
ntlmClient, _ = ntlmssp.NewClient(ntlmssp.SetDomain(domain), ntlmssp.SetWorkstation(workstation), ntlmssp.SetVersion(ntlmssp.DefaultVersion()))
}
c := &Client{
http: httpClient,
ntlm: ntlmClient,
logger: logr.Discard(),
}
if err := c.SetOption(options...); err != nil {
return nil, err
}
return c, nil
}
func (c *Client) SetOption(options ...func(*Client) error) error {
for _, option := range options {
if err := option(c); err != nil {
return err
}
}
return nil
}
func SendCBT(value bool) func(*Client) error {
return func(c *Client) error {
c.sendCBT = value
return nil
}
}
func Encryption(value bool) func(*Client) error {
return func(c *Client) error {
c.encryption = value
return nil
}
}
func Logger(logger logr.Logger) func(*Client) error {
return func(c *Client) error {
c.logger = logger
return nil
}
}
func (c *Client) wrap(req *http.Request) error {
if session := c.ntlm.SecuritySession(); c.ntlm.Complete() && c.encryption && session != nil && req.Body != nil {
contentType := req.Header.Get(contentTypeHeader)
if contentType == "" {
return errors.New("no Content-Type header")
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return err
}
sealed, signature, err := session.Wrap(body)
if err != nil {
return err
}
length := make([]byte, 4)
binary.LittleEndian.PutUint32(length, uint32(len(signature)))
body, newContentType, err := Wrap(concat(length, signature, sealed), contentType)
if err != nil {
return err
}
req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
req.Header.Set(contentTypeHeader, newContentType)
}
return nil
}
func (c *Client) unwrap(resp *http.Response) error {
if session := c.ntlm.SecuritySession(); c.ntlm.Complete() && c.encryption && session != nil && resp.Body != nil {
contentType := resp.Header.Get(contentTypeHeader)
if contentType == "" {
return errors.New("no Content-Type header")
}
sealed, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
defer resp.Body.Close()
data, newContentType, err := Unwrap(sealed, contentType)
if err != nil {
return err
}
length := binary.LittleEndian.Uint32(data[:4])
signature := make([]byte, length)
copy(signature, data[4:4+length])
body, err := session.Unwrap(data[4+length:], signature)
if err != nil {
return err
}
resp.Body = ioutil.NopCloser(bytes.NewBuffer(body))
resp.Header.Set(contentTypeHeader, newContentType)
resp.Header.Set("Content-Length", fmt.Sprint(len(body)))
}
return nil
}
func (c *Client) Do(req *http.Request) (resp *http.Response, err error) {
// Potentially replace the request body with a signed and sealed copy
if err := c.wrap(req); err != nil {
return nil, err
}
var body bytes.Buffer
if req.Body != nil {
tr := io.TeeReader(req.Body, &body)
req.Body = teeReadCloser{tr, req.Body}
}
c.logger.Info("request", req)
resp, err = c.http.Do(req)
if err != nil {
return nil, err
}
if c.ntlm.Complete() || resp.StatusCode != http.StatusUnauthorized {
// Potentially unseal and check signature
if err := c.unwrap(resp); err != nil {
return nil, err
}
return resp, nil
}
for i := 0; i < 2; i++ {
ok, input, err := isAuthenticationMethod(resp.Header, "Negotiate")
if err != nil {
return nil, err
}
if !ok {
return resp, nil
}
var cbt *ntlmssp.ChannelBindings
if c.sendCBT && resp.TLS != nil {
cbt = generateChannelBindings(resp.TLS.PeerCertificates[0]) // Presume it's the first one?
}
b, err := c.ntlm.Authenticate(input, cbt)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Negotiate "+base64.StdEncoding.EncodeToString(b))
if req.Body != nil {
req.Body = ioutil.NopCloser(&body)
}
c.logger.Info("request", req)
resp, err = c.http.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusUnauthorized {
return resp, nil
}
}
return resp, nil
}
func isAuthenticationMethod(headers http.Header, method string) (bool, []byte, error) {
if h, ok := headers[httpAuthenticateHeader]; ok {
for _, x := range h {
if x == method {
return true, nil, nil
}
if strings.HasPrefix(x, method+" ") {
parts := strings.SplitN(x, " ", 2)
if len(parts) < 2 {
return true, nil, errors.New("malformed " + method + " header value")
}
b, err := base64.StdEncoding.DecodeString(parts[1])
return true, b, err
}
}
}
return false, nil, nil
}
func (c *Client) Get(url string) (resp *http.Response, err error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
func (c *Client) Head(url string) (resp *http.Response, err error) {
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
func (c *Client) Post(url, contentType string, body io.Reader) (resp *http.Response, err error) {
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentType)
return c.Do(req)
}
func (c *Client) PostForm(url string, data url.Values) (resp *http.Response, err error) {
return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}