login.c revision 269067
1242381Sbapt/*-
2242381Sbapt * Copyright (c) 2012 The FreeBSD Foundation
3242381Sbapt * All rights reserved.
4242381Sbapt *
5242381Sbapt * This software was developed by Edward Tomasz Napierala under sponsorship
6242381Sbapt * from the FreeBSD Foundation.
7242381Sbapt *
8242381Sbapt * Redistribution and use in source and binary forms, with or without
9242381Sbapt * modification, are permitted provided that the following conditions
10242381Sbapt * are met:
11242381Sbapt * 1. Redistributions of source code must retain the above copyright
12242381Sbapt *    notice, this list of conditions and the following disclaimer.
13242381Sbapt * 2. Redistributions in binary form must reproduce the above copyright
14242381Sbapt *    notice, this list of conditions and the following disclaimer in the
15242381Sbapt *    documentation and/or other materials provided with the distribution.
16242381Sbapt *
17242381Sbapt * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18242381Sbapt * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19242381Sbapt * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20242381Sbapt * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21242381Sbapt * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22242381Sbapt * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23242381Sbapt * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24242381Sbapt * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25242381Sbapt * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26242381Sbapt * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27285205Sgarga * SUCH DAMAGE.
28242381Sbapt *
29242381Sbapt * $FreeBSD: stable/10/usr.sbin/iscsid/login.c 269067 2014-07-24 15:38:49Z mav $
30242381Sbapt */
31242381Sbapt
32242381Sbapt#include <sys/types.h>
33242381Sbapt#include <sys/ioctl.h>
34242381Sbapt#include <assert.h>
35242381Sbapt#include <stdbool.h>
36242381Sbapt#include <stdio.h>
37242381Sbapt#include <stdlib.h>
38242381Sbapt#include <string.h>
39242381Sbapt#include <netinet/in.h>
40242381Sbapt#include <openssl/err.h>
41242381Sbapt#include <openssl/md5.h>
42242381Sbapt#include <openssl/rand.h>
43242381Sbapt
44242381Sbapt#include "iscsid.h"
45242381Sbapt#include "iscsi_proto.h"
46242381Sbapt
47242381Sbaptstatic int
48242381Sbaptlogin_nsg(const struct pdu *response)
49242381Sbapt{
50242381Sbapt	struct iscsi_bhs_login_response *bhslr;
51261954Seadler
52242381Sbapt	bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
53242381Sbapt
54242381Sbapt	return (bhslr->bhslr_flags & 0x03);
55242381Sbapt}
56242381Sbapt
57261954Seadlerstatic void
58242381Sbaptlogin_set_nsg(struct pdu *request, int nsg)
59242381Sbapt{
60242381Sbapt	struct iscsi_bhs_login_request *bhslr;
61242381Sbapt
62242381Sbapt	assert(nsg == BHSLR_STAGE_SECURITY_NEGOTIATION ||
63242381Sbapt	    nsg == BHSLR_STAGE_OPERATIONAL_NEGOTIATION ||
64242381Sbapt	    nsg == BHSLR_STAGE_FULL_FEATURE_PHASE);
65242381Sbapt
66242381Sbapt	bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
67242381Sbapt
68242381Sbapt	bhslr->bhslr_flags &= 0xFC;
69242381Sbapt	bhslr->bhslr_flags |= nsg;
70242381Sbapt}
71242381Sbapt
72242381Sbaptstatic void
73242381Sbaptlogin_set_csg(struct pdu *request, int csg)
74242381Sbapt{
75242381Sbapt	struct iscsi_bhs_login_request *bhslr;
76242381Sbapt
77242381Sbapt	assert(csg == BHSLR_STAGE_SECURITY_NEGOTIATION ||
78242381Sbapt	    csg == BHSLR_STAGE_OPERATIONAL_NEGOTIATION ||
79242381Sbapt	    csg == BHSLR_STAGE_FULL_FEATURE_PHASE);
80242381Sbapt
81242381Sbapt	bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
82242381Sbapt
83242381Sbapt	bhslr->bhslr_flags &= 0xF3;
84242381Sbapt	bhslr->bhslr_flags |= csg << 2;
85242381Sbapt}
86242381Sbapt
87242381Sbaptstatic const char *
88242381Sbaptlogin_target_error_str(int class, int detail)
89242381Sbapt{
90242381Sbapt	static char msg[128];
91242381Sbapt
92242381Sbapt	/*
93242381Sbapt	 * RFC 3270, 10.13.5.  Status-Class and Status-Detail
94242381Sbapt	 */
95242381Sbapt	switch (class) {
96242381Sbapt	case 0x01:
97242381Sbapt		switch (detail) {
98242381Sbapt		case 0x01:
99242381Sbapt			return ("Target moved temporarily");
100242381Sbapt		case 0x02:
101242381Sbapt			return ("Target moved permanently");
102242381Sbapt		default:
103242381Sbapt			snprintf(msg, sizeof(msg), "unknown redirection; "
104242381Sbapt			    "Status-Class 0x%x, Status-Detail 0x%x",
105242381Sbapt			    class, detail);
106242383Sjoel			return (msg);
107242381Sbapt		}
108242381Sbapt	case 0x02:
109242381Sbapt		switch (detail) {
110242381Sbapt		case 0x00:
111242381Sbapt			return ("Initiator error");
112242381Sbapt		case 0x01:
113242381Sbapt			return ("Authentication failure");
114242381Sbapt		case 0x02:
115242381Sbapt			return ("Authorization failure");
116242381Sbapt		case 0x03:
117242381Sbapt			return ("Not found");
118242381Sbapt		case 0x04:
119242381Sbapt			return ("Target removed");
120242381Sbapt		case 0x05:
121242381Sbapt			return ("Unsupported version");
122242381Sbapt		case 0x06:
123242381Sbapt			return ("Too many connections");
124242381Sbapt		case 0x07:
125242381Sbapt			return ("Missing parameter");
126242381Sbapt		case 0x08:
127242381Sbapt			return ("Can't include in session");
128242381Sbapt		case 0x09:
129242381Sbapt			return ("Session type not supported");
130242381Sbapt		case 0x0a:
131242381Sbapt			return ("Session does not exist");
132242381Sbapt		case 0x0b:
133242381Sbapt			return ("Invalid during login");
134242381Sbapt		default:
135242381Sbapt			snprintf(msg, sizeof(msg), "unknown initiator error; "
136242381Sbapt			    "Status-Class 0x%x, Status-Detail 0x%x",
137242381Sbapt			    class, detail);
138242381Sbapt			return (msg);
139242381Sbapt		}
140242381Sbapt	case 0x03:
141242381Sbapt		switch (detail) {
142242381Sbapt		case 0x00:
143242381Sbapt			return ("Target error");
144242381Sbapt		case 0x01:
145242381Sbapt			return ("Service unavailable");
146242381Sbapt		case 0x02:
147242381Sbapt			return ("Out of resources");
148242381Sbapt		default:
149242381Sbapt			snprintf(msg, sizeof(msg), "unknown target error; "
150242381Sbapt			    "Status-Class 0x%x, Status-Detail 0x%x",
151242381Sbapt			    class, detail);
152242381Sbapt			return (msg);
153242381Sbapt		}
154242381Sbapt	default:
155242381Sbapt		snprintf(msg, sizeof(msg), "unknown error; "
156242381Sbapt		    "Status-Class 0x%x, Status-Detail 0x%x",
157242381Sbapt		    class, detail);
158242381Sbapt		return (msg);
159242381Sbapt	}
160242381Sbapt}
161242381Sbapt
162242381Sbaptstatic void
163242381Sbaptkernel_modify(const struct connection *conn, const char *target_address)
164242381Sbapt{
165242381Sbapt	struct iscsi_session_modify ism;
166242381Sbapt	int error;
167242381Sbapt
168242381Sbapt	memset(&ism, 0, sizeof(ism));
169242381Sbapt	ism.ism_session_id = conn->conn_session_id;
170242381Sbapt	memcpy(&ism.ism_conf, &conn->conn_conf, sizeof(ism.ism_conf));
171242381Sbapt	strlcpy(ism.ism_conf.isc_target_addr, target_address,
172242381Sbapt	    sizeof(ism.ism_conf.isc_target));
173242383Sjoel	error = ioctl(conn->conn_iscsi_fd, ISCSISMODIFY, &ism);
174242381Sbapt	if (error != 0) {
175242381Sbapt		log_err(1, "failed to redirect to %s: ISCSISMODIFY",
176242381Sbapt		    target_address);
177242381Sbapt	}
178242381Sbapt}
179242381Sbapt
180242381Sbapt/*
181242381Sbapt * XXX:	The way it works is suboptimal; what should happen is described
182242381Sbapt *	in draft-gilligan-iscsi-fault-tolerance-00.  That, however, would
183242381Sbapt *	be much more complicated: we would need to keep "dependencies"
184242381Sbapt *	for sessions, so that, in case described in draft and using draft
185242381Sbapt *	terminology, we would have three sessions: one for discovery,
186242381Sbapt *	one for initial target portal, and one for redirect portal.
187242381Sbapt *	This would allow us to "backtrack" on connection failure,
188242381Sbapt *	as described in draft.
189242381Sbapt */
190242381Sbaptstatic void
191242381Sbaptlogin_handle_redirection(struct connection *conn, struct pdu *response)
192242381Sbapt{
193242381Sbapt	struct iscsi_bhs_login_response *bhslr;
194242381Sbapt	struct keys *response_keys;
195242381Sbapt	const char *target_address;
196242381Sbapt
197242381Sbapt	bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
198242381Sbapt	assert (bhslr->bhslr_status_class == 1);
199242381Sbapt
200242381Sbapt	response_keys = keys_new();
201242381Sbapt	keys_load(response_keys, response);
202242381Sbapt
203242381Sbapt	target_address = keys_find(response_keys, "TargetAddress");
204242381Sbapt	if (target_address == NULL)
205242381Sbapt		log_errx(1, "received redirection without TargetAddress");
206242381Sbapt	if (target_address[0] == '\0')
207242381Sbapt		log_errx(1, "received redirection with empty TargetAddress");
208242381Sbapt	if (strlen(target_address) >=
209242381Sbapt	    sizeof(conn->conn_conf.isc_target_addr) - 1)
210242381Sbapt		log_errx(1, "received TargetAddress is too long");
211242381Sbapt
212242381Sbapt	log_debugx("received redirection to \"%s\"", target_address);
213242381Sbapt	kernel_modify(conn, target_address);
214242381Sbapt}
215242381Sbapt
216242381Sbaptstatic struct pdu *
217242381Sbaptlogin_receive(struct connection *conn, bool initial)
218242381Sbapt{
219242381Sbapt	struct pdu *response;
220242381Sbapt	struct iscsi_bhs_login_response *bhslr;
221242381Sbapt	const char *errorstr;
222242381Sbapt
223242381Sbapt	response = pdu_new(conn);
224242381Sbapt	pdu_receive(response);
225242381Sbapt	if (response->pdu_bhs->bhs_opcode != ISCSI_BHS_OPCODE_LOGIN_RESPONSE) {
226242381Sbapt		log_errx(1, "protocol error: received invalid opcode 0x%x",
227242381Sbapt		    response->pdu_bhs->bhs_opcode);
228242381Sbapt	}
229242381Sbapt	bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
230242381Sbapt	/*
231242381Sbapt	 * XXX: Implement the C flag some day.
232242381Sbapt	 */
233242381Sbapt	if ((bhslr->bhslr_flags & BHSLR_FLAGS_CONTINUE) != 0)
234242381Sbapt		log_errx(1, "received Login PDU with unsupported \"C\" flag");
235242381Sbapt	if (bhslr->bhslr_version_max != 0x00)
236285205Sgarga		log_errx(1, "received Login PDU with unsupported "
237285205Sgarga		    "Version-max 0x%x", bhslr->bhslr_version_max);
238242381Sbapt	if (bhslr->bhslr_version_active != 0x00)
239242381Sbapt		log_errx(1, "received Login PDU with unsupported "
240242381Sbapt		    "Version-active 0x%x", bhslr->bhslr_version_active);
241242381Sbapt	if (bhslr->bhslr_status_class == 1) {
242242381Sbapt		login_handle_redirection(conn, response);
243242381Sbapt		log_debugx("redirection handled; exiting");
244242381Sbapt		exit(0);
245242381Sbapt	}
246242381Sbapt	if (bhslr->bhslr_status_class != 0) {
247242381Sbapt		errorstr = login_target_error_str(bhslr->bhslr_status_class,
248242381Sbapt		    bhslr->bhslr_status_detail);
249242381Sbapt		fail(conn, errorstr);
250242381Sbapt		log_errx(1, "target returned error: %s", errorstr);
251242381Sbapt	}
252242381Sbapt	if (initial == false &&
253242381Sbapt	    ntohl(bhslr->bhslr_statsn) != conn->conn_statsn + 1) {
254242381Sbapt		/*
255242381Sbapt		 * It's a warning, not an error, to work around what seems
256242381Sbapt		 * to be bug in NetBSD iSCSI target.
257242381Sbapt		 */
258242381Sbapt		log_warnx("received Login PDU with wrong StatSN: "
259242381Sbapt		    "is %d, should be %d", ntohl(bhslr->bhslr_statsn),
260242381Sbapt		    conn->conn_statsn + 1);
261242381Sbapt	}
262242381Sbapt	conn->conn_tsih = ntohs(bhslr->bhslr_tsih);
263242381Sbapt	conn->conn_statsn = ntohl(bhslr->bhslr_statsn);
264242381Sbapt
265242381Sbapt	return (response);
266242381Sbapt}
267242381Sbapt
268242381Sbaptstatic struct pdu *
269242381Sbaptlogin_new_request(struct connection *conn)
270242381Sbapt{
271242381Sbapt	struct pdu *request;
272242381Sbapt	struct iscsi_bhs_login_request *bhslr;
273242381Sbapt
274242381Sbapt	request = pdu_new(conn);
275242381Sbapt	bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
276242381Sbapt	bhslr->bhslr_opcode = ISCSI_BHS_OPCODE_LOGIN_REQUEST |
277242381Sbapt	    ISCSI_BHS_OPCODE_IMMEDIATE;
278242398Sdes	bhslr->bhslr_flags = BHSLR_FLAGS_TRANSIT;
279242398Sdes	login_set_csg(request, BHSLR_STAGE_SECURITY_NEGOTIATION);
280242398Sdes	login_set_nsg(request, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
281242398Sdes	memcpy(bhslr->bhslr_isid, &conn->conn_isid, sizeof(bhslr->bhslr_isid));
282242398Sdes	bhslr->bhslr_tsih = htons(conn->conn_tsih);
283242398Sdes	bhslr->bhslr_initiator_task_tag = 0;
284242398Sdes	bhslr->bhslr_cmdsn = 0;
285242398Sdes	bhslr->bhslr_expstatsn = htonl(conn->conn_statsn + 1);
286242381Sbapt
287242381Sbapt	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