]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - usr.sbin/iscsid/login.c
MFC r261747:
[FreeBSD/stable/10.git] / usr.sbin / iscsid / login.c
1 /*-
2  * Copyright (c) 2012 The FreeBSD Foundation
3  * All rights reserved.
4  *
5  * This software was developed by Edward Tomasz Napierala under sponsorship
6  * from the FreeBSD Foundation.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31
32 #include <sys/types.h>
33 #include <assert.h>
34 #include <stdbool.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <netinet/in.h>
39 #include <openssl/err.h>
40 #include <openssl/md5.h>
41 #include <openssl/rand.h>
42
43 #include "iscsid.h"
44 #include "iscsi_proto.h"
45
46 static int
47 login_nsg(const struct pdu *response)
48 {
49         struct iscsi_bhs_login_response *bhslr;
50
51         bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
52
53         return (bhslr->bhslr_flags & 0x03);
54 }
55
56 static void
57 login_set_nsg(struct pdu *request, int nsg)
58 {
59         struct iscsi_bhs_login_request *bhslr;
60
61         assert(nsg == BHSLR_STAGE_SECURITY_NEGOTIATION ||
62             nsg == BHSLR_STAGE_OPERATIONAL_NEGOTIATION ||
63             nsg == BHSLR_STAGE_FULL_FEATURE_PHASE);
64
65         bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
66
67         bhslr->bhslr_flags &= 0xFC;
68         bhslr->bhslr_flags |= nsg;
69 }
70
71 static void
72 login_set_csg(struct pdu *request, int csg)
73 {
74         struct iscsi_bhs_login_request *bhslr;
75
76         assert(csg == BHSLR_STAGE_SECURITY_NEGOTIATION ||
77             csg == BHSLR_STAGE_OPERATIONAL_NEGOTIATION ||
78             csg == BHSLR_STAGE_FULL_FEATURE_PHASE);
79
80         bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
81
82         bhslr->bhslr_flags &= 0xF3;
83         bhslr->bhslr_flags |= csg << 2;
84 }
85
86 static const char *
87 login_target_error_str(int class, int detail)
88 {
89         static char msg[128];
90
91         /*
92          * RFC 3270, 10.13.5.  Status-Class and Status-Detail
93          */
94         switch (class) {
95         case 0x01:
96                 switch (detail) {
97                 case 0x01:
98                         return ("Target moved temporarily");
99                 case 0x02:
100                         return ("Target moved permanently");
101                 default:
102                         snprintf(msg, sizeof(msg), "unknown redirection; "
103                             "Status-Class 0x%x, Status-Detail 0x%x",
104                             class, detail);
105                         return (msg);
106                 }
107         case 0x02:
108                 switch (detail) {
109                 case 0x00:
110                         return ("Initiator error");
111                 case 0x01:
112                         return ("Authentication failure");
113                 case 0x02:
114                         return ("Authorization failure");
115                 case 0x03:
116                         return ("Not found");
117                 case 0x04:
118                         return ("Target removed");
119                 case 0x05:
120                         return ("Unsupported version");
121                 case 0x06:
122                         return ("Too many connections");
123                 case 0x07:
124                         return ("Missing parameter");
125                 case 0x08:
126                         return ("Can't include in session");
127                 case 0x09:
128                         return ("Session type not supported");
129                 case 0x0a:
130                         return ("Session does not exist");
131                 case 0x0b:
132                         return ("Invalid during login");
133                 default:
134                         snprintf(msg, sizeof(msg), "unknown initiator error; "
135                             "Status-Class 0x%x, Status-Detail 0x%x",
136                             class, detail);
137                         return (msg);
138                 }
139         case 0x03:
140                 switch (detail) {
141                 case 0x00:
142                         return ("Target error");
143                 case 0x01:
144                         return ("Service unavailable");
145                 case 0x02:
146                         return ("Out of resources");
147                 default:
148                         snprintf(msg, sizeof(msg), "unknown target error; "
149                             "Status-Class 0x%x, Status-Detail 0x%x",
150                             class, detail);
151                         return (msg);
152                 }
153         default:
154                 snprintf(msg, sizeof(msg), "unknown error; "
155                     "Status-Class 0x%x, Status-Detail 0x%x",
156                     class, detail);
157                 return (msg);
158         }
159 }
160
161 static struct pdu *
162 login_receive(struct connection *conn, bool initial)
163 {
164         struct pdu *response;
165         struct iscsi_bhs_login_response *bhslr;
166         const char *errorstr;
167
168         response = pdu_new(conn);
169         pdu_receive(response);
170         if (response->pdu_bhs->bhs_opcode != ISCSI_BHS_OPCODE_LOGIN_RESPONSE) {
171                 log_errx(1, "protocol error: received invalid opcode 0x%x",
172                     response->pdu_bhs->bhs_opcode);
173         }
174         bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
175         /*
176          * XXX: Implement the C flag some day.
177          */
178         if ((bhslr->bhslr_flags & BHSLR_FLAGS_CONTINUE) != 0)
179                 log_errx(1, "received Login PDU with unsupported \"C\" flag");
180         if (bhslr->bhslr_version_max != 0x00)
181                 log_errx(1, "received Login PDU with unsupported "
182                     "Version-max 0x%x", bhslr->bhslr_version_max);
183         if (bhslr->bhslr_version_active != 0x00)
184                 log_errx(1, "received Login PDU with unsupported "
185                     "Version-active 0x%x", bhslr->bhslr_version_active);
186         if (bhslr->bhslr_status_class != 0) {
187                 errorstr = login_target_error_str(bhslr->bhslr_status_class,
188                     bhslr->bhslr_status_detail);
189                 fail(conn, errorstr);
190                 log_errx(1, "target returned error: %s", errorstr);
191         }
192         if (initial == false &&
193             ntohl(bhslr->bhslr_statsn) != conn->conn_statsn + 1) {
194                 /*
195                  * It's a warning, not an error, to work around what seems
196                  * to be bug in NetBSD iSCSI target.
197                  */
198                 log_warnx("received Login PDU with wrong StatSN: "
199                     "is %d, should be %d", ntohl(bhslr->bhslr_statsn),
200                     conn->conn_statsn + 1);
201         }
202         conn->conn_statsn = ntohl(bhslr->bhslr_statsn);
203
204         return (response);
205 }
206
207 static struct pdu *
208 login_new_request(struct connection *conn)
209 {
210         struct pdu *request;
211         struct iscsi_bhs_login_request *bhslr;
212
213         request = pdu_new(conn);
214         bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
215         bhslr->bhslr_opcode = ISCSI_BHS_OPCODE_LOGIN_REQUEST |
216             ISCSI_BHS_OPCODE_IMMEDIATE;
217         bhslr->bhslr_flags = BHSLR_FLAGS_TRANSIT;
218         login_set_csg(request, BHSLR_STAGE_SECURITY_NEGOTIATION);
219         login_set_nsg(request, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
220         memcpy(bhslr->bhslr_isid, &conn->conn_isid, sizeof(bhslr->bhslr_isid));
221         bhslr->bhslr_initiator_task_tag = 0;
222         bhslr->bhslr_cmdsn = 0;
223         bhslr->bhslr_expstatsn = htonl(conn->conn_statsn + 1);
224
225         return (request);
226 }
227
228 static int
229 login_list_prefers(const char *list,
230     const char *choice1, const char *choice2)
231 {
232         char *tofree, *str, *token;
233
234         tofree = str = checked_strdup(list);
235
236         while ((token = strsep(&str, ",")) != NULL) {
237                 if (strcmp(token, choice1) == 0) {
238                         free(tofree);
239                         return (1);
240                 }
241                 if (strcmp(token, choice2) == 0) {
242                         free(tofree);
243                         return (2);
244                 }
245         }
246         free(tofree);
247         return (-1);
248 }
249
250 static int
251 login_hex2int(const char hex)
252 {
253         switch (hex) {
254         case '0':
255                 return (0x00);
256         case '1':
257                 return (0x01);
258         case '2':
259                 return (0x02);
260         case '3':
261                 return (0x03);
262         case '4':
263                 return (0x04);
264         case '5':
265                 return (0x05);
266         case '6':
267                 return (0x06);
268         case '7':
269                 return (0x07);
270         case '8':
271                 return (0x08);
272         case '9':
273                 return (0x09);
274         case 'a':
275         case 'A':
276                 return (0x0a);
277         case 'b':
278         case 'B':
279                 return (0x0b);
280         case 'c':
281         case 'C':
282                 return (0x0c);
283         case 'd':
284         case 'D':
285                 return (0x0d);
286         case 'e':
287         case 'E':
288                 return (0x0e);
289         case 'f':
290         case 'F':
291                 return (0x0f);
292         default:
293                 return (-1);
294         }
295 }
296
297 /*
298  * XXX: Review this _carefully_.
299  */
300 static int
301 login_hex2bin(const char *hex, char **binp, size_t *bin_lenp)
302 {
303         int i, hex_len, nibble;
304         bool lo = true; /* As opposed to 'hi'. */
305         char *bin;
306         size_t bin_off, bin_len;
307
308         if (strncasecmp(hex, "0x", strlen("0x")) != 0) {
309                 log_warnx("malformed variable, should start with \"0x\"");
310                 return (-1);
311         }
312
313         hex += strlen("0x");
314         hex_len = strlen(hex);
315         if (hex_len < 1) {
316                 log_warnx("malformed variable; doesn't contain anything "
317                     "but \"0x\"");
318                 return (-1);
319         }
320
321         bin_len = hex_len / 2 + hex_len % 2;
322         bin = calloc(bin_len, 1);
323         if (bin == NULL)
324                 log_err(1, "calloc");
325
326         bin_off = bin_len - 1;
327         for (i = hex_len - 1; i >= 0; i--) {
328                 nibble = login_hex2int(hex[i]);
329                 if (nibble < 0) {
330                         log_warnx("malformed variable, invalid char \"%c\"",
331                             hex[i]);
332                         return (-1);
333                 }
334
335                 assert(bin_off < bin_len);
336                 if (lo) {
337                         bin[bin_off] = nibble;
338                         lo = false;
339                 } else {
340                         bin[bin_off] |= nibble << 4;
341                         bin_off--;
342                         lo = true;
343                 }
344         }
345
346         *binp = bin;
347         *bin_lenp = bin_len;
348         return (0);
349 }
350
351 static char *
352 login_bin2hex(const char *bin, size_t bin_len)
353 {
354         unsigned char *hex, *tmp, ch;
355         size_t hex_len;
356         size_t i;
357
358         hex_len = bin_len * 2 + 3; /* +2 for "0x", +1 for '\0'. */
359         hex = malloc(hex_len);
360         if (hex == NULL)
361                 log_err(1, "malloc");
362
363         tmp = hex;
364         tmp += sprintf(tmp, "0x");
365         for (i = 0; i < bin_len; i++) {
366                 ch = bin[i];
367                 tmp += sprintf(tmp, "%02x", ch);
368         }
369
370         return (hex);
371 }
372
373 static void
374 login_compute_md5(const char id, const char *secret,
375     const void *challenge, size_t challenge_len, void *response,
376     size_t response_len)
377 {
378         MD5_CTX ctx;
379         int rv;
380
381         assert(response_len == MD5_DIGEST_LENGTH);
382
383         MD5_Init(&ctx);
384         MD5_Update(&ctx, &id, sizeof(id));
385         MD5_Update(&ctx, secret, strlen(secret));
386         MD5_Update(&ctx, challenge, challenge_len);
387         rv = MD5_Final(response, &ctx);
388         if (rv != 1)
389                 log_errx(1, "MD5_Final");
390 }
391
392 static void
393 login_negotiate_key(struct connection *conn, const char *name,
394     const char *value)
395 {
396         int which, tmp;
397
398         if (strcmp(name, "TargetAlias") == 0) {
399                 strlcpy(conn->conn_target_alias, value,
400                     sizeof(conn->conn_target_alias));
401         } else if (strcmp(value, "Irrelevant") == 0) {
402                 /* Ignore. */
403         } else if (strcmp(name, "HeaderDigest") == 0) {
404                 which = login_list_prefers(value, "CRC32C", "None");
405                 switch (which) {
406                 case 1:
407                         log_debugx("target prefers CRC32C "
408                             "for header digest; we'll use it");
409                         conn->conn_header_digest = CONN_DIGEST_CRC32C;
410                         break;
411                 case 2:
412                         log_debugx("target prefers not to do "
413                             "header digest; we'll comply");
414                         break;
415                 default:
416                         log_warnx("target sent unrecognized "
417                             "HeaderDigest value \"%s\"; will use None", value);
418                         break;
419                 }
420         } else if (strcmp(name, "DataDigest") == 0) {
421                 which = login_list_prefers(value, "CRC32C", "None");
422                 switch (which) {
423                 case 1:
424                         log_debugx("target prefers CRC32C "
425                             "for data digest; we'll use it");
426                         conn->conn_data_digest = CONN_DIGEST_CRC32C;
427                         break;
428                 case 2:
429                         log_debugx("target prefers not to do "
430                             "data digest; we'll comply");
431                         break;
432                 default:
433                         log_warnx("target sent unrecognized "
434                             "DataDigest value \"%s\"; will use None", value);
435                         break;
436                 }
437         } else if (strcmp(name, "MaxConnections") == 0) {
438                 /* Ignore. */
439         } else if (strcmp(name, "InitialR2T") == 0) {
440                 if (strcmp(value, "Yes") == 0)
441                         conn->conn_initial_r2t = true;
442                 else
443                         conn->conn_initial_r2t = false;
444         } else if (strcmp(name, "ImmediateData") == 0) {
445                 if (strcmp(value, "Yes") == 0)
446                         conn->conn_immediate_data = true;
447                 else
448                         conn->conn_immediate_data = false;
449         } else if (strcmp(name, "MaxRecvDataSegmentLength") == 0) {
450                 tmp = strtoul(value, NULL, 10);
451                 if (tmp <= 0)
452                         log_errx(1, "received invalid "
453                             "MaxRecvDataSegmentLength");
454                 conn->conn_max_data_segment_length = tmp;
455         } else if (strcmp(name, "MaxBurstLength") == 0) {
456                 if (conn->conn_immediate_data) {
457                         tmp = strtoul(value, NULL, 10);
458                         if (tmp <= 0)
459                                 log_errx(1, "received invalid MaxBurstLength");
460                         conn->conn_max_burst_length = tmp;
461                 }
462         } else if (strcmp(name, "FirstBurstLength") == 0) {
463                 tmp = strtoul(value, NULL, 10);
464                 if (tmp <= 0)
465                         log_errx(1, "received invalid FirstBurstLength");
466                 conn->conn_first_burst_length = tmp;
467         } else if (strcmp(name, "DefaultTime2Wait") == 0) {
468                 /* Ignore */
469         } else if (strcmp(name, "DefaultTime2Retain") == 0) {
470                 /* Ignore */
471         } else if (strcmp(name, "MaxOutstandingR2T") == 0) {
472                 /* Ignore */
473         } else if (strcmp(name, "DataPDUInOrder") == 0) {
474                 /* Ignore */
475         } else if (strcmp(name, "DataSequenceInOrder") == 0) {
476                 /* Ignore */
477         } else if (strcmp(name, "ErrorRecoveryLevel") == 0) {
478                 /* Ignore */
479         } else if (strcmp(name, "OFMarker") == 0) {
480                 /* Ignore */
481         } else if (strcmp(name, "IFMarker") == 0) {
482                 /* Ignore */
483         } else if (strcmp(name, "TargetPortalGroupTag") == 0) {
484                 /* Ignore */
485         } else {
486                 log_debugx("unknown key \"%s\"; ignoring",  name);
487         }
488 }
489
490 static void
491 login_negotiate(struct connection *conn)
492 {
493         struct pdu *request, *response;
494         struct keys *request_keys, *response_keys;
495         struct iscsi_bhs_login_response *bhslr;
496         int i;
497
498         log_debugx("beginning parameter negotiation");
499         request = login_new_request(conn);
500         login_set_csg(request, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
501         login_set_nsg(request, BHSLR_STAGE_FULL_FEATURE_PHASE);
502         request_keys = keys_new();
503
504         /*
505          * The following keys are irrelevant for discovery sessions.
506          */
507         if (conn->conn_conf.isc_discovery == 0) {
508                 if (conn->conn_conf.isc_header_digest != 0)
509                         keys_add(request_keys, "HeaderDigest", "CRC32C");
510                 else
511                         keys_add(request_keys, "HeaderDigest", "None");
512                 if (conn->conn_conf.isc_data_digest != 0)
513                         keys_add(request_keys, "DataDigest", "CRC32C");
514                 else
515                         keys_add(request_keys, "DataDigest", "None");
516
517                 keys_add(request_keys, "ImmediateData", "Yes");
518                 keys_add_int(request_keys, "MaxBurstLength",
519                     ISCSI_MAX_DATA_SEGMENT_LENGTH);
520                 keys_add_int(request_keys, "FirstBurstLength",
521                     ISCSI_MAX_DATA_SEGMENT_LENGTH);
522                 keys_add(request_keys, "InitialR2T", "Yes");
523         } else {
524                 keys_add(request_keys, "HeaderDigest", "None");
525                 keys_add(request_keys, "DataDigest", "None");
526         }
527
528         keys_add_int(request_keys, "MaxRecvDataSegmentLength",
529             ISCSI_MAX_DATA_SEGMENT_LENGTH);
530         keys_add(request_keys, "DefaultTime2Wait", "0");
531         keys_add(request_keys, "DefaultTime2Retain", "0");
532         keys_add(request_keys, "ErrorRecoveryLevel", "0");
533         keys_add(request_keys, "MaxOutstandingR2T", "1");
534         keys_save(request_keys, request);
535         keys_delete(request_keys);
536         request_keys = NULL;
537         pdu_send(request);
538         pdu_delete(request);
539         request = NULL;
540
541         response = login_receive(conn, false);
542         response_keys = keys_new();
543         keys_load(response_keys, response);
544         for (i = 0; i < KEYS_MAX; i++) {
545                 if (response_keys->keys_names[i] == NULL)
546                         break;
547
548                 login_negotiate_key(conn,
549                     response_keys->keys_names[i], response_keys->keys_values[i]);
550         }
551
552         bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
553         if ((bhslr->bhslr_flags & BHSLR_FLAGS_TRANSIT) == 0)
554                 log_warnx("received final login response "
555                     "without the \"T\" flag");
556         else if (login_nsg(response) != BHSLR_STAGE_FULL_FEATURE_PHASE)
557                 log_warnx("received final login response with wrong NSG 0x%x",
558                     login_nsg(response));
559
560         log_debugx("parameter negotiation done; "
561             "transitioning to Full Feature phase");
562
563         keys_delete(response_keys);
564         pdu_delete(response);
565 }
566
567 static void
568 login_send_chap_a(struct connection *conn)
569 {
570         struct pdu *request;
571         struct keys *request_keys;
572
573         request = login_new_request(conn);
574         request_keys = keys_new();
575         keys_add(request_keys, "CHAP_A", "5");
576         keys_save(request_keys, request);
577         keys_delete(request_keys);
578         pdu_send(request);
579         pdu_delete(request);
580 }
581
582 static void
583 login_send_chap_r(struct pdu *response)
584 {
585         struct connection *conn;
586         struct pdu *request;
587         struct keys *request_keys, *response_keys;
588         const char *chap_a, *chap_c, *chap_i;
589         char *chap_r, *challenge, response_bin[MD5_DIGEST_LENGTH];
590         size_t challenge_len;
591         int error, rv;
592         unsigned char id;
593         char *mutual_chap_c, mutual_chap_i[4];
594
595         /*
596          * As in the rest of the initiator, 'request' means
597          * 'initiator -> target', and 'response' means 'target -> initiator',
598          *
599          * So, here the 'response' from the target is the packet that contains
600          * CHAP challenge; our CHAP response goes into 'request'.
601          */
602
603         conn = response->pdu_connection;
604
605         response_keys = keys_new();
606         keys_load(response_keys, response);
607
608         /*
609          * First, compute the response.
610          */
611         chap_a = keys_find(response_keys, "CHAP_A");
612         if (chap_a == NULL)
613                 log_errx(1, "received CHAP packet without CHAP_A");
614         chap_c = keys_find(response_keys, "CHAP_C");
615         if (chap_c == NULL)
616                 log_errx(1, "received CHAP packet without CHAP_C");
617         chap_i = keys_find(response_keys, "CHAP_I");
618         if (chap_i == NULL)
619                 log_errx(1, "received CHAP packet without CHAP_I");
620
621         if (strcmp(chap_a, "5") != 0)
622                 log_errx(1, "received CHAP packet "
623                     "with unsupported CHAP_A \"%s\"", chap_a);
624         id = strtoul(chap_i, NULL, 10);
625         error = login_hex2bin(chap_c, &challenge, &challenge_len);
626         if (error != 0)
627                 log_errx(1, "received CHAP packet with malformed CHAP_C");
628         login_compute_md5(id, conn->conn_conf.isc_secret,
629             challenge, challenge_len, response_bin, sizeof(response_bin));
630         free(challenge);
631         chap_r = login_bin2hex(response_bin, sizeof(response_bin));
632
633         keys_delete(response_keys);
634
635         request = login_new_request(conn);
636         request_keys = keys_new();
637         keys_add(request_keys, "CHAP_N", conn->conn_conf.isc_user);
638         keys_add(request_keys, "CHAP_R", chap_r);
639         free(chap_r);
640
641         /*
642          * If we want mutual authentication, we're expected to send
643          * our CHAP_I/CHAP_C now.
644          */
645         if (conn->conn_conf.isc_mutual_user[0] != '\0') {
646                 log_debugx("requesting mutual authentication; "
647                     "binary challenge size is %zd bytes",
648                     sizeof(conn->conn_mutual_challenge));
649
650                 rv = RAND_bytes(conn->conn_mutual_challenge,
651                     sizeof(conn->conn_mutual_challenge));
652                 if (rv != 1) {
653                         log_errx(1, "RAND_bytes failed: %s",
654                             ERR_error_string(ERR_get_error(), NULL));
655                 }
656                 rv = RAND_bytes(&conn->conn_mutual_id,
657                     sizeof(conn->conn_mutual_id));
658                 if (rv != 1) {
659                         log_errx(1, "RAND_bytes failed: %s",
660                             ERR_error_string(ERR_get_error(), NULL));
661                 }
662                 mutual_chap_c = login_bin2hex(conn->conn_mutual_challenge,
663                     sizeof(conn->conn_mutual_challenge));
664                 snprintf(mutual_chap_i, sizeof(mutual_chap_i),
665                     "%d", conn->conn_mutual_id);
666                 keys_add(request_keys, "CHAP_I", mutual_chap_i);
667                 keys_add(request_keys, "CHAP_C", mutual_chap_c);
668                 free(mutual_chap_c);
669         }
670
671         keys_save(request_keys, request);
672         keys_delete(request_keys);
673         pdu_send(request);
674         pdu_delete(request);
675 }
676
677 static void
678 login_verify_mutual(const struct pdu *response)
679 {
680         struct connection *conn;
681         struct keys *response_keys;
682         const char *chap_n, *chap_r;
683         char *response_bin, expected_response_bin[MD5_DIGEST_LENGTH];
684         size_t response_bin_len;
685         int error;
686
687         conn = response->pdu_connection;
688
689         response_keys = keys_new();
690         keys_load(response_keys, response);
691
692         chap_n = keys_find(response_keys, "CHAP_N");
693         if (chap_n == NULL)
694                 log_errx(1, "received CHAP Response PDU without CHAP_N");
695         chap_r = keys_find(response_keys, "CHAP_R");
696         if (chap_r == NULL)
697                 log_errx(1, "received CHAP Response PDU without CHAP_R");
698         error = login_hex2bin(chap_r, &response_bin, &response_bin_len);
699         if (error != 0)
700                 log_errx(1, "received CHAP Response PDU with malformed CHAP_R");
701
702         if (strcmp(chap_n, conn->conn_conf.isc_mutual_user) != 0) {
703                 fail(conn, "Mutual CHAP failed");
704                 log_errx(1, "mutual CHAP authentication failed: wrong user");
705         }
706
707         login_compute_md5(conn->conn_mutual_id,
708             conn->conn_conf.isc_mutual_secret, conn->conn_mutual_challenge,
709             sizeof(conn->conn_mutual_challenge), expected_response_bin,
710             sizeof(expected_response_bin));
711
712         if (memcmp(response_bin, expected_response_bin,
713             sizeof(expected_response_bin)) != 0) {
714                 fail(conn, "Mutual CHAP failed");
715                 log_errx(1, "mutual CHAP authentication failed: wrong secret");
716         }
717
718         keys_delete(response_keys);
719         free(response_bin);
720
721         log_debugx("mutual CHAP authentication succeeded");
722 }
723
724 static void
725 login_chap(struct connection *conn)
726 {
727         struct pdu *response;
728
729         log_debugx("beginning CHAP authentication; sending CHAP_A");
730         login_send_chap_a(conn);
731
732         log_debugx("waiting for CHAP_A/CHAP_C/CHAP_I");
733         response = login_receive(conn, false);
734
735         log_debugx("sending CHAP_N/CHAP_R");
736         login_send_chap_r(response);
737         pdu_delete(response);
738
739         /*
740          * XXX: Make sure this is not susceptible to MITM.
741          */
742
743         log_debugx("waiting for CHAP result");
744         response = login_receive(conn, false);
745         if (conn->conn_conf.isc_mutual_user[0] != '\0')
746                 login_verify_mutual(response);
747         pdu_delete(response);
748
749         log_debugx("CHAP authentication done");
750 }
751
752 static void
753 login_create_isid(struct connection *conn)
754 {
755         int rv;
756
757         /*
758          * RFC 3720, 10.12.5: 10b, "Random" ISID.
759          *
760          */
761         conn->conn_isid[0] = 0x80; 
762
763         rv = RAND_bytes(&conn->conn_isid[1], 3);
764         if (rv != 1) {
765                 log_errx(1, "RAND_bytes failed: %s",
766                     ERR_error_string(ERR_get_error(), NULL));
767         }
768 }
769
770 void
771 login(struct connection *conn)
772 {
773         struct pdu *request, *response;
774         struct keys *request_keys, *response_keys;
775         struct iscsi_bhs_login_request *bhslr;
776         struct iscsi_bhs_login_response *bhslr2;
777         const char *auth_method;
778         int i;
779
780         login_create_isid(conn);
781
782         log_debugx("beginning Login phase; sending Login PDU");
783         request = login_new_request(conn);
784
785         bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
786         bhslr->bhslr_flags |= BHSLR_FLAGS_TRANSIT;
787
788         request_keys = keys_new();
789         if (conn->conn_conf.isc_mutual_user[0] != '\0') {
790                 keys_add(request_keys, "AuthMethod", "CHAP");
791         } else if (conn->conn_conf.isc_user[0] != '\0') {
792                 /*
793                  * Give target a chance to skip authentication if it
794                  * doesn't feel like it.
795                  *
796                  * None is first, CHAP second; this is to work around
797                  * what seems to be LIO (Linux target) bug: otherwise,
798                  * if target is configured with no authentication,
799                  * and we are configured to authenticate, the target
800                  * will erroneously respond with AuthMethod=CHAP
801                  * instead of AuthMethod=None, and will subsequently
802                  * fail the connection.  This usually happens with
803                  * Discovery sessions, which default to no authentication.
804                  */
805                 keys_add(request_keys, "AuthMethod", "None,CHAP");
806         } else {
807                 keys_add(request_keys, "AuthMethod", "None");
808         }
809         keys_add(request_keys, "InitiatorName",
810             conn->conn_conf.isc_initiator);
811         if (conn->conn_conf.isc_initiator_alias[0] != '\0') {
812                 keys_add(request_keys, "InitiatorAlias",
813                     conn->conn_conf.isc_initiator_alias);
814         }
815         if (conn->conn_conf.isc_discovery == 0) {
816                 keys_add(request_keys, "SessionType", "Normal");
817                 keys_add(request_keys,
818                     "TargetName", conn->conn_conf.isc_target);
819         } else {
820                 keys_add(request_keys, "SessionType", "Discovery");
821         }
822         keys_save(request_keys, request);
823         keys_delete(request_keys);
824         pdu_send(request);
825         pdu_delete(request);
826
827         response = login_receive(conn, true);
828
829         response_keys = keys_new();
830         keys_load(response_keys, response);
831
832         for (i = 0; i < KEYS_MAX; i++) {
833                 if (response_keys->keys_names[i] == NULL)
834                         break;
835
836                 /*
837                  * Not interested in AuthMethod at this point; we only need
838                  * to parse things such as TargetAlias.
839                  *
840                  * XXX: This is somewhat ugly.  We should have a way to apply
841                  *      all the keys to the session and use that by default
842                  *      instead of discarding them.
843                  */
844                 if (strcmp(response_keys->keys_names[i], "AuthMethod") == 0)
845                         continue;
846
847                 login_negotiate_key(conn,
848                     response_keys->keys_names[i], response_keys->keys_values[i]);
849         }
850
851         bhslr2 = (struct iscsi_bhs_login_response *)response->pdu_bhs;
852         if ((bhslr2->bhslr_flags & BHSLR_FLAGS_TRANSIT) != 0 &&
853             login_nsg(response) == BHSLR_STAGE_OPERATIONAL_NEGOTIATION) {
854                 if (conn->conn_conf.isc_mutual_user[0] != '\0') {
855                         log_errx(1, "target requested transition "
856                             "to operational negotiation, but we require "
857                             "mutual CHAP");
858                 }
859
860                 log_debugx("target requested transition "
861                     "to operational negotiation");
862                 keys_delete(response_keys);
863                 pdu_delete(response);
864                 login_negotiate(conn);
865                 return;
866         }
867
868         auth_method = keys_find(response_keys, "AuthMethod");
869         if (auth_method == NULL)
870                 log_errx(1, "received response without AuthMethod");
871         if (strcmp(auth_method, "None") == 0) {
872                 if (conn->conn_conf.isc_mutual_user[0] != '\0') {
873                         log_errx(1, "target does not require authantication, "
874                             "but we require mutual CHAP");
875                 }
876
877                 log_debugx("target does not require authentication");
878                 keys_delete(response_keys);
879                 pdu_delete(response);
880                 login_negotiate(conn);
881                 return;
882         }
883
884         if (strcmp(auth_method, "CHAP") != 0) {
885                 fail(conn, "Unsupported AuthMethod");
886                 log_errx(1, "received response "
887                     "with unsupported AuthMethod \"%s\"", auth_method);
888         }
889
890         if (conn->conn_conf.isc_user[0] == '\0' ||
891             conn->conn_conf.isc_secret[0] == '\0') {
892                 fail(conn, "Authentication required");
893                 log_errx(1, "target requests CHAP authentication, but we don't "
894                     "have user and secret");
895         }
896
897         keys_delete(response_keys);
898         response_keys = NULL;
899         pdu_delete(response);
900         response = NULL;
901
902         login_chap(conn);
903         login_negotiate(conn);
904 }