2 * (C) 2000 Francesco Chemolli <kinkie@kame.usr.dsi.unimi.it>
3 * Distributed freely under the terms of the GNU General Public License,
4 * version 2. See the file COPYING for licensing details
6 * This program is distributed in the hope that it will be useful,
7 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 * GNU General Public License for more details.
11 * You should have received a copy of the GNU General Public License
12 * along with this program; if not, write to the Free Software
13 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
18 #include "compat/debug.h"
19 #include "ntlmauth/ntlmauth.h"
20 #include "ntlmauth/support_bits.cci"
21 #include "rfcnb/rfcnb.h"
22 #include "smblib/smblib.h"
41 /************* CONFIGURATION ***************/
43 #define DEAD_DC_RETRY_INTERVAL 30
45 /************* END CONFIGURATION ***************/
47 /* A couple of harmless helper macros */
48 #define SEND(X) debug("sending '%s' to squid\n",X); printf(X "\n");
50 #define SEND2(X,Y...) debug("sending '" X "' to squid\n",Y); printf(X "\n",Y);
51 #define SEND3(X,Y...) debug("sending '" X "' to squid\n",Y); printf(X "\n",Y);
53 /* no gcc, no debugging. varargs macros are a gcc extension */
58 const char *make_challenge(char *domain
, char *controller
);
59 char *ntlm_check_auth(ntlm_authenticate
* auth
, int auth_length
);
60 void dc_disconnect(void);
62 int is_dc_ok(char *domain
, char *domain_controller
);
64 typedef struct _dc dc
;
68 time_t dead
; /* 0 if it's alive, otherwise time of death */
74 void process_options(int argc
, char *argv
[]);
75 const char * obtain_challenge(void);
76 void manage_request(void);
78 #define ENCODED_PASS_LEN 24
79 #define MAX_USERNAME_LEN 255
80 #define MAX_DOMAIN_LEN 255
81 #define MAX_PASSWD_LEN 31
83 static unsigned char challenge
[NTLM_NONCE_LEN
];
84 static unsigned char lmencoded_empty_pass
[ENCODED_PASS_LEN
],
85 ntencoded_empty_pass
[ENCODED_PASS_LEN
];
86 SMB_Handle_Type handle
= NULL
;
88 static char credentials
[MAX_USERNAME_LEN
+MAX_DOMAIN_LEN
+2]; /* we can afford to waste */
89 static char my_domain
[100], my_domain_controller
[100];
90 static char errstr
[1001];
92 char error_messages_buffer
[NTLM_BLOB_BUFFER_SIZE
];
94 char load_balance
= 0, protocol_pedantic
= 0;
95 dc
*controllers
= NULL
;
96 int numcontrollers
= 0;
98 char smb_error_buffer
[1000];
100 /* Disconnects from the DC. A reconnection will be done upon the next request
106 SMB_Discon(handle
, 0);
113 return (handle
!= NULL
);
116 /* Tries to connect to a DC. Returns 0 on failure, 1 on OK */
118 is_dc_ok(char *domain
, char *domain_controller
)
120 SMB_Handle_Type h
= SMB_Connect_Server(NULL
, domain_controller
, domain
);
127 /* returns 0 on success, > 0 on failure */
129 init_challenge(char *domain
, char *domain_controller
)
133 if (handle
!= NULL
) {
136 debug("Connecting to server %s domain %s\n", domain_controller
, domain
);
137 handle
= SMB_Connect_Server(NULL
, domain_controller
, domain
);
138 smberr
= SMB_Get_Last_Error();
139 SMB_Get_Error_Msg(smberr
, errstr
, 1000);
141 if (handle
== NULL
) { /* couldn't connect */
142 debug("Couldn't connect to SMB Server. Error:%s\n", errstr
);
145 if (SMB_Negotiate(handle
, SMB_Prots
) < 0) { /* An error */
146 debug("Error negotiating protocol with SMB Server\n");
147 SMB_Discon(handle
, 0);
151 if (handle
->Security
== 0) { /* share-level security, unuseable */
152 debug("SMB Server uses share-level security .. we need user security.\n");
153 SMB_Discon(handle
, 0);
157 memcpy(challenge
, handle
->Encrypt_Key
, NTLM_NONCE_LEN
);
158 SMBencrypt((unsigned char *)"",challenge
,lmencoded_empty_pass
);
159 SMBNTencrypt((unsigned char *)"",challenge
,ntencoded_empty_pass
);
164 make_challenge(char *domain
, char *domain_controller
)
166 /* trying to circumvent some strange problem wih pointers in SMBLib */
167 /* Ugly as hell, but the lib is going to be dropped... */
168 strncpy(my_domain
, domain
, sizeof(my_domain
)-1);
169 my_domain
[sizeof(my_domain
)-1] = '\0';
170 strncpy(my_domain_controller
, domain_controller
, sizeof(my_domain_controller
)-1);
171 my_domain_controller
[sizeof(my_domain_controller
)-1] = '\0';
173 if (init_challenge(my_domain
, my_domain_controller
) > 0) {
177 uint32_t flags
= NTLM_REQUEST_NON_NT_SESSION_KEY
|
178 NTLM_CHALLENGE_TARGET_IS_DOMAIN
|
179 NTLM_NEGOTIATE_ALWAYS_SIGN
|
180 NTLM_NEGOTIATE_USE_NTLM
|
181 NTLM_NEGOTIATE_USE_LM
|
182 NTLM_NEGOTIATE_ASCII
;
183 ntlm_make_challenge(&chal
, my_domain
, my_domain_controller
, (char *)challenge
, NTLM_NONCE_LEN
, flags
);
184 int len
= sizeof(chal
) - sizeof(chal
.payload
) + le16toh(chal
.target
.maxlen
);
185 return base64_encode_bin((char *)&chal
, len
);
188 /* returns NULL on failure, or a pointer to
189 * the user's credentials (domain\\username)
190 * upon success. WARNING. It's pointing to static storage.
191 * In case of problem sets as side-effect ntlm_errno to one of the
192 * codes defined in ntlm.h
195 ntlm_check_auth(ntlm_authenticate
* auth
, int auth_length
)
198 char pass
[MAX_PASSWD_LEN
+1];
199 char *domain
= credentials
;
203 if (handle
== NULL
) { /*if null we aren't connected, but it shouldn't happen */
204 debug("Weird, we've been disconnected\n");
205 ntlm_errno
= NTLM_ERR_NOT_CONNECTED
;
209 /* debug("fetching domain\n"); */
210 tmp
= ntlm_fetch_string(&(auth
->hdr
), auth_length
, &auth
->domain
, auth
->flags
);
211 if (tmp
.str
== NULL
|| tmp
.l
== 0) {
212 debug("No domain supplied. Returning no-auth\n");
213 ntlm_errno
= NTLM_ERR_LOGON
;
216 if (tmp
.l
> MAX_DOMAIN_LEN
) {
217 debug("Domain string exceeds %d bytes, rejecting\n", MAX_DOMAIN_LEN
);
218 ntlm_errno
= NTLM_ERR_LOGON
;
221 memcpy(domain
, tmp
.str
, tmp
.l
);
222 user
= domain
+ tmp
.l
;
226 /* debug("fetching user name\n"); */
227 tmp
= ntlm_fetch_string(&(auth
->hdr
), auth_length
, &auth
->user
, auth
->flags
);
228 if (tmp
.str
== NULL
|| tmp
.l
== 0) {
229 debug("No username supplied. Returning no-auth\n");
230 ntlm_errno
= NTLM_ERR_LOGON
;
233 if (tmp
.l
> MAX_USERNAME_LEN
) {
234 debug("Username string exceeds %d bytes, rejecting\n", MAX_USERNAME_LEN
);
235 ntlm_errno
= NTLM_ERR_LOGON
;
238 memcpy(user
, tmp
.str
, tmp
.l
);
239 *(user
+ tmp
.l
) = '\0';
241 /* Authenticating against the NT response doesn't seem to work... */
242 tmp
= ntlm_fetch_string(&(auth
->hdr
), auth_length
, &auth
->lmresponse
, auth
->flags
);
243 if (tmp
.str
== NULL
|| tmp
.l
== 0) {
244 fprintf(stderr
, "No auth at all. Returning no-auth\n");
245 ntlm_errno
= NTLM_ERR_LOGON
;
248 if (tmp
.l
> MAX_PASSWD_LEN
) {
249 debug("Password string exceeds %d bytes, rejecting\n", MAX_PASSWD_LEN
);
250 ntlm_errno
= NTLM_ERR_LOGON
;
254 memcpy(pass
, tmp
.str
, tmp
.l
);
255 pass
[min(MAX_PASSWD_LEN
,tmp
.l
)] = '\0';
258 debug("Empty LM pass detection: user: '%s', ours:'%s', his: '%s' (length: %d)\n",
259 user
,lmencoded_empty_pass
,tmp
.str
,tmp
.l
);
260 if (memcmp(tmp
.str
,lmencoded_empty_pass
,ENCODED_PASS_LEN
)==0) {
261 fprintf(stderr
,"Empty LM password supplied for user %s\\%s. "
262 "No-auth\n",domain
,user
);
263 ntlm_errno
=NTLM_ERR_LOGON
;
267 tmp
= ntlm_fetch_string(&(auth
->hdr
), auth_length
, &auth
->ntresponse
, auth
->flags
);
268 if (tmp
.str
!= NULL
&& tmp
.l
!= 0) {
269 debug("Empty NT pass detection: user: '%s', ours:'%s', his: '%s' (length: %d)\n",
270 user
,ntencoded_empty_pass
,tmp
.str
,tmp
.l
);
271 if (memcmp(tmp
.str
,lmencoded_empty_pass
,ENCODED_PASS_LEN
)==0) {
272 fprintf(stderr
,"ERROR: Empty NT password supplied for user %s\\%s. No-auth\n", domain
, user
);
273 ntlm_errno
= NTLM_ERR_LOGON
;
279 /* TODO: check against empty password!!!!! */
281 debug("checking domain: '%s', user: '%s', pass='%s'\n", domain
, user
, pass
);
283 rv
= SMB_Logon_Server(handle
, user
, pass
, domain
, 1);
284 debug("Login attempt had result %d\n", rv
);
286 if (rv
!= NTLM_ERR_NONE
) { /* failed */
290 *(user
- 1) = '\\'; /* hack. Performing, but ugly. */
292 debug("credentials: %s\n", credentials
);
296 extern "C" void timeout_during_auth(int signum
);
298 static char got_timeout
= 0;
299 /** signal handler to be invoked when the authentication operation
302 timeout_during_auth(int signum
)
309 * -b try load-balancing the domain-controllers
310 * -f fail-over to another DC if DC connection fails.
311 * DEPRECATED and VERBOSELY IGNORED. This is on by default now.
313 * domain\controller ...
315 char *my_program_name
= NULL
;
321 "%s usage:\n%s [-b] [-f] [-d] [-l] domain\\controller [domain\\controller ...]\n"
322 "-b enables load-balancing among controllers\n"
323 "-f enables failover among controllers (DEPRECATED and always active)\n"
324 "-d enables debugging statements if DEBUG was defined at build-time.\n\n"
325 "You MUST specify at least one Domain Controller.\n"
326 "You can use either \\ or / as separator between the domain name \n"
327 "and the controller name\n",
328 my_program_name
, my_program_name
);
331 /* int debug_enabled=0; defined in libcompat */
334 process_options(int argc
, char *argv
[])
336 int opt
, j
, had_error
= 0;
337 dc
*new_dc
= NULL
, *last_dc
= NULL
;
338 while (-1 != (opt
= getopt(argc
, argv
, "bfld"))) {
345 "WARNING. The -f flag is DEPRECATED and always active.\n");
351 fprintf(stderr
, "unknown option: -%c. Exiting\n", opt
);
358 /* Okay, now begin filling controllers up */
359 /* we can avoid memcpy-ing, and just reuse argv[] */
360 for (j
= optind
; j
< argc
; ++j
) {
362 /* d will not be freed in case of non-error. Since we don't reconfigure,
363 * it's going to live as long as the process anyways */
364 d
= (char*)malloc(strlen(argv
[j
]) + 1);
366 debug("Adding domain-controller %s\n", d
);
367 if (NULL
== (c
= strchr(d
, '\\')) && NULL
== (c
= strchr(d
, '/'))) {
368 fprintf(stderr
, "Couldn't grok domain-controller %s\n", d
);
372 /* more than one delimiter is not allowed */
373 if (NULL
!= strchr(c
+ 1, '\\') || NULL
!= strchr(c
+ 1, '/')) {
374 fprintf(stderr
, "Broken domain-controller %s\n", d
);
380 new_dc
= (dc
*) malloc(sizeof(dc
));
382 fprintf(stderr
, "Malloc error while parsing DC options\n");
391 new_dc
->controller
= c
;
393 if (controllers
== NULL
) { /* first controller */
394 controllers
= new_dc
;
397 last_dc
->next
= new_dc
; /* can't be null */
401 if (numcontrollers
== 0) {
402 fprintf(stderr
, "You must specify at least one domain-controller!\n");
406 last_dc
->next
= controllers
; /* close the queue, now it's circular */
410 * tries connecting to the domain controllers in the "controllers" ring,
411 * with failover if the adequate option is specified.
417 const char *ch
= NULL
;
418 for (j
= 0; j
< numcontrollers
; ++j
) {
419 debug("obtain_challenge: selecting %s\\%s (attempt #%d)\n",
420 current_dc
->domain
, current_dc
->controller
, j
+ 1);
421 if (current_dc
->dead
!= 0) {
422 if (time(NULL
) - current_dc
->dead
>= DEAD_DC_RETRY_INTERVAL
) {
423 /* mark helper as retry-worthy if it's so. */
424 debug("Reviving DC\n");
425 current_dc
->dead
= 0;
426 } else { /* skip it */
427 debug("Skipping it\n");
431 /* else branch. Here we KNOW that the DC is fine */
432 debug("attempting challenge retrieval\n");
433 ch
= make_challenge(current_dc
->domain
, current_dc
->controller
);
434 debug("make_challenge retuned %p\n", ch
);
437 return ch
; /* All went OK, returning */
439 /* Huston, we've got a problem. Take this DC out of the loop */
440 debug("Marking DC as DEAD\n");
441 current_dc
->dead
= time(NULL
);
442 /* Try with the next */
443 debug("moving on to next controller\n");
444 current_dc
= current_dc
->next
;
446 /* all DCs failed. */
453 ntlmhdr
*fast_header
;
454 char buf
[NTLM_BLOB_BUFFER_SIZE
];
455 char decoded
[NTLM_BLOB_BUFFER_SIZE
];
457 char *ch2
, *cred
= NULL
;
459 if (fgets(buf
, NTLM_BLOB_BUFFER_SIZE
, stdin
) == NULL
) {
460 fprintf(stderr
, "fgets() failed! dying..... errno=%d (%s)\n", errno
,
462 exit(1); /* BIIG buffer */
464 debug("managing request\n");
465 ch2
= (char*)memchr(buf
, '\n', NTLM_BLOB_BUFFER_SIZE
); /* safer against overrun than strchr */
467 *ch2
= '\0'; /* terminate the string at newline. */
470 debug("ntlm authenticator. Got '%s' from Squid\n", buf
);
472 if (memcmp(buf
, "KK ", 3) == 0) { /* authenticate-request */
473 /* figure out what we got */
474 int decodedLen
= base64_decode(decoded
, sizeof(decoded
), buf
+3);
476 if ((size_t)decodedLen
< sizeof(ntlmhdr
)) { /* decoding failure, return error */
477 SEND("NA Packet format error, couldn't base64-decode");
480 /* fast-track-decode request type. */
481 fast_header
= (ntlmhdr
*) decoded
;
483 /* sanity-check: it IS a NTLMSSP packet, isn't it? */
484 if (ntlm_validate_packet(fast_header
, NTLM_ANY
) < 0) {
485 SEND("NA Broken authentication packet");
488 switch (le32toh(fast_header
->type
)) {
490 SEND("NA Invalid negotiation request received");
494 SEND("NA Got a challenge. We refuse to have our authority disputed");
497 case NTLM_AUTHENTICATE
:
498 /* check against the DC */
499 signal(SIGALRM
, timeout_during_auth
);
501 cred
= ntlm_check_auth((ntlm_authenticate
*) decoded
, decodedLen
);
503 signal(SIGALRM
, SIG_DFL
);
504 if (got_timeout
!= 0) {
505 fprintf(stderr
, "ntlm-auth[%ld]: Timeout during authentication.\n", (long)getpid());
506 SEND("BH Timeout during authentication");
511 int smblib_err
, smb_errorclass
, smb_errorcode
, nb_error
;
512 if (ntlm_errno
== NTLM_ERR_LOGON
) { /* hackish */
513 SEND("NA Logon Failure");
516 /* there was an error. We have two errno's to look at.
517 * libntlmssp's erno is insufficient, we'll have to look at
518 * the actual SMB library error codes, to acually figure
519 * out what's happening. The thing has braindamaged interfacess..*/
520 smblib_err
= SMB_Get_Last_Error();
521 smb_errorclass
= SMBlib_Error_Class(SMB_Get_Last_SMB_Err());
522 smb_errorcode
= SMBlib_Error_Code(SMB_Get_Last_SMB_Err());
523 nb_error
= RFCNB_Get_Last_Error();
524 debug("No creds. SMBlib error %d, SMB error class %d, SMB error code %d, NB error %d\n",
525 smblib_err
, smb_errorclass
, smb_errorcode
, nb_error
);
526 /* Should I use smblib_err? Actually it seems I can do as well
528 if (nb_error
!= 0) { /* netbios-level error */
529 SEND("BH NetBios error!");
530 fprintf(stderr
, "NetBios error code %d (%s)\n", nb_error
,
531 RFCNB_Error_Strings
[abs(nb_error
)]);
534 switch (smb_errorclass
) {
536 debug("Huh? Got a SMB success code but could check auth..");
537 SEND("NA Authentication failed");
540 /*this is the most important one for errors */
541 debug("DOS error\n");
542 switch (smb_errorcode
) {
543 /* two categories matter to us: those which could be
544 * server errors, and those which are auth errors */
545 case SMBD_noaccess
: /* 5 */
546 SEND("NA Access denied");
549 SEND("NA bad format in authentication packet");
552 SEND("NA Bad access request");
558 SEND("BH DOS Error");
561 case SMBC_ERRSRV
: /* server errors */
562 debug("Server error");
563 switch (smb_errorcode
) {
564 /* mostly same as above */
566 SEND("NA Bad password");
569 SEND("NA Server access error");
572 SEND("BH Server Error");
575 case SMBC_ERRHRD
: /* hardware errors don't really matter */
576 SEND("BH Domain Controller Hardware error");
579 SEND("BH Domain Controller Command Error");
582 SEND("BH unknown internal error.");
586 lc(cred
); /* let's lowercase them for our convenience */
587 SEND2("AF %s", cred
);
590 SEND("BH unknown authentication packet type");
596 if (memcmp(buf
, "YR", 2) == 0) { /* refresh-request */
598 ch
= obtain_challenge();
599 /* Robert says we can afford to wait forever. I'll trust him on this
603 ch
= obtain_challenge();
608 SEND("BH Helper detected protocol error");
610 /********* END ********/
615 main(int argc
, char *argv
[])
617 debug("ntlm_auth build " __DATE__
", " __TIME__
" starting up...\n");
619 my_program_name
= argv
[0];
620 process_options(argc
, argv
);
622 debug("options processed OK\n");
624 /* initialize FDescs */
625 setbuf(stdout
, NULL
);
626 setbuf(stderr
, NULL
);
628 /* select the first domain controller we're going to use */
629 current_dc
= controllers
;
630 if (load_balance
!= 0 && numcontrollers
> 1) {
632 pid_t pid
= getpid();
633 n
= pid
% numcontrollers
;
634 debug("load balancing. Selected controller #%d\n", n
);
636 current_dc
= current_dc
->next
;