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"
59 /************* CONFIGURATION ***************/
61 #define DEAD_DC_RETRY_INTERVAL 30
63 /************* END CONFIGURATION ***************/
65 /* A couple of harmless helper macros */
66 #define SEND(X) debug("sending '%s' to squid\n",X); printf(X "\n");
68 #define SEND2(X,Y...) debug("sending '" X "' to squid\n",Y); printf(X "\n",Y);
69 #define SEND3(X,Y...) debug("sending '" X "' to squid\n",Y); printf(X "\n",Y);
71 /* no gcc, no debugging. varargs macros are a gcc extension */
76 const char *make_challenge(char *domain
, char *controller
);
77 char *ntlm_check_auth(ntlm_authenticate
* auth
, int auth_length
);
78 void dc_disconnect(void);
80 int is_dc_ok(char *domain
, char *domain_controller
);
82 typedef struct _dc dc
;
86 time_t dead
; /* 0 if it's alive, otherwise time of death */
92 void process_options(int argc
, char *argv
[]);
93 const char * obtain_challenge(void);
94 void manage_request(void);
96 #define ENCODED_PASS_LEN 24
97 #define MAX_USERNAME_LEN 255
98 #define MAX_DOMAIN_LEN 255
99 #define MAX_PASSWD_LEN 31
101 static unsigned char challenge
[NTLM_NONCE_LEN
];
102 static unsigned char lmencoded_empty_pass
[ENCODED_PASS_LEN
],
103 ntencoded_empty_pass
[ENCODED_PASS_LEN
];
104 SMB_Handle_Type handle
= NULL
;
106 static char credentials
[MAX_USERNAME_LEN
+MAX_DOMAIN_LEN
+2]; /* we can afford to waste */
107 static char my_domain
[100], my_domain_controller
[100];
108 static char errstr
[1001];
110 char error_messages_buffer
[NTLM_BLOB_BUFFER_SIZE
];
112 char load_balance
= 0, protocol_pedantic
= 0;
113 dc
*controllers
= NULL
;
114 int numcontrollers
= 0;
116 char smb_error_buffer
[1000];
118 /* Disconnects from the DC. A reconnection will be done upon the next request
124 SMB_Discon(handle
, 0);
131 return (handle
!= NULL
);
134 /* Tries to connect to a DC. Returns 0 on failure, 1 on OK */
136 is_dc_ok(char *domain
, char *domain_controller
)
138 SMB_Handle_Type h
= SMB_Connect_Server(NULL
, domain_controller
, domain
);
145 /* returns 0 on success, > 0 on failure */
147 init_challenge(char *domain
, char *domain_controller
)
151 if (handle
!= NULL
) {
154 debug("Connecting to server %s domain %s\n", domain_controller
, domain
);
155 handle
= SMB_Connect_Server(NULL
, domain_controller
, domain
);
156 smberr
= SMB_Get_Last_Error();
157 SMB_Get_Error_Msg(smberr
, errstr
, 1000);
159 if (handle
== NULL
) { /* couldn't connect */
160 debug("Couldn't connect to SMB Server. Error:%s\n", errstr
);
163 if (SMB_Negotiate(handle
, SMB_Prots
) < 0) { /* An error */
164 debug("Error negotiating protocol with SMB Server\n");
165 SMB_Discon(handle
, 0);
169 if (handle
->Security
== 0) { /* share-level security, unuseable */
170 debug("SMB Server uses share-level security .. we need user security.\n");
171 SMB_Discon(handle
, 0);
175 memcpy(challenge
, handle
->Encrypt_Key
, NTLM_NONCE_LEN
);
176 SMBencrypt((unsigned char *)"",challenge
,lmencoded_empty_pass
);
177 SMBNTencrypt((unsigned char *)"",challenge
,ntencoded_empty_pass
);
182 make_challenge(char *domain
, char *domain_controller
)
184 /* trying to circumvent some strange problem wih pointers in SMBLib */
185 /* Ugly as hell, but the lib is going to be dropped... */
186 strcpy(my_domain
,domain
);
187 strcpy(my_domain_controller
,domain_controller
);
188 if (init_challenge(my_domain
, my_domain_controller
) > 0) {
192 uint32_t flags
= NTLM_REQUEST_NON_NT_SESSION_KEY
|
193 NTLM_CHALLENGE_TARGET_IS_DOMAIN
|
194 NTLM_NEGOTIATE_ALWAYS_SIGN
|
195 NTLM_NEGOTIATE_USE_NTLM
|
196 NTLM_NEGOTIATE_USE_LM
|
197 NTLM_NEGOTIATE_ASCII
;
198 ntlm_make_challenge(&chal
, my_domain
, my_domain_controller
, (char *)challenge
, NTLM_NONCE_LEN
, flags
);
199 int len
= sizeof(chal
) - sizeof(chal
.payload
) + le16toh(chal
.target
.maxlen
);
200 return base64_encode_bin((char *)&chal
, len
);
203 /* returns NULL on failure, or a pointer to
204 * the user's credentials (domain\\username)
205 * upon success. WARNING. It's pointing to static storage.
206 * In case of problem sets as side-effect ntlm_errno to one of the
207 * codes defined in ntlm.h
210 ntlm_check_auth(ntlm_authenticate
* auth
, int auth_length
)
213 char pass
[MAX_PASSWD_LEN
+1];
214 char *domain
= credentials
;
218 if (handle
== NULL
) { /*if null we aren't connected, but it shouldn't happen */
219 debug("Weird, we've been disconnected\n");
220 ntlm_errno
= NTLM_ERR_NOT_CONNECTED
;
224 /* debug("fetching domain\n"); */
225 tmp
= ntlm_fetch_string(&(auth
->hdr
), auth_length
, &auth
->domain
, auth
->flags
);
226 if (tmp
.str
== NULL
|| tmp
.l
== 0) {
227 debug("No domain supplied. Returning no-auth\n");
228 ntlm_errno
= NTLM_ERR_LOGON
;
231 if (tmp
.l
> MAX_DOMAIN_LEN
) {
232 debug("Domain string exceeds %d bytes, rejecting\n", MAX_DOMAIN_LEN
);
233 ntlm_errno
= NTLM_ERR_LOGON
;
236 memcpy(domain
, tmp
.str
, tmp
.l
);
237 user
= domain
+ tmp
.l
;
241 /* debug("fetching user name\n"); */
242 tmp
= ntlm_fetch_string(&(auth
->hdr
), auth_length
, &auth
->user
, auth
->flags
);
243 if (tmp
.str
== NULL
|| tmp
.l
== 0) {
244 debug("No username supplied. Returning no-auth\n");
245 ntlm_errno
= NTLM_ERR_LOGON
;
248 if (tmp
.l
> MAX_USERNAME_LEN
) {
249 debug("Username string exceeds %d bytes, rejecting\n", MAX_USERNAME_LEN
);
250 ntlm_errno
= NTLM_ERR_LOGON
;
253 memcpy(user
, tmp
.str
, tmp
.l
);
254 *(user
+ tmp
.l
) = '\0';
256 /* Authenticating against the NT response doesn't seem to work... */
257 tmp
= ntlm_fetch_string(&(auth
->hdr
), auth_length
, &auth
->lmresponse
, auth
->flags
);
258 if (tmp
.str
== NULL
|| tmp
.l
== 0) {
259 fprintf(stderr
, "No auth at all. Returning no-auth\n");
260 ntlm_errno
= NTLM_ERR_LOGON
;
263 if (tmp
.l
> MAX_PASSWD_LEN
) {
264 debug("Password string exceeds %d bytes, rejecting\n", MAX_PASSWD_LEN
);
265 ntlm_errno
= NTLM_ERR_LOGON
;
269 memcpy(pass
, tmp
.str
, tmp
.l
);
270 pass
[min(MAX_PASSWD_LEN
,tmp
.l
)] = '\0';
273 debug("Empty LM pass detection: user: '%s', ours:'%s', his: '%s' (length: %d)\n",
274 user
,lmencoded_empty_pass
,tmp
.str
,tmp
.l
);
275 if (memcmp(tmp
.str
,lmencoded_empty_pass
,ENCODED_PASS_LEN
)==0) {
276 fprintf(stderr
,"Empty LM password supplied for user %s\\%s. "
277 "No-auth\n",domain
,user
);
278 ntlm_errno
=NTLM_ERR_LOGON
;
282 tmp
= ntlm_fetch_string(&(auth
->hdr
), auth_length
, &auth
->ntresponse
, auth
->flags
);
283 if (tmp
.str
!= NULL
&& tmp
.l
!= 0) {
284 debug("Empty NT pass detection: user: '%s', ours:'%s', his: '%s' (length: %d)\n",
285 user
,ntencoded_empty_pass
,tmp
.str
,tmp
.l
);
286 if (memcmp(tmp
.str
,lmencoded_empty_pass
,ENCODED_PASS_LEN
)==0) {
287 fprintf(stderr
,"ERROR: Empty NT password supplied for user %s\\%s. No-auth\n", domain
, user
);
288 ntlm_errno
= NTLM_ERR_LOGON
;
294 /* TODO: check against empty password!!!!! */
296 debug("checking domain: '%s', user: '%s', pass='%s'\n", domain
, user
, pass
);
298 rv
= SMB_Logon_Server(handle
, user
, pass
, domain
, 1);
299 debug("Login attempt had result %d\n", rv
);
301 if (rv
!= NTLM_ERR_NONE
) { /* failed */
305 *(user
- 1) = '\\'; /* hack. Performing, but ugly. */
307 debug("credentials: %s\n", credentials
);
311 extern "C" void timeout_during_auth(int signum
);
313 static char got_timeout
= 0;
314 /** signal handler to be invoked when the authentication operation
317 timeout_during_auth(int signum
)
324 * -b try load-balancing the domain-controllers
325 * -f fail-over to another DC if DC connection fails.
326 * DEPRECATED and VERBOSELY IGNORED. This is on by default now.
328 * domain\controller ...
330 char *my_program_name
= NULL
;
336 "%s usage:\n%s [-b] [-f] [-d] [-l] domain\\controller [domain\\controller ...]\n"
337 "-b enables load-balancing among controllers\n"
338 "-f enables failover among controllers (DEPRECATED and always active)\n"
339 "-d enables debugging statements if DEBUG was defined at build-time.\n\n"
340 "You MUST specify at least one Domain Controller.\n"
341 "You can use either \\ or / as separator between the domain name \n"
342 "and the controller name\n",
343 my_program_name
, my_program_name
);
346 /* int debug_enabled=0; defined in libcompat */
349 process_options(int argc
, char *argv
[])
351 int opt
, j
, had_error
= 0;
352 dc
*new_dc
= NULL
, *last_dc
= NULL
;
353 while (-1 != (opt
= getopt(argc
, argv
, "bfld"))) {
360 "WARNING. The -f flag is DEPRECATED and always active.\n");
366 fprintf(stderr
, "unknown option: -%c. Exiting\n", opt
);
373 /* Okay, now begin filling controllers up */
374 /* we can avoid memcpy-ing, and just reuse argv[] */
375 for (j
= optind
; j
< argc
; ++j
) {
377 /* d will not be freed in case of non-error. Since we don't reconfigure,
378 * it's going to live as long as the process anyways */
379 d
= (char*)malloc(strlen(argv
[j
]) + 1);
381 debug("Adding domain-controller %s\n", d
);
382 if (NULL
== (c
= strchr(d
, '\\')) && NULL
== (c
= strchr(d
, '/'))) {
383 fprintf(stderr
, "Couldn't grok domain-controller %s\n", d
);
387 /* more than one delimiter is not allowed */
388 if (NULL
!= strchr(c
+ 1, '\\') || NULL
!= strchr(c
+ 1, '/')) {
389 fprintf(stderr
, "Broken domain-controller %s\n", d
);
395 new_dc
= (dc
*) malloc(sizeof(dc
));
397 fprintf(stderr
, "Malloc error while parsing DC options\n");
406 new_dc
->controller
= c
;
408 if (controllers
== NULL
) { /* first controller */
409 controllers
= new_dc
;
412 last_dc
->next
= new_dc
; /* can't be null */
416 if (numcontrollers
== 0) {
417 fprintf(stderr
, "You must specify at least one domain-controller!\n");
421 last_dc
->next
= controllers
; /* close the queue, now it's circular */
425 * tries connecting to the domain controllers in the "controllers" ring,
426 * with failover if the adequate option is specified.
432 const char *ch
= NULL
;
433 for (j
= 0; j
< numcontrollers
; ++j
) {
434 debug("obtain_challenge: selecting %s\\%s (attempt #%d)\n",
435 current_dc
->domain
, current_dc
->controller
, j
+ 1);
436 if (current_dc
->dead
!= 0) {
437 if (time(NULL
) - current_dc
->dead
>= DEAD_DC_RETRY_INTERVAL
) {
438 /* mark helper as retry-worthy if it's so. */
439 debug("Reviving DC\n");
440 current_dc
->dead
= 0;
441 } else { /* skip it */
442 debug("Skipping it\n");
446 /* else branch. Here we KNOW that the DC is fine */
447 debug("attempting challenge retrieval\n");
448 ch
= make_challenge(current_dc
->domain
, current_dc
->controller
);
449 debug("make_challenge retuned %p\n", ch
);
452 return ch
; /* All went OK, returning */
454 /* Huston, we've got a problem. Take this DC out of the loop */
455 debug("Marking DC as DEAD\n");
456 current_dc
->dead
= time(NULL
);
457 /* Try with the next */
458 debug("moving on to next controller\n");
459 current_dc
= current_dc
->next
;
461 /* all DCs failed. */
468 ntlmhdr
*fast_header
;
469 char buf
[NTLM_BLOB_BUFFER_SIZE
];
470 char decoded
[NTLM_BLOB_BUFFER_SIZE
];
472 char *ch2
, *cred
= NULL
;
474 if (fgets(buf
, NTLM_BLOB_BUFFER_SIZE
, stdin
) == NULL
) {
475 fprintf(stderr
, "fgets() failed! dying..... errno=%d (%s)\n", errno
,
477 exit(1); /* BIIG buffer */
479 debug("managing request\n");
480 ch2
= (char*)memchr(buf
, '\n', NTLM_BLOB_BUFFER_SIZE
); /* safer against overrun than strchr */
482 *ch2
= '\0'; /* terminate the string at newline. */
485 debug("ntlm authenticator. Got '%s' from Squid\n", buf
);
487 if (memcmp(buf
, "KK ", 3) == 0) { /* authenticate-request */
488 /* figure out what we got */
489 int decodedLen
= base64_decode(decoded
, sizeof(decoded
), buf
+3);
491 if ((size_t)decodedLen
< sizeof(ntlmhdr
)) { /* decoding failure, return error */
492 SEND("NA Packet format error, couldn't base64-decode");
495 /* fast-track-decode request type. */
496 fast_header
= (ntlmhdr
*) decoded
;
498 /* sanity-check: it IS a NTLMSSP packet, isn't it? */
499 if (ntlm_validate_packet(fast_header
, NTLM_ANY
) < 0) {
500 SEND("NA Broken authentication packet");
503 switch (le32toh(fast_header
->type
)) {
505 SEND("NA Invalid negotiation request received");
509 SEND("NA Got a challenge. We refuse to have our authority disputed");
512 case NTLM_AUTHENTICATE
:
513 /* check against the DC */
514 signal(SIGALRM
, timeout_during_auth
);
516 cred
= ntlm_check_auth((ntlm_authenticate
*) decoded
, decodedLen
);
518 signal(SIGALRM
, SIG_DFL
);
519 if (got_timeout
!= 0) {
520 fprintf(stderr
, "ntlm-auth[%ld]: Timeout during authentication.\n", (long)getpid());
521 SEND("BH Timeout during authentication");
526 int smblib_err
, smb_errorclass
, smb_errorcode
, nb_error
;
527 if (ntlm_errno
== NTLM_ERR_LOGON
) { /* hackish */
528 SEND("NA Logon Failure");
531 /* there was an error. We have two errno's to look at.
532 * libntlmssp's erno is insufficient, we'll have to look at
533 * the actual SMB library error codes, to acually figure
534 * out what's happening. The thing has braindamaged interfacess..*/
535 smblib_err
= SMB_Get_Last_Error();
536 smb_errorclass
= SMBlib_Error_Class(SMB_Get_Last_SMB_Err());
537 smb_errorcode
= SMBlib_Error_Code(SMB_Get_Last_SMB_Err());
538 nb_error
= RFCNB_Get_Last_Error();
539 debug("No creds. SMBlib error %d, SMB error class %d, SMB error code %d, NB error %d\n",
540 smblib_err
, smb_errorclass
, smb_errorcode
, nb_error
);
541 /* Should I use smblib_err? Actually it seems I can do as well
543 if (nb_error
!= 0) { /* netbios-level error */
544 SEND("BH NetBios error!");
545 fprintf(stderr
, "NetBios error code %d (%s)\n", nb_error
,
546 RFCNB_Error_Strings
[abs(nb_error
)]);
549 switch (smb_errorclass
) {
551 debug("Huh? Got a SMB success code but could check auth..");
552 SEND("NA Authentication failed");
555 /*this is the most important one for errors */
556 debug("DOS error\n");
557 switch (smb_errorcode
) {
558 /* two categories matter to us: those which could be
559 * server errors, and those which are auth errors */
560 case SMBD_noaccess
: /* 5 */
561 SEND("NA Access denied");
564 SEND("NA bad format in authentication packet");
567 SEND("NA Bad access request");
573 SEND("BH DOS Error");
576 case SMBC_ERRSRV
: /* server errors */
577 debug("Server error");
578 switch (smb_errorcode
) {
579 /* mostly same as above */
581 SEND("NA Bad password");
584 SEND("NA Server access error");
587 SEND("BH Server Error");
590 case SMBC_ERRHRD
: /* hardware errors don't really matter */
591 SEND("BH Domain Controller Hardware error");
594 SEND("BH Domain Controller Command Error");
597 SEND("BH unknown internal error.");
601 lc(cred
); /* let's lowercase them for our convenience */
602 SEND2("AF %s", cred
);
605 SEND("BH unknown authentication packet type");
611 if (memcmp(buf
, "YR", 2) == 0) { /* refresh-request */
613 ch
= obtain_challenge();
614 /* Robert says we can afford to wait forever. I'll trust him on this
618 ch
= obtain_challenge();
623 SEND("BH Helper detected protocol error");
625 /********* END ********/
630 main(int argc
, char *argv
[])
632 debug("ntlm_auth build " __DATE__
", " __TIME__
" starting up...\n");
634 my_program_name
= argv
[0];
635 process_options(argc
, argv
);
637 debug("options processed OK\n");
639 /* initialize FDescs */
640 setbuf(stdout
, NULL
);
641 setbuf(stderr
, NULL
);
643 /* select the first domain controller we're going to use */
644 current_dc
= controllers
;
645 if (load_balance
!= 0 && numcontrollers
> 1) {
647 pid_t pid
= getpid();
648 n
= pid
% numcontrollers
;
649 debug("load balancing. Selected controller #%d\n", n
);
651 current_dc
= current_dc
->next
;