Home | History | Annotate | Line # | Download | only in iscsi
iscsi_text.c revision 1.10
      1 /*	$NetBSD: iscsi_text.c,v 1.10 2016/05/29 13:51:16 mlelstv Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2005,2006,2011 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Wasabi Systems, Inc.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #include "iscsi_globals.h"
     33 #include "base64.h"
     34 #include <sys/md5.h>
     35 #include <sys/cprng.h>
     36 
     37 /* define to send T_BIGNUM in hex format instead of base64 */
     38 /* #define ISCSI_HEXBIGNUMS */
     39 
     40 #define isdigit(x) ((x) >= '0' && (x) <= '9')
     41 #define toupper(x) ((x) & ~0x20)
     42 
     43 /*****************************************************************************/
     44 
     45 #define MAX_STRING   255	/* Maximum length of parameter value */
     46 #define MAX_LIST     4		/* Maximum number of list elements we'll ever send */
     47 
     48 /* Maximum number of negotiation parameters in the operational negotiation phase */
     49 /* 48 should be more than enough even with the target defining its own keys */
     50 #define MAX_NEG      48
     51 
     52 #define CHAP_CHALLENGE_LEN    32	/* Number of bytes to send in challenge */
     53 #define CHAP_MD5_SIZE         16	/* Number of bytes in MD5 hash */
     54 
     55 /*****************************************************************************/
     56 
     57 /* authentication states */
     58 
     59 typedef enum
     60 {
     61 	AUTH_INITIAL,				/* sending choice of algorithms */
     62 	AUTH_METHOD_SELECTED,		/* received choice, sending first parameter */
     63 	/* from here it's alg dependent */
     64 	AUTH_CHAP_ALG_SENT,			/* CHAP: Algorithm selected */
     65 	AUTH_CHAP_RSP_SENT,			/* CHAP: Response sent */
     66 	/* for all algorithms */
     67 	AUTH_DONE					/* in parameter negotiation stage */
     68 } auth_state_t;
     69 
     70 
     71 /* enumeration of all the keys we know, and a place for the ones we don't */
     72 
     73 typedef enum
     74 {
     75 	K_AuthMethod,
     76 	K_Auth_CHAP_Algorithm,
     77 	K_Auth_CHAP_Challenge,
     78 	K_Auth_CHAP_Identifier,
     79 	K_Auth_CHAP_Name,
     80 	K_Auth_CHAP_Response,
     81 	K_DataDigest,
     82 	K_DataPDUInOrder,
     83 	K_DataSequenceInOrder,
     84 	K_DefaultTime2Retain,
     85 	K_DefaultTime2Wait,
     86 	K_ErrorRecoveryLevel,
     87 	K_FirstBurstLength,
     88 	K_HeaderDigest,
     89 	K_IFMarker,
     90 	K_IFMarkInt,
     91 	K_ImmediateData,
     92 	K_InitialR2T,
     93 	K_InitiatorAlias,
     94 	K_InitiatorName,
     95 	K_MaxBurstLength,
     96 	K_MaxConnections,
     97 	K_MaxOutstandingR2T,
     98 	K_MaxRecvDataSegmentLength,
     99 	K_OFMarker,
    100 	K_OFMarkInt,
    101 	K_SendTargets,
    102 	K_SessionType,
    103 	K_TargetAddress,
    104 	K_TargetAlias,
    105 	K_TargetName,
    106 	K_TargetPortalGroupTag,
    107 	K_NotUnderstood
    108 } text_key_t;
    109 
    110 /* maximum known key */
    111 #define MAX_KEY   K_TargetPortalGroupTag
    112 
    113 /* value types */
    114 typedef enum
    115 {						/* Value is... */
    116 	T_NUM,					/* numeric */
    117 	T_BIGNUM,				/* large numeric */
    118 	T_STRING,				/* string */
    119 	T_YESNO,				/* boolean (Yes or No) */
    120 	T_AUTH,					/* authentication type (CHAP or None for now) */
    121 	T_DIGEST,				/* digest (None or CRC32C) */
    122 	T_RANGE,				/* numeric range */
    123 	T_SENDT,				/* send target options (ALL, target-name, empty) */
    124 	T_SESS					/* session type (Discovery or Normal) */
    125 } val_kind_t;
    126 
    127 
    128 /* table of negotiation key strings with value type and default */
    129 
    130 typedef struct
    131 {
    132 	const uint8_t *name;				/* the key name */
    133 	val_kind_t val;				/* the value type */
    134 	uint32_t defval;			/* default value */
    135 } key_entry_t;
    136 
    137 STATIC key_entry_t entries[] = {
    138 	{"AuthMethod", T_AUTH, 0},
    139 	{"CHAP_A", T_NUM, 5},
    140 	{"CHAP_C", T_BIGNUM, 0},
    141 	{"CHAP_I", T_NUM, 0},
    142 	{"CHAP_N", T_STRING, 0},
    143 	{"CHAP_R", T_BIGNUM, 0},
    144 	{"DataDigest", T_DIGEST, 0},
    145 	{"DataPDUInOrder", T_YESNO, 1},
    146 	{"DataSequenceInOrder", T_YESNO, 1},
    147 	{"DefaultTime2Retain", T_NUM, 20},
    148 	{"DefaultTime2Wait", T_NUM, 2},
    149 	{"ErrorRecoveryLevel", T_NUM, 0},
    150 	{"FirstBurstLength", T_NUM, 64 * 1024},
    151 	{"HeaderDigest", T_DIGEST, 0},
    152 	{"IFMarker", T_YESNO, 0},
    153 	{"IFMarkInt", T_RANGE, 2048},
    154 	{"ImmediateData", T_YESNO, 1},
    155 	{"InitialR2T", T_YESNO, 1},
    156 	{"InitiatorAlias", T_STRING, 0},
    157 	{"InitiatorName", T_STRING, 0},
    158 	{"MaxBurstLength", T_NUM, 256 * 1024},
    159 	{"MaxConnections", T_NUM, 1},
    160 	{"MaxOutstandingR2T", T_NUM, 1},
    161 	{"MaxRecvDataSegmentLength", T_NUM, 8192},
    162 	{"OFMarker", T_YESNO, 0},
    163 	{"OFMarkInt", T_RANGE, 2048},
    164 	{"SendTargets", T_SENDT, 0},
    165 	{"SessionType", T_SESS, 0},
    166 	{"TargetAddress", T_STRING, 0},
    167 	{"TargetAlias", T_STRING, 0},
    168 	{"TargetName", T_STRING, 0},
    169 	{"TargetPortalGroupTag", T_NUM, 0},
    170 	{NULL, T_STRING, 0}
    171 };
    172 
    173 /* a negotiation parameter: key and values (there may be more than 1 for lists) */
    174 typedef struct
    175 {
    176 	text_key_t key;				/* the key */
    177 	int list_num;				/* number of elements in list, doubles as */
    178 	/* data size for large numeric values */
    179 	union
    180 	{
    181 		uint32_t nval[MAX_LIST];	/* numeric or enumeration values */
    182 		uint8_t *sval;				/* string or data pointer */
    183 	} val;
    184 } negotiation_parameter_t;
    185 
    186 
    187 /* Negotiation state flags */
    188 #define NS_SENT      0x01		/* key was sent to target */
    189 #define NS_RECEIVED  0x02		/* key was received from target */
    190 
    191 typedef struct
    192 {
    193 	negotiation_parameter_t pars[MAX_NEG];	/* the parameters to send */
    194 	negotiation_parameter_t *cpar;			/* the last parameter set */
    195 	uint16_t num_pars;						/* number of parameters to send */
    196 	auth_state_t auth_state;				/* authentication state */
    197 	iscsi_auth_types_t auth_alg;			/* authentication algorithm */
    198 	uint8_t kflags[MAX_KEY + 2];			/* negotiation flags for each key */
    199 	uint8_t password[MAX_STRING + 1];		/* authentication secret */
    200 	uint8_t target_password[MAX_STRING + 1];	/* target authentication secret */
    201 	uint8_t user_name[MAX_STRING + 1];		/* authentication user ID */
    202 	uint8_t temp_buf[MAX_STRING + 1];		/* scratch buffer */
    203 
    204 	bool HeaderDigest;
    205 	bool DataDigest;
    206 	bool InitialR2T;
    207 	bool ImmediateData;
    208 	uint32_t ErrorRecoveryLevel;
    209 	uint32_t MaxRecvDataSegmentLength;
    210 	uint32_t MaxConnections;
    211 	uint32_t DefaultTime2Wait;
    212 	uint32_t DefaultTime2Retain;
    213 	uint32_t MaxBurstLength;
    214 	uint32_t FirstBurstLength;
    215 	uint32_t MaxOutstandingR2T;
    216 
    217 } negotiation_state_t;
    218 
    219 
    220 #define TX(state, key) (state->kflags [key] & NS_SENT)
    221 #define RX(state, key) (state->kflags [key] & NS_RECEIVED)
    222 
    223 /*****************************************************************************/
    224 
    225 
    226 STATIC void
    227 chap_md5_response(uint8_t *buffer, uint8_t identifier, uint8_t *secret,
    228 				  uint8_t *challenge, int challenge_size)
    229 {
    230 	MD5_CTX md5;
    231 
    232 	MD5Init(&md5);
    233 	MD5Update(&md5, &identifier, 1);
    234 	MD5Update(&md5, secret, strlen(secret));
    235 	MD5Update(&md5, challenge, challenge_size);
    236 	MD5Final(buffer, &md5);
    237 }
    238 
    239 
    240 /*****************************************************************************/
    241 
    242 /*
    243  * hexdig:
    244  *    Return value of hex digit.
    245  *    Note: a null character is acceptable, and returns 0.
    246  *
    247  *    Parameter:
    248  *          c     The character
    249  *
    250  *    Returns:    The value, -1 on error.
    251  */
    252 
    253 static __inline int
    254 hexdig(uint8_t c)
    255 {
    256 
    257 	if (!c) {
    258 		return 0;
    259 	}
    260 	if (isdigit(c)) {
    261 		return c - '0';
    262 	}
    263 	c = toupper(c);
    264 	if (c >= 'A' && c <= 'F') {
    265 		return c - 'A' + 10;
    266 	}
    267 	return -1;
    268 }
    269 
    270 /*
    271  * skiptozero:
    272  *    Skip to next zero character in buffer.
    273  *
    274  *    Parameter:
    275  *          buf      The buffer pointer
    276  *
    277  *    Returns:    The pointer to the character after the zero character.
    278  */
    279 
    280 static __inline uint8_t *
    281 skiptozero(uint8_t *buf)
    282 {
    283 
    284 	while (*buf) {
    285 		buf++;
    286 	}
    287 	return buf + 1;
    288 }
    289 
    290 
    291 /*
    292  * get_bignumval:
    293  *    Get a large numeric value.
    294  *    NOTE: Overwrites source string.
    295  *
    296  *    Parameter:
    297  *          buf      The buffer pointer
    298  *          par      The parameter
    299  *
    300  *    Returns:    The pointer to the next parameter, NULL on error.
    301  */
    302 
    303 STATIC uint8_t *
    304 get_bignumval(uint8_t *buf, negotiation_parameter_t *par)
    305 {
    306 	int val;
    307 	char c;
    308 	uint8_t *dp = buf;
    309 
    310 	par->val.sval = buf;
    311 
    312 	if (buf[0] == '0' && (buf[1] == 'x' || buf[1] == 'X')) {
    313 		buf += 2;
    314 		while ((c = *buf) != 0x0) {
    315 			buf++;
    316 			val = (hexdig(c) << 4) | hexdig(*buf);
    317 			if (val < 0) {
    318 				return NULL;
    319 			}
    320 			*dp++ = (uint8_t) val;
    321 			if (*buf) {
    322 				buf++;
    323 			}
    324 		}
    325 		buf++;
    326 		par->list_num = dp - par->val.sval;
    327 	} else if (buf[0] == '0' && (buf[1] == 'b' || buf[1] == 'B')) {
    328 		buf = base64_decode(&buf[2], par->val.sval, &par->list_num);
    329 	} else {
    330 		DEBOUT(("Ill-formatted large number <%s>\n", buf));
    331 		return NULL;
    332 	}
    333 
    334 	return buf;
    335 }
    336 
    337 
    338 /*
    339  * get_numval:
    340  *    Get a numeric value.
    341  *
    342  *    Parameter:
    343  *          buf      The buffer pointer
    344  *          pval     The pointer to the result.
    345  *
    346  *    Returns:    The pointer to the next parameter, NULL on error.
    347  */
    348 
    349 STATIC uint8_t *
    350 get_numval(uint8_t *buf, uint32_t *pval)
    351 {
    352 	uint32_t val = 0;
    353 	char c;
    354 
    355 	if (buf[0] == '0' && (buf[1] == 'x' || buf[1] == 'X')) {
    356 		buf += 2;
    357 		while (*buf && *buf != '~') {
    358 			int n;
    359 
    360 			if ((n = hexdig(*buf++)) < 0)
    361 				return NULL;
    362 			val = (val << 4) | n;
    363 		}
    364 	} else
    365 		while (*buf && *buf != '~') {
    366 			c = *buf++;
    367 			if (!isdigit(c))
    368 				return NULL;
    369 			val = val * 10 + (c - '0');
    370 		}
    371 
    372 	*pval = val;
    373 
    374 	return buf + 1;
    375 }
    376 
    377 
    378 /*
    379  * get_range:
    380  *    Get a numeric range.
    381  *
    382  *    Parameter:
    383  *          buf      The buffer pointer
    384  *          pval1    The pointer to the first result.
    385  *          pval2    The pointer to the second result.
    386  *
    387  *    Returns:    The pointer to the next parameter, NULL on error.
    388  */
    389 
    390 STATIC uint8_t *
    391 get_range(uint8_t *buf, uint32_t *pval1, uint32_t *pval2)
    392 {
    393 
    394 	if ((buf = get_numval(buf, pval1)) == NULL)
    395 		return NULL;
    396 	if (!*buf)
    397 		return NULL;
    398 	if ((buf = get_numval(buf, pval2)) == NULL)
    399 		return NULL;
    400 	return buf;
    401 }
    402 
    403 
    404 /*
    405  * get_ynval:
    406  *    Get a yes/no selection.
    407  *
    408  *    Parameter:
    409  *          buf      The buffer pointer
    410  *          pval     The pointer to the result.
    411  *
    412  *    Returns:    The pointer to the next parameter, NULL on error.
    413  */
    414 
    415 STATIC uint8_t *
    416 get_ynval(uint8_t *buf, uint32_t *pval)
    417 {
    418 
    419 	if (strcmp(buf, "Yes") == 0)
    420 		*pval = 1;
    421 	else if (strcmp(buf, "No") == 0)
    422 		*pval = 0;
    423 	else
    424 		return NULL;
    425 
    426 	return skiptozero(buf);
    427 }
    428 
    429 
    430 /*
    431  * get_digestval:
    432  *    Get a digest selection.
    433  *
    434  *    Parameter:
    435  *          buf      The buffer pointer
    436  *          pval     The pointer to the result.
    437  *
    438  *    Returns:    The pointer to the next parameter, NULL on error.
    439  */
    440 
    441 STATIC uint8_t *
    442 get_digestval(uint8_t *buf, uint32_t *pval)
    443 {
    444 
    445 	if (strcmp(buf, "CRC32C") == 0)
    446 		*pval = 1;
    447 	else if (strcmp(buf, "None") == 0)
    448 		*pval = 0;
    449 	else
    450 		return NULL;
    451 
    452 	return skiptozero(buf);
    453 }
    454 
    455 
    456 /*
    457  * get_authval:
    458  *    Get an authentication method.
    459  *
    460  *    Parameter:
    461  *          buf      The buffer pointer
    462  *          pval     The pointer to the result.
    463  *
    464  *    Returns:    The pointer to the next parameter, NULL on error.
    465  */
    466 
    467 STATIC uint8_t *
    468 get_authval(uint8_t *buf, uint32_t *pval)
    469 {
    470 
    471 	if (strcmp(buf, "None") == 0)
    472 		*pval = ISCSI_AUTH_None;
    473 	else if (strcmp(buf, "CHAP") == 0)
    474 		*pval = ISCSI_AUTH_CHAP;
    475 	else if (strcmp(buf, "KRB5") == 0)
    476 		*pval = ISCSI_AUTH_KRB5;
    477 	else if (strcmp(buf, "SRP") == 0)
    478 		*pval = ISCSI_AUTH_SRP;
    479 	else
    480 		return NULL;
    481 
    482 	return skiptozero(buf);
    483 }
    484 
    485 
    486 /*
    487  * get_strval:
    488  *    Get a string value (returns pointer to original buffer, not a copy).
    489  *
    490  *    Parameter:
    491  *          buf      The buffer pointer
    492  *          pval     The pointer to the result pointer.
    493  *
    494  *    Returns:    The pointer to the next parameter, NULL on error.
    495  */
    496 
    497 STATIC uint8_t *
    498 get_strval(uint8_t *buf, uint8_t **pval)
    499 {
    500 
    501 	if (strlen(buf) > MAX_STRING)
    502 		return NULL;
    503 
    504 	*pval = buf;
    505 
    506 	return skiptozero(buf);
    507 }
    508 
    509 
    510 /*
    511  * get_parameter:
    512  *    Analyze a key=value string.
    513  *    NOTE: The string is modified in the process.
    514  *
    515  *    Parameter:
    516  *          buf      The buffer pointer
    517  *          par      The parameter descriptor to be filled in
    518  *
    519  *    Returns:    The pointer to the next parameter, NULL on error.
    520  */
    521 
    522 STATIC uint8_t *
    523 get_parameter(uint8_t *buf, negotiation_parameter_t *par)
    524 {
    525 	uint8_t *bp = buf;
    526 	int i;
    527 
    528 	while (*bp && *bp != '=') {
    529 		bp++;
    530 	}
    531 	if (!*bp) {
    532 		DEBOUT(("get_parameter: Premature end of parameter\n"));
    533 		return NULL;
    534 	}
    535 
    536 	*bp++ = 0;
    537 
    538 	for (i = 0; i <= MAX_KEY; i++)
    539 		if (!strcmp(buf, entries[i].name))
    540 			break;
    541 
    542 	par->key = i;
    543 	par->list_num = 1;
    544 
    545 	if (i > MAX_KEY) {
    546 		DEBOUT(("get_parameter: unrecognized key <%s>\n", buf));
    547 		if (strlen(buf) > MAX_STRING) {
    548 			DEBOUT(("get_parameter: key name > MAX_STRING\n"));
    549 			return NULL;
    550 		}
    551 		par->val.sval = buf;
    552 		return skiptozero(bp);
    553 	}
    554 
    555 	DEB(10, ("get_par: key <%s>=%d, val=%d, ret %p\n",
    556 			buf, i, entries[i].val, bp));
    557 	DEB(10, ("get_par: value '%s'\n",bp));
    558 
    559 	switch (entries[i].val) {
    560 	case T_NUM:
    561 		bp = get_numval(bp, &par->val.nval[0]);
    562 		break;
    563 
    564 	case T_BIGNUM:
    565 		bp = get_bignumval(bp, par);
    566 		break;
    567 
    568 	case T_STRING:
    569 		bp = get_strval(bp, &par->val.sval);
    570 		break;
    571 
    572 	case T_YESNO:
    573 		bp = get_ynval(bp, &par->val.nval[0]);
    574 		break;
    575 
    576 	case T_AUTH:
    577 		bp = get_authval(bp, &par->val.nval[0]);
    578 		break;
    579 
    580 	case T_DIGEST:
    581 		bp = get_digestval(bp, &par->val.nval[0]);
    582 		break;
    583 
    584 	case T_RANGE:
    585 		bp = get_range(bp, &par->val.nval[0], &par->val.nval[1]);
    586 		break;
    587 
    588 	default:
    589 		/* Target sending any other types is wrong */
    590 		bp = NULL;
    591 		break;
    592 	}
    593 	return bp;
    594 }
    595 
    596 /*****************************************************************************/
    597 
    598 /*
    599  * my_strcpy:
    600  *    Replacement for strcpy that returns the end of the result string
    601  *
    602  *    Parameter:
    603  *          dest     The destination buffer pointer
    604  *          src      The source string
    605  *
    606  *    Returns:    A pointer to the terminating zero of the result.
    607  */
    608 
    609 static __inline unsigned
    610 my_strcpy(uint8_t *dest, const uint8_t *src)
    611 {
    612 	unsigned	cc;
    613 
    614 	for (cc = 0 ; (*dest = *src) != 0x0 ; cc++) {
    615 		dest++;
    616 		src++;
    617 	}
    618 	return cc;
    619 }
    620 
    621 /*
    622  * put_bignumval:
    623  *    Write a large numeric value.
    624  *    NOTE: Overwrites source string.
    625  *
    626  *    Parameter:
    627  *          buf      The buffer pointer
    628  *          par      The parameter
    629  *
    630  *    Returns:    The pointer to the next parameter, NULL on error.
    631  */
    632 
    633 STATIC unsigned
    634 put_bignumval(negotiation_parameter_t *par, uint8_t *buf)
    635 {
    636 #ifdef ISCSI_HEXBIGNUMS
    637 	int k, c;
    638 
    639 	my_strcpy(buf, "0x");
    640 	for (k=0; k<par->list_num; ++k) {
    641 		c = par->val.sval[k] >> 4;
    642 		buf[2+2*k] = c < 10 ? '0' + c : 'a' + (c-10);
    643 		c = par->val.sval[k] & 0xf;
    644 		buf[2+2*k+1] = c < 10 ? '0' + c : 'a' + (c-10);
    645 	}
    646 	buf[2+2*k] = '\0';
    647 
    648 	return 2+2*par->list_num;
    649 #else
    650 	return base64_encode(par->val.sval, par->list_num, buf);
    651 #endif
    652 }
    653 
    654 /*
    655  * put_parameter:
    656  *    Create a key=value string.
    657  *
    658  *    Parameter:
    659  *          buf      The buffer pointer
    660  *          par      The parameter descriptor
    661  *
    662  *    Returns:    The pointer to the next free buffer space, NULL on error.
    663  */
    664 
    665 STATIC unsigned
    666 put_parameter(uint8_t *buf, unsigned len, negotiation_parameter_t *par)
    667 {
    668 	int i;
    669 	unsigned	cc, cl;
    670 	const uint8_t *sp;
    671 
    672 	DEB(10, ("put_par: key <%s>=%d, val=%d\n",
    673 		entries[par->key].name, par->key, entries[par->key].val));
    674 
    675 	if (par->key > MAX_KEY) {
    676 		return snprintf(buf, len, "%s=NotUnderstood", par->val.sval);
    677 	}
    678 
    679 	cc = snprintf(buf, len, "%s=", entries[par->key].name);
    680 	if (cc >= len)
    681 		return len;
    682 
    683 	for (i = 0; i < par->list_num; i++) {
    684 		switch (entries[par->key].val) {
    685 		case T_NUM:
    686 			cl = snprintf(&buf[cc], len - cc, "%d",
    687 			               par->val.nval[i]);
    688 			break;
    689 
    690 		case T_BIGNUM:
    691 			cl = put_bignumval(par, &buf[cc]);
    692 			i = par->list_num;
    693 			break;
    694 
    695 		case T_STRING:
    696 			cl =  my_strcpy(&buf[cc], par->val.sval);
    697 			break;
    698 
    699 		case T_YESNO:
    700 			cl = my_strcpy(&buf[cc],
    701 				(par->val.nval[i]) ? "Yes" : "No");
    702 			break;
    703 
    704 		case T_AUTH:
    705 			switch (par->val.nval[i]) {
    706 			case ISCSI_AUTH_CHAP:
    707 				sp = "CHAP";
    708 				break;
    709 			case ISCSI_AUTH_KRB5:
    710 				sp = "KRB5";
    711 				break;
    712 			case ISCSI_AUTH_SRP:
    713 				sp = "SRP";
    714 				break;
    715 			default:
    716 				sp = "None";
    717 				break;
    718 			}
    719 			cl = my_strcpy(&buf[cc], sp);
    720 			break;
    721 
    722 		case T_DIGEST:
    723 			cl = my_strcpy(&buf[cc],
    724 				(par->val.nval[i]) ? "CRC32C" : "None");
    725 			break;
    726 
    727 		case T_RANGE:
    728 			if ((i + 1) >= par->list_num) {
    729 				cl = my_strcpy(&buf[cc], "Reject");
    730 			} else {
    731 				cl = snprintf(&buf[cc], len - cc,
    732 						"%d~%d", par->val.nval[i],
    733 						par->val.nval[i + 1]);
    734 				i++;
    735 			}
    736 			break;
    737 
    738 		case T_SENDT:
    739 			cl = my_strcpy(&buf[cc], par->val.sval);
    740 			break;
    741 
    742 		case T_SESS:
    743 			cl = my_strcpy(&buf[cc],
    744 				(par->val.nval[i]) ? "Normal" : "Discovery");
    745 			break;
    746 
    747 		default:
    748 			cl = 0;
    749 			/* We should't be here... */
    750 			DEBOUT(("Invalid type %d in put_parameter!\n",
    751 					entries[par->key].val));
    752 			break;
    753 		}
    754 
    755 		DEB(10, ("put_par: value '%s'\n",&buf[cc]));
    756 
    757 		cc += cl;
    758 		if (cc >= len)
    759 			return len;
    760 		if ((i + 1) < par->list_num) {
    761 			if (cc >= len)
    762 				return len;
    763 			buf[cc++] = ',';
    764 		}
    765 	}
    766 
    767 	if (cc >= len)
    768 		return len;
    769 	buf[cc] = 0x0;				/* make sure it's terminated */
    770 	return cc + 1;				/* return next place in list */
    771 }
    772 
    773 
    774 /*
    775  * put_par_block:
    776  *    Fill a parameter block
    777  *
    778  *    Parameter:
    779  *          buf      The buffer pointer
    780  *          pars     The parameter descriptor array
    781  *          n        The number of elements
    782  *
    783  *    Returns:    result from put_parameter (ptr to buffer, NULL on error)
    784  */
    785 
    786 static __inline unsigned
    787 put_par_block(uint8_t *buf, unsigned len, negotiation_parameter_t *pars, int n)
    788 {
    789 	unsigned	cc;
    790 	int i;
    791 
    792 	for (cc = 0, i = 0; i < n; i++) {
    793 		cc += put_parameter(&buf[cc], len - cc, pars++);
    794 		if (cc >= len) {
    795 			break;
    796 		}
    797 	}
    798 	return cc;
    799 }
    800 
    801 /*
    802  * parameter_size:
    803  *    Determine the size of a key=value string.
    804  *
    805  *    Parameter:
    806  *          par      The parameter descriptor
    807  *
    808  *    Returns:    The size of the resulting string.
    809  */
    810 
    811 STATIC int
    812 parameter_size(negotiation_parameter_t *par)
    813 {
    814 	int i, size;
    815 	char buf[24];	/* max. 2 10-digit numbers + sep. */
    816 
    817 	if (par->key > MAX_KEY) {
    818 		return strlen(par->val.sval) + 15;
    819 	}
    820 	/* count '=' and terminal zero */
    821 	size = strlen(entries[par->key].name) + 2;
    822 
    823 	for (i = 0; i < par->list_num; i++) {
    824 		switch (entries[par->key].val) {
    825 		case T_NUM:
    826 			size += snprintf(buf, sizeof(buf), "%d",
    827 					par->val.nval[i]);
    828 			break;
    829 
    830 		case T_BIGNUM:
    831 			/* list_num holds value size */
    832 #ifdef ISCSI_HEXBIGNUMS
    833 			size += 2 + 2*par->list_num;
    834 #else
    835 			size += base64_enclen(par->list_num);
    836 #endif
    837 			i = par->list_num;
    838 			break;
    839 
    840 		case T_STRING:
    841 		case T_SENDT:
    842 			size += strlen(par->val.sval);
    843 			break;
    844 
    845 		case T_YESNO:
    846 			size += (par->val.nval[i]) ? 3 : 2;
    847 			break;
    848 
    849 		case T_AUTH:
    850 			size += (par->val.nval[i] == ISCSI_AUTH_SRP) ? 3 : 4;
    851 			break;
    852 
    853 		case T_DIGEST:
    854 			size += (par->val.nval[i]) ? 6 : 4;
    855 			break;
    856 
    857 		case T_RANGE:
    858 			if (i+1 < par->list_num) {
    859 				size += snprintf(buf, sizeof(buf), "%d~%d",
    860 					par->val.nval[i],
    861 					par->val.nval[i + 1]);
    862 				i++;
    863 			} else
    864 				DEBOUT(("Incomplete range parameter\n"));
    865 			break;
    866 
    867 		case T_SESS:
    868 			size += (par->val.nval[i]) ? 6 : 9;
    869 			break;
    870 
    871 		default:
    872 			/* We should't be here... */
    873 			DEBOUT(("Invalid type %d in parameter_size!\n",
    874 					entries[par->key].val));
    875 			break;
    876 		}
    877 		if ((i + 1) < par->list_num) {
    878 			size++;
    879 		}
    880 	}
    881 
    882 	return size;
    883 }
    884 
    885 
    886 /*
    887  * total_size:
    888  *    Determine the size of a negotiation data block
    889  *
    890  *    Parameter:
    891  *          pars     The parameter descriptor array
    892  *          n        The number of elements
    893  *
    894  *    Returns:    The size of the block
    895  */
    896 
    897 static __inline int
    898 total_size(negotiation_parameter_t *pars, int n)
    899 {
    900 	int i, size;
    901 
    902 	for (i = 0, size = 0; i < n; i++) {
    903 		size += parameter_size(pars++);
    904 	}
    905 	return size;
    906 }
    907 
    908 /*****************************************************************************/
    909 
    910 
    911 /*
    912  * complete_pars:
    913  *    Allocate space for text parameters, translate parameter values into
    914  *    text.
    915  *
    916  *    Parameter:
    917  *          state    Negotiation state
    918  *          pdu      The transmit PDU
    919  *
    920  *    Returns:    0     On success
    921  *                > 0   (an ISCSI error code) if an error occurred.
    922  */
    923 
    924 STATIC int
    925 complete_pars(negotiation_state_t *state, pdu_t *pdu)
    926 {
    927 	int len;
    928 	uint8_t *bp;
    929 
    930 	len = total_size(state->pars, state->num_pars);
    931 
    932 	DEB(10, ("complete_pars: n=%d, len=%d\n", state->num_pars, len));
    933 
    934 	if ((bp = malloc(len, M_TEMP, M_WAITOK)) == NULL) {
    935 		DEBOUT(("*** Out of memory in complete_pars\n"));
    936 		return ISCSI_STATUS_NO_RESOURCES;
    937 	}
    938 	pdu->temp_data = bp;
    939 
    940 	if (put_par_block(pdu->temp_data, len, state->pars,
    941 			state->num_pars) == 0) {
    942 		DEBOUT(("Bad parameter in complete_pars\n"));
    943 		return ISCSI_STATUS_PARAMETER_INVALID;
    944 	}
    945 
    946 	pdu->temp_data_len = len;
    947 	return 0;
    948 }
    949 
    950 
    951 /*
    952  * set_key_n:
    953  *    Initialize a key and its numeric value.
    954  *
    955  *    Parameter:
    956  *          state    Negotiation state
    957  *          key      The key
    958  *          val      The value
    959  */
    960 
    961 STATIC negotiation_parameter_t *
    962 set_key_n(negotiation_state_t *state, text_key_t key, uint32_t val)
    963 {
    964 	negotiation_parameter_t *par;
    965 
    966 	if (state->num_pars >= MAX_NEG) {
    967 		DEBOUT(("set_key_n: num_pars (%d) >= MAX_NEG (%d)\n",
    968 				state->num_pars, MAX_NEG));
    969 		return NULL;
    970 	}
    971 	par = &state->pars[state->num_pars];
    972 	par->key = key;
    973 	par->list_num = 1;
    974 	par->val.nval[0] = val;
    975 	state->num_pars++;
    976 	state->kflags[key] |= NS_SENT;
    977 
    978 	return par;
    979 }
    980 
    981 /*
    982  * set_key_s:
    983  *    Initialize a key and its string value.
    984  *
    985  *    Parameter:
    986  *          state    Negotiation state
    987  *          key      The key
    988  *          val      The value
    989  */
    990 
    991 STATIC negotiation_parameter_t *
    992 set_key_s(negotiation_state_t *state, text_key_t key, uint8_t *val)
    993 {
    994 	negotiation_parameter_t *par;
    995 
    996 	if (state->num_pars >= MAX_NEG) {
    997 		DEBOUT(("set_key_s: num_pars (%d) >= MAX_NEG (%d)\n",
    998 				state->num_pars, MAX_NEG));
    999 		return NULL;
   1000 	}
   1001 	par = &state->pars[state->num_pars];
   1002 	par->key = key;
   1003 	par->list_num = 1;
   1004 	par->val.sval = val;
   1005 	state->num_pars++;
   1006 	state->kflags[key] |= NS_SENT;
   1007 
   1008 	return par;
   1009 }
   1010 
   1011 
   1012 /*****************************************************************************/
   1013 
   1014 /*
   1015  * eval_parameter:
   1016  *    Evaluate a received negotiation value.
   1017  *
   1018  *    Parameter:
   1019  *          conn     The connection
   1020  *          state    The negotiation state
   1021  *          par      The parameter
   1022  *
   1023  *    Returns:    0 on success, else an ISCSI status value.
   1024  */
   1025 
   1026 STATIC int
   1027 eval_parameter(connection_t *conn, negotiation_state_t *state,
   1028 			   negotiation_parameter_t *par)
   1029 {
   1030 	uint32_t n = par->val.nval[0];
   1031 	size_t sz;
   1032 	text_key_t key = par->key;
   1033 	bool sent = (state->kflags[key] & NS_SENT) != 0;
   1034 
   1035 	state->kflags[key] |= NS_RECEIVED;
   1036 
   1037 	switch (key) {
   1038 		/*
   1039 		 *  keys connected to security negotiation
   1040 		 */
   1041 	case K_AuthMethod:
   1042 		if (n) {
   1043 			DEBOUT(("eval_par: AuthMethod nonzero (%d)\n", n));
   1044 			return ISCSI_STATUS_NEGOTIATION_ERROR;
   1045 		}
   1046 		break;
   1047 
   1048 	case K_Auth_CHAP_Algorithm:
   1049 	case K_Auth_CHAP_Challenge:
   1050 	case K_Auth_CHAP_Identifier:
   1051 	case K_Auth_CHAP_Name:
   1052 	case K_Auth_CHAP_Response:
   1053 		DEBOUT(("eval_par: Authorization Key in Operational Phase\n"));
   1054 		return ISCSI_STATUS_NEGOTIATION_ERROR;
   1055 
   1056 		/*
   1057 		 * keys we always send
   1058 		 */
   1059 	case K_DataDigest:
   1060 		state->DataDigest = n;
   1061 		if (!sent)
   1062 			set_key_n(state, key, n);
   1063 		break;
   1064 
   1065 	case K_HeaderDigest:
   1066 		state->HeaderDigest = n;
   1067 		if (!sent)
   1068 			set_key_n(state, key, n);
   1069 		break;
   1070 
   1071 	case K_ErrorRecoveryLevel:
   1072 		state->ErrorRecoveryLevel = n;
   1073 		if (!sent)
   1074 			set_key_n(state, key, n);
   1075 		break;
   1076 
   1077 	case K_ImmediateData:
   1078 		state->ImmediateData = n;
   1079 		if (!sent)
   1080 			set_key_n(state, key, n);
   1081 		break;
   1082 
   1083 	case K_InitialR2T:
   1084 		state->InitialR2T = n;
   1085 		if (!sent)
   1086 			set_key_n(state, key, n);
   1087 		break;
   1088 
   1089 	case K_MaxRecvDataSegmentLength:
   1090 		state->MaxRecvDataSegmentLength = n;
   1091 		/* this is basically declarative, not negotiated */
   1092 		/* (each side has its own value) */
   1093 		break;
   1094 
   1095 		/*
   1096 		 * keys we don't always send, so we may have to reflect the value
   1097 		 */
   1098 	case K_DefaultTime2Retain:
   1099 		state->DefaultTime2Retain = n = min(state->DefaultTime2Retain, n);
   1100 		if (!sent)
   1101 			set_key_n(state, key, n);
   1102 		break;
   1103 
   1104 	case K_DefaultTime2Wait:
   1105 		state->DefaultTime2Wait = n = min(state->DefaultTime2Wait, n);
   1106 		if (!sent)
   1107 			set_key_n(state, key, n);
   1108 		break;
   1109 
   1110 	case K_MaxConnections:
   1111 		if (state->MaxConnections)
   1112 			state->MaxConnections = n = min(state->MaxConnections, n);
   1113 		else
   1114 			state->MaxConnections = n;
   1115 
   1116 		if (!sent)
   1117 			set_key_n(state, key, n);
   1118 		break;
   1119 
   1120 	case K_MaxOutstandingR2T:
   1121 		state->MaxOutstandingR2T = n;
   1122 		if (!sent)
   1123 			set_key_n(state, key, n);
   1124 		break;
   1125 
   1126 	case K_FirstBurstLength:
   1127 		state->FirstBurstLength = n;
   1128 		if (!sent)
   1129 			set_key_n(state, key, n);
   1130 		break;
   1131 
   1132 	case K_MaxBurstLength:
   1133 		state->MaxBurstLength = n;
   1134 		if (!sent)
   1135 			set_key_n(state, key, n);
   1136 		break;
   1137 
   1138 	case K_IFMarker:
   1139 	case K_OFMarker:
   1140 		/* not (yet) supported */
   1141 		if (!sent)
   1142 			set_key_n(state, key, 0);
   1143 		break;
   1144 
   1145 	case K_IFMarkInt:
   1146 	case K_OFMarkInt:
   1147 		/* it's a range, and list_num will be 1, so this will reply "Reject" */
   1148 		if (!sent)
   1149 			set_key_n(state, key, 0);
   1150 		break;
   1151 
   1152 	case K_DataPDUInOrder:
   1153 	case K_DataSequenceInOrder:
   1154 		/* values are don't care */
   1155 		if (!sent)
   1156 			set_key_n(state, key, n);
   1157 		break;
   1158 
   1159 	case K_NotUnderstood:
   1160 		/* return "NotUnderstood" */
   1161 		set_key_s(state, key, par->val.sval);
   1162 		break;
   1163 
   1164 		/*
   1165 		 * Declarative keys (no response required)
   1166 		 */
   1167 	case K_TargetAddress:
   1168 		/* ignore for now... */
   1169 		break;
   1170 
   1171 	case K_TargetAlias:
   1172 		if (conn->login_par->is_present.TargetAlias) {
   1173 			copyoutstr(par->val.sval, conn->login_par->TargetAlias,
   1174 				ISCSI_STRING_LENGTH - 1, &sz);
   1175 			/* do anything with return code?? */
   1176 		}
   1177 		break;
   1178 
   1179 	case K_TargetPortalGroupTag:
   1180 		/* ignore for now... */
   1181 		break;
   1182 
   1183 	default:
   1184 		DEBOUT(("eval_par: Invalid parameter type %d\n", par->key));
   1185 		return ISCSI_STATUS_NEGOTIATION_ERROR;
   1186 	}
   1187 	return 0;
   1188 }
   1189 
   1190 /*****************************************************************************/
   1191 
   1192 
   1193 /*
   1194  * init_session_parameters:
   1195  *    Initialize session-related negotiation parameters from existing session
   1196  *
   1197  *    Parameter:
   1198  *          sess     The session
   1199  *          state    The negotiation state
   1200  */
   1201 
   1202 STATIC void
   1203 init_session_parameters(session_t *sess, negotiation_state_t *state)
   1204 {
   1205 
   1206 	state->ErrorRecoveryLevel = sess->ErrorRecoveryLevel;
   1207 	state->InitialR2T = sess->InitialR2T;
   1208 	state->ImmediateData = sess->ImmediateData;
   1209 	state->MaxConnections = sess->MaxConnections;
   1210 	state->DefaultTime2Wait = sess->DefaultTime2Wait;
   1211 	state->DefaultTime2Retain = sess->DefaultTime2Retain;
   1212 	state->MaxBurstLength = sess->MaxBurstLength;
   1213 	state->FirstBurstLength = sess->FirstBurstLength;
   1214 	state->MaxOutstandingR2T = sess->MaxOutstandingR2T;
   1215 }
   1216 
   1217 
   1218 
   1219 /*
   1220  * assemble_login_parameters:
   1221  *    Assemble the initial login negotiation parameters.
   1222  *
   1223  *    Parameter:
   1224  *          conn     The connection
   1225  *          ccb      The CCB for the login exchange
   1226  *          pdu      The PDU to use for sending
   1227  *
   1228  *    Returns:    < 0   if more security negotiation is required
   1229  *                0     if this is the last security negotiation block
   1230  *                > 0   (an ISCSI error code) if an error occurred.
   1231  */
   1232 
   1233 int
   1234 assemble_login_parameters(connection_t *conn, ccb_t *ccb, pdu_t *pdu)
   1235 {
   1236 	iscsi_login_parameters_t *par = conn->login_par;
   1237 	size_t sz;
   1238 	int rc, i, next;
   1239 	negotiation_state_t *state;
   1240 	negotiation_parameter_t *cpar;
   1241 
   1242 	state = malloc(sizeof(*state), M_TEMP, M_WAITOK | M_ZERO);
   1243 	if (state == NULL) {
   1244 		DEBOUT(("*** Out of memory in assemble_login_params\n"));
   1245 		return ISCSI_STATUS_NO_RESOURCES;
   1246 	}
   1247 	ccb->temp_data = state;
   1248 
   1249 	if (!iscsi_InitiatorName[0]) {
   1250 		DEBOUT(("No InitiatorName\n"));
   1251 		return ISCSI_STATUS_PARAMETER_MISSING;
   1252 	}
   1253 	set_key_s(state, K_InitiatorName, iscsi_InitiatorName);
   1254 
   1255 	if (iscsi_InitiatorAlias[0])
   1256 		set_key_s(state, K_InitiatorAlias, iscsi_InitiatorAlias);
   1257 
   1258 	conn->Our_MaxRecvDataSegmentLength =
   1259 		(par->is_present.MaxRecvDataSegmentLength)
   1260 		? par->MaxRecvDataSegmentLength : DEFAULT_MaxRecvDataSegmentLength;
   1261 
   1262 	/* setup some values for authentication */
   1263 	if (par->is_present.password)
   1264 		copyinstr(par->password, state->password, MAX_STRING, &sz);
   1265 	if (par->is_present.target_password)
   1266 		copyinstr(par->target_password, state->target_password,
   1267 			MAX_STRING, &sz);
   1268 	if (par->is_present.user_name)
   1269 		copyinstr(par->user_name, state->user_name, MAX_STRING, &sz);
   1270 	else
   1271 		strlcpy(state->user_name, iscsi_InitiatorName,
   1272 			sizeof(state->user_name));
   1273 
   1274 	next = TRUE;
   1275 
   1276 	set_key_n(state, K_SessionType,
   1277 			  par->login_type > ISCSI_LOGINTYPE_DISCOVERY);
   1278 
   1279 	cpar = set_key_n(state, K_AuthMethod, ISCSI_AUTH_None);
   1280 
   1281 	if (cpar != NULL && par->is_present.auth_info &&
   1282 		par->auth_info.auth_number > 0) {
   1283 		if (par->auth_info.auth_number > ISCSI_AUTH_OPTIONS) {
   1284 			DEBOUT(("Auth number too big in asm_login\n"));
   1285 			return ISCSI_STATUS_PARAMETER_INVALID;
   1286 		}
   1287 		cpar->list_num = par->auth_info.auth_number;
   1288 		for (i = 0; i < cpar->list_num; i++) {
   1289 			cpar->val.nval[i] = par->auth_info.auth_type[i];
   1290 			if (par->auth_info.auth_type[i])
   1291 				next = FALSE;
   1292 		}
   1293 	}
   1294 
   1295 	if (par->is_present.TargetName)
   1296 		copyinstr(par->TargetName, state->temp_buf, ISCSI_STRING_LENGTH - 1,
   1297 				  &sz);
   1298 	else {
   1299 		state->temp_buf[0] = 0;
   1300 		sz = 0;
   1301 	}
   1302 
   1303 	if ((!sz || !state->temp_buf[0]) &&
   1304 		par->login_type != ISCSI_LOGINTYPE_DISCOVERY) {
   1305 		DEBOUT(("No TargetName\n"));
   1306 		return ISCSI_STATUS_PARAMETER_MISSING;
   1307 	}
   1308 
   1309 	if (state->temp_buf[0]) {
   1310 		set_key_s(state, K_TargetName, state->temp_buf);
   1311 	}
   1312 
   1313 	if ((rc = complete_pars(state, pdu)) != 0)
   1314 		return rc;
   1315 
   1316 	return (next) ? 0 : -1;
   1317 }
   1318 
   1319 
   1320 /*
   1321  * assemble_security_parameters:
   1322  *    Assemble the security negotiation parameters.
   1323  *
   1324  *    Parameter:
   1325  *          conn     The connection
   1326  *          rx_pdu   The received login response PDU
   1327  *          tx_pdu   The transmit PDU
   1328  *
   1329  *    Returns:    < 0   if more security negotiation is required
   1330  *                0     if this is the last security negotiation block
   1331  *                > 0   (an ISCSI error code) if an error occurred.
   1332  */
   1333 
   1334 int
   1335 assemble_security_parameters(connection_t *conn, ccb_t *ccb, pdu_t *rx_pdu,
   1336 							 pdu_t *tx_pdu)
   1337 {
   1338 	negotiation_state_t *state = (negotiation_state_t *) ccb->temp_data;
   1339 	iscsi_login_parameters_t *par = conn->login_par;
   1340 	negotiation_parameter_t rxp, *cpar;
   1341 	uint8_t *rxpars;
   1342 	int rc, next;
   1343 	uint8_t identifier = 0;
   1344 	uint8_t *challenge = NULL;
   1345 	int challenge_size = 0;
   1346 	uint8_t *response = NULL;
   1347 	int response_size = 0;
   1348 
   1349 	state->num_pars = 0;
   1350 	next = 0;
   1351 
   1352 	rxpars = (uint8_t *) rx_pdu->temp_data;
   1353 	if (rxpars == NULL) {
   1354 		DEBOUT(("No received parameters!\n"));
   1355 		return ISCSI_STATUS_NEGOTIATION_ERROR;
   1356 	}
   1357 	/* Note: There are always at least 2 extra bytes past temp_data_len */
   1358 	rxpars[rx_pdu->temp_data_len] = '\0';
   1359 	rxpars[rx_pdu->temp_data_len + 1] = '\0';
   1360 
   1361 	while (*rxpars) {
   1362 		if ((rxpars = get_parameter(rxpars, &rxp)) == NULL) {
   1363 			DEBOUT(("get_parameter returned error\n"));
   1364 			return ISCSI_STATUS_NEGOTIATION_ERROR;
   1365 		}
   1366 
   1367 		state->kflags[rxp.key] |= NS_RECEIVED;
   1368 
   1369 		switch (rxp.key) {
   1370 		case K_AuthMethod:
   1371 			if (state->auth_state != AUTH_INITIAL) {
   1372 				DEBOUT(("AuthMethod received, auth_state = %d\n",
   1373 						state->auth_state));
   1374 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1375 			}
   1376 
   1377 			/* Note: if the selection is None, we shouldn't be here,
   1378 			 * the target should have transited the state to op-neg.
   1379 			 */
   1380 			if (rxp.val.nval[0] != ISCSI_AUTH_CHAP) {
   1381 				DEBOUT(("AuthMethod isn't CHAP (%d)\n", rxp.val.nval[0]));
   1382 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1383 			}
   1384 
   1385 			state->auth_state = AUTH_METHOD_SELECTED;
   1386 			state->auth_alg = rxp.val.nval[0];
   1387 			break;
   1388 
   1389 		case K_Auth_CHAP_Algorithm:
   1390 			if (state->auth_state != AUTH_CHAP_ALG_SENT ||
   1391 				rxp.val.nval[0] != 5) {
   1392 				DEBOUT(("Bad algorithm, auth_state = %d, alg %d\n",
   1393 						state->auth_state, rxp.val.nval[0]));
   1394 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1395 			}
   1396 			break;
   1397 
   1398 		case K_Auth_CHAP_Challenge:
   1399 			if (state->auth_state != AUTH_CHAP_ALG_SENT || !rxp.list_num) {
   1400 				DEBOUT(("Bad Challenge, auth_state = %d, len %d\n",
   1401 						state->auth_state, rxp.list_num));
   1402 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1403 			}
   1404 			challenge = rxp.val.sval;
   1405 			challenge_size = rxp.list_num;
   1406 			break;
   1407 
   1408 		case K_Auth_CHAP_Identifier:
   1409 			if (state->auth_state != AUTH_CHAP_ALG_SENT) {
   1410 				DEBOUT(("Bad ID, auth_state = %d, id %d\n",
   1411 						state->auth_state, rxp.val.nval[0]));
   1412 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1413 			}
   1414 			identifier = (uint8_t) rxp.val.nval[0];
   1415 			break;
   1416 
   1417 		case K_Auth_CHAP_Name:
   1418 			if (state->auth_state != AUTH_CHAP_RSP_SENT) {
   1419 				DEBOUT(("Bad Name, auth_state = %d, name <%s>\n",
   1420 						state->auth_state, rxp.val.sval));
   1421 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1422 			}
   1423 			/* what do we do with the name?? */
   1424 			break;
   1425 
   1426 		case K_Auth_CHAP_Response:
   1427 			if (state->auth_state != AUTH_CHAP_RSP_SENT) {
   1428 				DEBOUT(("Bad Response, auth_state = %d, size %d\n",
   1429 						state->auth_state, rxp.list_num));
   1430 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1431 			}
   1432 			response = rxp.val.sval;
   1433 			response_size = rxp.list_num;
   1434 			if (response_size != CHAP_MD5_SIZE)
   1435 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1436 			break;
   1437 
   1438 		default:
   1439 			rc = eval_parameter(conn, state, &rxp);
   1440 			if (rc)
   1441 				return rc;
   1442 			break;
   1443 		}
   1444 	}
   1445 
   1446 	switch (state->auth_state) {
   1447 	case AUTH_INITIAL:
   1448 		DEBOUT(("Didn't receive Method\n"));
   1449 		return ISCSI_STATUS_NEGOTIATION_ERROR;
   1450 
   1451 	case AUTH_METHOD_SELECTED:
   1452 		set_key_n(state, K_Auth_CHAP_Algorithm, 5);
   1453 		state->auth_state = AUTH_CHAP_ALG_SENT;
   1454 		next = -1;
   1455 		break;
   1456 
   1457 	case AUTH_CHAP_ALG_SENT:
   1458 		if (!RX(state, K_Auth_CHAP_Algorithm) ||
   1459 			!RX(state, K_Auth_CHAP_Identifier) ||
   1460 			!RX(state, K_Auth_CHAP_Challenge)) {
   1461 			DEBOUT(("Didn't receive all parameters\n"));
   1462 			return ISCSI_STATUS_NEGOTIATION_ERROR;
   1463 		}
   1464 
   1465 		set_key_s(state, K_Auth_CHAP_Name, state->user_name);
   1466 
   1467 		chap_md5_response(state->temp_buf, identifier, state->password,
   1468 						  challenge, challenge_size);
   1469 
   1470 		cpar = set_key_s(state, K_Auth_CHAP_Response, state->temp_buf);
   1471 		if (cpar != NULL)
   1472 			cpar->list_num = CHAP_MD5_SIZE;
   1473 
   1474 		if (par->auth_info.mutual_auth) {
   1475 			if (!state->target_password[0]) {
   1476 				DEBOUT(("No target password with mutual authentication!\n"));
   1477 				return ISCSI_STATUS_PARAMETER_MISSING;
   1478 			}
   1479 
   1480 			cprng_strong(kern_cprng,
   1481 				     &state->temp_buf[CHAP_MD5_SIZE],
   1482 				     CHAP_CHALLENGE_LEN + 1, 0);
   1483 			set_key_n(state, K_Auth_CHAP_Identifier,
   1484 					  state->temp_buf[CHAP_MD5_SIZE]);
   1485 			cpar = set_key_s(state, K_Auth_CHAP_Challenge,
   1486 							 &state->temp_buf[CHAP_MD5_SIZE + 1]);
   1487 			if (cpar != NULL)
   1488 				cpar->list_num = CHAP_CHALLENGE_LEN;
   1489 			next = -1;
   1490 		}
   1491 		state->auth_state = AUTH_CHAP_RSP_SENT;
   1492 		break;
   1493 
   1494 	case AUTH_CHAP_RSP_SENT:
   1495 		/* we can only be here for mutual authentication */
   1496 		if (!par->auth_info.mutual_auth || response == NULL) {
   1497 			DEBOUT(("Mutual authentication not requested\n"));
   1498 			return ISCSI_STATUS_NEGOTIATION_ERROR;
   1499 		}
   1500 
   1501 		chap_md5_response(state->temp_buf,
   1502 				state->temp_buf[CHAP_MD5_SIZE],
   1503 				state->password,
   1504 				&state->temp_buf[CHAP_MD5_SIZE + 1],
   1505 				CHAP_CHALLENGE_LEN);
   1506 
   1507 		if (memcmp(state->temp_buf, response, response_size)) {
   1508 			DEBOUT(("Mutual authentication mismatch\n"));
   1509 			return ISCSI_STATUS_AUTHENTICATION_FAILED;
   1510 		}
   1511 		break;
   1512 
   1513 	default:
   1514 		break;
   1515 	}
   1516 
   1517 	complete_pars(state, tx_pdu);
   1518 
   1519 	return next;
   1520 }
   1521 
   1522 
   1523 /*
   1524  * set_first_opnegs:
   1525  *    Set the operational negotiation parameters we want to negotiate in
   1526  *    the first login request in op_neg phase.
   1527  *
   1528  *    Parameter:
   1529  *          conn     The connection
   1530  *          state    Negotiation state
   1531  */
   1532 
   1533 STATIC void
   1534 set_first_opnegs(connection_t *conn, negotiation_state_t *state)
   1535 {
   1536 	iscsi_login_parameters_t *lpar = conn->login_par;
   1537 	negotiation_parameter_t *cpar;
   1538 
   1539     /* Digests - suggest None,CRC32C unless the user forces a value */
   1540 	cpar = set_key_n(state, K_HeaderDigest,
   1541 					 (lpar->is_present.HeaderDigest) ? lpar->HeaderDigest : 0);
   1542 	if (cpar != NULL && !lpar->is_present.HeaderDigest) {
   1543 		cpar->list_num = 2;
   1544 		cpar->val.nval[1] = 1;
   1545 	}
   1546 
   1547 	cpar = set_key_n(state, K_DataDigest, (lpar->is_present.DataDigest)
   1548 		? lpar->DataDigest : 0);
   1549 	if (cpar != NULL && !lpar->is_present.DataDigest) {
   1550 		cpar->list_num = 2;
   1551 		cpar->val.nval[1] = 1;
   1552 	}
   1553 
   1554 	set_key_n(state, K_MaxRecvDataSegmentLength,
   1555 		conn->Our_MaxRecvDataSegmentLength);
   1556 	/* This is direction-specific, we may have a different default */
   1557 	state->MaxRecvDataSegmentLength =
   1558 		entries[K_MaxRecvDataSegmentLength].defval;
   1559 
   1560 	/* First connection only */
   1561 	if (!conn->session->TSIH) {
   1562 		state->ErrorRecoveryLevel =
   1563 			(lpar->is_present.ErrorRecoveryLevel) ? lpar->ErrorRecoveryLevel
   1564 												  : 2;
   1565 		/*
   1566 		   Negotiate InitialR2T to FALSE and ImmediateData to TRUE, should
   1567 		   be slightly more efficient than the default InitialR2T=TRUE.
   1568 		 */
   1569 		state->InitialR2T = FALSE;
   1570 		state->ImmediateData = TRUE;
   1571 
   1572 		/* We don't really care about this, so don't negotiate by default */
   1573 		state->MaxBurstLength = entries[K_MaxBurstLength].defval;
   1574 		state->FirstBurstLength = entries[K_FirstBurstLength].defval;
   1575 		state->MaxOutstandingR2T = entries[K_MaxOutstandingR2T].defval;
   1576 
   1577 		set_key_n(state, K_ErrorRecoveryLevel, state->ErrorRecoveryLevel);
   1578 		set_key_n(state, K_InitialR2T, state->InitialR2T);
   1579 		set_key_n(state, K_ImmediateData, state->ImmediateData);
   1580 
   1581 		if (lpar->is_present.MaxConnections) {
   1582 			state->MaxConnections = lpar->MaxConnections;
   1583 			set_key_n(state, K_MaxConnections, lpar->MaxConnections);
   1584 		}
   1585 
   1586 		if (lpar->is_present.DefaultTime2Wait)
   1587 			set_key_n(state, K_DefaultTime2Wait, lpar->DefaultTime2Wait);
   1588 		else
   1589 			state->DefaultTime2Wait = entries[K_DefaultTime2Wait].defval;
   1590 
   1591 		if (lpar->is_present.DefaultTime2Retain)
   1592 			set_key_n(state, K_DefaultTime2Retain, lpar->DefaultTime2Retain);
   1593 		else
   1594 			state->DefaultTime2Retain = entries[K_DefaultTime2Retain].defval;
   1595 	} else
   1596 		init_session_parameters(conn->session, state);
   1597 
   1598 	DEBC(conn, 10, ("SetFirstOpnegs: recover=%d, MRDSL=%d\n",
   1599 		conn->recover, state->MaxRecvDataSegmentLength));
   1600 }
   1601 
   1602 
   1603 /*
   1604  * assemble_negotiation_parameters:
   1605  *    Assemble any negotiation parameters requested by the other side.
   1606  *
   1607  *    Parameter:
   1608  *          conn     The connection
   1609  *          ccb      The login ccb
   1610  *          rx_pdu   The received login response PDU
   1611  *          tx_pdu   The transmit PDU
   1612  *
   1613  *    Returns:    0     On success
   1614  *                > 0   (an ISCSI error code) if an error occurred.
   1615  */
   1616 
   1617 int
   1618 assemble_negotiation_parameters(connection_t *conn, ccb_t *ccb, pdu_t *rx_pdu,
   1619 							    pdu_t *tx_pdu)
   1620 {
   1621 	negotiation_state_t *state = (negotiation_state_t *) ccb->temp_data;
   1622 	negotiation_parameter_t rxp;
   1623 	uint8_t *rxpars;
   1624 	int rc;
   1625 
   1626 	state->num_pars = 0;
   1627 
   1628 	DEBC(conn, 10, ("AsmNegParams: connState=%d, MRDSL=%d\n",
   1629 		conn->state, state->MaxRecvDataSegmentLength));
   1630 
   1631 	if (conn->state == ST_SEC_NEG) {
   1632 		conn->state = ST_OP_NEG;
   1633 		set_first_opnegs(conn, state);
   1634 	}
   1635 
   1636 	rxpars = (uint8_t *) rx_pdu->temp_data;
   1637 	if (rxpars != NULL) {
   1638 		/* Note: There are always at least 2 extra bytes past temp_data_len */
   1639 		rxpars[rx_pdu->temp_data_len] = '\0';
   1640 		rxpars[rx_pdu->temp_data_len + 1] = '\0';
   1641 
   1642 		while (*rxpars) {
   1643 			if ((rxpars = get_parameter(rxpars, &rxp)) == NULL)
   1644 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1645 
   1646 			rc = eval_parameter(conn, state, &rxp);
   1647 			if (rc)
   1648 				return rc;
   1649 		}
   1650 	}
   1651 
   1652 	if (tx_pdu == NULL)
   1653 		return 0;
   1654 
   1655 	complete_pars(state, tx_pdu);
   1656 
   1657 	return 0;
   1658 }
   1659 
   1660 /*
   1661  * init_text_parameters:
   1662  *    Initialize text negotiation.
   1663  *
   1664  *    Parameter:
   1665  *          conn     The connection
   1666  *          tx_pdu   The transmit PDU
   1667  *
   1668  *    Returns:    0     On success
   1669  *                > 0   (an ISCSI error code) if an error occurred.
   1670  */
   1671 
   1672 int
   1673 init_text_parameters(connection_t *conn, ccb_t *ccb)
   1674 {
   1675 	negotiation_state_t *state;
   1676 
   1677 	state = malloc(sizeof(*state), M_TEMP, M_WAITOK | M_ZERO);
   1678 	if (state == NULL) {
   1679 		DEBOUT(("*** Out of memory in init_text_params\n"));
   1680 		return ISCSI_STATUS_NO_RESOURCES;
   1681 	}
   1682 	ccb->temp_data = state;
   1683 
   1684 	state->HeaderDigest = conn->HeaderDigest;
   1685 	state->DataDigest = conn->DataDigest;
   1686 	state->MaxRecvDataSegmentLength = conn->MaxRecvDataSegmentLength;
   1687 	init_session_parameters(conn->session, state);
   1688 
   1689 	return 0;
   1690 }
   1691 
   1692 
   1693 /*
   1694  * assemble_send_targets:
   1695  *    Assemble send targets request
   1696  *
   1697  *    Parameter:
   1698  *          pdu      The transmit PDU
   1699  *          val      The SendTargets key value
   1700  *
   1701  *    Returns:    0     On success
   1702  *                > 0   (an ISCSI error code) if an error occurred.
   1703  */
   1704 
   1705 int
   1706 assemble_send_targets(pdu_t *pdu, uint8_t *val)
   1707 {
   1708 	negotiation_parameter_t par;
   1709 	uint8_t *buf;
   1710 	int len;
   1711 
   1712 	par.key = K_SendTargets;
   1713 	par.list_num = 1;
   1714 	par.val.sval = val;
   1715 
   1716 	len = parameter_size(&par);
   1717 
   1718 	if ((buf = malloc(len, M_TEMP, M_WAITOK)) == NULL) {
   1719 		DEBOUT(("*** Out of memory in assemble_send_targets\n"));
   1720 		return ISCSI_STATUS_NO_RESOURCES;
   1721 	}
   1722 	pdu->temp_data = buf;
   1723 	pdu->temp_data_len = len;
   1724 
   1725 	if (put_parameter(buf, len, &par) == 0)
   1726 		return ISCSI_STATUS_PARAMETER_INVALID;
   1727 
   1728 	return 0;
   1729 }
   1730 
   1731 
   1732 /*
   1733  * set_negotiated_parameters:
   1734  *    Copy the negotiated parameters into the connection and session structure.
   1735  *
   1736  *    Parameter:
   1737  *          ccb      The ccb containing the state information
   1738  */
   1739 
   1740 void
   1741 set_negotiated_parameters(ccb_t *ccb)
   1742 {
   1743 	negotiation_state_t *state = (negotiation_state_t *) ccb->temp_data;
   1744 	connection_t *conn = ccb->connection;
   1745 	session_t *sess = ccb->session;
   1746 
   1747 	conn->HeaderDigest = state->HeaderDigest;
   1748 	conn->DataDigest = state->DataDigest;
   1749 	sess->ErrorRecoveryLevel = state->ErrorRecoveryLevel;
   1750 	sess->InitialR2T = state->InitialR2T;
   1751 	sess->ImmediateData = state->ImmediateData;
   1752 	conn->MaxRecvDataSegmentLength = state->MaxRecvDataSegmentLength;
   1753 	sess->MaxConnections = state->MaxConnections;
   1754 	sess->DefaultTime2Wait = conn->Time2Wait = state->DefaultTime2Wait;
   1755 	sess->DefaultTime2Retain = conn->Time2Retain =
   1756 		state->DefaultTime2Retain;
   1757 
   1758 	/* set idle connection timeout to half the Time2Retain window so we */
   1759 	/* don't miss it, unless Time2Retain is ridiculously small. */
   1760 	conn->idle_timeout_val = (conn->Time2Retain >= 10) ?
   1761 		(conn->Time2Retain / 2) * hz : CONNECTION_IDLE_TIMEOUT;
   1762 
   1763 	sess->MaxBurstLength = state->MaxBurstLength;
   1764 	sess->FirstBurstLength = state->FirstBurstLength;
   1765 	sess->MaxOutstandingR2T = state->MaxOutstandingR2T;
   1766 
   1767 	DEBC(conn, 10,("SetNegPar: MRDSL=%d, MBL=%d, FBL=%d, IR2T=%d, ImD=%d\n",
   1768 		state->MaxRecvDataSegmentLength, state->MaxBurstLength,
   1769 		state->FirstBurstLength, state->InitialR2T,
   1770 		state->ImmediateData));
   1771 
   1772 	conn->max_transfer = min(sess->MaxBurstLength, conn->MaxRecvDataSegmentLength);
   1773 
   1774 	conn->max_firstimmed = (!sess->ImmediateData) ? 0 :
   1775 				min(sess->FirstBurstLength, conn->max_transfer);
   1776 
   1777 	conn->max_firstdata = (sess->InitialR2T || sess->FirstBurstLength < conn->max_firstimmed) ? 0 :
   1778 				min(sess->FirstBurstLength - conn->max_firstimmed, conn->max_transfer);
   1779 
   1780 }
   1781