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