]> CyberLeo.Net >> Repos - FreeBSD/releng/10.3.git/blob - usr.sbin/ctld/login.c
- Copy stable/10@296371 to releng/10.3 in preparation for 10.3-RC1
[FreeBSD/releng/10.3.git] / usr.sbin / ctld / login.c
1 /*-
2  * Copyright (c) 2012 The FreeBSD Foundation
3  * All rights reserved.
4  *
5  * This software was developed by Edward Tomasz Napierala under sponsorship
6  * from the FreeBSD Foundation.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  */
30
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33
34 #include <assert.h>
35 #include <stdbool.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <netinet/in.h>
40
41 #include "ctld.h"
42 #include "iscsi_proto.h"
43
44 static void login_send_error(struct pdu *request,
45     char class, char detail);
46
47 static void
48 login_set_nsg(struct pdu *response, int nsg)
49 {
50         struct iscsi_bhs_login_response *bhslr;
51
52         assert(nsg == BHSLR_STAGE_SECURITY_NEGOTIATION ||
53             nsg == BHSLR_STAGE_OPERATIONAL_NEGOTIATION ||
54             nsg == BHSLR_STAGE_FULL_FEATURE_PHASE);
55
56         bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
57
58         bhslr->bhslr_flags &= 0xFC;
59         bhslr->bhslr_flags |= nsg;
60         bhslr->bhslr_flags |= BHSLR_FLAGS_TRANSIT;
61 }
62
63 static int
64 login_csg(const struct pdu *request)
65 {
66         struct iscsi_bhs_login_request *bhslr;
67
68         bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
69
70         return ((bhslr->bhslr_flags & 0x0C) >> 2);
71 }
72
73 static void
74 login_set_csg(struct pdu *response, int csg)
75 {
76         struct iscsi_bhs_login_response *bhslr;
77
78         assert(csg == BHSLR_STAGE_SECURITY_NEGOTIATION ||
79             csg == BHSLR_STAGE_OPERATIONAL_NEGOTIATION ||
80             csg == BHSLR_STAGE_FULL_FEATURE_PHASE);
81
82         bhslr = (struct iscsi_bhs_login_response *)response->pdu_bhs;
83
84         bhslr->bhslr_flags &= 0xF3;
85         bhslr->bhslr_flags |= csg << 2;
86 }
87
88 static struct pdu *
89 login_receive(struct connection *conn, bool initial)
90 {
91         struct pdu *request;
92         struct iscsi_bhs_login_request *bhslr;
93
94         request = pdu_new(conn);
95         pdu_receive(request);
96         if ((request->pdu_bhs->bhs_opcode & ~ISCSI_BHS_OPCODE_IMMEDIATE) !=
97             ISCSI_BHS_OPCODE_LOGIN_REQUEST) {
98                 /*
99                  * The first PDU in session is special - if we receive any PDU
100                  * different than login request, we have to drop the connection
101                  * without sending response ("A target receiving any PDU
102                  * except a Login request before the Login Phase is started MUST
103                  * immediately terminate the connection on which the PDU
104                  * was received.")
105                  */
106                 if (initial == false)
107                         login_send_error(request, 0x02, 0x0b);
108                 log_errx(1, "protocol error: received invalid opcode 0x%x",
109                     request->pdu_bhs->bhs_opcode);
110         }
111         bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
112         /*
113          * XXX: Implement the C flag some day.
114          */
115         if ((bhslr->bhslr_flags & BHSLR_FLAGS_CONTINUE) != 0) {
116                 login_send_error(request, 0x03, 0x00);
117                 log_errx(1, "received Login PDU with unsupported \"C\" flag");
118         }
119         if (bhslr->bhslr_version_max != 0x00) {
120                 login_send_error(request, 0x02, 0x05);
121                 log_errx(1, "received Login PDU with unsupported "
122                     "Version-max 0x%x", bhslr->bhslr_version_max);
123         }
124         if (bhslr->bhslr_version_min != 0x00) {
125                 login_send_error(request, 0x02, 0x05);
126                 log_errx(1, "received Login PDU with unsupported "
127                     "Version-min 0x%x", bhslr->bhslr_version_min);
128         }
129         if (ISCSI_SNLT(ntohl(bhslr->bhslr_cmdsn), conn->conn_cmdsn)) {
130                 login_send_error(request, 0x02, 0x05);
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, 0x05);
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
147 static struct pdu *
148 login_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
172 static void
173 login_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
189 static int
190 login_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
206 static int
207 login_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
228 static struct pdu *
229 login_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(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
254 static void
255 login_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(response_keys, response);
272         pdu_send(response);
273         pdu_delete(response);
274         keys_delete(response_keys);
275 }
276
277 static struct pdu *
278 login_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(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
335 static void
336 login_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(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(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
401 static void
402 login_chap(struct 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);
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, ag, chap, &auth);
432
433         /*
434          * Yay, authentication succeeded!
435          */
436         log_debugx("authentication succeeded for user \"%s\"; "
437             "transitioning to Negotiation Phase", 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
448 static void
449 login_negotiate_key(struct pdu *request, const char *name,
450     const char *value, bool skipped_security, struct keys *response_keys)
451 {
452         int which, tmp;
453         struct connection *conn;
454
455         conn = request->pdu_connection;
456
457         if (strcmp(name, "InitiatorName") == 0) {
458                 if (!skipped_security)
459                         log_errx(1, "initiator resent InitiatorName");
460         } else if (strcmp(name, "SessionType") == 0) {
461                 if (!skipped_security)
462                         log_errx(1, "initiator resent SessionType");
463         } else if (strcmp(name, "TargetName") == 0) {
464                 if (!skipped_security)
465                         log_errx(1, "initiator resent TargetName");
466         } else if (strcmp(name, "InitiatorAlias") == 0) {
467                 if (conn->conn_initiator_alias != NULL)
468                         free(conn->conn_initiator_alias);
469                 conn->conn_initiator_alias = checked_strdup(value);
470         } else if (strcmp(value, "Irrelevant") == 0) {
471                 /* Ignore. */
472         } else if (strcmp(name, "HeaderDigest") == 0) {
473                 /*
474                  * We don't handle digests for discovery sessions.
475                  */
476                 if (conn->conn_session_type == CONN_SESSION_TYPE_DISCOVERY) {
477                         log_debugx("discovery session; digests disabled");
478                         keys_add(response_keys, name, "None");
479                         return;
480                 }
481
482                 which = login_list_prefers(value, "CRC32C", "None");
483                 switch (which) {
484                 case 1:
485                         log_debugx("initiator prefers CRC32C "
486                             "for header digest; we'll use it");
487                         conn->conn_header_digest = CONN_DIGEST_CRC32C;
488                         keys_add(response_keys, name, "CRC32C");
489                         break;
490                 case 2:
491                         log_debugx("initiator prefers not to do "
492                             "header digest; we'll comply");
493                         keys_add(response_keys, name, "None");
494                         break;
495                 default:
496                         log_warnx("initiator sent unrecognized "
497                             "HeaderDigest value \"%s\"; will use None", value);
498                         keys_add(response_keys, name, "None");
499                         break;
500                 }
501         } else if (strcmp(name, "DataDigest") == 0) {
502                 if (conn->conn_session_type == CONN_SESSION_TYPE_DISCOVERY) {
503                         log_debugx("discovery session; digests disabled");
504                         keys_add(response_keys, name, "None");
505                         return;
506                 }
507
508                 which = login_list_prefers(value, "CRC32C", "None");
509                 switch (which) {
510                 case 1:
511                         log_debugx("initiator prefers CRC32C "
512                             "for data digest; we'll use it");
513                         conn->conn_data_digest = CONN_DIGEST_CRC32C;
514                         keys_add(response_keys, name, "CRC32C");
515                         break;
516                 case 2:
517                         log_debugx("initiator prefers not to do "
518                             "data digest; we'll comply");
519                         keys_add(response_keys, name, "None");
520                         break;
521                 default:
522                         log_warnx("initiator sent unrecognized "
523                             "DataDigest value \"%s\"; will use None", value);
524                         keys_add(response_keys, name, "None");
525                         break;
526                 }
527         } else if (strcmp(name, "MaxConnections") == 0) {
528                 keys_add(response_keys, name, "1");
529         } else if (strcmp(name, "InitialR2T") == 0) {
530                 keys_add(response_keys, name, "Yes");
531         } else if (strcmp(name, "ImmediateData") == 0) {
532                 if (conn->conn_session_type == CONN_SESSION_TYPE_DISCOVERY) {
533                         log_debugx("discovery session; ImmediateData irrelevant");
534                         keys_add(response_keys, name, "Irrelevant");
535                 } else {
536                         if (strcmp(value, "Yes") == 0) {
537                                 conn->conn_immediate_data = true;
538                                 keys_add(response_keys, name, "Yes");
539                         } else {
540                                 conn->conn_immediate_data = false;
541                                 keys_add(response_keys, name, "No");
542                         }
543                 }
544         } else if (strcmp(name, "MaxRecvDataSegmentLength") == 0) {
545                 tmp = strtoul(value, NULL, 10);
546                 if (tmp <= 0) {
547                         login_send_error(request, 0x02, 0x00);
548                         log_errx(1, "received invalid "
549                             "MaxRecvDataSegmentLength");
550                 }
551                 if (tmp > MAX_DATA_SEGMENT_LENGTH) {
552                         log_debugx("capping MaxRecvDataSegmentLength "
553                             "from %d to %d", tmp, MAX_DATA_SEGMENT_LENGTH);
554                         tmp = MAX_DATA_SEGMENT_LENGTH;
555                 }
556                 conn->conn_max_data_segment_length = tmp;
557                 keys_add_int(response_keys, name, MAX_DATA_SEGMENT_LENGTH);
558         } else if (strcmp(name, "MaxBurstLength") == 0) {
559                 tmp = strtoul(value, NULL, 10);
560                 if (tmp <= 0) {
561                         login_send_error(request, 0x02, 0x00);
562                         log_errx(1, "received invalid MaxBurstLength");
563                 }
564                 if (tmp > MAX_BURST_LENGTH) {
565                         log_debugx("capping MaxBurstLength from %d to %d",
566                             tmp, MAX_BURST_LENGTH);
567                         tmp = MAX_BURST_LENGTH;
568                 }
569                 conn->conn_max_burst_length = tmp;
570                 keys_add(response_keys, name, value);
571         } else if (strcmp(name, "FirstBurstLength") == 0) {
572                 tmp = strtoul(value, NULL, 10);
573                 if (tmp <= 0) {
574                         login_send_error(request, 0x02, 0x00);
575                         log_errx(1, "received invalid "
576                             "FirstBurstLength");
577                 }
578                 if (tmp > MAX_DATA_SEGMENT_LENGTH) {
579                         log_debugx("capping FirstBurstLength from %d to %d",
580                             tmp, MAX_DATA_SEGMENT_LENGTH);
581                         tmp = MAX_DATA_SEGMENT_LENGTH;
582                 }
583                 /*
584                  * We don't pass the value to the kernel; it only enforces
585                  * hardcoded limit anyway.
586                  */
587                 keys_add_int(response_keys, name, tmp);
588         } else if (strcmp(name, "DefaultTime2Wait") == 0) {
589                 keys_add(response_keys, name, value);
590         } else if (strcmp(name, "DefaultTime2Retain") == 0) {
591                 keys_add(response_keys, name, "0");
592         } else if (strcmp(name, "MaxOutstandingR2T") == 0) {
593                 keys_add(response_keys, name, "1");
594         } else if (strcmp(name, "DataPDUInOrder") == 0) {
595                 keys_add(response_keys, name, "Yes");
596         } else if (strcmp(name, "DataSequenceInOrder") == 0) {
597                 keys_add(response_keys, name, "Yes");
598         } else if (strcmp(name, "ErrorRecoveryLevel") == 0) {
599                 keys_add(response_keys, name, "0");
600         } else if (strcmp(name, "OFMarker") == 0) {
601                 keys_add(response_keys, name, "No");
602         } else if (strcmp(name, "IFMarker") == 0) {
603                 keys_add(response_keys, name, "No");
604         } else if (strcmp(name, "iSCSIProtocolLevel") == 0) {
605                 tmp = strtoul(value, NULL, 10);
606                 if (tmp > 2)
607                         tmp = 2;
608                 keys_add_int(response_keys, name, tmp);
609         } else {
610                 log_debugx("unknown key \"%s\"; responding "
611                     "with NotUnderstood", name);
612                 keys_add(response_keys, name, "NotUnderstood");
613         }
614 }
615
616 static void
617 login_redirect(struct pdu *request, const char *target_address)
618 {
619         struct pdu *response;
620         struct iscsi_bhs_login_response *bhslr2;
621         struct keys *response_keys;
622
623         response = login_new_response(request);
624         login_set_csg(response, login_csg(request));
625         bhslr2 = (struct iscsi_bhs_login_response *)response->pdu_bhs;
626         bhslr2->bhslr_status_class = 0x01;
627         bhslr2->bhslr_status_detail = 0x01;
628
629         response_keys = keys_new();
630         keys_add(response_keys, "TargetAddress", target_address);
631
632         keys_save(response_keys, response);
633         pdu_send(response);
634         pdu_delete(response);
635         keys_delete(response_keys);
636 }
637
638 static bool
639 login_portal_redirect(struct connection *conn, struct pdu *request)
640 {
641         const struct portal_group *pg;
642
643         pg = conn->conn_portal->p_portal_group;
644         if (pg->pg_redirection == NULL)
645                 return (false);
646
647         log_debugx("portal-group \"%s\" configured to redirect to %s",
648             pg->pg_name, pg->pg_redirection);
649         login_redirect(request, pg->pg_redirection);
650
651         return (true);
652 }
653
654 static bool
655 login_target_redirect(struct connection *conn, struct pdu *request)
656 {
657         const char *target_address;
658
659         assert(conn->conn_portal->p_portal_group->pg_redirection == NULL);
660
661         if (conn->conn_target == NULL)
662                 return (false);
663
664         target_address = conn->conn_target->t_redirection;
665         if (target_address == NULL)
666                 return (false);
667
668         log_debugx("target \"%s\" configured to redirect to %s",
669           conn->conn_target->t_name, target_address);
670         login_redirect(request, target_address);
671
672         return (true);
673 }
674
675 static void
676 login_negotiate(struct connection *conn, struct pdu *request)
677 {
678         struct pdu *response;
679         struct iscsi_bhs_login_response *bhslr2;
680         struct keys *request_keys, *response_keys;
681         int i;
682         bool redirected, skipped_security;
683
684         if (request == NULL) {
685                 log_debugx("beginning operational parameter negotiation; "
686                     "waiting for Login PDU");
687                 request = login_receive(conn, false);
688                 skipped_security = false;
689         } else
690                 skipped_security = true;
691
692         /*
693          * RFC 3720, 10.13.5.  Status-Class and Status-Detail, says
694          * the redirection SHOULD be accepted by the initiator before
695          * authentication, but MUST be be accepted afterwards; that's
696          * why we're doing it here and not earlier.
697          */
698         redirected = login_target_redirect(conn, request);
699         if (redirected) {
700                 log_debugx("initiator redirected; exiting");
701                 exit(0);
702         }
703
704         request_keys = keys_new();
705         keys_load(request_keys, request);
706
707         response = login_new_response(request);
708         bhslr2 = (struct iscsi_bhs_login_response *)response->pdu_bhs;
709         bhslr2->bhslr_tsih = htons(0xbadd);
710         login_set_csg(response, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
711         login_set_nsg(response, BHSLR_STAGE_FULL_FEATURE_PHASE);
712         response_keys = keys_new();
713
714         if (skipped_security &&
715             conn->conn_session_type == CONN_SESSION_TYPE_NORMAL) {
716                 if (conn->conn_target->t_alias != NULL)
717                         keys_add(response_keys,
718                             "TargetAlias", conn->conn_target->t_alias);
719                 keys_add_int(response_keys, "TargetPortalGroupTag",
720                     conn->conn_portal->p_portal_group->pg_tag);
721         }
722
723         for (i = 0; i < KEYS_MAX; i++) {
724                 if (request_keys->keys_names[i] == NULL)
725                         break;
726
727                 login_negotiate_key(request, request_keys->keys_names[i],
728                     request_keys->keys_values[i], skipped_security,
729                     response_keys);
730         }
731
732         log_debugx("operational parameter negotiation done; "
733             "transitioning to Full Feature Phase");
734
735         keys_save(response_keys, response);
736         pdu_send(response);
737         pdu_delete(response);
738         keys_delete(response_keys);
739         pdu_delete(request);
740         keys_delete(request_keys);
741 }
742
743 static void
744 login_wait_transition(struct connection *conn)
745 {
746         struct pdu *request, *response;
747         struct iscsi_bhs_login_request *bhslr;
748
749         log_debugx("waiting for state transition request");
750         request = login_receive(conn, false);
751         bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
752         if ((bhslr->bhslr_flags & BHSLR_FLAGS_TRANSIT) == 0) {
753                 login_send_error(request, 0x02, 0x00);
754                 log_errx(1, "got no \"T\" flag after answering AuthMethod");
755         }
756         pdu_delete(request);
757
758         log_debugx("got state transition request");
759         response = login_new_response(request);
760         login_set_nsg(response, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
761         pdu_send(response);
762         pdu_delete(response);
763
764         login_negotiate(conn, NULL);
765 }
766
767 void
768 login(struct connection *conn)
769 {
770         struct pdu *request, *response;
771         struct iscsi_bhs_login_request *bhslr;
772         struct keys *request_keys, *response_keys;
773         struct auth_group *ag;
774         struct portal_group *pg;
775         const char *initiator_name, *initiator_alias, *session_type,
776             *target_name, *auth_method;
777         bool redirected, fail, trans;
778
779         /*
780          * Handle the initial Login Request - figure out required authentication
781          * method and either transition to the next phase, if no authentication
782          * is required, or call appropriate authentication code.
783          */
784         log_debugx("beginning Login Phase; waiting for Login PDU");
785         request = login_receive(conn, true);
786         bhslr = (struct iscsi_bhs_login_request *)request->pdu_bhs;
787         if (bhslr->bhslr_tsih != 0) {
788                 login_send_error(request, 0x02, 0x0a);
789                 log_errx(1, "received Login PDU with non-zero TSIH");
790         }
791
792         pg = conn->conn_portal->p_portal_group;
793
794         memcpy(conn->conn_initiator_isid, bhslr->bhslr_isid,
795             sizeof(conn->conn_initiator_isid));
796
797         /*
798          * XXX: Implement the C flag some day.
799          */
800         request_keys = keys_new();
801         keys_load(request_keys, request);
802
803         assert(conn->conn_initiator_name == NULL);
804         initiator_name = keys_find(request_keys, "InitiatorName");
805         if (initiator_name == NULL) {
806                 login_send_error(request, 0x02, 0x07);
807                 log_errx(1, "received Login PDU without InitiatorName");
808         }
809         if (valid_iscsi_name(initiator_name) == false) {
810                 login_send_error(request, 0x02, 0x00);
811                 log_errx(1, "received Login PDU with invalid InitiatorName");
812         }
813         conn->conn_initiator_name = checked_strdup(initiator_name);
814         log_set_peer_name(conn->conn_initiator_name);
815         setproctitle("%s (%s)", conn->conn_initiator_addr, conn->conn_initiator_name);
816
817         redirected = login_portal_redirect(conn, request);
818         if (redirected) {
819                 log_debugx("initiator redirected; exiting");
820                 exit(0);
821         }
822
823         initiator_alias = keys_find(request_keys, "InitiatorAlias");
824         if (initiator_alias != NULL)
825                 conn->conn_initiator_alias = checked_strdup(initiator_alias);
826
827         assert(conn->conn_session_type == CONN_SESSION_TYPE_NONE);
828         session_type = keys_find(request_keys, "SessionType");
829         if (session_type != NULL) {
830                 if (strcmp(session_type, "Normal") == 0) {
831                         conn->conn_session_type = CONN_SESSION_TYPE_NORMAL;
832                 } else if (strcmp(session_type, "Discovery") == 0) {
833                         conn->conn_session_type = CONN_SESSION_TYPE_DISCOVERY;
834                 } else {
835                         login_send_error(request, 0x02, 0x00);
836                         log_errx(1, "received Login PDU with invalid "
837                             "SessionType \"%s\"", session_type);
838                 }
839         } else
840                 conn->conn_session_type = CONN_SESSION_TYPE_NORMAL;
841
842         assert(conn->conn_target == NULL);
843         if (conn->conn_session_type == CONN_SESSION_TYPE_NORMAL) {
844                 target_name = keys_find(request_keys, "TargetName");
845                 if (target_name == NULL) {
846                         login_send_error(request, 0x02, 0x07);
847                         log_errx(1, "received Login PDU without TargetName");
848                 }
849
850                 conn->conn_port = port_find_in_pg(pg, target_name);
851                 if (conn->conn_port == NULL) {
852                         login_send_error(request, 0x02, 0x03);
853                         log_errx(1, "requested target \"%s\" not found",
854                             target_name);
855                 }
856                 conn->conn_target = conn->conn_port->p_target;
857         }
858
859         /*
860          * At this point we know what kind of authentication we need.
861          */
862         if (conn->conn_session_type == CONN_SESSION_TYPE_NORMAL) {
863                 ag = conn->conn_port->p_auth_group;
864                 if (ag == NULL)
865                         ag = conn->conn_target->t_auth_group;
866                 if (ag->ag_name != NULL) {
867                         log_debugx("initiator requests to connect "
868                             "to target \"%s\"; auth-group \"%s\"",
869                             conn->conn_target->t_name,
870                             ag->ag_name);
871                 } else {
872                         log_debugx("initiator requests to connect "
873                             "to target \"%s\"", conn->conn_target->t_name);
874                 }
875         } else {
876                 assert(conn->conn_session_type == CONN_SESSION_TYPE_DISCOVERY);
877                 ag = pg->pg_discovery_auth_group;
878                 if (ag->ag_name != NULL) {
879                         log_debugx("initiator requests "
880                             "discovery session; auth-group \"%s\"", ag->ag_name);
881                 } else {
882                         log_debugx("initiator requests discovery session");
883                 }
884         }
885
886         if (ag->ag_type == AG_TYPE_DENY) {
887                 login_send_error(request, 0x02, 0x01);
888                 log_errx(1, "auth-type is \"deny\"");
889         }
890
891         if (ag->ag_type == AG_TYPE_UNKNOWN) {
892                 /*
893                  * This can happen with empty auth-group.
894                  */
895                 login_send_error(request, 0x02, 0x01);
896                 log_errx(1, "auth-type not set, denying access");
897         }
898
899         /*
900          * Enforce initiator-name and initiator-portal.
901          */
902         if (auth_name_check(ag, initiator_name) != 0) {
903                 login_send_error(request, 0x02, 0x02);
904                 log_errx(1, "initiator does not match allowed initiator names");
905         }
906
907         if (auth_portal_check(ag, &conn->conn_initiator_sa) != 0) {
908                 login_send_error(request, 0x02, 0x02);
909                 log_errx(1, "initiator does not match allowed "
910                     "initiator portals");
911         }
912
913         /*
914          * Let's see if the initiator intends to do any kind of authentication
915          * at all.
916          */
917         if (login_csg(request) == BHSLR_STAGE_OPERATIONAL_NEGOTIATION) {
918                 if (ag->ag_type != AG_TYPE_NO_AUTHENTICATION) {
919                         login_send_error(request, 0x02, 0x01);
920                         log_errx(1, "initiator skipped the authentication, "
921                             "but authentication is required");
922                 }
923
924                 keys_delete(request_keys);
925
926                 log_debugx("initiator skipped the authentication, "
927                     "and we don't need it; proceeding with negotiation");
928                 login_negotiate(conn, request);
929                 return;
930         }
931
932         fail = false;
933         response = login_new_response(request);
934         response_keys = keys_new();
935         trans = (bhslr->bhslr_flags & BHSLR_FLAGS_TRANSIT) != 0;
936         auth_method = keys_find(request_keys, "AuthMethod");
937         if (ag->ag_type == AG_TYPE_NO_AUTHENTICATION) {
938                 log_debugx("authentication not required");
939                 if (auth_method == NULL ||
940                     login_list_contains(auth_method, "None")) {
941                         keys_add(response_keys, "AuthMethod", "None");
942                 } else {
943                         log_warnx("initiator requests "
944                             "AuthMethod \"%s\" instead of \"None\"",
945                             auth_method);
946                         keys_add(response_keys, "AuthMethod", "Reject");
947                 }
948                 if (trans)
949                         login_set_nsg(response, BHSLR_STAGE_OPERATIONAL_NEGOTIATION);
950         } else {
951                 log_debugx("CHAP authentication required");
952                 if (auth_method == NULL ||
953                     login_list_contains(auth_method, "CHAP")) {
954                         keys_add(response_keys, "AuthMethod", "CHAP");
955                 } else {
956                         log_warnx("initiator requests unsupported "
957                             "AuthMethod \"%s\" instead of \"CHAP\"",
958                             auth_method);
959                         keys_add(response_keys, "AuthMethod", "Reject");
960                         fail = true;
961                 }
962         }
963         if (conn->conn_session_type == CONN_SESSION_TYPE_NORMAL) {
964                 if (conn->conn_target->t_alias != NULL)
965                         keys_add(response_keys,
966                             "TargetAlias", conn->conn_target->t_alias);
967                 keys_add_int(response_keys,
968                     "TargetPortalGroupTag", pg->pg_tag);
969         }
970         keys_save(response_keys, response);
971
972         pdu_send(response);
973         pdu_delete(response);
974         keys_delete(response_keys);
975         pdu_delete(request);
976         keys_delete(request_keys);
977
978         if (fail) {
979                 log_debugx("sent reject for AuthMethod; exiting");
980                 exit(1);
981         }
982
983         if (ag->ag_type != AG_TYPE_NO_AUTHENTICATION) {
984                 login_chap(conn, ag);
985                 login_negotiate(conn, NULL);
986         } else if (trans) {
987                 login_negotiate(conn, NULL);
988         } else {
989                 login_wait_transition(conn);
990         }
991 }