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