/
ntlm_auth_wrap.c
427 lines (376 loc) · 14.2 KB
/
ntlm_auth_wrap.c
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
/* A wrapper around ntlm_auth to log arguments and
running time.
WARNING: We cheat and do no bother to free memory allocated to strings here.
The process is meant to be very short lived and never reused. */
/*
Copyright (C) 2005-2024 Inverse inc.
This program 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.
This program 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 Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
#define MAX_STR_LENGTH 1023
#include <syslog.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <argp.h>
#include <signal.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>
const char *argp_program_version = "ntlm_auth_wrapper 1.0";
const char *argp_program_bug_address = "<info@inverse.ca>";
/* Program documentation. */
static char doc[] =
"ntm_auth_wrapper: \tA performance logging wrapper for ntlm_auth";
/* A description of the arguments we accept. */
static char args_doc[] = "[arguments passed to ntlm_auth]";
/* The options we understand. */
static struct argp_option options[] = {
{"host" ,'h', "hostname or ip", 0, "StatsD host. Default is localhost."},
{"port" ,'p', "port", 0, "StatsD port. Default is 8125."},
{"insecure" ,'i', 0, 0, "Log insecure arguments such as the password."},
{"nostatsd" ,'s', 0, 0, "Don't send performance counters to statsd."},
{"noresolv" ,'n', 0, 0, "Do not resolve value for host and port."},
{"log" ,'l', 0, 0, "Send results to syslog."},
{"logfacility",'f', "facility", 0, "Syslog facility. Default is local5."},
{"loglevel" ,'d', "level", 0, "Syslog level. Default is info."},
{"api_host" ,'a', "hostname/ip" ,0, "NTLM auth API host or IP" },
{"api_port" ,'t', "port" ,0, "NTLM auth API listening port" },
{0}
};
/* Used by main to communicate with parse_opt. */
struct arguments {
int insecure, nostatsd, noresolv, log, facility, level;
char *host;
char *port;
char *api_host;
char *api_port;
};
/* Parse a single option. */
static error_t parse_opt(int key, char *arg, struct argp_state *state)
{
/* Get the input argument from argp_parse, which we
know is a pointer to our arguments structure. */
struct arguments *arguments = state->input;
switch (key) {
case 'i':
arguments->insecure = 1;
break;
case 's':
arguments->nostatsd = 1;
break;
case 'n':
arguments->noresolv = 1;
break;
case 'l':
arguments->log = 1;
break;
case 'h':
arguments->host = arg;
break;
case 'p':
arguments->port = arg;
break;
case 'a':
arguments->api_host = arg;
break;
case 't':
arguments->api_port = arg;
break;
case 'f':
if (strcasecmp(arg, "auth") == 0) {
arguments->facility = LOG_AUTHPRIV;
} else if (strcasecmp(arg, "authpriv") == 0) {
arguments->facility = LOG_AUTHPRIV;
} else if (strcasecmp(arg, "daemon") == 0) {
arguments->facility = LOG_DAEMON;
} else if (strcasecmp(arg, "user") == 0) {
arguments->facility = LOG_USER;
} else if (strcasecmp(arg, "local0") == 0) {
arguments->facility = LOG_LOCAL0;
} else if (strcasecmp(arg, "local1") == 0) {
arguments->facility = LOG_LOCAL1;
} else if (strcasecmp(arg, "local2") == 0) {
arguments->facility = LOG_LOCAL2;
} else if (strcasecmp(arg, "local3") == 0) {
arguments->facility = LOG_LOCAL3;
} else if (strcasecmp(arg, "local4") == 0) {
arguments->facility = LOG_LOCAL4;
} else if (strcasecmp(arg, "local5") == 0) {
arguments->facility = LOG_LOCAL5;
} else if (strcasecmp(arg, "local6") == 0) {
arguments->facility = LOG_LOCAL6;
} else if (strcasecmp(arg, "local7") == 0) {
arguments->facility = LOG_LOCAL7;
} else {
return ARGP_ERR_UNKNOWN;
}
break;
case 'd':
if (strcasecmp(arg, "debug") == 0) {
arguments->level = LOG_DEBUG;
} else if (strcasecmp(arg, "notice") == 0) {
arguments->level = LOG_NOTICE;
} else if (strcasecmp(arg, "info") == 0) {
arguments->level = LOG_INFO;
} else if (strcasecmp(arg, "warning") == 0) {
arguments->level = LOG_WARNING;
} else if (strcasecmp(arg, "error") == 0) {
arguments->level = LOG_ERR;
} else if (strcasecmp(arg, "critical") == 0) {
arguments->level = LOG_CRIT;
} else if (strcasecmp(arg, "alert") == 0) {
arguments->level = LOG_ALERT;
} else if (strcasecmp(arg, "emerg") == 0) {
arguments->level = LOG_ALERT;
} else {
return ARGP_ERR_UNKNOWN;
}
break;
case ARGP_KEY_ARG:
if (state->arg_num >= 32)
/* Way too many arguments. */
argp_usage(state);
break;
case ARGP_KEY_END:
if (state->arg_num < 2)
/* Not enough arguments. */
argp_usage(state);
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
/* Our argp parser. */
static struct argp argp = { options, parse_opt, args_doc, doc };
// send results to syslog
void log_result(int argc, char **argv, const struct arguments args, int status, double elapsed)
{
openlog("radius-debug", LOG_PID, args.facility);
// build the log message
char *log_msg;
asprintf(&log_msg, "http://%s:%s", args.api_host, args.api_port);
// concatenate the command with all argv args separated by sep
int i = 1;
while (i < argc ) {
// split the argument on = and check the first part to reject excluded args.
if (!args.insecure)
if ((strncmp
(argv[i], "--password", strlen("--password")) == 0)
||
(strncmp
(argv[i], "--challenge", strlen("--challenge")) == 0))
{
i=i+2; // will skip the next argument
continue;
}
char *tmpstr = log_msg;
log_msg = NULL;
asprintf(&log_msg, "%s %s ", tmpstr, argv[i]);
i++;
}
syslog(args.level, "%s time: %g ms, status: %i", log_msg, elapsed, status);
closelog();
}
// send to statsd
void send_statsd(const struct arguments args , int status, double elapsed)
{
struct addrinfo *ailist;
struct addrinfo hint;
int sockfd, err;
memset(&hint, 0, sizeof(hint));
hint.ai_socktype = SOCK_DGRAM;
hint.ai_family = AF_INET;
if (args.noresolv)
hint.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
if ((err = getaddrinfo(args.host, args.port, &hint, &ailist)) != 0) {
sprintf("getaddrinfo error: %s", gai_strerror(err));
return;
}
if ((sockfd = socket(ailist->ai_family, SOCK_DGRAM, 0)) < 0) {
err = errno;
fprintf(stderr, "cannot contact %s:%s: %s\n", args.host,
args.port, strerror(err));
return;
}
char *buf;
asprintf(&buf, "ntlm_auth.time:%g|ms\n", elapsed);
sendto(sockfd, buf, strlen(buf), 0, ailist->ai_addr, ailist->ai_addrlen);
// increment counter if auth failed
if (status == SIGTERM) {
asprintf(&buf, "ntlm_auth.timeout:1|c\n");
sendto(sockfd, buf, strlen(buf), 0, ailist->ai_addr, ailist->ai_addrlen);
} else if (status > 0) {
asprintf(&buf, "ntlm_auth.failures:1|c\n");
sendto(sockfd, buf, strlen(buf), 0, ailist->ai_addr, ailist->ai_addrlen);
}
close(sockfd);
}
double howlong(struct timeval t1)
{
struct timeval end;
double elapsed;
gettimeofday(&end, NULL);
elapsed = (end.tv_sec - t1.tv_sec) * 1000.0; // sec to ms
elapsed += (end.tv_usec - t1.tv_usec) / 1000.0; // us to ms
return elapsed;
}
struct MemoryStruct {
char *memory;
size_t size;
};
size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
mem->memory = realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == NULL) {
printf("Not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
int main(argc, argv, envp)
int argc;
char **argv, **envp;
{
/* Default values. */
struct arguments arguments;
arguments.insecure = 0;
arguments.nostatsd = 0;
arguments.noresolv = 0;
arguments.log = 0;
arguments.host = "localhost";
arguments.port = "8125";
arguments.facility = LOG_LOCAL5;
arguments.level = LOG_INFO;
arguments.api_host = "";
arguments.api_port = "0";
/* Parse our arguments; every option seen by parse_opt will
be reflected in arguments. */
argp_parse(&argp, argc, argv, 0, 0, &arguments);
struct timeval t1;
double elapsed;
gettimeofday(&t1, NULL);
// Find the -- separator if any and reset the argv accordingly
// so it does not get passed to the execed program.
int opt_end = 0;
for (int i = 1; i < argc; i++) {
if ((strncmp(argv[i], "--", strlen("--"))) == 0) {
opt_end = i;
break;
}
}
if (opt_end) {
// Here we move the pointer so that argv starts at opt_end
// We also need to change argc to reflect discarding the wrapper arguments.
// This can have consequences so pay attention.
argv += opt_end;
argc = argc - opt_end;
}
// keep the same values we used before, so SIGTERM = timeout, other non-zero values = auth error
int status = 0;
if (strcmp(arguments.api_host, "") ==0 || strcmp(arguments.api_port, "0") == 0) {
fprintf(stderr, "Error: missing NTLM auth API host or port settings.\n");
fprintf(stderr, "This could happen if you previously manually joined this server to Windows AD.\n");
fprintf(stderr, "If this is the case, you need to go to the admin UI, re-create the domain configuration.\n");
exit(1);
}
cJSON *json = cJSON_CreateObject();
if (json == NULL) {
fprintf(stderr, "Error: could not create JSON object. Exiting.");
exit(1);
}
for (int i = 1; i < argc; i++) {
if (strncmp(argv[i], "--username=", strlen("--username=")) == 0) {
cJSON_AddStringToObject(json, "username", argv[i] + strlen("--username="));
} else if (strncmp(argv[i], "--password=", strlen("--password=")) == 0) {
cJSON_AddStringToObject(json, "password", argv[i] + strlen("--password="));
} else if (strncmp(argv[i], "--request-nt-key", strlen("--request-nt-key")) == 0) {
cJSON_AddItemToObject(json, "request-nt-key", cJSON_CreateTrue());
} else if (strncmp(argv[i], "--challenge=", strlen("--challenge=")) == 0) {
cJSON_AddStringToObject(json, "challenge", argv[i] + strlen("--challenge="));
} else if (strncmp(argv[i], "--nt-response=", strlen("--nt-response=")) == 0) {
cJSON_AddStringToObject(json, "nt-response", argv[i] + strlen("--nt-response="));
} else if (strncmp(argv[i], "--mac=", strlen("--mac=")) == 0) {
cJSON_AddStringToObject(json, "mac", argv[i] + strlen("--mac="));
}
}
char *json_string = cJSON_Print(json);
CURL *curl;
CURLcode cURLCode;
struct MemoryStruct chunk;
curl = curl_easy_init();
chunk.memory = malloc(1);
chunk.size = 0;
if(curl) {
char* uri;
asprintf(&uri, "http://%s:%s/ntlm/auth", arguments.api_host, arguments.api_port);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunk);
curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 2500L);
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_URL, uri);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_string);
cURLCode = curl_easy_perform(curl);
free(uri);
if (cURLCode == CURLE_OK) {
status = 0;
long http_response_code;
curl_easy_getinfo(curl, CURLINFO_HTTP_CODE, &http_response_code);
if (http_response_code != 200) {
status = http_response_code; // consider non-200 response as auth failures.
}
printf("%s\n", chunk.memory);
} else {
status = cURLCode;
if (cURLCode==CURLE_OPERATION_TIMEDOUT || cURLCode == CURLE_COULDNT_RESOLVE_HOST || cURLCode == CURLE_COULDNT_CONNECT) {
status = SIGTERM; // timeout or any network errors, considered as time-outs
}
fprintf(stderr, "exec curl failed: %s\n", curl_easy_strerror(cURLCode));
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
free(chunk.memory);
free(json_string);
cJSON_Delete(json);
elapsed = howlong(t1);
if (arguments.log)
log_result(argc, argv, arguments, status, elapsed);
// open socket to StatsD server and send message
if (!arguments.nostatsd)
send_statsd(arguments, status, elapsed);
if (status != 0) {
exit(1);
}
}