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