]> andersk Git - gssapi-openssh.git/blob - openssh/sshconnect1.c
port to OpenSSH 3.1p1
[gssapi-openssh.git] / openssh / sshconnect1.c
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * Code to connect to a remote host, and to perform the client side of the
6  * login (authentication) dialog.
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  */
14
15 #include "includes.h"
16 RCSID("$OpenBSD: sshconnect1.c,v 1.48 2002/02/11 16:15:46 markus Exp $");
17
18 #include <openssl/bn.h>
19 #include <openssl/md5.h>
20
21 #ifdef KRB4
22 #include <krb.h>
23 #endif
24 #ifdef KRB5
25 #include <krb5.h>
26 #ifndef HEIMDAL
27 #define krb5_get_err_text(context,code) error_message(code)
28 #endif /* !HEIMDAL */
29 #endif
30 #ifdef AFS
31 #include <kafs.h>
32 #include "radix.h"
33 #endif
34
35 #include "ssh.h"
36 #include "ssh1.h"
37 #include "xmalloc.h"
38 #include "rsa.h"
39 #include "buffer.h"
40 #include "packet.h"
41 #include "mpaux.h"
42 #include "uidswap.h"
43 #include "log.h"
44 #include "readconf.h"
45 #include "key.h"
46 #include "authfd.h"
47 #include "sshconnect.h"
48 #include "authfile.h"
49 #include "readpass.h"
50 #include "cipher.h"
51 #include "canohost.h"
52 #include "auth.h"
53
54 /*modified by binhe*/
55 #ifdef GSSAPI
56 #include <gssapi.h>
57 #include <openssl/md5.h>
58 #include "bufaux.h"
59 static char gssapi_patch_version[] = GSSAPI_PATCH_VERSION;
60 /*
61  * MD5 hash of host and session keys for verification. This is filled
62  * in in ssh_login() and then checked in try_gssapi_authentication().
63  */
64 unsigned char ssh_key_digest[16];
65 #endif /* GSSAPI */
66 /*end of modification*/
67
68 /* Session id for the current session. */
69 u_char session_id[16];
70 u_int supported_authentications = 0;
71
72 extern Options options;
73 extern char *__progname;
74
75 /*
76  * Checks if the user has an authentication agent, and if so, tries to
77  * authenticate using the agent.
78  */
79 static int
80 try_agent_authentication(void)
81 {
82         int type;
83         char *comment;
84         AuthenticationConnection *auth;
85         u_char response[16];
86         u_int i;
87         Key *key;
88         BIGNUM *challenge;
89
90         /* Get connection to the agent. */
91         auth = ssh_get_authentication_connection();
92         if (!auth)
93                 return 0;
94
95         if ((challenge = BN_new()) == NULL)
96                 fatal("try_agent_authentication: BN_new failed");
97         /* Loop through identities served by the agent. */
98         for (key = ssh_get_first_identity(auth, &comment, 1);
99             key != NULL;
100             key = ssh_get_next_identity(auth, &comment, 1)) {
101
102                 /* Try this identity. */
103                 debug("Trying RSA authentication via agent with '%.100s'", comment);
104                 xfree(comment);
105
106                 /* Tell the server that we are willing to authenticate using this key. */
107                 packet_start(SSH_CMSG_AUTH_RSA);
108                 packet_put_bignum(key->rsa->n);
109                 packet_send();
110                 packet_write_wait();
111
112                 /* Wait for server's response. */
113                 type = packet_read();
114
115                 /* The server sends failure if it doesn\'t like our key or
116                    does not support RSA authentication. */
117                 if (type == SSH_SMSG_FAILURE) {
118                         debug("Server refused our key.");
119                         key_free(key);
120                         continue;
121                 }
122                 /* Otherwise it should have sent a challenge. */
123                 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
124                         packet_disconnect("Protocol error during RSA authentication: %d",
125                                           type);
126
127                 packet_get_bignum(challenge);
128                 packet_check_eom();
129
130                 debug("Received RSA challenge from server.");
131
132                 /* Ask the agent to decrypt the challenge. */
133                 if (!ssh_decrypt_challenge(auth, key, challenge, session_id, 1, response)) {
134                         /*
135                          * The agent failed to authenticate this identifier
136                          * although it advertised it supports this.  Just
137                          * return a wrong value.
138                          */
139                         log("Authentication agent failed to decrypt challenge.");
140                         memset(response, 0, sizeof(response));
141                 }
142                 key_free(key);
143                 debug("Sending response to RSA challenge.");
144
145                 /* Send the decrypted challenge back to the server. */
146                 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
147                 for (i = 0; i < 16; i++)
148                         packet_put_char(response[i]);
149                 packet_send();
150                 packet_write_wait();
151
152                 /* Wait for response from the server. */
153                 type = packet_read();
154
155                 /* The server returns success if it accepted the authentication. */
156                 if (type == SSH_SMSG_SUCCESS) {
157                         ssh_close_authentication_connection(auth);
158                         BN_clear_free(challenge);
159                         debug("RSA authentication accepted by server.");
160                         return 1;
161                 }
162                 /* Otherwise it should return failure. */
163                 if (type != SSH_SMSG_FAILURE)
164                         packet_disconnect("Protocol error waiting RSA auth response: %d",
165                                           type);
166         }
167         ssh_close_authentication_connection(auth);
168         BN_clear_free(challenge);
169         debug("RSA authentication using agent refused.");
170         return 0;
171 }
172
173 /*
174  * Computes the proper response to a RSA challenge, and sends the response to
175  * the server.
176  */
177 static void
178 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
179 {
180         u_char buf[32], response[16];
181         MD5_CTX md;
182         int i, len;
183
184         /* Decrypt the challenge using the private key. */
185         /* XXX think about Bleichenbacher, too */
186         if (rsa_private_decrypt(challenge, challenge, prv) <= 0)
187                 packet_disconnect(
188                     "respond_to_rsa_challenge: rsa_private_decrypt failed");
189
190         /* Compute the response. */
191         /* The response is MD5 of decrypted challenge plus session id. */
192         len = BN_num_bytes(challenge);
193         if (len <= 0 || len > sizeof(buf))
194                 packet_disconnect(
195                     "respond_to_rsa_challenge: bad challenge length %d", len);
196
197         memset(buf, 0, sizeof(buf));
198         BN_bn2bin(challenge, buf + sizeof(buf) - len);
199         MD5_Init(&md);
200         MD5_Update(&md, buf, 32);
201         MD5_Update(&md, session_id, 16);
202         MD5_Final(response, &md);
203
204         debug("Sending response to host key RSA challenge.");
205
206         /* Send the response back to the server. */
207         packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
208         for (i = 0; i < 16; i++)
209                 packet_put_char(response[i]);
210         packet_send();
211         packet_write_wait();
212
213         memset(buf, 0, sizeof(buf));
214         memset(response, 0, sizeof(response));
215         memset(&md, 0, sizeof(md));
216 }
217
218 /*
219  * Checks if the user has authentication file, and if so, tries to authenticate
220  * the user using it.
221  */
222 static int
223 try_rsa_authentication(int idx)
224 {
225         BIGNUM *challenge;
226         Key *public, *private;
227         char buf[300], *passphrase, *comment, *authfile;
228         int i, type, quit;
229
230         public = options.identity_keys[idx];
231         authfile = options.identity_files[idx];
232         comment = xstrdup(authfile);
233
234         debug("Trying RSA authentication with key '%.100s'", comment);
235
236         /* Tell the server that we are willing to authenticate using this key. */
237         packet_start(SSH_CMSG_AUTH_RSA);
238         packet_put_bignum(public->rsa->n);
239         packet_send();
240         packet_write_wait();
241
242         /* Wait for server's response. */
243         type = packet_read();
244
245         /*
246          * The server responds with failure if it doesn\'t like our key or
247          * doesn\'t support RSA authentication.
248          */
249         if (type == SSH_SMSG_FAILURE) {
250                 debug("Server refused our key.");
251                 xfree(comment);
252                 return 0;
253         }
254         /* Otherwise, the server should respond with a challenge. */
255         if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
256                 packet_disconnect("Protocol error during RSA authentication: %d", type);
257
258         /* Get the challenge from the packet. */
259         if ((challenge = BN_new()) == NULL)
260                 fatal("try_rsa_authentication: BN_new failed");
261         packet_get_bignum(challenge);
262         packet_check_eom();
263
264         debug("Received RSA challenge from server.");
265
266         /*
267          * If the key is not stored in external hardware, we have to
268          * load the private key.  Try first with empty passphrase; if it
269          * fails, ask for a passphrase.
270          */
271         if (public->flags && KEY_FLAG_EXT)
272                 private = public;
273         else
274                 private = key_load_private_type(KEY_RSA1, authfile, "", NULL);
275         if (private == NULL && !options.batch_mode) {
276                 snprintf(buf, sizeof(buf),
277                     "Enter passphrase for RSA key '%.100s': ", comment);
278                 for (i = 0; i < options.number_of_password_prompts; i++) {
279                         passphrase = read_passphrase(buf, 0);
280                         if (strcmp(passphrase, "") != 0) {
281                                 private = key_load_private_type(KEY_RSA1,
282                                     authfile, passphrase, NULL);
283                                 quit = 0;
284                         } else {
285                                 debug2("no passphrase given, try next key");
286                                 quit = 1;
287                         }
288                         memset(passphrase, 0, strlen(passphrase));
289                         xfree(passphrase);
290                         if (private != NULL || quit)
291                                 break;
292                         debug2("bad passphrase given, try again...");
293                 }
294         }
295         /* We no longer need the comment. */
296         xfree(comment);
297
298         if (private == NULL) {
299                 if (!options.batch_mode)
300                         error("Bad passphrase.");
301
302                 /* Send a dummy response packet to avoid protocol error. */
303                 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
304                 for (i = 0; i < 16; i++)
305                         packet_put_char(0);
306                 packet_send();
307                 packet_write_wait();
308
309                 /* Expect the server to reject it... */
310                 packet_read_expect(SSH_SMSG_FAILURE);
311                 BN_clear_free(challenge);
312                 return 0;
313         }
314
315         /* Compute and send a response to the challenge. */
316         respond_to_rsa_challenge(challenge, private->rsa);
317
318         /* Destroy the private key unless it in external hardware. */
319         if (!(private->flags & KEY_FLAG_EXT))
320                 key_free(private);
321
322         /* We no longer need the challenge. */
323         BN_clear_free(challenge);
324
325         /* Wait for response from the server. */
326         type = packet_read();
327         if (type == SSH_SMSG_SUCCESS) {
328                 debug("RSA authentication accepted by server.");
329                 return 1;
330         }
331         if (type != SSH_SMSG_FAILURE)
332                 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
333         debug("RSA authentication refused.");
334         return 0;
335 }
336
337 /*
338  * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
339  * authentication and RSA host authentication.
340  */
341 static int
342 try_rhosts_rsa_authentication(const char *local_user, Key * host_key)
343 {
344         int type;
345         BIGNUM *challenge;
346
347         debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
348
349         /* Tell the server that we are willing to authenticate using this key. */
350         packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
351         packet_put_cstring(local_user);
352         packet_put_int(BN_num_bits(host_key->rsa->n));
353         packet_put_bignum(host_key->rsa->e);
354         packet_put_bignum(host_key->rsa->n);
355         packet_send();
356         packet_write_wait();
357
358         /* Wait for server's response. */
359         type = packet_read();
360
361         /* The server responds with failure if it doesn't admit our
362            .rhosts authentication or doesn't know our host key. */
363         if (type == SSH_SMSG_FAILURE) {
364                 debug("Server refused our rhosts authentication or host key.");
365                 return 0;
366         }
367         /* Otherwise, the server should respond with a challenge. */
368         if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
369                 packet_disconnect("Protocol error during RSA authentication: %d", type);
370
371         /* Get the challenge from the packet. */
372         if ((challenge = BN_new()) == NULL)
373                 fatal("try_rhosts_rsa_authentication: BN_new failed");
374         packet_get_bignum(challenge);
375         packet_check_eom();
376
377         debug("Received RSA challenge for host key from server.");
378
379         /* Compute a response to the challenge. */
380         respond_to_rsa_challenge(challenge, host_key->rsa);
381
382         /* We no longer need the challenge. */
383         BN_clear_free(challenge);
384
385         /* Wait for response from the server. */
386         type = packet_read();
387         if (type == SSH_SMSG_SUCCESS) {
388                 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
389                 return 1;
390         }
391         if (type != SSH_SMSG_FAILURE)
392                 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
393         debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
394         return 0;
395 }
396
397 #ifdef KRB4
398 static int
399 try_krb4_authentication(void)
400 {
401         KTEXT_ST auth;          /* Kerberos data */
402         char *reply;
403         char inst[INST_SZ];
404         char *realm;
405         CREDENTIALS cred;
406         int r, type;
407         socklen_t slen;
408         Key_schedule schedule;
409         u_long checksum, cksum;
410         MSG_DAT msg_data;
411         struct sockaddr_in local, foreign;
412         struct stat st;
413
414         /* Don't do anything if we don't have any tickets. */
415         if (stat(tkt_string(), &st) < 0)
416                 return 0;
417
418         strlcpy(inst, (char *)krb_get_phost(get_canonical_hostname(1)),
419             INST_SZ);
420
421         realm = (char *)krb_realmofhost(get_canonical_hostname(1));
422         if (!realm) {
423                 debug("Kerberos v4: no realm for %s", get_canonical_hostname(1));
424                 return 0;
425         }
426         /* This can really be anything. */
427         checksum = (u_long)getpid();
428
429         r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
430         if (r != KSUCCESS) {
431                 debug("Kerberos v4 krb_mk_req failed: %s", krb_err_txt[r]);
432                 return 0;
433         }
434         /* Get session key to decrypt the server's reply with. */
435         r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
436         if (r != KSUCCESS) {
437                 debug("get_cred failed: %s", krb_err_txt[r]);
438                 return 0;
439         }
440         des_key_sched((des_cblock *) cred.session, schedule);
441
442         /* Send authentication info to server. */
443         packet_start(SSH_CMSG_AUTH_KERBEROS);
444         packet_put_string((char *) auth.dat, auth.length);
445         packet_send();
446         packet_write_wait();
447
448         /* Zero the buffer. */
449         (void) memset(auth.dat, 0, MAX_KTXT_LEN);
450
451         slen = sizeof(local);
452         memset(&local, 0, sizeof(local));
453         if (getsockname(packet_get_connection_in(),
454             (struct sockaddr *)&local, &slen) < 0)
455                 debug("getsockname failed: %s", strerror(errno));
456
457         slen = sizeof(foreign);
458         memset(&foreign, 0, sizeof(foreign));
459         if (getpeername(packet_get_connection_in(),
460             (struct sockaddr *)&foreign, &slen) < 0) {
461                 debug("getpeername failed: %s", strerror(errno));
462                 fatal_cleanup();
463         }
464         /* Get server reply. */
465         type = packet_read();
466         switch (type) {
467         case SSH_SMSG_FAILURE:
468                 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
469                 debug("Kerberos v4 authentication failed.");
470                 return 0;
471                 break;
472
473         case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
474                 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
475                 debug("Kerberos v4 authentication accepted.");
476
477                 /* Get server's response. */
478                 reply = packet_get_string((u_int *) &auth.length);
479                 memcpy(auth.dat, reply, auth.length);
480                 xfree(reply);
481
482                 packet_check_eom();
483
484                 /*
485                  * If his response isn't properly encrypted with the session
486                  * key, and the decrypted checksum fails to match, he's
487                  * bogus. Bail out.
488                  */
489                 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
490                     &foreign, &local, &msg_data);
491                 if (r != KSUCCESS) {
492                         debug("Kerberos v4 krb_rd_priv failed: %s",
493                             krb_err_txt[r]);
494                         packet_disconnect("Kerberos v4 challenge failed!");
495                 }
496                 /* Fetch the (incremented) checksum that we supplied in the request. */
497                 memcpy((char *)&cksum, (char *)msg_data.app_data,
498                     sizeof(cksum));
499                 cksum = ntohl(cksum);
500
501                 /* If it matches, we're golden. */
502                 if (cksum == checksum + 1) {
503                         debug("Kerberos v4 challenge successful.");
504                         return 1;
505                 } else
506                         packet_disconnect("Kerberos v4 challenge failed!");
507                 break;
508
509         default:
510                 packet_disconnect("Protocol error on Kerberos v4 response: %d", type);
511         }
512         return 0;
513 }
514
515 #endif /* KRB4 */
516
517 #ifdef KRB5
518 static int
519 try_krb5_authentication(krb5_context *context, krb5_auth_context *auth_context)
520 {
521         krb5_error_code problem;
522         const char *tkfile;
523         struct stat buf;
524         krb5_ccache ccache = NULL;
525         const char *remotehost;
526         krb5_data ap;
527         int type;
528         krb5_ap_rep_enc_part *reply = NULL;
529         int ret;
530
531         memset(&ap, 0, sizeof(ap));
532
533         problem = krb5_init_context(context);
534         if (problem) {
535                 debug("Kerberos v5: krb5_init_context failed");
536                 ret = 0;
537                 goto out;
538         }
539         
540         problem = krb5_auth_con_init(*context, auth_context);
541         if (problem) {
542                 debug("Kerberos v5: krb5_auth_con_init failed");
543                 ret = 0;
544                 goto out;
545         }
546
547 #ifndef HEIMDAL
548         problem = krb5_auth_con_setflags(*context, *auth_context,
549                                          KRB5_AUTH_CONTEXT_RET_TIME);
550         if (problem) {
551                 debug("Keberos v5: krb5_auth_con_setflags failed");
552                 ret = 0;
553                 goto out;
554         }
555 #endif
556
557         tkfile = krb5_cc_default_name(*context);
558         if (strncmp(tkfile, "FILE:", 5) == 0)
559                 tkfile += 5;
560
561         if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) {
562                 debug("Kerberos v5: could not get default ccache (permission denied).");
563                 ret = 0;
564                 goto out;
565         }
566
567         problem = krb5_cc_default(*context, &ccache);
568         if (problem) {
569                 debug("Kerberos v5: krb5_cc_default failed: %s",
570                     krb5_get_err_text(*context, problem));
571                 ret = 0;
572                 goto out;
573         }
574
575         remotehost = get_canonical_hostname(1);
576
577         problem = krb5_mk_req(*context, auth_context, AP_OPTS_MUTUAL_REQUIRED,
578             "host", remotehost, NULL, ccache, &ap);
579         if (problem) {
580                 debug("Kerberos v5: krb5_mk_req failed: %s",
581                     krb5_get_err_text(*context, problem));
582                 ret = 0;
583                 goto out;
584         }
585
586         packet_start(SSH_CMSG_AUTH_KERBEROS);
587         packet_put_string((char *) ap.data, ap.length);
588         packet_send();
589         packet_write_wait();
590
591         xfree(ap.data);
592         ap.length = 0;
593
594         type = packet_read();
595         switch (type) {
596         case SSH_SMSG_FAILURE:
597                 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
598                 debug("Kerberos v5 authentication failed.");
599                 ret = 0;
600                 break;
601
602         case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
603                 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
604                 debug("Kerberos v5 authentication accepted.");
605
606                 /* Get server's response. */
607                 ap.data = packet_get_string((unsigned int *) &ap.length);
608                 packet_check_eom();
609                 /* XXX je to dobre? */
610
611                 problem = krb5_rd_rep(*context, *auth_context, &ap, &reply);
612                 if (problem) {
613                         ret = 0;
614                 }
615                 ret = 1;
616                 break;
617
618         default:
619                 packet_disconnect("Protocol error on Kerberos v5 response: %d",
620                     type);
621                 ret = 0;
622                 break;
623
624         }
625
626  out:
627         if (ccache != NULL)
628                 krb5_cc_close(*context, ccache);
629         if (reply != NULL)
630                 krb5_free_ap_rep_enc_part(*context, reply);
631         if (ap.length > 0)
632 #ifdef HEIMDAL
633                 krb5_data_free(&ap);
634 #else
635                 krb5_free_data_contents(*context, &ap);
636 #endif
637
638         return (ret);
639 }
640
641 static void
642 send_krb5_tgt(krb5_context context, krb5_auth_context auth_context)
643 {
644         int fd, type;
645         krb5_error_code problem;
646         krb5_data outbuf;
647         krb5_ccache ccache = NULL;
648         krb5_creds creds;
649 #ifdef HEIMDAL
650         krb5_kdc_flags flags;
651 #else
652         int forwardable;
653 #endif
654         const char *remotehost;
655
656         memset(&creds, 0, sizeof(creds));
657         memset(&outbuf, 0, sizeof(outbuf));
658
659         fd = packet_get_connection_in();
660
661 #ifdef HEIMDAL
662         problem = krb5_auth_con_setaddrs_from_fd(context, auth_context, &fd);
663 #else
664         problem = krb5_auth_con_genaddrs(context, auth_context, fd,
665                         KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR |
666                         KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR);
667 #endif
668         if (problem)
669                 goto out;
670
671         problem = krb5_cc_default(context, &ccache);
672         if (problem)
673                 goto out;
674
675         problem = krb5_cc_get_principal(context, ccache, &creds.client);
676         if (problem)
677                 goto out;
678
679         remotehost = get_canonical_hostname(1);
680         
681 #ifdef HEIMDAL
682         problem = krb5_build_principal(context, &creds.server,
683             strlen(creds.client->realm), creds.client->realm,
684             "krbtgt", creds.client->realm, NULL);
685 #else
686         problem = krb5_build_principal(context, &creds.server,
687             creds.client->realm.length, creds.client->realm.data,
688             "host", remotehost, NULL);
689 #endif
690         if (problem)
691                 goto out;
692
693         creds.times.endtime = 0;
694
695 #ifdef HEIMDAL
696         flags.i = 0;
697         flags.b.forwarded = 1;
698         flags.b.forwardable = krb5_config_get_bool(context,  NULL,
699             "libdefaults", "forwardable", NULL);
700         problem = krb5_get_forwarded_creds(context, auth_context,
701             ccache, flags.i, remotehost, &creds, &outbuf);
702 #else
703         forwardable = 1;
704         problem = krb5_fwd_tgt_creds(context, auth_context, remotehost,
705             creds.client, creds.server, ccache, forwardable, &outbuf);
706 #endif
707
708         if (problem)
709                 goto out;
710
711         packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
712         packet_put_string((char *)outbuf.data, outbuf.length);
713         packet_send();
714         packet_write_wait();
715
716         type = packet_read();
717
718         if (type == SSH_SMSG_SUCCESS) {
719                 char *pname;
720
721                 krb5_unparse_name(context, creds.client, &pname);
722                 debug("Kerberos v5 TGT forwarded (%s).", pname);
723                 xfree(pname);
724         } else
725                 debug("Kerberos v5 TGT forwarding failed.");
726
727         return;
728
729  out:
730         if (problem)
731                 debug("Kerberos v5 TGT forwarding failed: %s",
732                     krb5_get_err_text(context, problem));
733         if (creds.client)
734                 krb5_free_principal(context, creds.client);
735         if (creds.server)
736                 krb5_free_principal(context, creds.server);
737         if (ccache)
738                 krb5_cc_close(context, ccache);
739         if (outbuf.data)
740                 xfree(outbuf.data);
741 }
742 #endif /* KRB5 */
743
744 #ifdef AFS
745 static void
746 send_krb4_tgt(void)
747 {
748         CREDENTIALS *creds;
749         struct stat st;
750         char buffer[4096], pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
751         int problem, type;
752
753         /* Don't do anything if we don't have any tickets. */
754         if (stat(tkt_string(), &st) < 0)
755                 return;
756
757         creds = xmalloc(sizeof(*creds));
758
759         problem = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm);
760         if (problem)
761                 goto out;
762
763         problem = krb_get_cred("krbtgt", prealm, prealm, creds);
764         if (problem)
765                 goto out;
766
767         if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
768                 problem = RD_AP_EXP;
769                 goto out;
770         }
771         creds_to_radix(creds, (u_char *)buffer, sizeof(buffer));
772
773         packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
774         packet_put_cstring(buffer);
775         packet_send();
776         packet_write_wait();
777
778         type = packet_read();
779
780         if (type == SSH_SMSG_SUCCESS)
781                 debug("Kerberos v4 TGT forwarded (%s%s%s@%s).",
782                     creds->pname, creds->pinst[0] ? "." : "",
783                     creds->pinst, creds->realm);
784         else
785                 debug("Kerberos v4 TGT rejected.");
786
787         xfree(creds);
788         return;
789
790  out:
791         debug("Kerberos v4 TGT passing failed: %s", krb_err_txt[problem]);
792         xfree(creds);
793 }
794
795 static void
796 send_afs_tokens(void)
797 {
798         CREDENTIALS creds;
799         struct ViceIoctl parms;
800         struct ClearToken ct;
801         int i, type, len;
802         char buf[2048], *p, *server_cell;
803         char buffer[8192];
804
805         /* Move over ktc_GetToken, here's something leaner. */
806         for (i = 0; i < 100; i++) {     /* just in case */
807                 parms.in = (char *) &i;
808                 parms.in_size = sizeof(i);
809                 parms.out = buf;
810                 parms.out_size = sizeof(buf);
811                 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
812                         break;
813                 p = buf;
814
815                 /* Get secret token. */
816                 memcpy(&creds.ticket_st.length, p, sizeof(u_int));
817                 if (creds.ticket_st.length > MAX_KTXT_LEN)
818                         break;
819                 p += sizeof(u_int);
820                 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
821                 p += creds.ticket_st.length;
822
823                 /* Get clear token. */
824                 memcpy(&len, p, sizeof(len));
825                 if (len != sizeof(struct ClearToken))
826                         break;
827                 p += sizeof(len);
828                 memcpy(&ct, p, len);
829                 p += len;
830                 p += sizeof(len);       /* primary flag */
831                 server_cell = p;
832
833                 /* Flesh out our credentials. */
834                 strlcpy(creds.service, "afs", sizeof(creds.service));
835                 creds.instance[0] = '\0';
836                 strlcpy(creds.realm, server_cell, REALM_SZ);
837                 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
838                 creds.issue_date = ct.BeginTimestamp;
839                 creds.lifetime = krb_time_to_life(creds.issue_date,
840                     ct.EndTimestamp);
841                 creds.kvno = ct.AuthHandle;
842                 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
843                 creds.pinst[0] = '\0';
844
845                 /* Encode token, ship it off. */
846                 if (creds_to_radix(&creds, (u_char *)buffer,
847                     sizeof(buffer)) <= 0)
848                         break;
849                 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
850                 packet_put_cstring(buffer);
851                 packet_send();
852                 packet_write_wait();
853
854                 /* Roger, Roger. Clearance, Clarence. What's your vector,
855                    Victor? */
856                 type = packet_read();
857
858                 if (type == SSH_SMSG_FAILURE)
859                         debug("AFS token for cell %s rejected.", server_cell);
860                 else if (type != SSH_SMSG_SUCCESS)
861                         packet_disconnect("Protocol error on AFS token response: %d", type);
862         }
863 }
864
865 #endif /* AFS */
866
867 /*
868  * Tries to authenticate with any string-based challenge/response system.
869  * Note that the client code is not tied to s/key or TIS.
870  */
871 static int
872 try_challenge_response_authentication(void)
873 {
874         int type, i;
875         u_int clen;
876         char prompt[1024];
877         char *challenge, *response;
878
879         debug("Doing challenge response authentication.");
880
881         for (i = 0; i < options.number_of_password_prompts; i++) {
882                 /* request a challenge */
883                 packet_start(SSH_CMSG_AUTH_TIS);
884                 packet_send();
885                 packet_write_wait();
886
887                 type = packet_read();
888                 if (type != SSH_SMSG_FAILURE &&
889                     type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
890                         packet_disconnect("Protocol error: got %d in response "
891                             "to SSH_CMSG_AUTH_TIS", type);
892                 }
893                 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
894                         debug("No challenge.");
895                         return 0;
896                 }
897                 challenge = packet_get_string(&clen);
898                 packet_check_eom();
899                 snprintf(prompt, sizeof prompt, "%s%s", challenge,
900                     strchr(challenge, '\n') ? "" : "\nResponse: ");
901                 xfree(challenge);
902                 if (i != 0)
903                         error("Permission denied, please try again.");
904                 if (options.cipher == SSH_CIPHER_NONE)
905                         log("WARNING: Encryption is disabled! "
906                             "Reponse will be transmitted in clear text.");
907                 response = read_passphrase(prompt, 0);
908                 if (strcmp(response, "") == 0) {
909                         xfree(response);
910                         break;
911                 }
912                 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
913                 ssh_put_password(response);
914                 memset(response, 0, strlen(response));
915                 xfree(response);
916                 packet_send();
917                 packet_write_wait();
918                 type = packet_read();
919                 if (type == SSH_SMSG_SUCCESS)
920                         return 1;
921                 if (type != SSH_SMSG_FAILURE)
922                         packet_disconnect("Protocol error: got %d in response "
923                             "to SSH_CMSG_AUTH_TIS_RESPONSE", type);
924         }
925         /* failure */
926         return 0;
927 }
928
929 /*
930  * Tries to authenticate with plain passwd authentication.
931  */
932 static int
933 try_password_authentication(char *prompt)
934 {
935         int type, i;
936         char *password;
937
938         debug("Doing password authentication.");
939         if (options.cipher == SSH_CIPHER_NONE)
940                 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
941         for (i = 0; i < options.number_of_password_prompts; i++) {
942                 if (i != 0)
943                         error("Permission denied, please try again.");
944                 password = read_passphrase(prompt, 0);
945                 packet_start(SSH_CMSG_AUTH_PASSWORD);
946                 ssh_put_password(password);
947                 memset(password, 0, strlen(password));
948                 xfree(password);
949                 packet_send();
950                 packet_write_wait();
951
952                 type = packet_read();
953                 if (type == SSH_SMSG_SUCCESS)
954                         return 1;
955                 if (type != SSH_SMSG_FAILURE)
956                         packet_disconnect("Protocol error: got %d in response to passwd auth", type);
957         }
958         /* failure */
959         return 0;
960 }
961
962 /*modified by binhe*/
963 #ifdef GSSAPI
964 /*
965  * This code stolen from the gss-client.c sample program from MIT's
966  * kerberos 5 distribution.
967  */
968
969 gss_cred_id_t gss_cred = GSS_C_NO_CREDENTIAL;
970
971 static void display_status_1(m, code, type)
972  char *m;
973  OM_uint32 code;
974  int type;
975 {
976   OM_uint32 maj_stat, min_stat;
977   gss_buffer_desc msg;
978   OM_uint32 msg_ctx;
979
980   msg_ctx = 0;
981   while (1) {
982     maj_stat = gss_display_status(&min_stat, code,
983                                   type, GSS_C_NULL_OID,
984                                   &msg_ctx, &msg);
985     debug("GSS-API error %s: %s", m, (char *)msg.value);
986     (void) gss_release_buffer(&min_stat, &msg);
987
988     if (!msg_ctx)
989       break;
990   }
991 }
992
993 static void display_gssapi_status(msg, maj_stat, min_stat)
994   char *msg;
995   OM_uint32 maj_stat;
996   OM_uint32 min_stat;
997 {
998   display_status_1(msg, maj_stat, GSS_C_GSS_CODE);
999   display_status_1(msg, min_stat, GSS_C_MECH_CODE);
1000 }
1001
1002 #ifdef GSI
1003 int get_gssapi_cred()
1004 {
1005   OM_uint32 maj_stat;
1006   OM_uint32 min_stat;
1007
1008
1009   debug("calling gss_acquire_cred");
1010   maj_stat = gss_acquire_cred(&min_stat,
1011                               GSS_C_NO_NAME,
1012                               GSS_C_INDEFINITE,
1013                               GSS_C_NO_OID_SET,
1014                               GSS_C_INITIATE,
1015                               &gss_cred,
1016                               NULL,
1017                               NULL);
1018
1019   if (maj_stat != GSS_S_COMPLETE) {
1020     display_gssapi_status("Failuring acquiring GSSAPI credentials",
1021                           maj_stat, min_stat);
1022     gss_cred = GSS_C_NO_CREDENTIAL; /* should not be needed */
1023     return 0;
1024   }
1025
1026   return 1;     /* Success */
1027 }
1028
1029 char * get_gss_our_name()
1030 {
1031   OM_uint32 maj_stat;
1032   OM_uint32 min_stat;
1033   gss_name_t pname = GSS_C_NO_NAME;
1034   gss_buffer_desc tmpname;
1035   gss_buffer_t tmpnamed = &tmpname;
1036   char *retname;
1037
1038   debug("calling gss_inquire_cred");
1039   maj_stat = gss_inquire_cred(&min_stat,
1040                               gss_cred,
1041                               &pname,
1042                               NULL,
1043                               NULL,
1044                               NULL);
1045   if (maj_stat != GSS_S_COMPLETE) {
1046     return NULL;
1047   }
1048
1049   maj_stat = gss_export_name(&min_stat,
1050                              pname,
1051                              tmpnamed);
1052   if (maj_stat != GSS_S_COMPLETE) {
1053     return NULL;
1054   }
1055   debug("gss_export_name finsished");
1056   retname = (char *)malloc(tmpname.length + 1);
1057   if (!retname) {
1058     return NULL;
1059   }
1060   memcpy(retname, tmpname.value, tmpname.length);
1061   retname[tmpname.length] = '\0';
1062
1063   gss_release_name(&min_stat, &pname);
1064   gss_release_buffer(&min_stat, tmpnamed);
1065
1066   return retname;
1067 }
1068 #endif /* GSI */
1069
1070 int try_gssapi_authentication(char *host, Options *options)
1071 {
1072   char *service_name = NULL;
1073   gss_buffer_desc name_tok;
1074   gss_buffer_desc send_tok;
1075   gss_buffer_desc recv_tok;
1076   gss_buffer_desc *token_ptr;
1077   gss_name_t target_name = NULL;
1078   gss_ctx_id_t gss_context;
1079   gss_OID_desc mech_oid;
1080   gss_OID name_type;
1081   gss_OID_set my_mechs;
1082   int my_mech_num;
1083   OM_uint32 maj_stat;
1084   OM_uint32 min_stat;
1085   int ret_stat = 0;                             /* 1 == success */
1086   OM_uint32 req_flags = 0;
1087   OM_uint32 ret_flags;
1088   int type;
1089   char *gssapi_auth_type = NULL;
1090   struct hostent *hostinfo;
1091
1092
1093   /*
1094    * host is not guarenteed to be a FQDN, so we need to make sure it is.
1095    */
1096   hostinfo = gethostbyname(host);
1097
1098   if ((hostinfo == NULL) || (hostinfo->h_name == NULL)) {
1099       debug("GSSAPI authentication: Unable to get FQDN for \"%s\"", host);
1100       goto cleanup;
1101   }
1102
1103   /*
1104    * Default flags
1105    */
1106   req_flags |= GSS_C_REPLAY_FLAG;
1107
1108   /* Do mutual authentication */
1109   req_flags |= GSS_C_MUTUAL_FLAG;
1110
1111 #ifdef GSSAPI_KRB5
1112
1113   gssapi_auth_type = "GSSAPI/Kerberos 5";
1114
1115 #endif /* GSSAPI_KRB5 */
1116
1117 #ifdef GSI
1118
1119   gssapi_auth_type = "GSSAPI/GLOBUS";
1120
1121 #endif /* GSI */
1122
1123   if (gssapi_auth_type == NULL) {
1124       debug("No GSSAPI type defined during compile");
1125       goto cleanup;
1126   }
1127
1128   debug("Attempting %s authentication", gssapi_auth_type);
1129
1130   service_name = (char *) malloc(strlen(GSSAPI_SERVICE_NAME) +
1131                                  strlen(hostinfo->h_name) +
1132                                  2 /* 1 for '@', 1 for NUL */);
1133
1134   if (service_name == NULL) {
1135     debug("malloc() failed");
1136     goto cleanup;
1137   }
1138
1139
1140   sprintf(service_name, "%s@%s", GSSAPI_SERVICE_NAME, hostinfo->h_name);
1141
1142   name_type = GSS_C_NT_HOSTBASED_SERVICE;
1143
1144   debug("Service name is %s", service_name);
1145
1146   /* Forward credentials? */
1147
1148 #ifdef GSSAPI_KRB5
1149   if (options->kerberos_tgt_passing) {
1150       debug("Forwarding Kerberos credentials");
1151       req_flags |= GSS_C_DELEG_FLAG;
1152   }
1153 #endif /* GSSAPI_KRB5 */
1154
1155 #ifdef GSSAPI
1156   if(options->gss_deleg_creds) {
1157     debug("Forwarding X509 proxy certificate");
1158     req_flags |= GSS_C_DELEG_FLAG;
1159   }
1160 #ifdef GSS_C_GLOBUS_LIMITED_DELEG_PROXY_FLAG
1161   /* Forward limited credentials, overrides gss_deleg_creds */
1162   if(options->gss_globus_deleg_limited_proxy) {
1163     debug("Forwarding limited X509 proxy certificate");
1164     req_flags |= (GSS_C_DELEG_FLAG | GSS_C_GLOBUS_LIMITED_DELEG_PROXY_FLAG);
1165   }
1166 #endif /* GSS_C_GLOBUS_LIMITED_DELEG_PROXY_FLAG */
1167
1168 #endif /* GSSAPI */
1169
1170   debug("req_flags = %lu", req_flags);
1171
1172   name_tok.value = service_name;
1173   name_tok.length = strlen(service_name) + 1;
1174   maj_stat = gss_import_name(&min_stat, &name_tok,
1175                              name_type, &target_name);
1176
1177   free(service_name);
1178   service_name = NULL;
1179
1180   if (maj_stat != GSS_S_COMPLETE) {
1181     display_gssapi_status("importing service name", maj_stat, min_stat);
1182     goto cleanup;
1183   }
1184
1185   maj_stat = gss_indicate_mechs(&min_stat, &my_mechs);
1186
1187   if (maj_stat != GSS_S_COMPLETE) {
1188     display_gssapi_status("indicating mechs", maj_stat, min_stat);
1189     goto cleanup;
1190   }
1191
1192   /*
1193    * Send over a packet to the daemon, letting it know we're doing
1194    * GSSAPI and our mech_oid(s).
1195    */
1196   debug("Sending mech oid to server");
1197   packet_start(SSH_CMSG_AUTH_GSSAPI);
1198   packet_put_int(my_mechs->count); /* Number of mechs we're sending */
1199   for (my_mech_num = 0; my_mech_num < my_mechs->count; my_mech_num++)
1200       packet_put_string(my_mechs->elements[my_mech_num].elements,
1201                         my_mechs->elements[my_mech_num].length);
1202   packet_send();
1203   packet_write_wait();
1204
1205   /*
1206    * Get reply from the daemon to see if our mech was acceptable
1207    */
1208   type = packet_read();
1209
1210   switch (type) {
1211   case SSH_SMSG_AUTH_GSSAPI_RESPONSE:
1212       debug("Server accepted mechanism");
1213       /* Successful negotiation */
1214       break;
1215
1216   case SSH_MSG_AUTH_GSSAPI_ABORT:
1217       debug("Unable to negotiate GSSAPI mechanism type with server");
1218       packet_get_all();
1219       goto cleanup;
1220
1221   default:
1222       packet_disconnect("Protocol error during GSSAPI authentication:"
1223                         " packet type %d received",
1224                         type);
1225       /* Does not return */
1226   }
1227
1228   /* Read the mechanism the server returned */
1229   mech_oid.elements = packet_get_string((unsigned int *) &(mech_oid.length));
1230   packet_get_all();
1231
1232   /*
1233    * Perform the context-establishement loop.
1234    *
1235    * On each pass through the loop, token_ptr points to the token
1236    * to send to the server (or GSS_C_NO_BUFFER on the first pass).
1237    * Every generated token is stored in send_tok which is then
1238    * transmitted to the server; every received token is stored in
1239    * recv_tok, which token_ptr is then set to, to be processed by
1240    * the next call to gss_init_sec_context.
1241    *
1242    * GSS-API guarantees that send_tok's length will be non-zero
1243    * if and only if the server is expecting another token from us,
1244    * and that gss_init_sec_context returns GSS_S_CONTINUE_NEEDED if
1245    * and only if the server has another token to send us.
1246    */
1247
1248   token_ptr = GSS_C_NO_BUFFER;
1249   gss_context = GSS_C_NO_CONTEXT;
1250
1251   do {
1252     maj_stat =
1253       gss_init_sec_context(&min_stat,
1254                            gss_cred,
1255                            &gss_context,
1256                            target_name,
1257                            &mech_oid,
1258                            req_flags,
1259                            0,
1260                            NULL,        /* no channel bindings */
1261                            token_ptr,
1262                            NULL,        /* ignore mech type */
1263                            &send_tok,
1264                            &ret_flags,
1265                            NULL);       /* ignore time_rec */
1266
1267     if (token_ptr != GSS_C_NO_BUFFER)
1268       (void) gss_release_buffer(&min_stat, &recv_tok);
1269
1270     if (maj_stat != GSS_S_COMPLETE && maj_stat != GSS_S_CONTINUE_NEEDED) {
1271       display_gssapi_status("initializing context", maj_stat, min_stat);
1272
1273       /* Send an abort message */
1274       packet_start(SSH_MSG_AUTH_GSSAPI_ABORT);
1275       packet_send();
1276       packet_write_wait();
1277
1278       goto cleanup;
1279     }
1280
1281     if (send_tok.length != 0) {
1282       debug("Sending authenticaton token...");
1283       packet_start(SSH_MSG_AUTH_GSSAPI_TOKEN);
1284       packet_put_string((char *) send_tok.value, send_tok.length);
1285       packet_send();
1286       packet_write_wait();
1287
1288       (void) gss_release_buffer(&min_stat, &send_tok);
1289     }
1290
1291     if (maj_stat == GSS_S_CONTINUE_NEEDED) {
1292
1293       debug("Continue needed. Reading response...");
1294
1295       type = packet_read();
1296
1297       switch(type) {
1298
1299       case SSH_MSG_AUTH_GSSAPI_TOKEN:
1300         /* This is what we expected */
1301         break;
1302
1303       case SSH_MSG_AUTH_GSSAPI_ABORT:
1304         debug("Server aborted GSSAPI authentication.");
1305         packet_get_all();
1306         goto cleanup;
1307
1308       default:
1309         packet_disconnect("Protocol error during GSSAPI authentication:"
1310                           " packet type %d received",
1311                           type);
1312         /* Does not return */
1313       }
1314
1315       recv_tok.value = packet_get_string((unsigned int *) &recv_tok.length);
1316       packet_get_all();
1317       token_ptr = &recv_tok;
1318     }
1319   } while (maj_stat == GSS_S_CONTINUE_NEEDED);
1320
1321   /* Success */
1322   ret_stat = 1;
1323
1324   debug("%s authentication successful", gssapi_auth_type);
1325
1326   /*
1327    * Read hash of host and server keys and make sure it
1328    * matches what we got earlier.
1329    */
1330   debug("Reading hash of server and host keys...");
1331   type = packet_read();
1332
1333   if (type == SSH_MSG_AUTH_GSSAPI_ABORT) {
1334     debug("Server aborted GSSAPI authentication.");
1335     packet_get_all();
1336     ret_stat = 0;
1337     goto cleanup;
1338
1339   } else if (type == SSH_SMSG_AUTH_GSSAPI_HASH) {
1340     gss_buffer_desc wrapped_buf;
1341     gss_buffer_desc unwrapped_buf;
1342     int conf_state;
1343     gss_qop_t qop_state;
1344
1345
1346     wrapped_buf.value = packet_get_string(&(wrapped_buf.length));
1347     packet_get_all();
1348
1349     maj_stat = gss_unwrap(&min_stat,
1350                           gss_context,
1351                           &wrapped_buf,
1352                           &unwrapped_buf,
1353                           &conf_state,
1354                           &qop_state);
1355
1356     if (maj_stat != GSS_S_COMPLETE) {
1357       display_gssapi_status("unwraping SSHD key hash",
1358                             maj_stat, min_stat);
1359       packet_disconnect("Verification of SSHD keys through GSSAPI-secured channel failed: "
1360                         "Unwrapping of hash failed.");
1361     }
1362
1363     if (unwrapped_buf.length != sizeof(ssh_key_digest)) {
1364       packet_disconnect("Verification of SSHD keys through GSSAPI-secured channel failed: "
1365                         "Size of key hashes do not match (%d != %d)!",
1366                         unwrapped_buf.length, sizeof(ssh_key_digest));
1367     }
1368
1369     if (memcmp(ssh_key_digest, unwrapped_buf.value, sizeof(ssh_key_digest)) != 0) {
1370       packet_disconnect("Verification of SSHD keys through GSSAPI-secured channel failed: "
1371                         "Hashes don't match!");
1372     }
1373
1374     debug("Verified SSHD keys through GSSAPI-secured channel.");
1375
1376     gss_release_buffer(&min_stat, &unwrapped_buf);
1377
1378   } else {
1379       packet_disconnect("Protocol error during GSSAPI authentication:"
1380                         "packet type %d received", type);
1381       /* Does not return */
1382   }
1383
1384
1385  cleanup:
1386   if (target_name != NULL)
1387       (void) gss_release_name(&min_stat, &target_name);
1388
1389   return ret_stat;
1390 }
1391
1392 #endif /* GSSAPI */
1393
1394 /*end of modification*/
1395
1396 /*
1397  * SSH1 key exchange
1398  */
1399 void
1400 ssh_kex(char *host, struct sockaddr *hostaddr)
1401 {
1402         int i;
1403         BIGNUM *key;
1404         Key *host_key, *server_key;
1405         int bits, rbits;
1406         int ssh_cipher_default = SSH_CIPHER_3DES;
1407         u_char session_key[SSH_SESSION_KEY_LENGTH];
1408         u_char cookie[8];
1409         u_int supported_ciphers;
1410         u_int server_flags, client_flags;
1411         u_int32_t rand = 0;
1412
1413         debug("Waiting for server public key.");
1414
1415         /* Wait for a public key packet from the server. */
1416         packet_read_expect(SSH_SMSG_PUBLIC_KEY);
1417
1418         /* Get cookie from the packet. */
1419         for (i = 0; i < 8; i++)
1420                 cookie[i] = packet_get_char();
1421
1422         /* Get the public key. */
1423         server_key = key_new(KEY_RSA1);
1424         bits = packet_get_int();
1425         packet_get_bignum(server_key->rsa->e);
1426         packet_get_bignum(server_key->rsa->n);
1427
1428         rbits = BN_num_bits(server_key->rsa->n);
1429         if (bits != rbits) {
1430                 log("Warning: Server lies about size of server public key: "
1431                     "actual size is %d bits vs. announced %d.", rbits, bits);
1432                 log("Warning: This may be due to an old implementation of ssh.");
1433         }
1434         /* Get the host key. */
1435         host_key = key_new(KEY_RSA1);
1436         bits = packet_get_int();
1437         packet_get_bignum(host_key->rsa->e);
1438         packet_get_bignum(host_key->rsa->n);
1439
1440         rbits = BN_num_bits(host_key->rsa->n);
1441         if (bits != rbits) {
1442                 log("Warning: Server lies about size of server host key: "
1443                     "actual size is %d bits vs. announced %d.", rbits, bits);
1444                 log("Warning: This may be due to an old implementation of ssh.");
1445         }
1446
1447 /*modified by binhe*/
1448 #ifdef GSSAPI
1449   {
1450     MD5_CTX md5context;
1451     Buffer buf;
1452     unsigned char *data;
1453     unsigned int data_len;
1454
1455     /*
1456      * Hash the server and host keys. Later we will check them against
1457      * a hash sent over a secure channel to make sure they are legit.
1458      */
1459     debug("Calculating MD5 hash of server and host keys...");
1460
1461     /* Write all the keys to a temporary buffer */
1462     buffer_init(&buf);
1463
1464     /* Server key */
1465     buffer_put_bignum(&buf, server_key->rsa->e);
1466     buffer_put_bignum(&buf, server_key->rsa->n);
1467
1468     /* Host key */
1469     buffer_put_bignum(&buf, host_key->rsa->e);
1470     buffer_put_bignum(&buf, host_key->rsa->n);
1471
1472     /* Get the resulting data */
1473     data = (unsigned char *) buffer_ptr(&buf);
1474     data_len = buffer_len(&buf);
1475
1476     /* And hash it */
1477     MD5_Init(&md5context);
1478     MD5_Update(&md5context, data, data_len);
1479     MD5_Final(ssh_key_digest, &md5context);
1480
1481     /* Clean up */
1482     buffer_clear(&buf);
1483     buffer_free(&buf);
1484   }
1485 #endif /* GSSAPI */
1486 /*end of modification*/
1487
1488         /* Get protocol flags. */
1489         server_flags = packet_get_int();
1490         packet_set_protocol_flags(server_flags);
1491
1492         supported_ciphers = packet_get_int();
1493         supported_authentications = packet_get_int();
1494         packet_check_eom();
1495
1496         debug("Received server public key (%d bits) and host key (%d bits).",
1497             BN_num_bits(server_key->rsa->n), BN_num_bits(host_key->rsa->n));
1498
1499         if (verify_host_key(host, hostaddr, host_key) == -1)
1500                 fatal("Host key verification failed.");
1501
1502         client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
1503
1504         compute_session_id(session_id, cookie, host_key->rsa->n, server_key->rsa->n);
1505
1506         /* Generate a session key. */
1507         arc4random_stir();
1508
1509         /*
1510          * Generate an encryption key for the session.   The key is a 256 bit
1511          * random number, interpreted as a 32-byte key, with the least
1512          * significant 8 bits being the first byte of the key.
1513          */
1514         for (i = 0; i < 32; i++) {
1515                 if (i % 4 == 0)
1516                         rand = arc4random();
1517                 session_key[i] = rand & 0xff;
1518                 rand >>= 8;
1519         }
1520
1521         /*
1522          * According to the protocol spec, the first byte of the session key
1523          * is the highest byte of the integer.  The session key is xored with
1524          * the first 16 bytes of the session id.
1525          */
1526         if ((key = BN_new()) == NULL)
1527                 fatal("respond_to_rsa_challenge: BN_new failed");
1528         BN_set_word(key, 0);
1529         for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1530                 BN_lshift(key, key, 8);
1531                 if (i < 16)
1532                         BN_add_word(key, session_key[i] ^ session_id[i]);
1533                 else
1534                         BN_add_word(key, session_key[i]);
1535         }
1536
1537         /*
1538          * Encrypt the integer using the public key and host key of the
1539          * server (key with smaller modulus first).
1540          */
1541         if (BN_cmp(server_key->rsa->n, host_key->rsa->n) < 0) {
1542                 /* Public key has smaller modulus. */
1543                 if (BN_num_bits(host_key->rsa->n) <
1544                     BN_num_bits(server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1545                         fatal("respond_to_rsa_challenge: host_key %d < server_key %d + "
1546                             "SSH_KEY_BITS_RESERVED %d",
1547                             BN_num_bits(host_key->rsa->n),
1548                             BN_num_bits(server_key->rsa->n),
1549                             SSH_KEY_BITS_RESERVED);
1550                 }
1551                 rsa_public_encrypt(key, key, server_key->rsa);
1552                 rsa_public_encrypt(key, key, host_key->rsa);
1553         } else {
1554                 /* Host key has smaller modulus (or they are equal). */
1555                 if (BN_num_bits(server_key->rsa->n) <
1556                     BN_num_bits(host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1557                         fatal("respond_to_rsa_challenge: server_key %d < host_key %d + "
1558                             "SSH_KEY_BITS_RESERVED %d",
1559                             BN_num_bits(server_key->rsa->n),
1560                             BN_num_bits(host_key->rsa->n),
1561                             SSH_KEY_BITS_RESERVED);
1562                 }
1563                 rsa_public_encrypt(key, key, host_key->rsa);
1564                 rsa_public_encrypt(key, key, server_key->rsa);
1565         }
1566
1567         /* Destroy the public keys since we no longer need them. */
1568         key_free(server_key);
1569         key_free(host_key);
1570
1571         if (options.cipher == SSH_CIPHER_NOT_SET) {
1572                 if (cipher_mask_ssh1(1) & supported_ciphers & (1 << ssh_cipher_default))
1573                         options.cipher = ssh_cipher_default;
1574         } else if (options.cipher == SSH_CIPHER_ILLEGAL ||
1575             !(cipher_mask_ssh1(1) & (1 << options.cipher))) {
1576                 log("No valid SSH1 cipher, using %.100s instead.",
1577                     cipher_name(ssh_cipher_default));
1578                 options.cipher = ssh_cipher_default;
1579         }
1580         /* Check that the selected cipher is supported. */
1581         if (!(supported_ciphers & (1 << options.cipher)))
1582                 fatal("Selected cipher type %.100s not supported by server.",
1583                     cipher_name(options.cipher));
1584
1585         debug("Encryption type: %.100s", cipher_name(options.cipher));
1586
1587         /* Send the encrypted session key to the server. */
1588         packet_start(SSH_CMSG_SESSION_KEY);
1589         packet_put_char(options.cipher);
1590
1591         /* Send the cookie back to the server. */
1592         for (i = 0; i < 8; i++)
1593                 packet_put_char(cookie[i]);
1594
1595         /* Send and destroy the encrypted encryption key integer. */
1596         packet_put_bignum(key);
1597         BN_clear_free(key);
1598
1599         /* Send protocol flags. */
1600         packet_put_int(client_flags);
1601
1602         /* Send the packet now. */
1603         packet_send();
1604         packet_write_wait();
1605
1606         debug("Sent encrypted session key.");
1607
1608         /* Set the encryption key. */
1609         packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1610
1611         /* We will no longer need the session key here.  Destroy any extra copies. */
1612         memset(session_key, 0, sizeof(session_key));
1613
1614         /*
1615          * Expect a success message from the server.  Note that this message
1616          * will be received in encrypted form.
1617          */
1618         packet_read_expect(SSH_SMSG_SUCCESS);
1619
1620         debug("Received encrypted confirmation.");
1621 }
1622
1623 /*
1624  * Authenticate user
1625  */
1626 void
1627 ssh_userauth1(const char *local_user, const char *server_user, char *host,
1628     Key **keys, int nkeys)
1629 {
1630 /*modified by binhe*/
1631 #ifdef GSSAPI
1632 #ifdef GSI
1633         const char *save_server_user = NULL;
1634 #endif /* GSI */
1635 #endif /* GSSAPI */
1636 /*end of modification*/
1637
1638 #ifdef KRB5
1639         krb5_context context = NULL;
1640         krb5_auth_context auth_context = NULL;
1641 #endif
1642         int i, type;
1643
1644         if (supported_authentications == 0)
1645                 fatal("ssh_userauth1: server supports no auth methods");
1646
1647 /*modified by binhe*/
1648 #ifdef GSSAPI
1649 #ifdef GSI
1650   /* if no user given, tack on the subject name after the server_user.
1651    * This will allow us to run gridmap early to get real user
1652    * This name will start with /C=
1653    */
1654   if ((supported_authentications & (1 << SSH_AUTH_GSSAPI)) &&
1655       options.gss_authentication) {
1656     if (get_gssapi_cred()) {
1657       char * retname;
1658       char * newname;
1659
1660
1661       save_server_user = server_user;
1662
1663       retname = get_gss_our_name();
1664
1665       if (retname) {
1666         debug("passing gssapi name '%s'", retname);
1667         if (server_user) {
1668           newname = (char *) malloc(strlen(retname) + strlen(server_user) + 4);
1669           if (newname) {
1670             strcpy(newname, server_user);
1671             if(options.user == NULL)
1672               {
1673                 strcat(newname,":i:");
1674               }
1675             else
1676               {
1677                 strcat(newname,":x:");
1678               }
1679             strcat(newname, retname);
1680             server_user = newname;
1681             free(retname);
1682           }
1683         }
1684       }
1685     } else {
1686       /*
1687        * If we couldn't successfully get our GSSAPI credentials then
1688        * turn off gssapi authentication
1689        */
1690       options.gss_authentication = 0;
1691     }
1692     debug("server_user %s", server_user);
1693   }
1694 #endif /* GSI */
1695 #endif /* GSSAPI */
1696 /*end of modification*/
1697
1698         /* Send the name of the user to log in as on the server. */
1699         packet_start(SSH_CMSG_USER);
1700         packet_put_cstring(server_user);
1701         packet_send();
1702         packet_write_wait();
1703
1704 /*modified by binhe*/
1705 #if defined(GSI)
1706   if(save_server_user)
1707     {
1708       server_user = save_server_user;
1709     }
1710 #endif
1711 /*end of modification*/
1712         /*
1713          * The server should respond with success if no authentication is
1714          * needed (the user has no password).  Otherwise the server responds
1715          * with failure.
1716          */
1717         type = packet_read();
1718
1719         /* check whether the connection was accepted without authentication. */
1720         if (type == SSH_SMSG_SUCCESS)
1721                 goto success;
1722         if (type != SSH_SMSG_FAILURE)
1723                 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER", type);
1724
1725 /*modified by binhe*/
1726 #ifdef GSSAPI
1727   /* Try GSSAPI authentication */
1728   if ((supported_authentications & (1 << SSH_AUTH_GSSAPI)) &&
1729       options.gss_authentication)
1730     {
1731       debug("Trying GSSAPI authentication (%s)...", gssapi_patch_version);
1732       try_gssapi_authentication(host, &options);
1733
1734       /*
1735        * XXX Hmmm. Kerberos authentication only reads a packet if it thinks
1736        * the authentication went OK, but the server seems to always send
1737        * a packet back. So I'm not sure if I'm missing something or
1738        * the Kerberos code is broken. - vwelch 1/27/99
1739        */
1740
1741       type = packet_read();
1742       if (type == SSH_SMSG_SUCCESS)
1743         return; /* Successful connection. */
1744       if (type != SSH_SMSG_FAILURE)
1745         packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1746
1747       debug("GSSAPI authentication failed");
1748     }
1749 #endif /* GSSAPI */
1750 /*end of modification*/
1751         
1752 #ifdef KRB5
1753         if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1754             options.kerberos_authentication) {
1755                 debug("Trying Kerberos v5 authentication.");
1756
1757                 if (try_krb5_authentication(&context, &auth_context)) {
1758                         type = packet_read();
1759                         if (type == SSH_SMSG_SUCCESS)
1760                                 goto success;
1761                         if (type != SSH_SMSG_FAILURE)
1762                                 packet_disconnect("Protocol error: got %d in response to Kerberos v5 auth", type);
1763                 }
1764         }
1765 #endif /* KRB5 */
1766
1767 #ifdef KRB4
1768         if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1769             options.kerberos_authentication) {
1770                 debug("Trying Kerberos v4 authentication.");
1771
1772                 if (try_krb4_authentication()) {
1773                         type = packet_read();
1774                         if (type == SSH_SMSG_SUCCESS)
1775                                 goto success;
1776                         if (type != SSH_SMSG_FAILURE)
1777                                 packet_disconnect("Protocol error: got %d in response to Kerberos v4 auth", type);
1778                 }
1779         }
1780 #endif /* KRB4 */
1781
1782         /*
1783          * Use rhosts authentication if running in privileged socket and we
1784          * do not wish to remain anonymous.
1785          */
1786         if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1787             options.rhosts_authentication) {
1788                 debug("Trying rhosts authentication.");
1789                 packet_start(SSH_CMSG_AUTH_RHOSTS);
1790                 packet_put_cstring(local_user);
1791                 packet_send();
1792                 packet_write_wait();
1793
1794                 /* The server should respond with success or failure. */
1795                 type = packet_read();
1796                 if (type == SSH_SMSG_SUCCESS)
1797                         goto success;
1798                 if (type != SSH_SMSG_FAILURE)
1799                         packet_disconnect("Protocol error: got %d in response to rhosts auth",
1800                                           type);
1801         }
1802         /*
1803          * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1804          * authentication.
1805          */
1806         if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1807             options.rhosts_rsa_authentication) {
1808                 for (i = 0; i < nkeys; i++) {
1809                         if (keys[i] != NULL && keys[i]->type == KEY_RSA1 &&
1810                             try_rhosts_rsa_authentication(local_user, keys[i]))
1811                                 goto success;
1812                 }
1813         }
1814         /* Try RSA authentication if the server supports it. */
1815         if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1816             options.rsa_authentication) {
1817                 /*
1818                  * Try RSA authentication using the authentication agent. The
1819                  * agent is tried first because no passphrase is needed for
1820                  * it, whereas identity files may require passphrases.
1821                  */
1822                 if (try_agent_authentication())
1823                         goto success;
1824
1825                 /* Try RSA authentication for each identity. */
1826                 for (i = 0; i < options.num_identity_files; i++)
1827                         if (options.identity_keys[i] != NULL &&
1828                             options.identity_keys[i]->type == KEY_RSA1 &&
1829                             try_rsa_authentication(i))
1830                                 goto success;
1831         }
1832         /* Try challenge response authentication if the server supports it. */
1833         if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1834             options.challenge_response_authentication && !options.batch_mode) {
1835                 if (try_challenge_response_authentication())
1836                         goto success;
1837         }
1838         /* Try password authentication if the server supports it. */
1839         if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1840             options.password_authentication && !options.batch_mode) {
1841                 char prompt[80];
1842
1843                 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
1844                     server_user, host);
1845                 if (try_password_authentication(prompt))
1846                         goto success;
1847         }
1848         /* All authentication methods have failed.  Exit with an error message. */
1849         fatal("Permission denied.");
1850         /* NOTREACHED */
1851
1852  success:
1853 #ifdef KRB5
1854         /* Try Kerberos v5 TGT passing. */
1855         if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1856             options.kerberos_tgt_passing && context && auth_context) {
1857                 if (options.cipher == SSH_CIPHER_NONE)
1858                         log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1859                 send_krb5_tgt(context, auth_context);
1860         }
1861         if (auth_context)
1862                 krb5_auth_con_free(context, auth_context);
1863         if (context)
1864                 krb5_free_context(context);
1865 #endif
1866
1867 #ifdef AFS
1868         /* Try Kerberos v4 TGT passing if the server supports it. */
1869         if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1870             options.kerberos_tgt_passing) {
1871                 if (options.cipher == SSH_CIPHER_NONE)
1872                         log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1873                 send_krb4_tgt();
1874         }
1875         /* Try AFS token passing if the server supports it. */
1876         if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1877             options.afs_token_passing && k_hasafs()) {
1878                 if (options.cipher == SSH_CIPHER_NONE)
1879                         log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1880                 send_afs_tokens();
1881         }
1882 #endif /* AFS */
1883
1884         return; /* need statement after label */
1885 }
This page took 0.249965 seconds and 5 git commands to generate.