login.c revision 269069
1/*-
2 * Copyright (c) 2012 The FreeBSD Foundation
3 * All rights reserved.
4 *
5 * This software was developed by Edward Tomasz Napierala under sponsorship
6 * from the FreeBSD Foundation.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 * $FreeBSD: stable/10/usr.sbin/iscsid/login.c 269069 2014-07-24 15:42:32Z mav $
30 */
31
32#include <sys/types.h>
33#include <sys/ioctl.h>
34#include <assert.h>
35#include <stdbool.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <netinet/in.h>
40#include <openssl/err.h>
41#include <openssl/md5.h>
42#include <openssl/rand.h>
43
44#include "iscsid.h"
45#include "iscsi_proto.h"
46
47static int
48login_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
57static void
58login_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
72static void
73login_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
87static const char *
88login_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
162static void
163kernel_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));
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 */
190static void
191login_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}
215
216static struct pdu *
217login_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 %d, should be %d", 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
271static struct pdu *
272login_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
307static int
308login_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
329static int
330login_hex2int(const char hex)
331{
332	switch (hex) {
333	case '0':
334		return (0x00);
335	case '1':
336		return (0x01);
337	case '2':
338		return (0x02);
339	case '3':
340		return (0x03);
341	case '4':
342		return (0x04);
343	case '5':
344		return (0x05);
345	case '6':
346		return (0x06);
347	case '7':
348		return (0x07);
349	case '8':
350		return (0x08);
351	case '9':
352		return (0x09);
353	case 'a':
354	case 'A':
355		return (0x0a);
356	case 'b':
357	case 'B':
358		return (0x0b);
359	case 'c':
360	case 'C':
361		return (0x0c);
362	case 'd':
363	case 'D':
364		return (0x0d);
365	case 'e':
366	case 'E':
367		return (0x0e);
368	case 'f':
369	case 'F':
370		return (0x0f);
371	default:
372		return (-1);
373	}
374}
375
376/*
377 * XXX: Review this _carefully_.
378 */
379static int
380login_hex2bin(const char *hex, char **binp, size_t *bin_lenp)
381{
382	int i, hex_len, nibble;
383	bool lo = true; /* As opposed to 'hi'. */
384	char *bin;
385	size_t bin_off, bin_len;
386
387	if (strncasecmp(hex, "0x", strlen("0x")) != 0) {
388		log_warnx("malformed variable, should start with \"0x\"");
389		return (-1);
390	}
391
392	hex += strlen("0x");
393	hex_len = strlen(hex);
394	if (hex_len < 1) {
395		log_warnx("malformed variable; doesn't contain anything "
396		    "but \"0x\"");
397		return (-1);
398	}
399
400	bin_len = hex_len / 2 + hex_len % 2;
401	bin = calloc(bin_len, 1);
402	if (bin == NULL)
403		log_err(1, "calloc");
404
405	bin_off = bin_len - 1;
406	for (i = hex_len - 1; i >= 0; i--) {
407		nibble = login_hex2int(hex[i]);
408		if (nibble < 0) {
409			log_warnx("malformed variable, invalid char \"%c\"",
410			    hex[i]);
411			return (-1);
412		}
413
414		assert(bin_off < bin_len);
415		if (lo) {
416			bin[bin_off] = nibble;
417			lo = false;
418		} else {
419			bin[bin_off] |= nibble << 4;
420			bin_off--;
421			lo = true;
422		}
423	}
424
425	*binp = bin;
426	*bin_lenp = bin_len;
427	return (0);
428}
429
430static char *
431login_bin2hex(const char *bin, size_t bin_len)
432{
433	unsigned char *hex, *tmp, ch;
434	size_t hex_len;
435	size_t i;
436
437	hex_len = bin_len * 2 + 3; /* +2 for "0x", +1 for '\0'. */
438	hex = malloc(hex_len);
439	if (hex == NULL)
440		log_err(1, "malloc");
441
442	tmp = hex;
443	tmp += sprintf(tmp, "0x");
444	for (i = 0; i < bin_len; i++) {
445		ch = bin[i];
446		tmp += sprintf(tmp, "%02x", ch);
447	}
448
449	return (hex);
450}
451
452static void
453login_compute_md5(const char id, const char *secret,
454    const void *challenge, size_t challenge_len, void *response,
455    size_t response_len)
456{
457	MD5_CTX ctx;
458	int rv;
459
460	assert(response_len == MD5_DIGEST_LENGTH);
461
462	MD5_Init(&ctx);
463	MD5_Update(&ctx, &id, sizeof(id));
464	MD5_Update(&ctx, secret, strlen(secret));
465	MD5_Update(&ctx, challenge, challenge_len);
466	rv = MD5_Final(response, &ctx);
467	if (rv != 1)
468		log_errx(1, "MD5_Final");
469}
470
471static void
472login_negotiate_key(struct connection *conn, const char *name,
473    const char *value)
474{
475	int which, tmp;
476
477	if (strcmp(name, "TargetAlias") == 0) {
478		strlcpy(conn->conn_target_alias, value,
479		    sizeof(conn->conn_target_alias));
480	} else if (strcmp(value, "Irrelevant") == 0) {
481		/* Ignore. */
482	} else if (strcmp(name, "HeaderDigest") == 0) {
483		which = login_list_prefers(value, "CRC32C", "None");
484		switch (which) {
485		case 1:
486			log_debugx("target prefers CRC32C "
487			    "for header digest; we'll use it");
488			conn->conn_header_digest = CONN_DIGEST_CRC32C;
489			break;
490		case 2:
491			log_debugx("target prefers not to do "
492			    "header digest; we'll comply");
493			break;
494		default:
495			log_warnx("target sent unrecognized "
496			    "HeaderDigest value \"%s\"; will use None", value);
497			break;
498		}
499	} else if (strcmp(name, "DataDigest") == 0) {
500		which = login_list_prefers(value, "CRC32C", "None");
501		switch (which) {
502		case 1:
503			log_debugx("target prefers CRC32C "
504			    "for data digest; we'll use it");
505			conn->conn_data_digest = CONN_DIGEST_CRC32C;
506			break;
507		case 2:
508			log_debugx("target prefers not to do "
509			    "data digest; we'll comply");
510			break;
511		default:
512			log_warnx("target sent unrecognized "
513			    "DataDigest value \"%s\"; will use None", value);
514			break;
515		}
516	} else if (strcmp(name, "MaxConnections") == 0) {
517		/* Ignore. */
518	} else if (strcmp(name, "InitialR2T") == 0) {
519		if (strcmp(value, "Yes") == 0)
520			conn->conn_initial_r2t = true;
521		else
522			conn->conn_initial_r2t = false;
523	} else if (strcmp(name, "ImmediateData") == 0) {
524		if (strcmp(value, "Yes") == 0)
525			conn->conn_immediate_data = true;
526		else
527			conn->conn_immediate_data = false;
528	} else if (strcmp(name, "MaxRecvDataSegmentLength") == 0) {
529		tmp = strtoul(value, NULL, 10);
530		if (tmp <= 0)
531			log_errx(1, "received invalid "
532			    "MaxRecvDataSegmentLength");
533		conn->conn_max_data_segment_length = tmp;
534	} else if (strcmp(name, "MaxBurstLength") == 0) {
535		if (conn->conn_immediate_data) {
536			tmp = strtoul(value, NULL, 10);
537			if (tmp <= 0)
538				log_errx(1, "received invalid MaxBurstLength");
539			conn->conn_max_burst_length = tmp;
540		}
541	} else if (strcmp(name, "FirstBurstLength") == 0) {
542		tmp = strtoul(value, NULL, 10);
543		if (tmp <= 0)
544			log_errx(1, "received invalid FirstBurstLength");
545		conn->conn_first_burst_length = tmp;
546	} else if (strcmp(name, "DefaultTime2Wait") == 0) {
547		/* Ignore */
548	} else if (strcmp(name, "DefaultTime2Retain") == 0) {
549		/* Ignore */
550	} else if (strcmp(name, "MaxOutstandingR2T") == 0) {
551		/* Ignore */
552	} else if (strcmp(name, "DataPDUInOrder") == 0) {
553		/* Ignore */
554	} else if (strcmp(name, "DataSequenceInOrder") == 0) {
555		/* Ignore */
556	} else if (strcmp(name, "ErrorRecoveryLevel") == 0) {
557		/* Ignore */
558	} else if (strcmp(name, "OFMarker") == 0) {
559		/* Ignore */
560	} else if (strcmp(name, "IFMarker") == 0) {
561		/* Ignore */
562	} else if (strcmp(name, "TargetPortalGroupTag") == 0) {
563		/* Ignore */
564	} else {
565		log_debugx("unknown key \"%s\"; ignoring",  name);
566	}
567}
568
569static void
570login_negotiate(struct connection *conn)
571{
572	struct pdu *request, *response;
573	struct keys *request_keys, *response_keys;
574	struct iscsi_bhs_login_response *bhslr;
575	int i;
576
577	log_debugx("beginning operational parameter negotiation");
578	request = login_new_request(conn, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
579	request_keys = keys_new();
580
581	/*
582	 * The following keys are irrelevant for discovery sessions.
583	 */
584	if (conn->conn_conf.isc_discovery == 0) {
585		if (conn->conn_conf.isc_header_digest != 0)
586			keys_add(request_keys, "HeaderDigest", "CRC32C");
587		else
588			keys_add(request_keys, "HeaderDigest", "None");
589		if (conn->conn_conf.isc_data_digest != 0)
590			keys_add(request_keys, "DataDigest", "CRC32C");
591		else
592			keys_add(request_keys, "DataDigest", "None");
593
594		keys_add(request_keys, "ImmediateData", "Yes");
595		keys_add_int(request_keys, "MaxBurstLength",
596		    ISCSI_MAX_DATA_SEGMENT_LENGTH);
597		keys_add_int(request_keys, "FirstBurstLength",
598		    ISCSI_MAX_DATA_SEGMENT_LENGTH);
599		keys_add(request_keys, "InitialR2T", "Yes");
600	} else {
601		keys_add(request_keys, "HeaderDigest", "None");
602		keys_add(request_keys, "DataDigest", "None");
603	}
604
605	keys_add_int(request_keys, "MaxRecvDataSegmentLength",
606	    ISCSI_MAX_DATA_SEGMENT_LENGTH);
607	keys_add(request_keys, "DefaultTime2Wait", "0");
608	keys_add(request_keys, "DefaultTime2Retain", "0");
609	keys_add(request_keys, "ErrorRecoveryLevel", "0");
610	keys_add(request_keys, "MaxOutstandingR2T", "1");
611	keys_save(request_keys, request);
612	keys_delete(request_keys);
613	request_keys = NULL;
614	pdu_send(request);
615	pdu_delete(request);
616	request = NULL;
617
618	response = login_receive(conn);
619	response_keys = keys_new();
620	keys_load(response_keys, response);
621	for (i = 0; i < KEYS_MAX; i++) {
622		if (response_keys->keys_names[i] == NULL)
623			break;
624
625		login_negotiate_key(conn,
626		    response_keys->keys_names[i], response_keys->keys_values[i]);
627	}
628
629	bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
630	if ((bhslr->bhslr_flags & BHSLR_FLAGS_TRANSIT) == 0)
631		log_warnx("received final login response "
632		    "without the \"T\" flag");
633	else if (login_nsg(response) != BHSLR_STAGE_FULL_FEATURE_PHASE)
634		log_warnx("received final login response with wrong NSG 0x%x",
635		    login_nsg(response));
636
637	log_debugx("operational parameter negotiation done; "
638	    "transitioning to Full Feature phase");
639
640	keys_delete(response_keys);
641	pdu_delete(response);
642}
643
644static void
645login_send_chap_a(struct connection *conn)
646{
647	struct pdu *request;
648	struct keys *request_keys;
649
650	request = login_new_request(conn, BHSLR_STAGE_SECURITY_NEGOTIATION);
651	request_keys = keys_new();
652	keys_add(request_keys, "CHAP_A", "5");
653	keys_save(request_keys, request);
654	keys_delete(request_keys);
655	pdu_send(request);
656	pdu_delete(request);
657}
658
659static void
660login_send_chap_r(struct pdu *response)
661{
662	struct connection *conn;
663	struct pdu *request;
664	struct keys *request_keys, *response_keys;
665	const char *chap_a, *chap_c, *chap_i;
666	char *chap_r, *challenge, response_bin[MD5_DIGEST_LENGTH];
667	size_t challenge_len;
668	int error, rv;
669	unsigned char id;
670        char *mutual_chap_c, mutual_chap_i[4];
671
672	/*
673	 * As in the rest of the initiator, 'request' means
674	 * 'initiator -> target', and 'response' means 'target -> initiator',
675	 *
676	 * So, here the 'response' from the target is the packet that contains
677	 * CHAP challenge; our CHAP response goes into 'request'.
678	 */
679
680	conn = response->pdu_connection;
681
682	response_keys = keys_new();
683	keys_load(response_keys, response);
684
685	/*
686	 * First, compute the response.
687	 */
688	chap_a = keys_find(response_keys, "CHAP_A");
689	if (chap_a == NULL)
690		log_errx(1, "received CHAP packet without CHAP_A");
691	chap_c = keys_find(response_keys, "CHAP_C");
692	if (chap_c == NULL)
693		log_errx(1, "received CHAP packet without CHAP_C");
694	chap_i = keys_find(response_keys, "CHAP_I");
695	if (chap_i == NULL)
696		log_errx(1, "received CHAP packet without CHAP_I");
697
698	if (strcmp(chap_a, "5") != 0)
699		log_errx(1, "received CHAP packet "
700		    "with unsupported CHAP_A \"%s\"", chap_a);
701	id = strtoul(chap_i, NULL, 10);
702	error = login_hex2bin(chap_c, &challenge, &challenge_len);
703	if (error != 0)
704		log_errx(1, "received CHAP packet with malformed CHAP_C");
705	login_compute_md5(id, conn->conn_conf.isc_secret,
706	    challenge, challenge_len, response_bin, sizeof(response_bin));
707	free(challenge);
708	chap_r = login_bin2hex(response_bin, sizeof(response_bin));
709
710	keys_delete(response_keys);
711
712	request = login_new_request(conn, BHSLR_STAGE_SECURITY_NEGOTIATION);
713	request_keys = keys_new();
714	keys_add(request_keys, "CHAP_N", conn->conn_conf.isc_user);
715	keys_add(request_keys, "CHAP_R", chap_r);
716	free(chap_r);
717
718	/*
719	 * If we want mutual authentication, we're expected to send
720	 * our CHAP_I/CHAP_C now.
721	 */
722	if (conn->conn_conf.isc_mutual_user[0] != '\0') {
723		log_debugx("requesting mutual authentication; "
724		    "binary challenge size is %zd bytes",
725		    sizeof(conn->conn_mutual_challenge));
726
727		rv = RAND_bytes(conn->conn_mutual_challenge,
728		    sizeof(conn->conn_mutual_challenge));
729		if (rv != 1) {
730			log_errx(1, "RAND_bytes failed: %s",
731			    ERR_error_string(ERR_get_error(), NULL));
732		}
733		rv = RAND_bytes(&conn->conn_mutual_id,
734		    sizeof(conn->conn_mutual_id));
735		if (rv != 1) {
736			log_errx(1, "RAND_bytes failed: %s",
737			    ERR_error_string(ERR_get_error(), NULL));
738		}
739		mutual_chap_c = login_bin2hex(conn->conn_mutual_challenge,
740		    sizeof(conn->conn_mutual_challenge));
741		snprintf(mutual_chap_i, sizeof(mutual_chap_i),
742		    "%d", conn->conn_mutual_id);
743		keys_add(request_keys, "CHAP_I", mutual_chap_i);
744		keys_add(request_keys, "CHAP_C", mutual_chap_c);
745		free(mutual_chap_c);
746	}
747
748	keys_save(request_keys, request);
749	keys_delete(request_keys);
750	pdu_send(request);
751	pdu_delete(request);
752}
753
754static void
755login_verify_mutual(const struct pdu *response)
756{
757	struct connection *conn;
758	struct keys *response_keys;
759	const char *chap_n, *chap_r;
760	char *response_bin, expected_response_bin[MD5_DIGEST_LENGTH];
761	size_t response_bin_len;
762	int error;
763
764	conn = response->pdu_connection;
765
766	response_keys = keys_new();
767	keys_load(response_keys, response);
768
769        chap_n = keys_find(response_keys, "CHAP_N");
770        if (chap_n == NULL)
771                log_errx(1, "received CHAP Response PDU without CHAP_N");
772        chap_r = keys_find(response_keys, "CHAP_R");
773        if (chap_r == NULL)
774                log_errx(1, "received CHAP Response PDU without CHAP_R");
775        error = login_hex2bin(chap_r, &response_bin, &response_bin_len);
776        if (error != 0)
777                log_errx(1, "received CHAP Response PDU with malformed CHAP_R");
778
779	if (strcmp(chap_n, conn->conn_conf.isc_mutual_user) != 0) {
780		fail(conn, "Mutual CHAP failed");
781		log_errx(1, "mutual CHAP authentication failed: wrong user");
782	}
783
784	login_compute_md5(conn->conn_mutual_id,
785	    conn->conn_conf.isc_mutual_secret, conn->conn_mutual_challenge,
786	    sizeof(conn->conn_mutual_challenge), expected_response_bin,
787	    sizeof(expected_response_bin));
788
789        if (memcmp(response_bin, expected_response_bin,
790            sizeof(expected_response_bin)) != 0) {
791		fail(conn, "Mutual CHAP failed");
792                log_errx(1, "mutual CHAP authentication failed: wrong secret");
793	}
794
795        keys_delete(response_keys);
796        free(response_bin);
797
798	log_debugx("mutual CHAP authentication succeeded");
799}
800
801static void
802login_chap(struct connection *conn)
803{
804	struct pdu *response;
805
806	log_debugx("beginning CHAP authentication; sending CHAP_A");
807	login_send_chap_a(conn);
808
809	log_debugx("waiting for CHAP_A/CHAP_C/CHAP_I");
810	response = login_receive(conn);
811
812	log_debugx("sending CHAP_N/CHAP_R");
813	login_send_chap_r(response);
814	pdu_delete(response);
815
816	/*
817	 * XXX: Make sure this is not susceptible to MITM.
818	 */
819
820	log_debugx("waiting for CHAP result");
821	response = login_receive(conn);
822	if (conn->conn_conf.isc_mutual_user[0] != '\0')
823		login_verify_mutual(response);
824	pdu_delete(response);
825
826	log_debugx("CHAP authentication done");
827}
828
829void
830login(struct connection *conn)
831{
832	struct pdu *request, *response;
833	struct keys *request_keys, *response_keys;
834	struct iscsi_bhs_login_response *bhslr2;
835	const char *auth_method;
836	int i;
837
838	log_debugx("beginning Login phase; sending Login PDU");
839	request = login_new_request(conn, BHSLR_STAGE_SECURITY_NEGOTIATION);
840	request_keys = keys_new();
841	if (conn->conn_conf.isc_mutual_user[0] != '\0') {
842		keys_add(request_keys, "AuthMethod", "CHAP");
843	} else if (conn->conn_conf.isc_user[0] != '\0') {
844		/*
845		 * Give target a chance to skip authentication if it
846		 * doesn't feel like it.
847		 *
848		 * None is first, CHAP second; this is to work around
849		 * what seems to be LIO (Linux target) bug: otherwise,
850		 * if target is configured with no authentication,
851		 * and we are configured to authenticate, the target
852		 * will erroneously respond with AuthMethod=CHAP
853		 * instead of AuthMethod=None, and will subsequently
854		 * fail the connection.  This usually happens with
855		 * Discovery sessions, which default to no authentication.
856		 */
857		keys_add(request_keys, "AuthMethod", "None,CHAP");
858	} else {
859		keys_add(request_keys, "AuthMethod", "None");
860	}
861	keys_add(request_keys, "InitiatorName",
862	    conn->conn_conf.isc_initiator);
863	if (conn->conn_conf.isc_initiator_alias[0] != '\0') {
864		keys_add(request_keys, "InitiatorAlias",
865		    conn->conn_conf.isc_initiator_alias);
866	}
867	if (conn->conn_conf.isc_discovery == 0) {
868		keys_add(request_keys, "SessionType", "Normal");
869		keys_add(request_keys,
870		    "TargetName", conn->conn_conf.isc_target);
871	} else {
872		keys_add(request_keys, "SessionType", "Discovery");
873	}
874	keys_save(request_keys, request);
875	keys_delete(request_keys);
876	pdu_send(request);
877	pdu_delete(request);
878
879	response = login_receive(conn);
880
881	response_keys = keys_new();
882	keys_load(response_keys, response);
883
884	for (i = 0; i < KEYS_MAX; i++) {
885		if (response_keys->keys_names[i] == NULL)
886			break;
887
888		/*
889		 * Not interested in AuthMethod at this point; we only need
890		 * to parse things such as TargetAlias.
891		 *
892		 * XXX: This is somewhat ugly.  We should have a way to apply
893		 * 	all the keys to the session and use that by default
894		 * 	instead of discarding them.
895		 */
896		if (strcmp(response_keys->keys_names[i], "AuthMethod") == 0)
897			continue;
898
899		login_negotiate_key(conn,
900		    response_keys->keys_names[i], response_keys->keys_values[i]);
901	}
902
903	bhslr2 = (struct iscsi_bhs_login_response *)response->pdu_bhs;
904	if ((bhslr2->bhslr_flags & BHSLR_FLAGS_TRANSIT) != 0 &&
905	    login_nsg(response) == BHSLR_STAGE_OPERATIONAL_NEGOTIATION) {
906		if (conn->conn_conf.isc_mutual_user[0] != '\0') {
907			log_errx(1, "target requested transition "
908			    "to operational parameter negotiation, "
909			    "but we require mutual CHAP");
910		}
911
912		log_debugx("target requested transition "
913		    "to operational parameter negotiation");
914		keys_delete(response_keys);
915		pdu_delete(response);
916		login_negotiate(conn);
917		return;
918	}
919
920	auth_method = keys_find(response_keys, "AuthMethod");
921	if (auth_method == NULL)
922		log_errx(1, "received response without AuthMethod");
923	if (strcmp(auth_method, "None") == 0) {
924		if (conn->conn_conf.isc_mutual_user[0] != '\0') {
925			log_errx(1, "target does not require authantication, "
926			    "but we require mutual CHAP");
927		}
928
929		log_debugx("target does not require authentication");
930		keys_delete(response_keys);
931		pdu_delete(response);
932		login_negotiate(conn);
933		return;
934	}
935
936	if (strcmp(auth_method, "CHAP") != 0) {
937		fail(conn, "Unsupported AuthMethod");
938		log_errx(1, "received response "
939		    "with unsupported AuthMethod \"%s\"", auth_method);
940	}
941
942	if (conn->conn_conf.isc_user[0] == '\0' ||
943	    conn->conn_conf.isc_secret[0] == '\0') {
944		fail(conn, "Authentication required");
945		log_errx(1, "target requests CHAP authentication, but we don't "
946		    "have user and secret");
947	}
948
949	keys_delete(response_keys);
950	response_keys = NULL;
951	pdu_delete(response);
952	response = NULL;
953
954	login_chap(conn);
955	login_negotiate(conn);
956}
957