login.c revision 269068
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 269068 2014-07-24 15:41:16Z 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, bool initial)
218{
219	struct pdu *response;
220	struct iscsi_bhs_login_response *bhslr;
221	const char *errorstr;
222
223	response = pdu_new(conn);
224	pdu_receive(response);
225	if (response->pdu_bhs->bhs_opcode != ISCSI_BHS_OPCODE_LOGIN_RESPONSE) {
226		log_errx(1, "protocol error: received invalid opcode 0x%x",
227		    response->pdu_bhs->bhs_opcode);
228	}
229	bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
230	/*
231	 * XXX: Implement the C flag some day.
232	 */
233	if ((bhslr->bhslr_flags & BHSLR_FLAGS_CONTINUE) != 0)
234		log_errx(1, "received Login PDU with unsupported \"C\" flag");
235	if (bhslr->bhslr_version_max != 0x00)
236		log_errx(1, "received Login PDU with unsupported "
237		    "Version-max 0x%x", bhslr->bhslr_version_max);
238	if (bhslr->bhslr_version_active != 0x00)
239		log_errx(1, "received Login PDU with unsupported "
240		    "Version-active 0x%x", bhslr->bhslr_version_active);
241	if (bhslr->bhslr_status_class == 1) {
242		login_handle_redirection(conn, response);
243		log_debugx("redirection handled; exiting");
244		exit(0);
245	}
246	if (bhslr->bhslr_status_class != 0) {
247		errorstr = login_target_error_str(bhslr->bhslr_status_class,
248		    bhslr->bhslr_status_detail);
249		fail(conn, errorstr);
250		log_errx(1, "target returned error: %s", errorstr);
251	}
252	if (initial == false &&
253	    ntohl(bhslr->bhslr_statsn) != conn->conn_statsn + 1) {
254		/*
255		 * It's a warning, not an error, to work around what seems
256		 * to be bug in NetBSD iSCSI target.
257		 */
258		log_warnx("received Login PDU with wrong StatSN: "
259		    "is %d, should be %d", ntohl(bhslr->bhslr_statsn),
260		    conn->conn_statsn + 1);
261	}
262	conn->conn_tsih = ntohs(bhslr->bhslr_tsih);
263	conn->conn_statsn = ntohl(bhslr->bhslr_statsn);
264
265	return (response);
266}
267
268static struct pdu *
269login_new_request(struct connection *conn, int csg)
270{
271	struct pdu *request;
272	struct iscsi_bhs_login_request *bhslr;
273	int nsg;
274
275	request = pdu_new(conn);
276	bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
277	bhslr->bhslr_opcode = ISCSI_BHS_OPCODE_LOGIN_REQUEST |
278	    ISCSI_BHS_OPCODE_IMMEDIATE;
279
280	bhslr->bhslr_flags = BHSLR_FLAGS_TRANSIT;
281	switch (csg) {
282	case BHSLR_STAGE_SECURITY_NEGOTIATION:
283		nsg = BHSLR_STAGE_OPERATIONAL_NEGOTIATION;
284		break;
285	case BHSLR_STAGE_OPERATIONAL_NEGOTIATION:
286		nsg = BHSLR_STAGE_FULL_FEATURE_PHASE;
287		break;
288	default:
289		assert(!"invalid csg");
290		log_errx(1, "invalid csg %d", csg);
291	}
292	login_set_csg(request, csg);
293	login_set_nsg(request, nsg);
294
295	memcpy(bhslr->bhslr_isid, &conn->conn_isid, sizeof(bhslr->bhslr_isid));
296	bhslr->bhslr_tsih = htons(conn->conn_tsih);
297	bhslr->bhslr_initiator_task_tag = 0;
298	bhslr->bhslr_cmdsn = 0;
299	bhslr->bhslr_expstatsn = htonl(conn->conn_statsn + 1);
300
301	return (request);
302}
303
304static int
305login_list_prefers(const char *list,
306    const char *choice1, const char *choice2)
307{
308	char *tofree, *str, *token;
309
310	tofree = str = checked_strdup(list);
311
312	while ((token = strsep(&str, ",")) != NULL) {
313		if (strcmp(token, choice1) == 0) {
314			free(tofree);
315			return (1);
316		}
317		if (strcmp(token, choice2) == 0) {
318			free(tofree);
319			return (2);
320		}
321	}
322	free(tofree);
323	return (-1);
324}
325
326static int
327login_hex2int(const char hex)
328{
329	switch (hex) {
330	case '0':
331		return (0x00);
332	case '1':
333		return (0x01);
334	case '2':
335		return (0x02);
336	case '3':
337		return (0x03);
338	case '4':
339		return (0x04);
340	case '5':
341		return (0x05);
342	case '6':
343		return (0x06);
344	case '7':
345		return (0x07);
346	case '8':
347		return (0x08);
348	case '9':
349		return (0x09);
350	case 'a':
351	case 'A':
352		return (0x0a);
353	case 'b':
354	case 'B':
355		return (0x0b);
356	case 'c':
357	case 'C':
358		return (0x0c);
359	case 'd':
360	case 'D':
361		return (0x0d);
362	case 'e':
363	case 'E':
364		return (0x0e);
365	case 'f':
366	case 'F':
367		return (0x0f);
368	default:
369		return (-1);
370	}
371}
372
373/*
374 * XXX: Review this _carefully_.
375 */
376static int
377login_hex2bin(const char *hex, char **binp, size_t *bin_lenp)
378{
379	int i, hex_len, nibble;
380	bool lo = true; /* As opposed to 'hi'. */
381	char *bin;
382	size_t bin_off, bin_len;
383
384	if (strncasecmp(hex, "0x", strlen("0x")) != 0) {
385		log_warnx("malformed variable, should start with \"0x\"");
386		return (-1);
387	}
388
389	hex += strlen("0x");
390	hex_len = strlen(hex);
391	if (hex_len < 1) {
392		log_warnx("malformed variable; doesn't contain anything "
393		    "but \"0x\"");
394		return (-1);
395	}
396
397	bin_len = hex_len / 2 + hex_len % 2;
398	bin = calloc(bin_len, 1);
399	if (bin == NULL)
400		log_err(1, "calloc");
401
402	bin_off = bin_len - 1;
403	for (i = hex_len - 1; i >= 0; i--) {
404		nibble = login_hex2int(hex[i]);
405		if (nibble < 0) {
406			log_warnx("malformed variable, invalid char \"%c\"",
407			    hex[i]);
408			return (-1);
409		}
410
411		assert(bin_off < bin_len);
412		if (lo) {
413			bin[bin_off] = nibble;
414			lo = false;
415		} else {
416			bin[bin_off] |= nibble << 4;
417			bin_off--;
418			lo = true;
419		}
420	}
421
422	*binp = bin;
423	*bin_lenp = bin_len;
424	return (0);
425}
426
427static char *
428login_bin2hex(const char *bin, size_t bin_len)
429{
430	unsigned char *hex, *tmp, ch;
431	size_t hex_len;
432	size_t i;
433
434	hex_len = bin_len * 2 + 3; /* +2 for "0x", +1 for '\0'. */
435	hex = malloc(hex_len);
436	if (hex == NULL)
437		log_err(1, "malloc");
438
439	tmp = hex;
440	tmp += sprintf(tmp, "0x");
441	for (i = 0; i < bin_len; i++) {
442		ch = bin[i];
443		tmp += sprintf(tmp, "%02x", ch);
444	}
445
446	return (hex);
447}
448
449static void
450login_compute_md5(const char id, const char *secret,
451    const void *challenge, size_t challenge_len, void *response,
452    size_t response_len)
453{
454	MD5_CTX ctx;
455	int rv;
456
457	assert(response_len == MD5_DIGEST_LENGTH);
458
459	MD5_Init(&ctx);
460	MD5_Update(&ctx, &id, sizeof(id));
461	MD5_Update(&ctx, secret, strlen(secret));
462	MD5_Update(&ctx, challenge, challenge_len);
463	rv = MD5_Final(response, &ctx);
464	if (rv != 1)
465		log_errx(1, "MD5_Final");
466}
467
468static void
469login_negotiate_key(struct connection *conn, const char *name,
470    const char *value)
471{
472	int which, tmp;
473
474	if (strcmp(name, "TargetAlias") == 0) {
475		strlcpy(conn->conn_target_alias, value,
476		    sizeof(conn->conn_target_alias));
477	} else if (strcmp(value, "Irrelevant") == 0) {
478		/* Ignore. */
479	} else if (strcmp(name, "HeaderDigest") == 0) {
480		which = login_list_prefers(value, "CRC32C", "None");
481		switch (which) {
482		case 1:
483			log_debugx("target prefers CRC32C "
484			    "for header digest; we'll use it");
485			conn->conn_header_digest = CONN_DIGEST_CRC32C;
486			break;
487		case 2:
488			log_debugx("target prefers not to do "
489			    "header digest; we'll comply");
490			break;
491		default:
492			log_warnx("target sent unrecognized "
493			    "HeaderDigest value \"%s\"; will use None", value);
494			break;
495		}
496	} else if (strcmp(name, "DataDigest") == 0) {
497		which = login_list_prefers(value, "CRC32C", "None");
498		switch (which) {
499		case 1:
500			log_debugx("target prefers CRC32C "
501			    "for data digest; we'll use it");
502			conn->conn_data_digest = CONN_DIGEST_CRC32C;
503			break;
504		case 2:
505			log_debugx("target prefers not to do "
506			    "data digest; we'll comply");
507			break;
508		default:
509			log_warnx("target sent unrecognized "
510			    "DataDigest value \"%s\"; will use None", value);
511			break;
512		}
513	} else if (strcmp(name, "MaxConnections") == 0) {
514		/* Ignore. */
515	} else if (strcmp(name, "InitialR2T") == 0) {
516		if (strcmp(value, "Yes") == 0)
517			conn->conn_initial_r2t = true;
518		else
519			conn->conn_initial_r2t = false;
520	} else if (strcmp(name, "ImmediateData") == 0) {
521		if (strcmp(value, "Yes") == 0)
522			conn->conn_immediate_data = true;
523		else
524			conn->conn_immediate_data = false;
525	} else if (strcmp(name, "MaxRecvDataSegmentLength") == 0) {
526		tmp = strtoul(value, NULL, 10);
527		if (tmp <= 0)
528			log_errx(1, "received invalid "
529			    "MaxRecvDataSegmentLength");
530		conn->conn_max_data_segment_length = tmp;
531	} else if (strcmp(name, "MaxBurstLength") == 0) {
532		if (conn->conn_immediate_data) {
533			tmp = strtoul(value, NULL, 10);
534			if (tmp <= 0)
535				log_errx(1, "received invalid MaxBurstLength");
536			conn->conn_max_burst_length = tmp;
537		}
538	} else if (strcmp(name, "FirstBurstLength") == 0) {
539		tmp = strtoul(value, NULL, 10);
540		if (tmp <= 0)
541			log_errx(1, "received invalid FirstBurstLength");
542		conn->conn_first_burst_length = tmp;
543	} else if (strcmp(name, "DefaultTime2Wait") == 0) {
544		/* Ignore */
545	} else if (strcmp(name, "DefaultTime2Retain") == 0) {
546		/* Ignore */
547	} else if (strcmp(name, "MaxOutstandingR2T") == 0) {
548		/* Ignore */
549	} else if (strcmp(name, "DataPDUInOrder") == 0) {
550		/* Ignore */
551	} else if (strcmp(name, "DataSequenceInOrder") == 0) {
552		/* Ignore */
553	} else if (strcmp(name, "ErrorRecoveryLevel") == 0) {
554		/* Ignore */
555	} else if (strcmp(name, "OFMarker") == 0) {
556		/* Ignore */
557	} else if (strcmp(name, "IFMarker") == 0) {
558		/* Ignore */
559	} else if (strcmp(name, "TargetPortalGroupTag") == 0) {
560		/* Ignore */
561	} else {
562		log_debugx("unknown key \"%s\"; ignoring",  name);
563	}
564}
565
566static void
567login_negotiate(struct connection *conn)
568{
569	struct pdu *request, *response;
570	struct keys *request_keys, *response_keys;
571	struct iscsi_bhs_login_response *bhslr;
572	int i;
573
574	log_debugx("beginning operational parameter negotiation");
575	request = login_new_request(conn, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
576	request_keys = keys_new();
577
578	/*
579	 * The following keys are irrelevant for discovery sessions.
580	 */
581	if (conn->conn_conf.isc_discovery == 0) {
582		if (conn->conn_conf.isc_header_digest != 0)
583			keys_add(request_keys, "HeaderDigest", "CRC32C");
584		else
585			keys_add(request_keys, "HeaderDigest", "None");
586		if (conn->conn_conf.isc_data_digest != 0)
587			keys_add(request_keys, "DataDigest", "CRC32C");
588		else
589			keys_add(request_keys, "DataDigest", "None");
590
591		keys_add(request_keys, "ImmediateData", "Yes");
592		keys_add_int(request_keys, "MaxBurstLength",
593		    ISCSI_MAX_DATA_SEGMENT_LENGTH);
594		keys_add_int(request_keys, "FirstBurstLength",
595		    ISCSI_MAX_DATA_SEGMENT_LENGTH);
596		keys_add(request_keys, "InitialR2T", "Yes");
597	} else {
598		keys_add(request_keys, "HeaderDigest", "None");
599		keys_add(request_keys, "DataDigest", "None");
600	}
601
602	keys_add_int(request_keys, "MaxRecvDataSegmentLength",
603	    ISCSI_MAX_DATA_SEGMENT_LENGTH);
604	keys_add(request_keys, "DefaultTime2Wait", "0");
605	keys_add(request_keys, "DefaultTime2Retain", "0");
606	keys_add(request_keys, "ErrorRecoveryLevel", "0");
607	keys_add(request_keys, "MaxOutstandingR2T", "1");
608	keys_save(request_keys, request);
609	keys_delete(request_keys);
610	request_keys = NULL;
611	pdu_send(request);
612	pdu_delete(request);
613	request = NULL;
614
615	response = login_receive(conn, false);
616	response_keys = keys_new();
617	keys_load(response_keys, response);
618	for (i = 0; i < KEYS_MAX; i++) {
619		if (response_keys->keys_names[i] == NULL)
620			break;
621
622		login_negotiate_key(conn,
623		    response_keys->keys_names[i], response_keys->keys_values[i]);
624	}
625
626	bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
627	if ((bhslr->bhslr_flags & BHSLR_FLAGS_TRANSIT) == 0)
628		log_warnx("received final login response "
629		    "without the \"T\" flag");
630	else if (login_nsg(response) != BHSLR_STAGE_FULL_FEATURE_PHASE)
631		log_warnx("received final login response with wrong NSG 0x%x",
632		    login_nsg(response));
633
634	log_debugx("operational parameter negotiation done; "
635	    "transitioning to Full Feature phase");
636
637	keys_delete(response_keys);
638	pdu_delete(response);
639}
640
641static void
642login_send_chap_a(struct connection *conn)
643{
644	struct pdu *request;
645	struct keys *request_keys;
646
647	request = login_new_request(conn, BHSLR_STAGE_SECURITY_NEGOTIATION);
648	request_keys = keys_new();
649	keys_add(request_keys, "CHAP_A", "5");
650	keys_save(request_keys, request);
651	keys_delete(request_keys);
652	pdu_send(request);
653	pdu_delete(request);
654}
655
656static void
657login_send_chap_r(struct pdu *response)
658{
659	struct connection *conn;
660	struct pdu *request;
661	struct keys *request_keys, *response_keys;
662	const char *chap_a, *chap_c, *chap_i;
663	char *chap_r, *challenge, response_bin[MD5_DIGEST_LENGTH];
664	size_t challenge_len;
665	int error, rv;
666	unsigned char id;
667        char *mutual_chap_c, mutual_chap_i[4];
668
669	/*
670	 * As in the rest of the initiator, 'request' means
671	 * 'initiator -> target', and 'response' means 'target -> initiator',
672	 *
673	 * So, here the 'response' from the target is the packet that contains
674	 * CHAP challenge; our CHAP response goes into 'request'.
675	 */
676
677	conn = response->pdu_connection;
678
679	response_keys = keys_new();
680	keys_load(response_keys, response);
681
682	/*
683	 * First, compute the response.
684	 */
685	chap_a = keys_find(response_keys, "CHAP_A");
686	if (chap_a == NULL)
687		log_errx(1, "received CHAP packet without CHAP_A");
688	chap_c = keys_find(response_keys, "CHAP_C");
689	if (chap_c == NULL)
690		log_errx(1, "received CHAP packet without CHAP_C");
691	chap_i = keys_find(response_keys, "CHAP_I");
692	if (chap_i == NULL)
693		log_errx(1, "received CHAP packet without CHAP_I");
694
695	if (strcmp(chap_a, "5") != 0)
696		log_errx(1, "received CHAP packet "
697		    "with unsupported CHAP_A \"%s\"", chap_a);
698	id = strtoul(chap_i, NULL, 10);
699	error = login_hex2bin(chap_c, &challenge, &challenge_len);
700	if (error != 0)
701		log_errx(1, "received CHAP packet with malformed CHAP_C");
702	login_compute_md5(id, conn->conn_conf.isc_secret,
703	    challenge, challenge_len, response_bin, sizeof(response_bin));
704	free(challenge);
705	chap_r = login_bin2hex(response_bin, sizeof(response_bin));
706
707	keys_delete(response_keys);
708
709	request = login_new_request(conn, BHSLR_STAGE_SECURITY_NEGOTIATION);
710	request_keys = keys_new();
711	keys_add(request_keys, "CHAP_N", conn->conn_conf.isc_user);
712	keys_add(request_keys, "CHAP_R", chap_r);
713	free(chap_r);
714
715	/*
716	 * If we want mutual authentication, we're expected to send
717	 * our CHAP_I/CHAP_C now.
718	 */
719	if (conn->conn_conf.isc_mutual_user[0] != '\0') {
720		log_debugx("requesting mutual authentication; "
721		    "binary challenge size is %zd bytes",
722		    sizeof(conn->conn_mutual_challenge));
723
724		rv = RAND_bytes(conn->conn_mutual_challenge,
725		    sizeof(conn->conn_mutual_challenge));
726		if (rv != 1) {
727			log_errx(1, "RAND_bytes failed: %s",
728			    ERR_error_string(ERR_get_error(), NULL));
729		}
730		rv = RAND_bytes(&conn->conn_mutual_id,
731		    sizeof(conn->conn_mutual_id));
732		if (rv != 1) {
733			log_errx(1, "RAND_bytes failed: %s",
734			    ERR_error_string(ERR_get_error(), NULL));
735		}
736		mutual_chap_c = login_bin2hex(conn->conn_mutual_challenge,
737		    sizeof(conn->conn_mutual_challenge));
738		snprintf(mutual_chap_i, sizeof(mutual_chap_i),
739		    "%d", conn->conn_mutual_id);
740		keys_add(request_keys, "CHAP_I", mutual_chap_i);
741		keys_add(request_keys, "CHAP_C", mutual_chap_c);
742		free(mutual_chap_c);
743	}
744
745	keys_save(request_keys, request);
746	keys_delete(request_keys);
747	pdu_send(request);
748	pdu_delete(request);
749}
750
751static void
752login_verify_mutual(const struct pdu *response)
753{
754	struct connection *conn;
755	struct keys *response_keys;
756	const char *chap_n, *chap_r;
757	char *response_bin, expected_response_bin[MD5_DIGEST_LENGTH];
758	size_t response_bin_len;
759	int error;
760
761	conn = response->pdu_connection;
762
763	response_keys = keys_new();
764	keys_load(response_keys, response);
765
766        chap_n = keys_find(response_keys, "CHAP_N");
767        if (chap_n == NULL)
768                log_errx(1, "received CHAP Response PDU without CHAP_N");
769        chap_r = keys_find(response_keys, "CHAP_R");
770        if (chap_r == NULL)
771                log_errx(1, "received CHAP Response PDU without CHAP_R");
772        error = login_hex2bin(chap_r, &response_bin, &response_bin_len);
773        if (error != 0)
774                log_errx(1, "received CHAP Response PDU with malformed CHAP_R");
775
776	if (strcmp(chap_n, conn->conn_conf.isc_mutual_user) != 0) {
777		fail(conn, "Mutual CHAP failed");
778		log_errx(1, "mutual CHAP authentication failed: wrong user");
779	}
780
781	login_compute_md5(conn->conn_mutual_id,
782	    conn->conn_conf.isc_mutual_secret, conn->conn_mutual_challenge,
783	    sizeof(conn->conn_mutual_challenge), expected_response_bin,
784	    sizeof(expected_response_bin));
785
786        if (memcmp(response_bin, expected_response_bin,
787            sizeof(expected_response_bin)) != 0) {
788		fail(conn, "Mutual CHAP failed");
789                log_errx(1, "mutual CHAP authentication failed: wrong secret");
790	}
791
792        keys_delete(response_keys);
793        free(response_bin);
794
795	log_debugx("mutual CHAP authentication succeeded");
796}
797
798static void
799login_chap(struct connection *conn)
800{
801	struct pdu *response;
802
803	log_debugx("beginning CHAP authentication; sending CHAP_A");
804	login_send_chap_a(conn);
805
806	log_debugx("waiting for CHAP_A/CHAP_C/CHAP_I");
807	response = login_receive(conn, false);
808
809	log_debugx("sending CHAP_N/CHAP_R");
810	login_send_chap_r(response);
811	pdu_delete(response);
812
813	/*
814	 * XXX: Make sure this is not susceptible to MITM.
815	 */
816
817	log_debugx("waiting for CHAP result");
818	response = login_receive(conn, false);
819	if (conn->conn_conf.isc_mutual_user[0] != '\0')
820		login_verify_mutual(response);
821	pdu_delete(response);
822
823	log_debugx("CHAP authentication done");
824}
825
826void
827login(struct connection *conn)
828{
829	struct pdu *request, *response;
830	struct keys *request_keys, *response_keys;
831	struct iscsi_bhs_login_response *bhslr2;
832	const char *auth_method;
833	int i;
834
835	log_debugx("beginning Login phase; sending Login PDU");
836	request = login_new_request(conn, BHSLR_STAGE_SECURITY_NEGOTIATION);
837	request_keys = keys_new();
838	if (conn->conn_conf.isc_mutual_user[0] != '\0') {
839		keys_add(request_keys, "AuthMethod", "CHAP");
840	} else if (conn->conn_conf.isc_user[0] != '\0') {
841		/*
842		 * Give target a chance to skip authentication if it
843		 * doesn't feel like it.
844		 *
845		 * None is first, CHAP second; this is to work around
846		 * what seems to be LIO (Linux target) bug: otherwise,
847		 * if target is configured with no authentication,
848		 * and we are configured to authenticate, the target
849		 * will erroneously respond with AuthMethod=CHAP
850		 * instead of AuthMethod=None, and will subsequently
851		 * fail the connection.  This usually happens with
852		 * Discovery sessions, which default to no authentication.
853		 */
854		keys_add(request_keys, "AuthMethod", "None,CHAP");
855	} else {
856		keys_add(request_keys, "AuthMethod", "None");
857	}
858	keys_add(request_keys, "InitiatorName",
859	    conn->conn_conf.isc_initiator);
860	if (conn->conn_conf.isc_initiator_alias[0] != '\0') {
861		keys_add(request_keys, "InitiatorAlias",
862		    conn->conn_conf.isc_initiator_alias);
863	}
864	if (conn->conn_conf.isc_discovery == 0) {
865		keys_add(request_keys, "SessionType", "Normal");
866		keys_add(request_keys,
867		    "TargetName", conn->conn_conf.isc_target);
868	} else {
869		keys_add(request_keys, "SessionType", "Discovery");
870	}
871	keys_save(request_keys, request);
872	keys_delete(request_keys);
873	pdu_send(request);
874	pdu_delete(request);
875
876	response = login_receive(conn, true);
877
878	response_keys = keys_new();
879	keys_load(response_keys, response);
880
881	for (i = 0; i < KEYS_MAX; i++) {
882		if (response_keys->keys_names[i] == NULL)
883			break;
884
885		/*
886		 * Not interested in AuthMethod at this point; we only need
887		 * to parse things such as TargetAlias.
888		 *
889		 * XXX: This is somewhat ugly.  We should have a way to apply
890		 * 	all the keys to the session and use that by default
891		 * 	instead of discarding them.
892		 */
893		if (strcmp(response_keys->keys_names[i], "AuthMethod") == 0)
894			continue;
895
896		login_negotiate_key(conn,
897		    response_keys->keys_names[i], response_keys->keys_values[i]);
898	}
899
900	bhslr2 = (struct iscsi_bhs_login_response *)response->pdu_bhs;
901	if ((bhslr2->bhslr_flags & BHSLR_FLAGS_TRANSIT) != 0 &&
902	    login_nsg(response) == BHSLR_STAGE_OPERATIONAL_NEGOTIATION) {
903		if (conn->conn_conf.isc_mutual_user[0] != '\0') {
904			log_errx(1, "target requested transition "
905			    "to operational parameter negotiation, "
906			    "but we require mutual CHAP");
907		}
908
909		log_debugx("target requested transition "
910		    "to operational parameter negotiation");
911		keys_delete(response_keys);
912		pdu_delete(response);
913		login_negotiate(conn);
914		return;
915	}
916
917	auth_method = keys_find(response_keys, "AuthMethod");
918	if (auth_method == NULL)
919		log_errx(1, "received response without AuthMethod");
920	if (strcmp(auth_method, "None") == 0) {
921		if (conn->conn_conf.isc_mutual_user[0] != '\0') {
922			log_errx(1, "target does not require authantication, "
923			    "but we require mutual CHAP");
924		}
925
926		log_debugx("target does not require authentication");
927		keys_delete(response_keys);
928		pdu_delete(response);
929		login_negotiate(conn);
930		return;
931	}
932
933	if (strcmp(auth_method, "CHAP") != 0) {
934		fail(conn, "Unsupported AuthMethod");
935		log_errx(1, "received response "
936		    "with unsupported AuthMethod \"%s\"", auth_method);
937	}
938
939	if (conn->conn_conf.isc_user[0] == '\0' ||
940	    conn->conn_conf.isc_secret[0] == '\0') {
941		fail(conn, "Authentication required");
942		log_errx(1, "target requests CHAP authentication, but we don't "
943		    "have user and secret");
944	}
945
946	keys_delete(response_keys);
947	response_keys = NULL;
948	pdu_delete(response);
949	response = NULL;
950
951	login_chap(conn);
952	login_negotiate(conn);
953}
954