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