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