~ubuntu-branches/ubuntu/trusty/cntlm/trusty

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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*
 * CNTLM is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * CNTLM is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
 * St, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * Copyright (c) 2007 David Kubicek
 *
 */

#include <sys/types.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <syslog.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>

extern int h_errno;

#include "utils.h"
#include "globals.h"
#include "auth.h"
#include "http.h"
#include "socket.h"
#include "ntlm.h"
#include "direct.h"
#include "pages.h"

int host_connect(const char *hostname, int port) {
	struct in_addr addr;

	errno = 0;
	if (!so_resolv(&addr, hostname)) {
		//if (debug)
		//	printf("so_resolv: %s failed (%d: %s)\n", hostname, h_errno, hstrerror(h_errno));
		return -1;
	}

	return so_connect(addr, port);

}

int www_authenticate(int sd, rr_data_t request, rr_data_t response, struct auth_s *creds) {
	char *tmp, *buf, *challenge;
	rr_data_t auth;
	int len;
	
	int rc = 0;

	buf = new(BUFSIZE);

	strcpy(buf, "NTLM ");
	len = ntlm_request(&tmp, creds);
	if (len) {
		to_base64(MEM(buf, uint8_t, 5), MEM(tmp, uint8_t, 0), len, BUFSIZE-5);
		free(tmp);
	}

	auth = dup_rr_data(request);
	auth->headers = hlist_mod(auth->headers, "Connection", "keep-alive", 1);
	auth->headers = hlist_mod(auth->headers, "Authorization", buf, 1);
	auth->headers = hlist_mod(auth->headers, "Content-Length", "0", 1);
	auth->headers = hlist_del(auth->headers, "Transfer-Encoding");

	/*
	 * Drop whatever error page server returned
	 */
	if (!http_body_drop(sd, response))
		goto bailout;

	if (debug) {
		printf("\nSending WWW auth request...\n");
		hlist_dump(auth->headers);
	}

	if (!headers_send(sd, auth))
		goto bailout;

	if (debug)
		printf("\nReading WWW auth response...\n");

	/*
	 * Get NTLM challenge
	 */
	reset_rr_data(auth);
	if (!headers_recv(sd, auth)) {
		goto bailout;
	}

	if (debug)
		hlist_dump(auth->headers);

	/*
	 * Auth required?
	 */
	if (auth->code == 401) {
		if (!http_body_drop(sd, auth))
			goto bailout;

		tmp = hlist_get(auth->headers, "WWW-Authenticate");
		if (tmp && strlen(tmp) > 6 + 8) {
			challenge = new(strlen(tmp) + 5 + 1);
			len = from_base64(challenge, tmp + 5);
			if (len > NTLM_CHALLENGE_MIN) {
				len = ntlm_response(&tmp, challenge, len, creds);
				if (len > 0) {
					strcpy(buf, "NTLM ");
					to_base64(MEM(buf, uint8_t, 5), MEM(tmp, uint8_t, 0), len, BUFSIZE-5);
					request->headers = hlist_mod(request->headers, "Authorization", buf, 1);
					free(tmp);
				} else {
					syslog(LOG_ERR, "No target info block. Cannot do NTLMv2!\n");
					response->errmsg = "Invalid NTLM challenge from web server";
					free(challenge);
					goto bailout;
				}
			} else {
				syslog(LOG_ERR, "Server returning invalid challenge!\n");
				response->errmsg = "Invalid NTLM challenge from web server";
				free(challenge);
				goto bailout;
			}

			free(challenge);
		} else {
			syslog(LOG_WARNING, "No challenge in WWW-Authenticate!\n");
			response->errmsg = "Web server reply missing NTLM challenge";
			goto bailout;
		}
	} else {
		goto bailout;
	}

	if (debug)
		printf("\nSending WWW auth...\n");

	if (!headers_send(sd, request)) {
		goto bailout;
	}

	if (debug)
		printf("\nReading final server response...\n");

	reset_rr_data(auth);
	if (!headers_recv(sd, auth)) {
		goto bailout;
	}

	rc = 1;

	if (debug)
		hlist_dump(auth->headers);

bailout:
	if (rc)
		response = copy_rr_data(response, auth);
	free_rr_data(auth);
	free(buf);

	return rc;
}

rr_data_t direct_request(void *cdata, rr_data_t request) {
	rr_data_t data[2], rc = NULL;
	struct auth_s *tcreds = NULL;
	int *rsocket[2], *wsocket[2];
	int w, loop, sd;
	char *tmp;

	char *hostname = NULL;
	int port = 0;
	int conn_alive = 0;

	int cd = ((struct thread_arg_s *)cdata)->fd;
	struct sockaddr_in caddr = ((struct thread_arg_s *)cdata)->addr;

	if (debug)
		printf("Direct thread processing...\n");

	sd = host_connect(request->hostname, request->port);
	if (sd < 0) {
		syslog(LOG_WARNING, "Connection failed for %s:%d (%s)", request->hostname, request->port, strerror(errno));
		tmp = gen_502_page(request->http, strerror(errno));
		w = write(cd, tmp, strlen(tmp));
		free(tmp);

		rc = (void *)-1;
		goto bailout;
	}

	/*
	 * Now save NTLM credentials for purposes of this thread.
	 * If web auth fails, we'll rewrite them like with NTLM-to-Basic in proxy mode.
	 */
	tcreds = dup_auth(g_creds, /* fullcopy */ 1);

	if (request->hostname) {
		hostname = strdup(request->hostname);
		port = request->port;
	} else {
		tmp = gen_502_page(request->http, "Invalid request URL");
		w = write(cd, tmp, strlen(tmp));
		free(tmp);

		rc = (void *)-1;
		goto bailout;
	}

	do {
		if (request) {
			data[0] = dup_rr_data(request);
			request = NULL;
		} else {
			data[0] = new_rr_data();
		}
		data[1] = new_rr_data();

		rsocket[0] = wsocket[1] = &cd;
		rsocket[1] = wsocket[0] = &sd;

		conn_alive = 0;

		for (loop = 0; loop < 2; ++loop) {
			if (data[loop]->empty) {				// Isn't this the first loop with request supplied by caller?
				if (debug) {
					printf("\n******* Round %d C: %d, S: %d *******\n", loop+1, cd, sd);
					printf("Reading headers (%d)...\n", *rsocket[loop]);
				}
				if (!headers_recv(*rsocket[loop], data[loop])) {
					free_rr_data(data[0]);
					free_rr_data(data[1]);
					rc = (void *)-1;
					goto bailout;
				}
			}

			/*
			 * Check whether this new request still talks to the same server as previous.
			 * If no, return request to caller, he must decide on forward or direct
			 * approach.
			 */
			if (loop == 0 && hostname && data[0]->hostname
					&& (strcasecmp(hostname, data[0]->hostname) || port != data[0]->port)) {
				if (debug)
					printf("\n******* D RETURN: %s *******\n", data[0]->url);

				rc = dup_rr_data(data[0]);
				free_rr_data(data[0]);
				free_rr_data(data[1]);
				goto bailout;
			}

			if (debug)
				hlist_dump(data[loop]->headers);

			if (loop == 0 && data[0]->req) {
				syslog(LOG_DEBUG, "%s %s %s", inet_ntoa(caddr.sin_addr), data[0]->method, data[0]->url);
				
				/*
				 * Convert full proxy request URL into a relative URL
				 * Host header is already inserted by headers_recv()
				 */
				if (data[0]->rel_url) {
					if (data[0]->url)
						free(data[0]->url);
					data[0]->url = strdup(data[0]->rel_url);
				}

				/*
				 * Force proxy keep-alive if the client can handle it (HTTP >= 1.1)
				 */
				if (data[0]->http_version >= 11)
					data[0]->headers = hlist_mod(data[0]->headers, "Connection", "keep-alive", 1);

				/*
				 * Also remove runaway P-A from the client (e.g. Basic from N-t-B), which might 
				 * cause some ISAs to deny us, even if the connection is already auth'd.
				 */
				while (hlist_get(data[loop]->headers, "Proxy-Authorization")) {
					data[loop]->headers = hlist_del(data[loop]->headers, "Proxy-Authorization");
				}

				/*
				 * Try to get auth from client if present
				 */
				if (http_parse_basic(data[0]->headers, "Authorization", tcreds) > 0 && debug)
					printf("NTLM-to-basic: Credentials parsed: %s\\%s at %s\n", tcreds->domain, tcreds->user, tcreds->workstation);
			}

			/*
			 * Is this a CONNECT request?
			 */
			if (loop == 0 && CONNECT(data[0])) {
				if (debug)
					printf("CONNECTing...\n");

				data[1]->empty = 0;
				data[1]->req = 0;
				data[1]->code = 200;
				data[1]->msg = strdup("Connection established");
				data[1]->http = strdup(data[0]->http);
				
				if (headers_send(cd, data[1]))
					tunnel(cd, sd);

				free_rr_data(data[0]);
				free_rr_data(data[1]);
				rc = (void *)-1;
				goto bailout;
			}

			if (loop == 1 && data[1]->code == 401 && hlist_subcmp_all(data[1]->headers, "WWW-Authenticate", "NTLM")) {
				/*
				 * Server closing the connection after 401?
				 * Should never happen.
				 */
				if (hlist_subcmp(data[1]->headers, "Connection", "close")) {
					if (debug)
						printf("Reconnect before WWW auth\n");
					close(sd);
					sd = host_connect(data[0]->hostname, data[0]->port);
					if (sd < 0) {
						tmp = gen_502_page(data[0]->http, "WWW authentication reconnect failed");
						w = write(cd, tmp, strlen(tmp));
						free(tmp);

						rc = (void *)-1;
						goto bailout;
					}
				}
				if (!www_authenticate(*wsocket[0], data[0], data[1], tcreds)) {
					if (debug)
						printf("WWW auth connection error.\n");

					tmp = gen_502_page(data[1]->http, data[1]->errmsg ? data[1]->errmsg : "Error during WWW-Authenticate");
					w = write(cd, tmp, strlen(tmp));
					free(tmp);

					free_rr_data(data[0]);
					free_rr_data(data[1]);

					rc = (void *)-1;
					goto bailout;
				} else if (data[1]->code == 401) {
					/*
					 * Server giving 401 after auth?
					 * Request basic auth
					 */
					tmp = gen_401_page(data[1]->http, data[0]->hostname, data[0]->port);
					w = write(cd, tmp, strlen(tmp));
					free(tmp);

					free_rr_data(data[0]);
					free_rr_data(data[1]);

					rc = (void *)-1;
					goto bailout;
				}
			}

			/*
			 * Check if we should loop for another request.  Required for keep-alive
			 * connections, client might really need a non-interrupted conversation.
			 *
			 * We default to keep-alive server connections, unless server explicitly
			 * flags closing the connection or we detect a body with unknown size
			 * (end marked by server closing).
			 */
			if (loop == 1) {
				conn_alive = !hlist_subcmp(data[1]->headers, "Connection", "close")
					&& http_has_body(data[0], data[1]) != -1
					&& data[0]->http_version >= 11;
				if (conn_alive) {
					data[1]->headers = hlist_mod(data[1]->headers, "Proxy-Connection", "keep-alive", 1);
					data[1]->headers = hlist_mod(data[1]->headers, "Connection", "keep-alive", 1);
				} else {
					data[1]->headers = hlist_mod(data[1]->headers, "Proxy-Connection", "close", 1);
					data[1]->headers = hlist_mod(data[1]->headers, "Connection", "close", 1);
					rc = (void *)-1;
				}
			}

			if (debug) {
				printf("Sending headers (%d)...\n", *wsocket[loop]);
				if (loop == 0) {
					printf("HEAD: %s %s %s\n", data[loop]->method, data[loop]->url, data[loop]->http);
					hlist_dump(data[loop]->headers);
				}
			}

			/*
			 * Send headers
			 */
			if (!headers_send(*wsocket[loop], data[loop])) {
				free_rr_data(data[0]);
				free_rr_data(data[1]);
				rc = (void *)-1;
				goto bailout;
			}

			if (!http_body_send(*wsocket[loop], *rsocket[loop], data[0], data[1])) {
				free_rr_data(data[0]);
				free_rr_data(data[1]);
				rc = (void *)-1;
				goto bailout;
			}
		}

		free_rr_data(data[0]);
		free_rr_data(data[1]);

	} while (conn_alive && !so_closed(sd) && !so_closed(cd) && !serialize);

bailout:
	if (tcreds)
		free(tcreds);
	if (hostname)
		free(hostname);

	close(sd);

	return rc;
}

void direct_tunnel(void *thread_data) {
	int sd, port = 0;
	char *pos, *hostname;

	int cd = ((struct thread_arg_s *)thread_data)->fd;
	char *thost = ((struct thread_arg_s *)thread_data)->target;
	struct sockaddr_in caddr = ((struct thread_arg_s *)thread_data)->addr;

	hostname = strdup(thost);
	if ((pos = strchr(hostname, ':')) != NULL) {
		*pos = 0;
		port = atoi(++pos);
	}

	sd = host_connect(hostname, port);
	if (sd <= 0)
		goto bailout;

	syslog(LOG_DEBUG, "%s FORWARD %s", inet_ntoa(caddr.sin_addr), thost);
	if (debug)
		printf("Portforwarding to %s for client %d...\n", thost, cd);

	tunnel(cd, sd);

bailout:
	free(hostname);
	close(sd);
	close(cd);

	return;
}