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