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