xref: /freebsd/usr.sbin/iscsid/login.c (revision f0574f5cf69e168cc4ea71ebbe5fdec9ec9a3dfe)
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  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/types.h>
35 #include <sys/ioctl.h>
36 #include <assert.h>
37 #include <stdbool.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <netinet/in.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 void
162 kernel_modify(const struct connection *conn, const char *target_address)
163 {
164 	struct iscsi_session_modify ism;
165 	int error;
166 
167 	memset(&ism, 0, sizeof(ism));
168 	ism.ism_session_id = conn->conn_session_id;
169 	memcpy(&ism.ism_conf, &conn->conn_conf, sizeof(ism.ism_conf));
170 	strlcpy(ism.ism_conf.isc_target_addr, target_address,
171 	    sizeof(ism.ism_conf.isc_target));
172 	error = ioctl(conn->conn_iscsi_fd, ISCSISMODIFY, &ism);
173 	if (error != 0) {
174 		log_err(1, "failed to redirect to %s: ISCSISMODIFY",
175 		    target_address);
176 	}
177 }
178 
179 /*
180  * XXX:	The way it works is suboptimal; what should happen is described
181  *	in draft-gilligan-iscsi-fault-tolerance-00.  That, however, would
182  *	be much more complicated: we would need to keep "dependencies"
183  *	for sessions, so that, in case described in draft and using draft
184  *	terminology, we would have three sessions: one for discovery,
185  *	one for initial target portal, and one for redirect portal.
186  *	This would allow us to "backtrack" on connection failure,
187  *	as described in draft.
188  */
189 static void
190 login_handle_redirection(struct connection *conn, struct pdu *response)
191 {
192 	struct iscsi_bhs_login_response *bhslr;
193 	struct keys *response_keys;
194 	const char *target_address;
195 
196 	bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
197 	assert (bhslr->bhslr_status_class == 1);
198 
199 	response_keys = keys_new();
200 	keys_load(response_keys, response);
201 
202 	target_address = keys_find(response_keys, "TargetAddress");
203 	if (target_address == NULL)
204 		log_errx(1, "received redirection without TargetAddress");
205 	if (target_address[0] == '\0')
206 		log_errx(1, "received redirection with empty TargetAddress");
207 	if (strlen(target_address) >=
208 	    sizeof(conn->conn_conf.isc_target_addr) - 1)
209 		log_errx(1, "received TargetAddress is too long");
210 
211 	log_debugx("received redirection to \"%s\"", target_address);
212 	kernel_modify(conn, target_address);
213 	keys_delete(response_keys);
214 }
215 
216 static struct pdu *
217 login_receive(struct connection *conn)
218 {
219 	struct pdu *response;
220 	struct iscsi_bhs_login_response *bhslr;
221 	const char *errorstr;
222 	static bool initial = true;
223 
224 	response = pdu_new(conn);
225 	pdu_receive(response);
226 	if (response->pdu_bhs->bhs_opcode != ISCSI_BHS_OPCODE_LOGIN_RESPONSE) {
227 		log_errx(1, "protocol error: received invalid opcode 0x%x",
228 		    response->pdu_bhs->bhs_opcode);
229 	}
230 	bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
231 	/*
232 	 * XXX: Implement the C flag some day.
233 	 */
234 	if ((bhslr->bhslr_flags & BHSLR_FLAGS_CONTINUE) != 0)
235 		log_errx(1, "received Login PDU with unsupported \"C\" flag");
236 	if (bhslr->bhslr_version_max != 0x00)
237 		log_errx(1, "received Login PDU with unsupported "
238 		    "Version-max 0x%x", bhslr->bhslr_version_max);
239 	if (bhslr->bhslr_version_active != 0x00)
240 		log_errx(1, "received Login PDU with unsupported "
241 		    "Version-active 0x%x", bhslr->bhslr_version_active);
242 	if (bhslr->bhslr_status_class == 1) {
243 		login_handle_redirection(conn, response);
244 		log_debugx("redirection handled; exiting");
245 		exit(0);
246 	}
247 	if (bhslr->bhslr_status_class != 0) {
248 		errorstr = login_target_error_str(bhslr->bhslr_status_class,
249 		    bhslr->bhslr_status_detail);
250 		fail(conn, errorstr);
251 		log_errx(1, "target returned error: %s", errorstr);
252 	}
253 	if (initial == false &&
254 	    ntohl(bhslr->bhslr_statsn) != conn->conn_statsn + 1) {
255 		/*
256 		 * It's a warning, not an error, to work around what seems
257 		 * to be bug in NetBSD iSCSI target.
258 		 */
259 		log_warnx("received Login PDU with wrong StatSN: "
260 		    "is %u, should be %u", ntohl(bhslr->bhslr_statsn),
261 		    conn->conn_statsn + 1);
262 	}
263 	conn->conn_tsih = ntohs(bhslr->bhslr_tsih);
264 	conn->conn_statsn = ntohl(bhslr->bhslr_statsn);
265 
266 	initial = false;
267 
268 	return (response);
269 }
270 
271 static struct pdu *
272 login_new_request(struct connection *conn, int csg)
273 {
274 	struct pdu *request;
275 	struct iscsi_bhs_login_request *bhslr;
276 	int nsg;
277 
278 	request = pdu_new(conn);
279 	bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
280 	bhslr->bhslr_opcode = ISCSI_BHS_OPCODE_LOGIN_REQUEST |
281 	    ISCSI_BHS_OPCODE_IMMEDIATE;
282 
283 	bhslr->bhslr_flags = BHSLR_FLAGS_TRANSIT;
284 	switch (csg) {
285 	case BHSLR_STAGE_SECURITY_NEGOTIATION:
286 		nsg = BHSLR_STAGE_OPERATIONAL_NEGOTIATION;
287 		break;
288 	case BHSLR_STAGE_OPERATIONAL_NEGOTIATION:
289 		nsg = BHSLR_STAGE_FULL_FEATURE_PHASE;
290 		break;
291 	default:
292 		assert(!"invalid csg");
293 		log_errx(1, "invalid csg %d", csg);
294 	}
295 	login_set_csg(request, csg);
296 	login_set_nsg(request, nsg);
297 
298 	memcpy(bhslr->bhslr_isid, &conn->conn_isid, sizeof(bhslr->bhslr_isid));
299 	bhslr->bhslr_tsih = htons(conn->conn_tsih);
300 	bhslr->bhslr_initiator_task_tag = 0;
301 	bhslr->bhslr_cmdsn = 0;
302 	bhslr->bhslr_expstatsn = htonl(conn->conn_statsn + 1);
303 
304 	return (request);
305 }
306 
307 static int
308 login_list_prefers(const char *list,
309     const char *choice1, const char *choice2)
310 {
311 	char *tofree, *str, *token;
312 
313 	tofree = str = checked_strdup(list);
314 
315 	while ((token = strsep(&str, ",")) != NULL) {
316 		if (strcmp(token, choice1) == 0) {
317 			free(tofree);
318 			return (1);
319 		}
320 		if (strcmp(token, choice2) == 0) {
321 			free(tofree);
322 			return (2);
323 		}
324 	}
325 	free(tofree);
326 	return (-1);
327 }
328 
329 static void
330 login_negotiate_key(struct connection *conn, const char *name,
331     const char *value)
332 {
333 	struct iscsi_session_limits *isl;
334 	int which, tmp;
335 
336 	isl = &conn->conn_limits;
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 > isl->isl_max_send_data_segment_length) {
394 			log_debugx("capping max_send_data_segment_length "
395 			    "from %d to %d", tmp,
396 			    isl->isl_max_send_data_segment_length);
397 			tmp = isl->isl_max_send_data_segment_length;
398 		}
399 		conn->conn_max_send_data_segment_length = tmp;
400 		/* We received target's limit, that means it accepted our's. */
401 		conn->conn_max_recv_data_segment_length =
402 		    isl->isl_max_recv_data_segment_length;
403 	} else if (strcmp(name, "MaxBurstLength") == 0) {
404 		tmp = strtoul(value, NULL, 10);
405 		if (tmp <= 0)
406 			log_errx(1, "received invalid MaxBurstLength");
407 		if (tmp > isl->isl_max_burst_length) {
408 			log_debugx("capping MaxBurstLength "
409 			    "from %d to %d", tmp, isl->isl_max_burst_length);
410 			tmp = isl->isl_max_burst_length;
411 		}
412 		conn->conn_max_burst_length = tmp;
413 	} else if (strcmp(name, "FirstBurstLength") == 0) {
414 		tmp = strtoul(value, NULL, 10);
415 		if (tmp <= 0)
416 			log_errx(1, "received invalid FirstBurstLength");
417 		if (tmp > isl->isl_first_burst_length) {
418 			log_debugx("capping FirstBurstLength "
419 			    "from %d to %d", tmp, isl->isl_first_burst_length);
420 			tmp = isl->isl_first_burst_length;
421 		}
422 		conn->conn_first_burst_length = tmp;
423 	} else if (strcmp(name, "DefaultTime2Wait") == 0) {
424 		/* Ignore */
425 	} else if (strcmp(name, "DefaultTime2Retain") == 0) {
426 		/* Ignore */
427 	} else if (strcmp(name, "MaxOutstandingR2T") == 0) {
428 		/* Ignore */
429 	} else if (strcmp(name, "DataPDUInOrder") == 0) {
430 		/* Ignore */
431 	} else if (strcmp(name, "DataSequenceInOrder") == 0) {
432 		/* Ignore */
433 	} else if (strcmp(name, "ErrorRecoveryLevel") == 0) {
434 		/* Ignore */
435 	} else if (strcmp(name, "OFMarker") == 0) {
436 		/* Ignore */
437 	} else if (strcmp(name, "IFMarker") == 0) {
438 		/* Ignore */
439 	} else if (strcmp(name, "RDMAExtensions") == 0) {
440 		if (conn->conn_conf.isc_iser == 1 &&
441 		    strcmp(value, "Yes") != 0) {
442 			log_errx(1, "received unsupported RDMAExtensions");
443 		}
444 	} else if (strcmp(name, "InitiatorRecvDataSegmentLength") == 0) {
445 		tmp = strtoul(value, NULL, 10);
446 		if (tmp <= 0)
447 			log_errx(1, "received invalid "
448 			    "InitiatorRecvDataSegmentLength");
449 		if ((int)tmp > isl->isl_max_recv_data_segment_length) {
450 			log_debugx("capping InitiatorRecvDataSegmentLength "
451 			    "from %d to %d", tmp,
452 			    isl->isl_max_recv_data_segment_length);
453 			tmp = isl->isl_max_recv_data_segment_length;
454 		}
455 		conn->conn_max_recv_data_segment_length = tmp;
456 	} else if (strcmp(name, "TargetPortalGroupTag") == 0) {
457 		/* Ignore */
458 	} else if (strcmp(name, "TargetRecvDataSegmentLength") == 0) {
459 		tmp = strtoul(value, NULL, 10);
460 		if (tmp <= 0) {
461 			log_errx(1,
462 			    "received invalid TargetRecvDataSegmentLength");
463 		}
464 		if (tmp > isl->isl_max_send_data_segment_length) {
465 			log_debugx("capping TargetRecvDataSegmentLength "
466 			    "from %d to %d", tmp,
467 			    isl->isl_max_send_data_segment_length);
468 			tmp = isl->isl_max_send_data_segment_length;
469 		}
470 		conn->conn_max_send_data_segment_length = tmp;
471 	} else {
472 		log_debugx("unknown key \"%s\"; ignoring",  name);
473 	}
474 }
475 
476 static void
477 login_negotiate(struct connection *conn)
478 {
479 	struct pdu *request, *response;
480 	struct keys *request_keys, *response_keys;
481 	struct iscsi_bhs_login_response *bhslr;
482 	int i, nrequests = 0;
483 	struct iscsi_session_limits *isl;
484 
485 	log_debugx("beginning operational parameter negotiation");
486 	request = login_new_request(conn, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
487 	request_keys = keys_new();
488 
489 	isl = &conn->conn_limits;
490 	log_debugx("Limits for offload \"%s\" are "
491 	    "MaxRecvDataSegment=%d, max_send_dsl=%d, "
492 	    "MaxBurstLength=%d, FirstBurstLength=%d",
493 	    conn->conn_conf.isc_offload, isl->isl_max_recv_data_segment_length,
494 	    isl->isl_max_send_data_segment_length, isl->isl_max_burst_length,
495 	    isl->isl_first_burst_length);
496 
497 	/*
498 	 * The following keys are irrelevant for discovery sessions.
499 	 */
500 	if (conn->conn_conf.isc_discovery == 0) {
501 		if (conn->conn_conf.isc_header_digest != 0)
502 			keys_add(request_keys, "HeaderDigest", "CRC32C");
503 		else
504 			keys_add(request_keys, "HeaderDigest", "None");
505 		if (conn->conn_conf.isc_data_digest != 0)
506 			keys_add(request_keys, "DataDigest", "CRC32C");
507 		else
508 			keys_add(request_keys, "DataDigest", "None");
509 
510 		keys_add(request_keys, "ImmediateData", "Yes");
511 		keys_add_int(request_keys, "MaxBurstLength",
512 		    isl->isl_max_burst_length);
513 		keys_add_int(request_keys, "FirstBurstLength",
514 		    isl->isl_first_burst_length);
515 		keys_add(request_keys, "InitialR2T", "Yes");
516 		keys_add(request_keys, "MaxOutstandingR2T", "1");
517 		if (conn->conn_conf.isc_iser == 1) {
518 			keys_add_int(request_keys, "InitiatorRecvDataSegmentLength",
519 			    isl->isl_max_recv_data_segment_length);
520 			keys_add_int(request_keys, "TargetRecvDataSegmentLength",
521 			    isl->isl_max_send_data_segment_length);
522 			keys_add(request_keys, "RDMAExtensions", "Yes");
523 		} else {
524 			keys_add_int(request_keys, "MaxRecvDataSegmentLength",
525 			    isl->isl_max_recv_data_segment_length);
526 		}
527 	} else {
528 		keys_add(request_keys, "HeaderDigest", "None");
529 		keys_add(request_keys, "DataDigest", "None");
530 		keys_add_int(request_keys, "MaxRecvDataSegmentLength",
531 		    isl->isl_max_recv_data_segment_length);
532 	}
533 
534 	keys_add(request_keys, "DefaultTime2Wait", "0");
535 	keys_add(request_keys, "DefaultTime2Retain", "0");
536 	keys_add(request_keys, "ErrorRecoveryLevel", "0");
537 	keys_save(request_keys, request);
538 	keys_delete(request_keys);
539 	request_keys = NULL;
540 	pdu_send(request);
541 	pdu_delete(request);
542 	request = NULL;
543 
544 	response = login_receive(conn);
545 	response_keys = keys_new();
546 	keys_load(response_keys, response);
547 	for (i = 0; i < KEYS_MAX; i++) {
548 		if (response_keys->keys_names[i] == NULL)
549 			break;
550 
551 		login_negotiate_key(conn,
552 		    response_keys->keys_names[i], response_keys->keys_values[i]);
553 	}
554 
555 	keys_delete(response_keys);
556 	response_keys = NULL;
557 
558 	for (;;) {
559 		bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
560 		if ((bhslr->bhslr_flags & BHSLR_FLAGS_TRANSIT) != 0)
561 			break;
562 
563 		nrequests++;
564 		if (nrequests > 5) {
565 			log_warnx("received login response "
566 			    "without the \"T\" flag too many times; giving up");
567 			break;
568 		}
569 
570 		log_debugx("received login response "
571 		    "without the \"T\" flag; sending another request");
572 
573 		pdu_delete(response);
574 
575 		request = login_new_request(conn,
576 		    BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
577 		pdu_send(request);
578 		pdu_delete(request);
579 
580 		response = login_receive(conn);
581 	}
582 
583 	if (login_nsg(response) != BHSLR_STAGE_FULL_FEATURE_PHASE)
584 		log_warnx("received final login response with wrong NSG 0x%x",
585 		    login_nsg(response));
586 	pdu_delete(response);
587 
588 	log_debugx("operational parameter negotiation done; "
589 	    "transitioning to Full Feature phase");
590 }
591 
592 static void
593 login_send_chap_a(struct connection *conn)
594 {
595 	struct pdu *request;
596 	struct keys *request_keys;
597 
598 	request = login_new_request(conn, BHSLR_STAGE_SECURITY_NEGOTIATION);
599 	request_keys = keys_new();
600 	keys_add(request_keys, "CHAP_A", "5");
601 	keys_save(request_keys, request);
602 	keys_delete(request_keys);
603 	pdu_send(request);
604 	pdu_delete(request);
605 }
606 
607 static void
608 login_send_chap_r(struct pdu *response)
609 {
610 	struct connection *conn;
611 	struct pdu *request;
612 	struct keys *request_keys, *response_keys;
613 	struct rchap *rchap;
614 	const char *chap_a, *chap_c, *chap_i;
615 	char *chap_r;
616 	int error;
617         char *mutual_chap_c, *mutual_chap_i;
618 
619 	/*
620 	 * As in the rest of the initiator, 'request' means
621 	 * 'initiator -> target', and 'response' means 'target -> initiator',
622 	 *
623 	 * So, here the 'response' from the target is the packet that contains
624 	 * CHAP challenge; our CHAP response goes into 'request'.
625 	 */
626 
627 	conn = response->pdu_connection;
628 
629 	response_keys = keys_new();
630 	keys_load(response_keys, response);
631 
632 	/*
633 	 * First, compute the response.
634 	 */
635 	chap_a = keys_find(response_keys, "CHAP_A");
636 	if (chap_a == NULL)
637 		log_errx(1, "received CHAP packet without CHAP_A");
638 	chap_c = keys_find(response_keys, "CHAP_C");
639 	if (chap_c == NULL)
640 		log_errx(1, "received CHAP packet without CHAP_C");
641 	chap_i = keys_find(response_keys, "CHAP_I");
642 	if (chap_i == NULL)
643 		log_errx(1, "received CHAP packet without CHAP_I");
644 
645 	if (strcmp(chap_a, "5") != 0) {
646 		log_errx(1, "received CHAP packet "
647 		    "with unsupported CHAP_A \"%s\"", chap_a);
648 	}
649 
650 	rchap = rchap_new(conn->conn_conf.isc_secret);
651 	error = rchap_receive(rchap, chap_i, chap_c);
652 	if (error != 0) {
653 		log_errx(1, "received CHAP packet "
654 		    "with malformed CHAP_I or CHAP_C");
655 	}
656 	chap_r = rchap_get_response(rchap);
657 	rchap_delete(rchap);
658 
659 	keys_delete(response_keys);
660 
661 	request = login_new_request(conn, BHSLR_STAGE_SECURITY_NEGOTIATION);
662 	request_keys = keys_new();
663 	keys_add(request_keys, "CHAP_N", conn->conn_conf.isc_user);
664 	keys_add(request_keys, "CHAP_R", chap_r);
665 	free(chap_r);
666 
667 	/*
668 	 * If we want mutual authentication, we're expected to send
669 	 * our CHAP_I/CHAP_C now.
670 	 */
671 	if (conn->conn_conf.isc_mutual_user[0] != '\0') {
672 		log_debugx("requesting mutual authentication; "
673 		    "binary challenge size is %zd bytes",
674 		    sizeof(conn->conn_mutual_chap->chap_challenge));
675 
676 		assert(conn->conn_mutual_chap == NULL);
677 		conn->conn_mutual_chap = chap_new();
678 		mutual_chap_i = chap_get_id(conn->conn_mutual_chap);
679 		mutual_chap_c = chap_get_challenge(conn->conn_mutual_chap);
680 		keys_add(request_keys, "CHAP_I", mutual_chap_i);
681 		keys_add(request_keys, "CHAP_C", mutual_chap_c);
682 		free(mutual_chap_i);
683 		free(mutual_chap_c);
684 	}
685 
686 	keys_save(request_keys, request);
687 	keys_delete(request_keys);
688 	pdu_send(request);
689 	pdu_delete(request);
690 }
691 
692 static void
693 login_verify_mutual(const struct pdu *response)
694 {
695 	struct connection *conn;
696 	struct keys *response_keys;
697 	const char *chap_n, *chap_r;
698 	int error;
699 
700 	conn = response->pdu_connection;
701 
702 	response_keys = keys_new();
703 	keys_load(response_keys, response);
704 
705         chap_n = keys_find(response_keys, "CHAP_N");
706         if (chap_n == NULL)
707                 log_errx(1, "received CHAP Response PDU without CHAP_N");
708         chap_r = keys_find(response_keys, "CHAP_R");
709         if (chap_r == NULL)
710                 log_errx(1, "received CHAP Response PDU without CHAP_R");
711 
712 	error = chap_receive(conn->conn_mutual_chap, chap_r);
713 	if (error != 0)
714                 log_errx(1, "received CHAP Response PDU with invalid CHAP_R");
715 
716 	if (strcmp(chap_n, conn->conn_conf.isc_mutual_user) != 0) {
717 		fail(conn, "Mutual CHAP failed");
718 		log_errx(1, "mutual CHAP authentication failed: wrong user");
719 	}
720 
721 	error = chap_authenticate(conn->conn_mutual_chap,
722 	    conn->conn_conf.isc_mutual_secret);
723 	if (error != 0) {
724 		fail(conn, "Mutual CHAP failed");
725                 log_errx(1, "mutual CHAP authentication failed: wrong secret");
726 	}
727 
728 	keys_delete(response_keys);
729 	chap_delete(conn->conn_mutual_chap);
730 	conn->conn_mutual_chap = NULL;
731 
732 	log_debugx("mutual CHAP authentication succeeded");
733 }
734 
735 static void
736 login_chap(struct connection *conn)
737 {
738 	struct pdu *response;
739 
740 	log_debugx("beginning CHAP authentication; sending CHAP_A");
741 	login_send_chap_a(conn);
742 
743 	log_debugx("waiting for CHAP_A/CHAP_C/CHAP_I");
744 	response = login_receive(conn);
745 
746 	log_debugx("sending CHAP_N/CHAP_R");
747 	login_send_chap_r(response);
748 	pdu_delete(response);
749 
750 	/*
751 	 * XXX: Make sure this is not susceptible to MITM.
752 	 */
753 
754 	log_debugx("waiting for CHAP result");
755 	response = login_receive(conn);
756 	if (conn->conn_conf.isc_mutual_user[0] != '\0')
757 		login_verify_mutual(response);
758 	pdu_delete(response);
759 
760 	log_debugx("CHAP authentication done");
761 }
762 
763 void
764 login(struct connection *conn)
765 {
766 	struct pdu *request, *response;
767 	struct keys *request_keys, *response_keys;
768 	struct iscsi_bhs_login_response *bhslr2;
769 	const char *auth_method;
770 	int i;
771 
772 	log_debugx("beginning Login phase; sending Login PDU");
773 	request = login_new_request(conn, BHSLR_STAGE_SECURITY_NEGOTIATION);
774 	request_keys = keys_new();
775 	if (conn->conn_conf.isc_mutual_user[0] != '\0') {
776 		keys_add(request_keys, "AuthMethod", "CHAP");
777 	} else if (conn->conn_conf.isc_user[0] != '\0') {
778 		/*
779 		 * Give target a chance to skip authentication if it
780 		 * doesn't feel like it.
781 		 *
782 		 * None is first, CHAP second; this is to work around
783 		 * what seems to be LIO (Linux target) bug: otherwise,
784 		 * if target is configured with no authentication,
785 		 * and we are configured to authenticate, the target
786 		 * will erroneously respond with AuthMethod=CHAP
787 		 * instead of AuthMethod=None, and will subsequently
788 		 * fail the connection.  This usually happens with
789 		 * Discovery sessions, which default to no authentication.
790 		 */
791 		keys_add(request_keys, "AuthMethod", "None,CHAP");
792 	} else {
793 		keys_add(request_keys, "AuthMethod", "None");
794 	}
795 	keys_add(request_keys, "InitiatorName",
796 	    conn->conn_conf.isc_initiator);
797 	if (conn->conn_conf.isc_initiator_alias[0] != '\0') {
798 		keys_add(request_keys, "InitiatorAlias",
799 		    conn->conn_conf.isc_initiator_alias);
800 	}
801 	if (conn->conn_conf.isc_discovery == 0) {
802 		keys_add(request_keys, "SessionType", "Normal");
803 		keys_add(request_keys,
804 		    "TargetName", conn->conn_conf.isc_target);
805 	} else {
806 		keys_add(request_keys, "SessionType", "Discovery");
807 	}
808 	keys_save(request_keys, request);
809 	keys_delete(request_keys);
810 	pdu_send(request);
811 	pdu_delete(request);
812 
813 	response = login_receive(conn);
814 
815 	response_keys = keys_new();
816 	keys_load(response_keys, response);
817 
818 	for (i = 0; i < KEYS_MAX; i++) {
819 		if (response_keys->keys_names[i] == NULL)
820 			break;
821 
822 		/*
823 		 * Not interested in AuthMethod at this point; we only need
824 		 * to parse things such as TargetAlias.
825 		 *
826 		 * XXX: This is somewhat ugly.  We should have a way to apply
827 		 *      all the keys to the session and use that by default
828 		 *      instead of discarding them.
829 		 */
830 		if (strcmp(response_keys->keys_names[i], "AuthMethod") == 0)
831 			continue;
832 
833 		login_negotiate_key(conn,
834 		    response_keys->keys_names[i], response_keys->keys_values[i]);
835 	}
836 
837 	bhslr2 = (struct iscsi_bhs_login_response *)response->pdu_bhs;
838 	if ((bhslr2->bhslr_flags & BHSLR_FLAGS_TRANSIT) != 0 &&
839 	    login_nsg(response) == BHSLR_STAGE_OPERATIONAL_NEGOTIATION) {
840 		if (conn->conn_conf.isc_mutual_user[0] != '\0') {
841 			log_errx(1, "target requested transition "
842 			    "to operational parameter negotiation, "
843 			    "but we require mutual CHAP");
844 		}
845 
846 		log_debugx("target requested transition "
847 		    "to operational parameter negotiation");
848 		keys_delete(response_keys);
849 		pdu_delete(response);
850 		login_negotiate(conn);
851 		return;
852 	}
853 
854 	auth_method = keys_find(response_keys, "AuthMethod");
855 	if (auth_method == NULL)
856 		log_errx(1, "received response without AuthMethod");
857 	if (strcmp(auth_method, "None") == 0) {
858 		if (conn->conn_conf.isc_mutual_user[0] != '\0') {
859 			log_errx(1, "target does not require authantication, "
860 			    "but we require mutual CHAP");
861 		}
862 
863 		log_debugx("target does not require authentication");
864 		keys_delete(response_keys);
865 		pdu_delete(response);
866 		login_negotiate(conn);
867 		return;
868 	}
869 
870 	if (strcmp(auth_method, "CHAP") != 0) {
871 		fail(conn, "Unsupported AuthMethod");
872 		log_errx(1, "received response "
873 		    "with unsupported AuthMethod \"%s\"", auth_method);
874 	}
875 
876 	if (conn->conn_conf.isc_user[0] == '\0' ||
877 	    conn->conn_conf.isc_secret[0] == '\0') {
878 		fail(conn, "Authentication required");
879 		log_errx(1, "target requests CHAP authentication, but we don't "
880 		    "have user and secret");
881 	}
882 
883 	keys_delete(response_keys);
884 	response_keys = NULL;
885 	pdu_delete(response);
886 	response = NULL;
887 
888 	login_chap(conn);
889 	login_negotiate(conn);
890 }
891