1/*-
2 * Copyright (c) 2012 The FreeBSD Foundation
3 * All rights reserved.
4 *
5 * This software was developed by Edward Tomasz Napierala under sponsorship
6 * from the FreeBSD Foundation.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 */
30
31#include <sys/cdefs.h>
32__FBSDID("$FreeBSD$");
33
34#include <assert.h>
35#include <stdbool.h>
36#include <stdlib.h>
37#include <string.h>
38#include <unistd.h>
39#include <netinet/in.h>
40
41#include "ctld.h"
42#include "iscsi_proto.h"
43
44static void login_send_error(struct pdu *request,
45    char class, char detail);
46
47static void
48login_set_nsg(struct pdu *response, int nsg)
49{
50	struct iscsi_bhs_login_response *bhslr;
51
52	assert(nsg == BHSLR_STAGE_SECURITY_NEGOTIATION ||
53	    nsg == BHSLR_STAGE_OPERATIONAL_NEGOTIATION ||
54	    nsg == BHSLR_STAGE_FULL_FEATURE_PHASE);
55
56	bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
57
58	bhslr->bhslr_flags &= 0xFC;
59	bhslr->bhslr_flags |= nsg;
60	bhslr->bhslr_flags |= BHSLR_FLAGS_TRANSIT;
61}
62
63static int
64login_csg(const struct pdu *request)
65{
66	struct iscsi_bhs_login_request *bhslr;
67
68	bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
69
70	return ((bhslr->bhslr_flags & 0x0C) >> 2);
71}
72
73static void
74login_set_csg(struct pdu *response, int csg)
75{
76	struct iscsi_bhs_login_response *bhslr;
77
78	assert(csg == BHSLR_STAGE_SECURITY_NEGOTIATION ||
79	    csg == BHSLR_STAGE_OPERATIONAL_NEGOTIATION ||
80	    csg == BHSLR_STAGE_FULL_FEATURE_PHASE);
81
82	bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
83
84	bhslr->bhslr_flags &= 0xF3;
85	bhslr->bhslr_flags |= csg << 2;
86}
87
88static struct pdu *
89login_receive(struct connection *conn, bool initial)
90{
91	struct pdu *request;
92	struct iscsi_bhs_login_request *bhslr;
93
94	request = pdu_new(conn);
95	pdu_receive(request);
96	if ((request->pdu_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) !=
97	    ISCSI_BHS_OPCODE_LOGIN_REQUEST) {
98		/*
99		 * The first PDU in session is special - if we receive any PDU
100		 * different than login request, we have to drop the connection
101		 * without sending response ("A target receiving any PDU
102		 * except a Login request before the Login Phase is started MUST
103		 * immediately terminate the connection on which the PDU
104		 * was received.")
105		 */
106		if (initial == false)
107			login_send_error(request, 0x02, 0x0b);
108		log_errx(1, "protocol error: received invalid opcode 0x%x",
109		    request->pdu_bhs->bhs_opcode);
110	}
111	bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
112	/*
113	 * XXX: Implement the C flag some day.
114	 */
115	if ((bhslr->bhslr_flags & BHSLR_FLAGS_CONTINUE) != 0) {
116		login_send_error(request, 0x03, 0x00);
117		log_errx(1, "received Login PDU with unsupported \"C\" flag");
118	}
119	if (bhslr->bhslr_version_max != 0x00) {
120		login_send_error(request, 0x02, 0x05);
121		log_errx(1, "received Login PDU with unsupported "
122		    "Version-max 0x%x", bhslr->bhslr_version_max);
123	}
124	if (bhslr->bhslr_version_min != 0x00) {
125		login_send_error(request, 0x02, 0x05);
126		log_errx(1, "received Login PDU with unsupported "
127		    "Version-min 0x%x", bhslr->bhslr_version_min);
128	}
129	if (initial == false &&
130	    ISCSI_SNLT(ntohl(bhslr->bhslr_cmdsn), conn->conn_cmdsn)) {
131		login_send_error(request, 0x02, 0x00);
132		log_errx(1, "received Login PDU with decreasing CmdSN: "
133		    "was %u, is %u", conn->conn_cmdsn,
134		    ntohl(bhslr->bhslr_cmdsn));
135	}
136	if (initial == false &&
137	    ntohl(bhslr->bhslr_expstatsn) != conn->conn_statsn) {
138		login_send_error(request, 0x02, 0x00);
139		log_errx(1, "received Login PDU with wrong ExpStatSN: "
140		    "is %u, should be %u", ntohl(bhslr->bhslr_expstatsn),
141		    conn->conn_statsn);
142	}
143	conn->conn_cmdsn = ntohl(bhslr->bhslr_cmdsn);
144
145	return (request);
146}
147
148static struct pdu *
149login_new_response(struct pdu *request)
150{
151	struct pdu *response;
152	struct connection *conn;
153	struct iscsi_bhs_login_request *bhslr;
154	struct iscsi_bhs_login_response *bhslr2;
155
156	bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
157	conn = request->pdu_connection;
158
159	response = pdu_new_response(request);
160	bhslr2 = (struct iscsi_bhs_login_response *)response->pdu_bhs;
161	bhslr2->bhslr_opcode = ISCSI_BHS_OPCODE_LOGIN_RESPONSE;
162	login_set_csg(response, BHSLR_STAGE_SECURITY_NEGOTIATION);
163	memcpy(bhslr2->bhslr_isid,
164	    bhslr->bhslr_isid, sizeof(bhslr2->bhslr_isid));
165	bhslr2->bhslr_initiator_task_tag = bhslr->bhslr_initiator_task_tag;
166	bhslr2->bhslr_statsn = htonl(conn->conn_statsn++);
167	bhslr2->bhslr_expcmdsn = htonl(conn->conn_cmdsn);
168	bhslr2->bhslr_maxcmdsn = htonl(conn->conn_cmdsn);
169
170	return (response);
171}
172
173static void
174login_send_error(struct pdu *request, char class, char detail)
175{
176	struct pdu *response;
177	struct iscsi_bhs_login_response *bhslr2;
178
179	log_debugx("sending Login Response PDU with failure class 0x%x/0x%x; "
180	    "see next line for reason", class, detail);
181	response = login_new_response(request);
182	bhslr2 = (struct iscsi_bhs_login_response *)response->pdu_bhs;
183	bhslr2->bhslr_status_class = class;
184	bhslr2->bhslr_status_detail = detail;
185
186	pdu_send(response);
187	pdu_delete(response);
188}
189
190static int
191login_list_contains(const char *list, const char *what)
192{
193	char *tofree, *str, *token;
194
195	tofree = str = checked_strdup(list);
196
197	while ((token = strsep(&str, ",")) != NULL) {
198		if (strcmp(token, what) == 0) {
199			free(tofree);
200			return (1);
201		}
202	}
203	free(tofree);
204	return (0);
205}
206
207static int
208login_list_prefers(const char *list,
209    const char *choice1, const char *choice2)
210{
211	char *tofree, *str, *token;
212
213	tofree = str = checked_strdup(list);
214
215	while ((token = strsep(&str, ",")) != NULL) {
216		if (strcmp(token, choice1) == 0) {
217			free(tofree);
218			return (1);
219		}
220		if (strcmp(token, choice2) == 0) {
221			free(tofree);
222			return (2);
223		}
224	}
225	free(tofree);
226	return (-1);
227}
228
229static struct pdu *
230login_receive_chap_a(struct connection *conn)
231{
232	struct pdu *request;
233	struct keys *request_keys;
234	const char *chap_a;
235
236	request = login_receive(conn, false);
237	request_keys = keys_new();
238	keys_load(request_keys, request);
239
240	chap_a = keys_find(request_keys, "CHAP_A");
241	if (chap_a == NULL) {
242		login_send_error(request, 0x02, 0x07);
243		log_errx(1, "received CHAP Login PDU without CHAP_A");
244	}
245	if (login_list_contains(chap_a, "5") == 0) {
246		login_send_error(request, 0x02, 0x01);
247		log_errx(1, "received CHAP Login PDU with unsupported CHAP_A "
248		    "\"%s\"", chap_a);
249	}
250	keys_delete(request_keys);
251
252	return (request);
253}
254
255static void
256login_send_chap_c(struct pdu *request, struct chap *chap)
257{
258	struct pdu *response;
259	struct keys *response_keys;
260	char *chap_c, *chap_i;
261
262	chap_c = chap_get_challenge(chap);
263	chap_i = chap_get_id(chap);
264
265	response = login_new_response(request);
266	response_keys = keys_new();
267	keys_add(response_keys, "CHAP_A", "5");
268	keys_add(response_keys, "CHAP_I", chap_i);
269	keys_add(response_keys, "CHAP_C", chap_c);
270	free(chap_i);
271	free(chap_c);
272	keys_save(response_keys, response);
273	pdu_send(response);
274	pdu_delete(response);
275	keys_delete(response_keys);
276}
277
278static struct pdu *
279login_receive_chap_r(struct connection *conn, struct auth_group *ag,
280    struct chap *chap, const struct auth **authp)
281{
282	struct pdu *request;
283	struct keys *request_keys;
284	const char *chap_n, *chap_r;
285	const struct auth *auth;
286	int error;
287
288	request = login_receive(conn, false);
289	request_keys = keys_new();
290	keys_load(request_keys, request);
291
292	chap_n = keys_find(request_keys, "CHAP_N");
293	if (chap_n == NULL) {
294		login_send_error(request, 0x02, 0x07);
295		log_errx(1, "received CHAP Login PDU without CHAP_N");
296	}
297	chap_r = keys_find(request_keys, "CHAP_R");
298	if (chap_r == NULL) {
299		login_send_error(request, 0x02, 0x07);
300		log_errx(1, "received CHAP Login PDU without CHAP_R");
301	}
302	error = chap_receive(chap, chap_r);
303	if (error != 0) {
304		login_send_error(request, 0x02, 0x07);
305		log_errx(1, "received CHAP Login PDU with malformed CHAP_R");
306	}
307
308	/*
309	 * Verify the response.
310	 */
311	assert(ag->ag_type == AG_TYPE_CHAP ||
312	    ag->ag_type == AG_TYPE_CHAP_MUTUAL);
313	auth = auth_find(ag, chap_n);
314	if (auth == NULL) {
315		login_send_error(request, 0x02, 0x01);
316		log_errx(1, "received CHAP Login with invalid user \"%s\"",
317		    chap_n);
318	}
319
320	assert(auth->a_secret != NULL);
321	assert(strlen(auth->a_secret) > 0);
322
323	error = chap_authenticate(chap, auth->a_secret);
324	if (error != 0) {
325		login_send_error(request, 0x02, 0x01);
326		log_errx(1, "CHAP authentication failed for user \"%s\"",
327		    auth->a_user);
328	}
329
330	keys_delete(request_keys);
331
332	*authp = auth;
333	return (request);
334}
335
336static void
337login_send_chap_success(struct pdu *request,
338    const struct auth *auth)
339{
340	struct pdu *response;
341	struct keys *request_keys, *response_keys;
342	struct rchap *rchap;
343	const char *chap_i, *chap_c;
344	char *chap_r;
345	int error;
346
347	response = login_new_response(request);
348	login_set_nsg(response, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
349
350	/*
351	 * Actually, one more thing: mutual authentication.
352	 */
353	request_keys = keys_new();
354	keys_load(request_keys, request);
355	chap_i = keys_find(request_keys, "CHAP_I");
356	chap_c = keys_find(request_keys, "CHAP_C");
357	if (chap_i != NULL || chap_c != NULL) {
358		if (chap_i == NULL) {
359			login_send_error(request, 0x02, 0x07);
360			log_errx(1, "initiator requested target "
361			    "authentication, but didn't send CHAP_I");
362		}
363		if (chap_c == NULL) {
364			login_send_error(request, 0x02, 0x07);
365			log_errx(1, "initiator requested target "
366			    "authentication, but didn't send CHAP_C");
367		}
368		if (auth->a_auth_group->ag_type != AG_TYPE_CHAP_MUTUAL) {
369			login_send_error(request, 0x02, 0x01);
370			log_errx(1, "initiator requests target authentication "
371			    "for user \"%s\", but mutual user/secret "
372			    "is not set", auth->a_user);
373		}
374
375		log_debugx("performing mutual authentication as user \"%s\"",
376		    auth->a_mutual_user);
377
378		rchap = rchap_new(auth->a_mutual_secret);
379		error = rchap_receive(rchap, chap_i, chap_c);
380		if (error != 0) {
381			login_send_error(request, 0x02, 0x07);
382			log_errx(1, "received CHAP Login PDU with malformed "
383			    "CHAP_I or CHAP_C");
384		}
385		chap_r = rchap_get_response(rchap);
386		rchap_delete(rchap);
387		response_keys = keys_new();
388		keys_add(response_keys, "CHAP_N", auth->a_mutual_user);
389		keys_add(response_keys, "CHAP_R", chap_r);
390		free(chap_r);
391		keys_save(response_keys, response);
392		keys_delete(response_keys);
393	} else {
394		log_debugx("initiator did not request target authentication");
395	}
396
397	keys_delete(request_keys);
398	pdu_send(response);
399	pdu_delete(response);
400}
401
402static void
403login_chap(struct connection *conn, struct auth_group *ag)
404{
405	const struct auth *auth;
406	struct chap *chap;
407	struct pdu *request;
408
409	/*
410	 * Receive CHAP_A PDU.
411	 */
412	log_debugx("beginning CHAP authentication; waiting for CHAP_A");
413	request = login_receive_chap_a(conn);
414
415	/*
416	 * Generate the challenge.
417	 */
418	chap = chap_new();
419
420	/*
421	 * Send the challenge.
422	 */
423	log_debugx("sending CHAP_C, binary challenge size is %zd bytes",
424	    sizeof(chap->chap_challenge));
425	login_send_chap_c(request, chap);
426	pdu_delete(request);
427
428	/*
429	 * Receive CHAP_N/CHAP_R PDU and authenticate.
430	 */
431	log_debugx("waiting for CHAP_N/CHAP_R");
432	request = login_receive_chap_r(conn, ag, chap, &auth);
433
434	/*
435	 * Yay, authentication succeeded!
436	 */
437	log_debugx("authentication succeeded for user \"%s\"; "
438	    "transitioning to Negotiation Phase", auth->a_user);
439	login_send_chap_success(request, auth);
440	pdu_delete(request);
441
442	/*
443	 * Leave username and CHAP information for discovery().
444	 */
445	conn->conn_user = auth->a_user;
446	conn->conn_chap = chap;
447}
448
449static void
450login_negotiate_key(struct pdu *request, const char *name,
451    const char *value, bool skipped_security, struct keys *response_keys)
452{
453	int which, tmp;
454	struct connection *conn;
455
456	conn = request->pdu_connection;
457
458	if (strcmp(name, "InitiatorName") == 0) {
459		if (!skipped_security)
460			log_errx(1, "initiator resent InitiatorName");
461	} else if (strcmp(name, "SessionType") == 0) {
462		if (!skipped_security)
463			log_errx(1, "initiator resent SessionType");
464	} else if (strcmp(name, "TargetName") == 0) {
465		if (!skipped_security)
466			log_errx(1, "initiator resent TargetName");
467	} else if (strcmp(name, "InitiatorAlias") == 0) {
468		if (conn->conn_initiator_alias != NULL)
469			free(conn->conn_initiator_alias);
470		conn->conn_initiator_alias = checked_strdup(value);
471	} else if (strcmp(value, "Irrelevant") == 0) {
472		/* Ignore. */
473	} else if (strcmp(name, "HeaderDigest") == 0) {
474		/*
475		 * We don't handle digests for discovery sessions.
476		 */
477		if (conn->conn_session_type == CONN_SESSION_TYPE_DISCOVERY) {
478			log_debugx("discovery session; digests disabled");
479			keys_add(response_keys, name, "None");
480			return;
481		}
482
483		which = login_list_prefers(value, "CRC32C", "None");
484		switch (which) {
485		case 1:
486			log_debugx("initiator prefers CRC32C "
487			    "for header digest; we'll use it");
488			conn->conn_header_digest = CONN_DIGEST_CRC32C;
489			keys_add(response_keys, name, "CRC32C");
490			break;
491		case 2:
492			log_debugx("initiator prefers not to do "
493			    "header digest; we'll comply");
494			keys_add(response_keys, name, "None");
495			break;
496		default:
497			log_warnx("initiator sent unrecognized "
498			    "HeaderDigest value \"%s\"; will use None", value);
499			keys_add(response_keys, name, "None");
500			break;
501		}
502	} else if (strcmp(name, "DataDigest") == 0) {
503		if (conn->conn_session_type == CONN_SESSION_TYPE_DISCOVERY) {
504			log_debugx("discovery session; digests disabled");
505			keys_add(response_keys, name, "None");
506			return;
507		}
508
509		which = login_list_prefers(value, "CRC32C", "None");
510		switch (which) {
511		case 1:
512			log_debugx("initiator prefers CRC32C "
513			    "for data digest; we'll use it");
514			conn->conn_data_digest = CONN_DIGEST_CRC32C;
515			keys_add(response_keys, name, "CRC32C");
516			break;
517		case 2:
518			log_debugx("initiator prefers not to do "
519			    "data digest; we'll comply");
520			keys_add(response_keys, name, "None");
521			break;
522		default:
523			log_warnx("initiator sent unrecognized "
524			    "DataDigest value \"%s\"; will use None", value);
525			keys_add(response_keys, name, "None");
526			break;
527		}
528	} else if (strcmp(name, "MaxConnections") == 0) {
529		keys_add(response_keys, name, "1");
530	} else if (strcmp(name, "InitialR2T") == 0) {
531		keys_add(response_keys, name, "Yes");
532	} else if (strcmp(name, "ImmediateData") == 0) {
533		if (conn->conn_session_type == CONN_SESSION_TYPE_DISCOVERY) {
534			log_debugx("discovery session; ImmediateData irrelevant");
535			keys_add(response_keys, name, "Irrelevant");
536		} else {
537			if (strcmp(value, "Yes") == 0) {
538				conn->conn_immediate_data = true;
539				keys_add(response_keys, name, "Yes");
540			} else {
541				conn->conn_immediate_data = false;
542				keys_add(response_keys, name, "No");
543			}
544		}
545	} else if (strcmp(name, "MaxRecvDataSegmentLength") == 0) {
546		tmp = strtoul(value, NULL, 10);
547		if (tmp <= 0) {
548			login_send_error(request, 0x02, 0x00);
549			log_errx(1, "received invalid "
550			    "MaxRecvDataSegmentLength");
551		}
552		if (tmp > MAX_DATA_SEGMENT_LENGTH) {
553			log_debugx("capping MaxRecvDataSegmentLength "
554			    "from %d to %d", tmp, MAX_DATA_SEGMENT_LENGTH);
555			tmp = MAX_DATA_SEGMENT_LENGTH;
556		}
557		conn->conn_max_data_segment_length = tmp;
558		keys_add_int(response_keys, name, MAX_DATA_SEGMENT_LENGTH);
559	} else if (strcmp(name, "MaxBurstLength") == 0) {
560		tmp = strtoul(value, NULL, 10);
561		if (tmp <= 0) {
562			login_send_error(request, 0x02, 0x00);
563			log_errx(1, "received invalid MaxBurstLength");
564		}
565		if (tmp > MAX_BURST_LENGTH) {
566			log_debugx("capping MaxBurstLength from %d to %d",
567			    tmp, MAX_BURST_LENGTH);
568			tmp = MAX_BURST_LENGTH;
569		}
570		conn->conn_max_burst_length = tmp;
571		keys_add(response_keys, name, value);
572	} else if (strcmp(name, "FirstBurstLength") == 0) {
573		tmp = strtoul(value, NULL, 10);
574		if (tmp <= 0) {
575			login_send_error(request, 0x02, 0x00);
576			log_errx(1, "received invalid "
577			    "FirstBurstLength");
578		}
579		if (tmp > MAX_DATA_SEGMENT_LENGTH) {
580			log_debugx("capping FirstBurstLength from %d to %d",
581			    tmp, MAX_DATA_SEGMENT_LENGTH);
582			tmp = MAX_DATA_SEGMENT_LENGTH;
583		}
584		/*
585		 * We don't pass the value to the kernel; it only enforces
586		 * hardcoded limit anyway.
587		 */
588		keys_add_int(response_keys, name, tmp);
589	} else if (strcmp(name, "DefaultTime2Wait") == 0) {
590		keys_add(response_keys, name, value);
591	} else if (strcmp(name, "DefaultTime2Retain") == 0) {
592		keys_add(response_keys, name, "0");
593	} else if (strcmp(name, "MaxOutstandingR2T") == 0) {
594		keys_add(response_keys, name, "1");
595	} else if (strcmp(name, "DataPDUInOrder") == 0) {
596		keys_add(response_keys, name, "Yes");
597	} else if (strcmp(name, "DataSequenceInOrder") == 0) {
598		keys_add(response_keys, name, "Yes");
599	} else if (strcmp(name, "ErrorRecoveryLevel") == 0) {
600		keys_add(response_keys, name, "0");
601	} else if (strcmp(name, "OFMarker") == 0) {
602		keys_add(response_keys, name, "No");
603	} else if (strcmp(name, "IFMarker") == 0) {
604		keys_add(response_keys, name, "No");
605	} else if (strcmp(name, "iSCSIProtocolLevel") == 0) {
606		tmp = strtoul(value, NULL, 10);
607		if (tmp > 2)
608			tmp = 2;
609		keys_add_int(response_keys, name, tmp);
610	} else {
611		log_debugx("unknown key \"%s\"; responding "
612		    "with NotUnderstood", name);
613		keys_add(response_keys, name, "NotUnderstood");
614	}
615}
616
617static void
618login_redirect(struct pdu *request, const char *target_address)
619{
620	struct pdu *response;
621	struct iscsi_bhs_login_response *bhslr2;
622	struct keys *response_keys;
623
624	response = login_new_response(request);
625	login_set_csg(response, login_csg(request));
626	bhslr2 = (struct iscsi_bhs_login_response *)response->pdu_bhs;
627	bhslr2->bhslr_status_class = 0x01;
628	bhslr2->bhslr_status_detail = 0x01;
629
630	response_keys = keys_new();
631	keys_add(response_keys, "TargetAddress", target_address);
632
633	keys_save(response_keys, response);
634	pdu_send(response);
635	pdu_delete(response);
636	keys_delete(response_keys);
637}
638
639static bool
640login_portal_redirect(struct connection *conn, struct pdu *request)
641{
642	const struct portal_group *pg;
643
644	pg = conn->conn_portal->p_portal_group;
645	if (pg->pg_redirection == NULL)
646		return (false);
647
648	log_debugx("portal-group \"%s\" configured to redirect to %s",
649	    pg->pg_name, pg->pg_redirection);
650	login_redirect(request, pg->pg_redirection);
651
652	return (true);
653}
654
655static bool
656login_target_redirect(struct connection *conn, struct pdu *request)
657{
658	const char *target_address;
659
660	assert(conn->conn_portal->p_portal_group->pg_redirection == NULL);
661
662	if (conn->conn_target == NULL)
663		return (false);
664
665	target_address = conn->conn_target->t_redirection;
666	if (target_address == NULL)
667		return (false);
668
669	log_debugx("target \"%s\" configured to redirect to %s",
670	  conn->conn_target->t_name, target_address);
671	login_redirect(request, target_address);
672
673	return (true);
674}
675
676static void
677login_negotiate(struct connection *conn, struct pdu *request)
678{
679	struct pdu *response;
680	struct iscsi_bhs_login_response *bhslr2;
681	struct keys *request_keys, *response_keys;
682	int i;
683	bool redirected, skipped_security;
684
685	if (request == NULL) {
686		log_debugx("beginning operational parameter negotiation; "
687		    "waiting for Login PDU");
688		request = login_receive(conn, false);
689		skipped_security = false;
690	} else
691		skipped_security = true;
692
693	/*
694	 * RFC 3720, 10.13.5.  Status-Class and Status-Detail, says
695	 * the redirection SHOULD be accepted by the initiator before
696	 * authentication, but MUST be be accepted afterwards; that's
697	 * why we're doing it here and not earlier.
698	 */
699	redirected = login_target_redirect(conn, request);
700	if (redirected) {
701		log_debugx("initiator redirected; exiting");
702		exit(0);
703	}
704
705	request_keys = keys_new();
706	keys_load(request_keys, request);
707
708	response = login_new_response(request);
709	bhslr2 = (struct iscsi_bhs_login_response *)response->pdu_bhs;
710	bhslr2->bhslr_tsih = htons(0xbadd);
711	login_set_csg(response, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
712	login_set_nsg(response, BHSLR_STAGE_FULL_FEATURE_PHASE);
713	response_keys = keys_new();
714
715	if (skipped_security &&
716	    conn->conn_session_type == CONN_SESSION_TYPE_NORMAL) {
717		if (conn->conn_target->t_alias != NULL)
718			keys_add(response_keys,
719			    "TargetAlias", conn->conn_target->t_alias);
720		keys_add_int(response_keys, "TargetPortalGroupTag",
721		    conn->conn_portal->p_portal_group->pg_tag);
722	}
723
724	for (i = 0; i < KEYS_MAX; i++) {
725		if (request_keys->keys_names[i] == NULL)
726			break;
727
728		login_negotiate_key(request, request_keys->keys_names[i],
729		    request_keys->keys_values[i], skipped_security,
730		    response_keys);
731	}
732
733	log_debugx("operational parameter negotiation done; "
734	    "transitioning to Full Feature Phase");
735
736	keys_save(response_keys, response);
737	pdu_send(response);
738	pdu_delete(response);
739	keys_delete(response_keys);
740	pdu_delete(request);
741	keys_delete(request_keys);
742}
743
744static void
745login_wait_transition(struct connection *conn)
746{
747	struct pdu *request, *response;
748	struct iscsi_bhs_login_request *bhslr;
749
750	log_debugx("waiting for state transition request");
751	request = login_receive(conn, false);
752	bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
753	if ((bhslr->bhslr_flags & BHSLR_FLAGS_TRANSIT) == 0) {
754		login_send_error(request, 0x02, 0x00);
755		log_errx(1, "got no \"T\" flag after answering AuthMethod");
756	}
757
758	log_debugx("got state transition request");
759	response = login_new_response(request);
760	pdu_delete(request);
761	login_set_nsg(response, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
762	pdu_send(response);
763	pdu_delete(response);
764
765	login_negotiate(conn, NULL);
766}
767
768void
769login(struct connection *conn)
770{
771	struct pdu *request, *response;
772	struct iscsi_bhs_login_request *bhslr;
773	struct keys *request_keys, *response_keys;
774	struct auth_group *ag;
775	struct portal_group *pg;
776	const char *initiator_name, *initiator_alias, *session_type,
777	    *target_name, *auth_method;
778	bool redirected, fail, trans;
779
780	/*
781	 * Handle the initial Login Request - figure out required authentication
782	 * method and either transition to the next phase, if no authentication
783	 * is required, or call appropriate authentication code.
784	 */
785	log_debugx("beginning Login Phase; waiting for Login PDU");
786	request = login_receive(conn, true);
787	bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
788	if (bhslr->bhslr_tsih != 0) {
789		login_send_error(request, 0x02, 0x0a);
790		log_errx(1, "received Login PDU with non-zero TSIH");
791	}
792
793	pg = conn->conn_portal->p_portal_group;
794
795	memcpy(conn->conn_initiator_isid, bhslr->bhslr_isid,
796	    sizeof(conn->conn_initiator_isid));
797
798	/*
799	 * XXX: Implement the C flag some day.
800	 */
801	request_keys = keys_new();
802	keys_load(request_keys, request);
803
804	assert(conn->conn_initiator_name == NULL);
805	initiator_name = keys_find(request_keys, "InitiatorName");
806	if (initiator_name == NULL) {
807		login_send_error(request, 0x02, 0x07);
808		log_errx(1, "received Login PDU without InitiatorName");
809	}
810	if (valid_iscsi_name(initiator_name) == false) {
811		login_send_error(request, 0x02, 0x00);
812		log_errx(1, "received Login PDU with invalid InitiatorName");
813	}
814	conn->conn_initiator_name = checked_strdup(initiator_name);
815	log_set_peer_name(conn->conn_initiator_name);
816	setproctitle("%s (%s)", conn->conn_initiator_addr, conn->conn_initiator_name);
817
818	redirected = login_portal_redirect(conn, request);
819	if (redirected) {
820		log_debugx("initiator redirected; exiting");
821		exit(0);
822	}
823
824	initiator_alias = keys_find(request_keys, "InitiatorAlias");
825	if (initiator_alias != NULL)
826		conn->conn_initiator_alias = checked_strdup(initiator_alias);
827
828	assert(conn->conn_session_type == CONN_SESSION_TYPE_NONE);
829	session_type = keys_find(request_keys, "SessionType");
830	if (session_type != NULL) {
831		if (strcmp(session_type, "Normal") == 0) {
832			conn->conn_session_type = CONN_SESSION_TYPE_NORMAL;
833		} else if (strcmp(session_type, "Discovery") == 0) {
834			conn->conn_session_type = CONN_SESSION_TYPE_DISCOVERY;
835		} else {
836			login_send_error(request, 0x02, 0x00);
837			log_errx(1, "received Login PDU with invalid "
838			    "SessionType \"%s\"", session_type);
839		}
840	} else
841		conn->conn_session_type = CONN_SESSION_TYPE_NORMAL;
842
843	assert(conn->conn_target == NULL);
844	if (conn->conn_session_type == CONN_SESSION_TYPE_NORMAL) {
845		target_name = keys_find(request_keys, "TargetName");
846		if (target_name == NULL) {
847			login_send_error(request, 0x02, 0x07);
848			log_errx(1, "received Login PDU without TargetName");
849		}
850
851		conn->conn_port = port_find_in_pg(pg, target_name);
852		if (conn->conn_port == NULL) {
853			login_send_error(request, 0x02, 0x03);
854			log_errx(1, "requested target \"%s\" not found",
855			    target_name);
856		}
857		conn->conn_target = conn->conn_port->p_target;
858	}
859
860	/*
861	 * At this point we know what kind of authentication we need.
862	 */
863	if (conn->conn_session_type == CONN_SESSION_TYPE_NORMAL) {
864		ag = conn->conn_port->p_auth_group;
865		if (ag == NULL)
866			ag = conn->conn_target->t_auth_group;
867		if (ag->ag_name != NULL) {
868			log_debugx("initiator requests to connect "
869			    "to target \"%s\"; auth-group \"%s\"",
870			    conn->conn_target->t_name,
871			    ag->ag_name);
872		} else {
873			log_debugx("initiator requests to connect "
874			    "to target \"%s\"", conn->conn_target->t_name);
875		}
876	} else {
877		assert(conn->conn_session_type == CONN_SESSION_TYPE_DISCOVERY);
878		ag = pg->pg_discovery_auth_group;
879		if (ag->ag_name != NULL) {
880			log_debugx("initiator requests "
881			    "discovery session; auth-group \"%s\"", ag->ag_name);
882		} else {
883			log_debugx("initiator requests discovery session");
884		}
885	}
886
887	if (ag->ag_type == AG_TYPE_DENY) {
888		login_send_error(request, 0x02, 0x01);
889		log_errx(1, "auth-type is \"deny\"");
890	}
891
892	if (ag->ag_type == AG_TYPE_UNKNOWN) {
893		/*
894		 * This can happen with empty auth-group.
895		 */
896		login_send_error(request, 0x02, 0x01);
897		log_errx(1, "auth-type not set, denying access");
898	}
899
900	/*
901	 * Enforce initiator-name and initiator-portal.
902	 */
903	if (auth_name_check(ag, initiator_name) != 0) {
904		login_send_error(request, 0x02, 0x02);
905		log_errx(1, "initiator does not match allowed initiator names");
906	}
907
908	if (auth_portal_check(ag, &conn->conn_initiator_sa) != 0) {
909		login_send_error(request, 0x02, 0x02);
910		log_errx(1, "initiator does not match allowed "
911		    "initiator portals");
912	}
913
914	/*
915	 * Let's see if the initiator intends to do any kind of authentication
916	 * at all.
917	 */
918	if (login_csg(request) == BHSLR_STAGE_OPERATIONAL_NEGOTIATION) {
919		if (ag->ag_type != AG_TYPE_NO_AUTHENTICATION) {
920			login_send_error(request, 0x02, 0x01);
921			log_errx(1, "initiator skipped the authentication, "
922			    "but authentication is required");
923		}
924
925		keys_delete(request_keys);
926
927		log_debugx("initiator skipped the authentication, "
928		    "and we don't need it; proceeding with negotiation");
929		login_negotiate(conn, request);
930		return;
931	}
932
933	fail = false;
934	response = login_new_response(request);
935	response_keys = keys_new();
936	trans = (bhslr->bhslr_flags & BHSLR_FLAGS_TRANSIT) != 0;
937	auth_method = keys_find(request_keys, "AuthMethod");
938	if (ag->ag_type == AG_TYPE_NO_AUTHENTICATION) {
939		log_debugx("authentication not required");
940		if (auth_method == NULL ||
941		    login_list_contains(auth_method, "None")) {
942			keys_add(response_keys, "AuthMethod", "None");
943		} else {
944			log_warnx("initiator requests "
945			    "AuthMethod \"%s\" instead of \"None\"",
946			    auth_method);
947			keys_add(response_keys, "AuthMethod", "Reject");
948		}
949		if (trans)
950			login_set_nsg(response, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
951	} else {
952		log_debugx("CHAP authentication required");
953		if (auth_method == NULL ||
954		    login_list_contains(auth_method, "CHAP")) {
955			keys_add(response_keys, "AuthMethod", "CHAP");
956		} else {
957			log_warnx("initiator requests unsupported "
958			    "AuthMethod \"%s\" instead of \"CHAP\"",
959			    auth_method);
960			keys_add(response_keys, "AuthMethod", "Reject");
961			fail = true;
962		}
963	}
964	if (conn->conn_session_type == CONN_SESSION_TYPE_NORMAL) {
965		if (conn->conn_target->t_alias != NULL)
966			keys_add(response_keys,
967			    "TargetAlias", conn->conn_target->t_alias);
968		keys_add_int(response_keys,
969		    "TargetPortalGroupTag", pg->pg_tag);
970	}
971	keys_save(response_keys, response);
972
973	pdu_send(response);
974	pdu_delete(response);
975	keys_delete(response_keys);
976	pdu_delete(request);
977	keys_delete(request_keys);
978
979	if (fail) {
980		log_debugx("sent reject for AuthMethod; exiting");
981		exit(1);
982	}
983
984	if (ag->ag_type != AG_TYPE_NO_AUTHENTICATION) {
985		login_chap(conn, ag);
986		login_negotiate(conn, NULL);
987	} else if (trans) {
988		login_negotiate(conn, NULL);
989	} else {
990		login_wait_transition(conn);
991	}
992}
993