Check-in [e58f2c78c8]
Overview
Comment:Code updates for gcc warnings
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | crypto
Files: files | file ages | folders
SHA3-256: e58f2c78c8eb66766a80ff55a2b1df3d0c3ada80cf30acdc6db36e2327f216c6
User & Date: bohagan on 2024-02-04 23:25:44
Other Links: branch diff | manifest | tags
Context
2024-02-05
01:37
Added provider command to load non-default providers in OpenSSL 3.0 check-in: b6001442d1 user: bohagan tags: crypto
2024-02-04
23:25
Code updates for gcc warnings check-in: e58f2c78c8 user: bohagan tags: crypto
03:31
Merged changes from master branch check-in: fa17431520 user: bohagan tags: crypto
Changes
294
295
296
297
298
299
300

301
302
303

304
305
306
307
308
309
310
311
312

313
314
315
316
317
318
319
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313

314
315
316
317
318
319
320
321







+



+








-
+







	break;
    case SSL3_RT_HANDSHAKE:
	type = "Handshake";
	break;
    case SSL3_RT_APPLICATION_DATA:
	type = "App Data";
	break;
#if OPENSSL_VERSION_NUMBER < 0x30000000L
    case DTLS1_RT_HEARTBEAT:
	type = "Heartbeat";
	break;
#endif
    default:
	type = "unknown";
    }

    /* Needs compile time option "enable-ssl-trace". */
    if ((bio = BIO_new(BIO_s_mem())) != NULL) {
	int n;
	SSL_trace(write_p, version, content_type, buf, len, ssl, (void *)bio);
	n = BIO_read(bio, buffer, min(BIO_pending(bio), 14999));
	n = BIO_read(bio, buffer, BIO_pending(bio) < 15000 ? BIO_pending(bio) : 14999);
	n = (n<0) ? 0 : n;
	buffer[n] = 0;
	(void)BIO_flush(bio);
	BIO_free(bio);
   }

    /* Create command to eval */
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
482
483
484
485
486
487
488

489
490
491
492
493
494
495







-







 *	none
 *
 *-------------------------------------------------------------------
 */
void KeyLogCallback(const SSL *ssl, const char *line) {
    char *str = getenv(SSLKEYLOGFILE);
    FILE *fd;
    (void *) ssl;

    dprintf("Called");

    if (str) {
	fd = fopen(str, "a");
	fprintf(fd, "%s\n",line);
	fclose(fd);
593
594
595
596
597
598
599
600

601
602
603
604
605
606
607
594
595
596
597
598
599
600

601
602
603
604
605
606
607
608







-
+







 * Return codes:
 *	0 = error where session will be immediately removed from the internal cache.
 *	1 = success where app retains session in session cache, and must call SSL_SESSION_free() when done.
 *
 *-------------------------------------------------------------------
 */
static int
SessionCallback(const SSL *ssl, SSL_SESSION *session) {
SessionCallback(SSL *ssl, SSL_SESSION *session) {
    State *statePtr = (State*)SSL_get_app_data((SSL *)ssl);
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    const unsigned char *ticket;
    const unsigned char *session_id;
    size_t len2;
    unsigned int ulen;
660
661
662
663
664
665
666
667

668
669
670
671
672
673
674
675
676
677
678
679
680
681

682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699

700
701
702
703
704
705
706
661
662
663
664
665
666
667

668
669
670
671
672
673
674
675
676
677
678
679
680
681

682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699

700
701
702
703
704
705
706
707







-
+













-
+

















-
+







 *	    supplied list and the server configuration. The connection will be aborted.
 *	SSL_TLSEXT_ERR_NOACK: ALPN protocol not selected, e.g., because no ALPN
 *	    protocols are configured for this connection. The connection continues.
 *
 *-------------------------------------------------------------------
 */
static int
ALPNCallback(const SSL *ssl, const unsigned char **out, unsigned char *outlen,
ALPNCallback(SSL *ssl, const unsigned char **out, unsigned char *outlen,
	const unsigned char *in, unsigned int inlen, void *arg) {
    State *statePtr = (State*)arg;
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    int code, res;

    dprintf("Called");

    if (ssl == NULL || arg == NULL) {
	return SSL_TLSEXT_ERR_NOACK;
    }

    /* Select protocol */
    if (SSL_select_next_proto(out, outlen, statePtr->protos, statePtr->protos_len,
    if (SSL_select_next_proto((unsigned char **) out, outlen, statePtr->protos, statePtr->protos_len,
	in, inlen) == OPENSSL_NPN_NEGOTIATED) {
	/* Match found */
	res = SSL_TLSEXT_ERR_OK;
    } else {
	/* OPENSSL_NPN_NO_OVERLAP = No overlap, so use first item from client protocol list */
	res = SSL_TLSEXT_ERR_NOACK;
    }

    if (statePtr->vcmd == (Tcl_Obj*)NULL) {
	return res;
    }

    /* Create command to eval */
    cmdPtr = Tcl_DuplicateObj(statePtr->vcmd);
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj("alpn", -1));
    Tcl_ListObjAppendElement(interp, cmdPtr,
	    Tcl_NewStringObj(Tcl_GetChannelName(statePtr->self), -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj(*out, -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewStringObj((const char *) *out, -1));
    Tcl_ListObjAppendElement(interp, cmdPtr, Tcl_NewBooleanObj(res == SSL_TLSEXT_ERR_OK));

    /* Eval callback command */
    Tcl_IncrRefCount(cmdPtr);
    if ((code = EvalCallback(interp, statePtr, cmdPtr)) > 1) {
	res = SSL_TLSEXT_ERR_NOACK;
    } else if (code == 1) {
782
783
784
785
786
787
788
789

790
791
792
793
794
795
796
783
784
785
786
787
788
789

790
791
792
793
794
795
796
797







-
+







 */
static int
SNICallback(const SSL *ssl, int *alert, void *arg) {
    State *statePtr = (State*)arg;
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    int code, res;
    char *servername = NULL;
    const char *servername = NULL;

    dprintf("Called");

    if (ssl == NULL || arg == NULL) {
	return SSL_TLSEXT_ERR_NOACK;
    }

849
850
851
852
853
854
855
856

857
858
859
860
861
862
863
850
851
852
853
854
855
856

857
858
859
860
861
862
863
864







-
+







 *	SSL_CLIENT_HELLO_RETRY: suspend the handshake, and the handshake function will return immediately
 *	SSL_CLIENT_HELLO_ERROR: failure, terminate connection. Set alert to error code.
 *	SSL_CLIENT_HELLO_SUCCESS: success
 *
 *-------------------------------------------------------------------
 */
static int
HelloCallback(const SSL *ssl, int *alert, void *arg) {
HelloCallback(SSL *ssl, int *alert, void *arg) {
    State *statePtr = (State*)arg;
    Tcl_Interp *interp	= statePtr->interp;
    Tcl_Obj *cmdPtr;
    int code, res;
    const char *servername;
    const unsigned char *p;
    size_t len, remaining;
2084
2085
2086
2087
2088
2089
2090
2091

2092
2093
2094
2095
2096
2097
2098
2085
2086
2087
2088
2089
2090
2091

2092
2093
2094
2095
2096
2097
2098
2099







-
+







	/* Get SNI requested server name */
	LAPPEND_STR(interp, objPtr, "servername", SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name), -1);

	/* Get protocol */
	LAPPEND_STR(interp, objPtr, "protocol", SSL_get_version(ssl), -1);

	/* Renegotiation allowed */
	LAPPEND_BOOL(interp, objPtr, "renegotiation_allowed", SSL_get_secure_renegotiation_support(ssl));
	LAPPEND_BOOL(interp, objPtr, "renegotiation_allowed", SSL_get_secure_renegotiation_support((SSL *) ssl));

	/* Get security level */
	LAPPEND_INT(interp, objPtr, "security_level", SSL_get_security_level(ssl));

	/* Session info */
	LAPPEND_BOOL(interp, objPtr, "session_reused", SSL_session_reused(ssl));

2158
2159
2160
2161
2162
2163
2164
2165

2166
2167
2168
2169
2170
2171
2172
2159
2160
2161
2162
2163
2164
2165

2166
2167
2168
2169
2170
2171
2172
2173







-
+







    /* Session info */
    session = SSL_get_session(ssl);
    if (session != NULL) {
	const unsigned char *ticket;
	size_t len2;
	unsigned int ulen;
	const unsigned char *session_id, *proto;
	char buffer[SSL_MAX_MASTER_KEY_LENGTH];
	unsigned char buffer[SSL_MAX_MASTER_KEY_LENGTH];

	/* Report the selected protocol as a result of the ALPN negotiation */
	SSL_SESSION_get0_alpn_selected(session, &proto, &len2);
	LAPPEND_STR(interp, objPtr, "alpn", (char *) proto, (Tcl_Size) len2);

	/* Report the selected protocol as a result of the NPN negotiation */
#ifdef USE_NPN
2195
2196
2197
2198
2199
2200
2201

2202

2203

2204
2205
2206
2207
2208
2209
2210
2196
2197
2198
2199
2200
2201
2202
2203

2204
2205
2206
2207
2208
2209
2210
2211
2212
2213







+
-
+

+







	SSL_SESSION_get0_ticket(session, &ticket, &len2);
	LAPPEND_BARRAY(interp, objPtr, "session_ticket", ticket, (Tcl_Size) len2);

	/* Session ticket lifetime hint (in seconds) */
	LAPPEND_LONG(interp, objPtr, "lifetime", SSL_SESSION_get_ticket_lifetime_hint(session));

	/* Ticket app data */
#if OPENSSL_VERSION_NUMBER < 0x30000000L
	SSL_SESSION_get0_ticket_appdata(session, &ticket, &len2);
	SSL_SESSION_get0_ticket_appdata((SSL_SESSION *) session, &ticket, &len2);
	LAPPEND_BARRAY(interp, objPtr, "ticket_app_data", ticket, (Tcl_Size) len2);
#endif

	/* Get master key */
	len2 = SSL_SESSION_get_master_key(session, buffer, SSL_MAX_MASTER_KEY_LENGTH);
	LAPPEND_BARRAY(interp, objPtr, "master_key", buffer, (Tcl_Size) len2);

	/* Compression id */
	unsigned int id = SSL_SESSION_get_compress_id(session);
148
149
150
151
152
153
154
155

156
157
158
159
160
161
162
163
164
148
149
150
151
152
153
154

155
156

157
158
159
160
161
162
163







-
+

-







 *-------------------------------------------------------------------
 */
int DigestInitialize(Tcl_Interp *interp, DigestState *statePtr, Tcl_Obj *digestObj,
	Tcl_Obj *cipherObj, Tcl_Obj *keyObj, Tcl_Obj *macObj) {
    int res = 0, type = statePtr->format & 0xFF0;
    const EVP_MD *md = NULL;
    const EVP_CIPHER *cipher = NULL;
    const void *key = NULL, *iv = NULL, *salt = NULL;
    const void *key = NULL;
    Tcl_Size key_len = 0;
    (void *) macObj;

    dprintf("Called");

    /* Get digest */
    md = Util_GetDigest(interp, digestObj, type != TYPE_CMAC);
    if (md == NULL && type != TYPE_CMAC) {
	return TCL_ERROR;
239
240
241
242
243
244
245
246

247
248
249
250
251
252
253
238
239
240
241
242
243
244

245
246
247
248
249
250
251
252







-
+







    dprintf("Called");

    switch(statePtr->format & 0xFF0) {
    case TYPE_MD:
        res = EVP_DigestUpdate(statePtr->ctx, buf, (size_t) read);
	break;
    case TYPE_HMAC:
        res = HMAC_Update(statePtr->hctx, buf, (size_t) read);
        res = HMAC_Update(statePtr->hctx, (const unsigned char *) buf, (size_t) read);
	break;
    case TYPE_CMAC:
        res = CMAC_Update(statePtr->cctx, buf, (size_t) read);
	break;
    }

    if (!res && do_result) {
397
398
399
400
401
402
403
404




405
406
407
408
409
410
411
396
397
398
399
400
401
402

403
404
405
406
407
408
409
410
411
412
413







-
+
+
+
+







    if (!(statePtr->flags & CHAN_EOF)) {
	Tcl_Channel parent = Tcl_GetStackedChannel(statePtr->self);
	Tcl_Obj *resultObj;
	Tcl_Size written, toWrite;

	if (DigestFinalize(statePtr->interp, statePtr, &resultObj) == TCL_OK) {
	    unsigned char *data = Tcl_GetByteArrayFromObj(resultObj, &toWrite);
	    written = Tcl_WriteRaw(parent, data, toWrite);
	    written = Tcl_WriteRaw(parent, (const char *) data, toWrite);
            if (written != toWrite) {
                /* Error */
            }
	    Tcl_DecrRefCount(resultObj);
	}
	statePtr->flags |= CHAN_EOF;
    }

    /* Clean-up */
    DigestStateFree(statePtr);
512
513
514
515
516
517
518
519

520
521
522
523
524
525
526
514
515
516
517
518
519
520

521
522
523
524
525
526
527
528







-
+








    /* Abort if nothing to process */
    if (toWrite <= 0 || statePtr->self == (Tcl_Channel) NULL) {
	return 0;
    }

    /* Update hash function */
    if (DigestUpdate(statePtr, buf, (Tcl_Size) toWrite, 0) != TCL_OK) {
    if (DigestUpdate(statePtr, (char *) buf, (Tcl_Size) toWrite, 0) != TCL_OK) {
	Tcl_SetChannelError(statePtr->self, Tcl_ObjPrintf("Update failed: %s", GET_ERR_REASON()));
	*errorCodePtr = EINVAL;
	return 0;
    }
    return toWrite;
}

900
901
902
903
904
905
906
907

908
909
910
911
912
913
914
902
903
904
905
906
907
908

909
910
911
912
913
914
915
916







-
+







 *
 *-------------------------------------------------------------------
 */
int DigestInstanceObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]) {
    DigestState *statePtr = (DigestState *) clientData;
    int fn;
    Tcl_Size data_len = 0;
    char *data = NULL;
    unsigned char *data = NULL;
    static const char *instance_fns [] = { "finalize", "update", NULL };

    dprintf("Called");

    /* Validate arg count */
    if (objc < 2 || objc > 3) {
	Tcl_WrongNumArgs(interp, 1, objv, "function ?data?");
927
928
929
930
931
932
933
934

935
936
937
938
939
940
941
929
930
931
932
933
934
935

936
937
938
939
940
941
942
943







-
+







	    data = Tcl_GetByteArrayFromObj(objv[2], &data_len);
	} else {
	    Tcl_WrongNumArgs(interp, 1, objv, "update data");
	    return TCL_ERROR;
	}

	/* Update hash function */
	if (DigestUpdate(statePtr, data, data_len, 1) != TCL_OK) {
	if (DigestUpdate(statePtr, (char *) data, data_len, 1) != TCL_OK) {
	    return TCL_ERROR;
	}

    } else {
	/* Finalize hash function and calculate message digest */
	if (DigestFinalize(interp, statePtr, NULL) != TCL_OK) {
	    return TCL_ERROR;
1030
1031
1032
1033
1034
1035
1036
1037

1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058

1059
1060
1061
1062
1063
1064
1065
1032
1033
1034
1035
1036
1037
1038

1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059

1060
1061
1062
1063
1064
1065
1066
1067







-
+




















-
+







 * Side effects:
 *	Sets result to message digest or error message
 *
 *-------------------------------------------------------------------
 */
int DigestDataHandler(Tcl_Interp *interp, Tcl_Obj *dataObj, Tcl_Obj *digestObj,
	Tcl_Obj *cipherObj, int format, Tcl_Obj *keyObj, Tcl_Obj *macObj) {
    char *data;
    unsigned char *data;
    Tcl_Size data_len;
    DigestState *statePtr;

    dprintf("Called");

    /* Get data */
    data = Tcl_GetByteArrayFromObj(dataObj, &data_len);
    if (data == NULL) {
	Tcl_SetResult(interp, "No data", NULL);
	return TCL_ERROR;
    }

    /* Create state data structure */
    if ((statePtr = DigestStateNew(interp, format)) == NULL) {
	Tcl_AppendResult(interp, "Memory allocation error", (char *) NULL);
	return TCL_ERROR;
    }

    /* Calc Digest */
    if (DigestInitialize(interp, statePtr, digestObj, cipherObj, keyObj, macObj) != TCL_OK ||
	DigestUpdate(statePtr, data, data_len, 1) != TCL_OK ||
	DigestUpdate(statePtr, (char *) data, data_len, 1) != TCL_OK ||
	DigestFinalize(interp, statePtr, NULL) != TCL_OK) {
	DigestStateFree(statePtr);
	return TCL_ERROR;
    }

    /* Clean-up */
    DigestStateFree(statePtr);
1116
1117
1118
1119
1120
1121
1122
1123

1124
1125
1126
1127
1128
1129
1130
1118
1119
1120
1121
1122
1123
1124

1125
1126
1127
1128
1129
1130
1131
1132







-
+







	goto done;
    }

    /* Read file data and update hash function */
    while (!Tcl_Eof(chan)) {
	Tcl_Size len = Tcl_ReadRaw(chan, (char *) buf, BUFFER_SIZE);
	if (len > 0) {
	    if ((res = DigestUpdate(statePtr, &buf[0], len, 1)) != TCL_OK) {
	    if ((res = DigestUpdate(statePtr, (char *) &buf[0], len, 1)) != TCL_OK) {
		goto done;
	    }
	}
    }

    /* Finalize hash function and calculate message digest */
    res = DigestFinalize(interp, statePtr, NULL);
134
135
136
137
138
139
140
141

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161

162
163

164
165
166
167
168
169
170

171
172

173
174
175
176
177
178
179
134
135
136
137
138
139
140

141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160

161
162

163
164
165
166
167
168
169

170
171

172
173
174
175
176
177
178
179







-
+



















-
+

-
+






-
+

-
+







 *	No result or error message
 *
 *-------------------------------------------------------------------
 */
int EncryptInitialize(Tcl_Interp *interp, int type, EVP_CIPHER_CTX **ctx,
	Tcl_Obj *cipherObj, Tcl_Obj *keyObj, Tcl_Obj *ivObj) {
    const EVP_CIPHER *cipher;
    char *keyString = NULL, *ivString = NULL;
    void *keyString = NULL, *ivString = NULL;
    Tcl_Size key_len = 0, iv_len = 0;
    int res, max;
    unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];

    dprintf("Called");

    /* Init buffers */
    memset(key, 0, EVP_MAX_KEY_LENGTH);
    memset(iv, 0, EVP_MAX_IV_LENGTH);

    /* Get cipher */
    cipher = Util_GetCipher(interp, cipherObj, 1);
    if (cipher == NULL) {
	return TCL_ERROR;
    }

    /*  Get key - Only support internally defined cipher lengths.
	Custom ciphers can be up to size_t bytes. */
    max = EVP_CIPHER_key_length(cipher);
    keyString = (const void *) Util_GetKey(interp, keyObj, &key_len, "key", max, FALSE);
    keyString = Util_GetKey(interp, keyObj, &key_len, "key", max, 0);
    if (keyString != NULL) {
	memcpy((void *) key, (const void *) keyString, (size_t) key_len);
	memcpy((void *) key, keyString, (size_t) key_len);
    } else if (keyObj != NULL)  {
	return TCL_ERROR;
    }

    /*  Get IV */
    max = EVP_CIPHER_iv_length(cipher);
    ivString = (const void *) Util_GetIV(interp, ivObj, &iv_len, max, FALSE);
    ivString = Util_GetIV(interp, ivObj, &iv_len, max, 0);
    if (ivString != NULL) {
	memcpy((void *) iv, (const void *) ivString, (size_t) iv_len);
	memcpy((void *) iv, ivString, (size_t) iv_len);
    } else if (ivObj != NULL) {
	return TCL_ERROR;
    }

    /* Create context */
    if((*ctx = EVP_CIPHER_CTX_new()) == NULL) {
	Tcl_AppendResult(interp, "Memory allocation error", (char *) NULL);
397
398
399
400
401
402
403
404

405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424

425
426
427
428
429
430
431
397
398
399
400
401
402
403

404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423

424
425
426
427
428
429
430
431







-
+



















-
+







    in_buf = Tcl_Alloc((Tcl_Size) toRead);
    parent = Tcl_GetStackedChannel(statePtr->self);
    read = Tcl_ReadRaw(parent, in_buf, (Tcl_Size) toRead);

    /* Update function */
    if (read > 0) {
	/* Have data - Update function */
	if (EncryptUpdate(statePtr->interp, statePtr->type, statePtr->ctx, buf, &out_len, in_buf, read) == TCL_OK) {
	if (EncryptUpdate(statePtr->interp, statePtr->type, statePtr->ctx, (unsigned char *) buf, &out_len, (unsigned char *) in_buf, read) == TCL_OK) {
	    /* If have data, put in buf, otherwise tell TCL to try again */
	    if (out_len > 0) {
		read = (Tcl_Size) out_len;
	    } else {
		*errorCodePtr = EAGAIN;
		read = -1;
	    }
	} else {
	    Tcl_SetChannelError(statePtr->self, Tcl_ObjPrintf("Update failed: %s", GET_ERR_REASON()));
	    *errorCodePtr = EINVAL;
	    read = 0;
	}

    } else if (read < 0) {
	/* Error */
	*errorCodePtr = Tcl_GetErrno();

    } else if (!(statePtr->flags & CHAN_EOF)) {
	/* EOF - Finalize function and put any remaining data in buf */
	if (EncryptFinalize(statePtr->interp, statePtr->type, statePtr->ctx, buf, &out_len) == TCL_OK) {
	if (EncryptFinalize(statePtr->interp, statePtr->type, statePtr->ctx, (unsigned char *) buf, &out_len) == TCL_OK) {
	    read = (Tcl_Size) out_len;
	} else {
	    Tcl_SetChannelError(statePtr->self, Tcl_ObjPrintf("Finalize failed: %s", GET_ERR_REASON()));
	    *errorCodePtr = EINVAL;
	    read = 0;
	}

462
463
464
465
466
467
468
469

470
471
472
473
474
475
476
462
463
464
465
466
467
468

469
470
471
472
473
474
475
476







-
+







    if (toWrite <= 0 || statePtr->self == (Tcl_Channel) NULL) {
	return 0;
    }

    out_buf = Tcl_Alloc((Tcl_Size) toWrite+EVP_MAX_BLOCK_LENGTH);

    /* Update function */
    if (EncryptUpdate(statePtr->interp, statePtr->type, statePtr->ctx, out_buf, &out_len, buf, (Tcl_Size) toWrite) == TCL_OK) {
    if (EncryptUpdate(statePtr->interp, statePtr->type, statePtr->ctx, (unsigned char *) out_buf, &out_len, (unsigned char *) buf, (Tcl_Size) toWrite) == TCL_OK) {
	/* If have data, output it, otherwise tell TCL to try again */
	if (out_len > 0) {
	    Tcl_Channel parent = Tcl_GetStackedChannel(statePtr->self);
	    write = (int) Tcl_WriteRaw(parent, (const char *) out_buf, (Tcl_Size) out_len);
	    write = toWrite;
	} else {
	    *errorCodePtr = EAGAIN;
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
740
741
742
743
744
745
746

747
748
749
750
751
752
753







-







 *----------------------------------------------------------------------
 */
static int EncryptChannelHandler(Tcl_Interp *interp, int type, const char *channel,
	Tcl_Obj *cipherObj, Tcl_Obj *digestObj, Tcl_Obj *keyObj, Tcl_Obj *ivObj) {
    int mode; /* OR-ed combination of TCL_READABLE and TCL_WRITABLE */
    Tcl_Channel chan;
    EncryptState *statePtr;
    (void *) digestObj;

    dprintf("Called");

    /* Validate args */
    if (channel == (const char *) NULL) {
	Tcl_AppendResult(interp, "No channel", (char *) NULL);
	return TCL_ERROR;
860
861
862
863
864
865
866
867

868
869
870
871
872
873
874
859
860
861
862
863
864
865

866
867
868
869
870
871
872
873







-
+







 *
 *-------------------------------------------------------------------
 */
int EncryptInstanceObjCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]) {
    EncryptState *statePtr = (EncryptState *) clientData;
    int fn, out_len;
    Tcl_Size data_len = 0;
    char *data = NULL;
    unsigned char *data = NULL;
    Tcl_Obj *resultObj;
    unsigned char *out_buf;
    static const char *instance_fns [] = { "finalize", "update", NULL };

    dprintf("Called");

    /* Validate arg count */
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
963
964
965
966
967
968
969

970
971
972
973
974
975
976







-







 *
 *-------------------------------------------------------------------
 */
int EncryptCommandHandler(Tcl_Interp *interp, int type, Tcl_Obj *cmdObj,
	Tcl_Obj *cipherObj, Tcl_Obj *digestObj, Tcl_Obj *keyObj, Tcl_Obj *ivObj) {
    EncryptState *statePtr;
    char *cmdName = Tcl_GetStringFromObj(cmdObj, (Tcl_Size *) NULL);
    (void *) digestObj;

    dprintf("Called");

    if ((statePtr = EncryptStateNew(interp, type)) == NULL) {
	Tcl_AppendResult(interp, "Memory allocation error", (char *) NULL);
	return TCL_ERROR;
    }
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1010
1011
1012
1013
1014
1015
1016

1017
1018
1019
1020
1021
1022
1023







-







int EncryptDataHandler(Tcl_Interp *interp, int type, Tcl_Obj *dataObj, Tcl_Obj *cipherObj,
	Tcl_Obj *digestObj, Tcl_Obj *keyObj, Tcl_Obj *ivObj) {
    EVP_CIPHER_CTX *ctx = NULL;
    int out_len = 0, len = 0, res = TCL_OK;
    Tcl_Size data_len = 0;
    unsigned char *data, *out_buf;
    Tcl_Obj *resultObj;
    (void *) digestObj;

    dprintf("Called");

    /* Get data */
    if (dataObj != NULL) {
	data = Tcl_GetByteArrayFromObj(dataObj, &data_len);
    } else {
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1080
1081
1082
1083
1084
1085
1086

1087
1088
1089
1090
1091
1092
1093







-







int EncryptFileHandler(Tcl_Interp *interp, int type, Tcl_Obj *inFileObj, Tcl_Obj *outFileObj,
	Tcl_Obj *cipherObj, Tcl_Obj *digestObj, Tcl_Obj *keyObj, Tcl_Obj *ivObj) {
    EVP_CIPHER_CTX *ctx = NULL;
    int total = 0, res, out_len = 0, len;
    Tcl_Channel in = NULL, out = NULL;
    unsigned char in_buf[BUFFER_SIZE];
    unsigned char out_buf[BUFFER_SIZE+EVP_MAX_BLOCK_LENGTH];
    (void *) digestObj;

    dprintf("Called");

    /* Open input file */
    if ((in = Tcl_FSOpenFileChannel(interp, inFileObj, "rb", 0444)) == (Tcl_Channel) NULL) {
	return TCL_ERROR;
    }
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
69
70
71
72
73
74
75

76
77
78
79
80
81
82







-







 * Side effects:
 *    Closes the socket of the channel.
 *
 *-------------------------------------------------------------------
 */
static int TlsCloseProc(ClientData instanceData, Tcl_Interp *interp) {
    State *statePtr = (State *) instanceData;
    (void *) interp;

    dprintf("TlsCloseProc(%p)", (void *) statePtr);

    Tls_Clean(statePtr);
    Tcl_EventuallyFree((ClientData)statePtr, Tls_Free);
    return(0);
}
225
226
227
228
229
230
231
232

233
234
235
236
237
238
239
240

241
242
243
244
245
246
247
248
249
250

251
252
253

254
255
256
257
258
259
260
224
225
226
227
228
229
230

231
232
233
234
235
236
237
238

239
240
241
242
243
244
245
246
247
248

249
250
251

252
253
254
255
256
257
258
259







-
+







-
+









-
+


-
+








	    } else if (backingError == 0 && err == -1) {
		dprintf("I/O error occurred (errno = %lu)", (unsigned long) Tcl_GetErrno());
		*errorCodePtr = Tcl_GetErrno();
		if (*errorCodePtr == ECONNRESET) {
		    *errorCodePtr = ECONNABORTED;
		}
		Tls_Error(statePtr, Tcl_ErrnoMsg(Tcl_GetErrno()));
		Tls_Error(statePtr, (char *) Tcl_ErrnoMsg(Tcl_GetErrno()));

	    } else {
		dprintf("I/O error occurred (backingError = %lu)", backingError);
		*errorCodePtr = backingError;
		if (*errorCodePtr == ECONNRESET) {
		    *errorCodePtr = ECONNABORTED;
		}
		Tls_Error(statePtr, ERR_reason_error_string(backingError));
		Tls_Error(statePtr, (char *) ERR_reason_error_string(backingError));
	    }

	    statePtr->flags |= TLS_TCL_HANDSHAKE_FAILED;
	    return(-1);

	case SSL_ERROR_SSL:
	    /* A non-recoverable, fatal error in the SSL library occurred, usually a protocol error */
	    dprintf("SSL_ERROR_SSL: Got permanent fatal SSL error, aborting immediately");
	    if (backingError != 0) {
		Tls_Error(statePtr, ERR_reason_error_string(backingError));
		Tls_Error(statePtr, (char *) ERR_reason_error_string(backingError));
	    }
	    if (SSL_get_verify_result(statePtr->ssl) != X509_V_OK) {
		Tls_Error(statePtr, X509_verify_cert_error_string(SSL_get_verify_result(statePtr->ssl)));
		Tls_Error(statePtr, (char *) X509_verify_cert_error_string(SSL_get_verify_result(statePtr->ssl)));
	    }
	    statePtr->flags |= TLS_TCL_HANDSHAKE_FAILED;
	    *errorCodePtr = ECONNABORTED;
	    return(-1);

	case SSL_ERROR_WANT_READ:
	case SSL_ERROR_WANT_WRITE:
363
364
365
366
367
368
369
370

371
372
373
374
375
376
377
362
363
364
365
366
367
368

369
370
371
372
373
374
375
376







-
+







	    dprintBuffer(buf, bytesRead);
	    break;

	case SSL_ERROR_SSL:
	    /* A non-recoverable, fatal error in the SSL library occurred, usually a protocol error */
	    dprintf("SSL error, indicating that the connection has been aborted");
	    if (backingError != 0) {
		Tls_Error(statePtr, ERR_reason_error_string(backingError));
		Tls_Error(statePtr, (char *) ERR_reason_error_string(backingError));
	    }
	    *errorCodePtr = ECONNABORTED;
	    bytesRead = -1;

#if OPENSSL_VERSION_NUMBER >= 0x30000000L
	    /* Unexpected EOF from the peer for OpenSSL 3.0+ */
	    if (ERR_GET_REASON(backingError) == SSL_R_UNEXPECTED_EOF_WHILE_READING) {
392
393
394
395
396
397
398
399

400
401
402
403
404
405

406
407
408
409
410
411
412
391
392
393
394
395
396
397

398
399
400
401
402
403

404
405
406
407
408
409
410
411







-
+





-
+







		bytesRead = 0;
		Tls_Error(statePtr, "EOF reached");

	    } else if (backingError == 0 && bytesRead == -1) {
		dprintf("I/O error occurred (errno = %lu)", (unsigned long) Tcl_GetErrno());
		*errorCodePtr = Tcl_GetErrno();
		bytesRead = -1;
		Tls_Error(statePtr, Tcl_ErrnoMsg(Tcl_GetErrno()));
		Tls_Error(statePtr, (char *) Tcl_ErrnoMsg(Tcl_GetErrno()));

	    } else {
		dprintf("I/O error occurred (backingError = %lu)", backingError);
		*errorCodePtr = backingError;
		bytesRead = -1;
		Tls_Error(statePtr, ERR_reason_error_string(backingError));
		Tls_Error(statePtr, (char *) ERR_reason_error_string(backingError));
	    }
	    break;

	case SSL_ERROR_ZERO_RETURN:
	    dprintf("Got SSL_ERROR_ZERO_RETURN, this means an EOF has been reached");
	    bytesRead = 0;
	    *errorCodePtr = 0;
559
560
561
562
563
564
565
566

567
568
569
570
571
572

573
574
575
576
577
578
579
580

581
582
583
584
585
586
587
558
559
560
561
562
563
564

565
566
567
568
569
570

571
572
573
574
575
576
577
578

579
580
581
582
583
584
585
586







-
+





-
+







-
+







		written = 0;
		Tls_Error(statePtr, "EOF reached");

	    } else if (backingError == 0 && written == -1) {
		dprintf("I/O error occurred (errno = %lu)", (unsigned long) Tcl_GetErrno());
		*errorCodePtr = Tcl_GetErrno();
		written = -1;
		Tls_Error(statePtr, Tcl_ErrnoMsg(Tcl_GetErrno()));
		Tls_Error(statePtr, (char *) Tcl_ErrnoMsg(Tcl_GetErrno()));

	    } else {
		dprintf("I/O error occurred (backingError = %lu)", backingError);
		*errorCodePtr = backingError;
		written = -1;
		Tls_Error(statePtr, ERR_reason_error_string(backingError));
		Tls_Error(statePtr, (char *) ERR_reason_error_string(backingError));
	    }
	    break;

	case SSL_ERROR_SSL:
	    /* A non-recoverable, fatal error in the SSL library occurred, usually a protocol error */
	    dprintf("SSL error, indicating that the connection has been aborted");
	    if (backingError != 0) {
		Tls_Error(statePtr, ERR_reason_error_string(backingError));
		Tls_Error(statePtr, (char *) ERR_reason_error_string(backingError));
	    }
	    *errorCodePtr = ECONNABORTED;
	    written = -1;
	    break;

	default:
	    dprintf("unknown error: %d", err);
940
941
942
943
944
945
946
947

948
949
939
940
941
942
943
944
945

946
947
948







-
+


    NULL,			/* Flush proc */
    TlsNotifyProc,		/* Handling of events bubbling up */
    NULL,			/* Wide seek proc */
    NULL,			/* Thread action */
    NULL			/* Truncate */
};

Tcl_ChannelType *Tls_ChannelType(void) {
const Tcl_ChannelType *Tls_ChannelType(void) {
    return &tlsChannelType;
}
65
66
67
68
69
70
71
72

73
74
75
76
77
78
79
65
66
67
68
69
70
71

72
73
74
75
76
77
78
79







-
+







 *
 *-------------------------------------------------------------------
 */
int CipherInfo(Tcl_Interp *interp, Tcl_Obj *nameObj) {
    const EVP_CIPHER *cipher;
    Tcl_Obj *resultObj, *listObj;
    unsigned long flags, mode;
    unsigned char *modeName = NULL;
    char *modeName = NULL;
    char *name = Tcl_GetStringFromObj(nameObj, (Tcl_Size *) NULL);

    /* Get cipher */
    cipher = EVP_get_cipherbyname(name);

    if (cipher == NULL) {
	Tcl_AppendResult(interp, "Invalid cipher \"", name, "\"", (char *) NULL);
376
377
378
379
380
381
382
383

384
385
386
387
388
389
390
391
392
393
394
395
396
397

398
399
400
401
402
403
404
376
377
378
379
380
381
382

383
384
385
386
387
388
389
390
391
392
393
394
395
396

397
398
399
400
401
402
403
404







-
+













-
+







	/*sk = SSL_CTX_get_ciphers(ctx);*/
    }

    if (sk != NULL) {
	Tcl_Obj *resultObj = NULL;

	if (!verbose) {
	    char *cp;
	    const char *cp;
	    resultObj = Tcl_NewListObj(0, NULL);
	    if (resultObj == NULL) {
		res = TCL_ERROR;
		goto done;
	    }

	    for (int i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
		const SSL_CIPHER *c = sk_SSL_CIPHER_value(sk, i);
		if (c == NULL) continue;

		/* cipher name or (NONE) */
		cp = SSL_CIPHER_get_name(c);
		if (cp == NULL) break;
		Tcl_ListObjAppendElement(interp, resultObj, Tcl_NewStringObj(cp, -1));
		Tcl_ListObjAppendElement(interp, resultObj, Tcl_NewStringObj((char *) cp, -1));
	    }

	} else {
	    char buf[BUFSIZ];
	    resultObj = Tcl_NewStringObj("", 0);
	    if (resultObj == NULL) {
		res = TCL_ERROR;
445
446
447
448
449
450
451
452

453
454
455
456
457
458
459
460
461
462
445
446
447
448
449
450
451

452
453
454

455
456
457
458
459
460
461







-
+


-







 *
 * Side effects:
 *	None.
 *
 *-------------------------------------------------------------------
 */
int DigestInfo(Tcl_Interp *interp, Tcl_Obj *nameObj) {
    EVP_MD *md;
    const EVP_MD *md;
    Tcl_Obj *resultObj, *listObj;
    unsigned long flags;
    int res = TCL_OK;
    char *name = Tcl_GetStringFromObj(nameObj, (Tcl_Size *) NULL);

    /* Get message digest */
    md = EVP_get_digestbyname(name);

    if (md == NULL) {
	Tcl_AppendResult(interp, "Invalid digest \"", name, "\"", (char *) NULL);
175
176
177
178
179
180
181
182

183
184
185
186
187
188
189
190
191
192
193
194
195
196
197

198
199
200
201
202
203
204
175
176
177
178
179
180
181

182
183
184
185
186
187
188
189
190
191
192
193
194
195
196

197
198
199
200
201
202
203
204







-
+














-
+








	int vflags;		/* verify flags */
	SSL *ssl;		/* Struct for SSL processing */
	SSL_CTX *ctx;		/* SSL Context */
	BIO *bio;		/* Struct for SSL processing */
	BIO *p_bio;		/* Parent BIO (that is layered on Tcl_Channel) */

	char *protos;		/* List of supported protocols in protocol format */
	unsigned char *protos;	/* List of supported protocols in protocol format */
	unsigned int protos_len; /* Length of protos */

	char *err;
} State;

#ifdef USE_TCL_STUBS
#ifndef Tcl_StackChannel
#error "Unable to compile on this version of Tcl"
#endif /* Tcl_GetStackedChannel */
#endif /* USE_TCL_STUBS */

/*
 * Forward declarations
 */
Tcl_ChannelType *Tls_ChannelType(void);
const Tcl_ChannelType *Tls_ChannelType(void);
Tcl_Channel     Tls_GetParent(State *statePtr, int maskFlags);

Tcl_Obj         *Tls_NewX509Obj(Tcl_Interp *interp, X509 *cert);
Tcl_Obj		*Tls_NewCAObj(Tcl_Interp *interp, const SSL *ssl, int peer);
void            Tls_Error(State *statePtr, char *msg);
void            Tls_Free(char *blockPtr);
void            Tls_Clean(State *statePtr);
77
78
79
80
81
82
83
84

85
86
87
88
89
90

91
92
93
94
95
96
97
98
99
100
101

102
103
104
105
106
107
108

109
110
111
112
113
114
115
77
78
79
80
81
82
83

84
85
86
87
88
89

90
91
92
93
94
95
96
97
98
99
100

101
102
103
104
105
106
107

108
109
110
111
112
113
114
115







-
+





-
+










-
+






-
+







	if (++idx >= objc) {
	    Tcl_AppendResult(interp, "No value for option \"", command_opts[fn], "\"", (char *) NULL);
	    return TCL_ERROR;
	}

	switch(fn) {
	case _opt_cipher:
	    if ((cipher = Util_GetCipher(interp, objv[idx], TRUE)) == NULL) {
	    if ((cipher = Util_GetCipher(interp, objv[idx], 1)) == NULL) {
		return TCL_ERROR;
	    }
	    break;
	case _opt_digest:
	case _opt_hash:
	    if ((md = Util_GetDigest(interp, objv[idx], TRUE)) == NULL) {
	    if ((md = Util_GetDigest(interp, objv[idx], 1)) == NULL) {
		return TCL_ERROR;
	    }
	    break;
	case _opt_iter:
	    if (Util_GetInt(interp, objv[idx], &iter, "iterations", 1, -1) != TCL_OK) {
		return TCL_ERROR;
	    }
	    break;
	case _opt_key:
	case _opt_password:
	    pass = Util_GetKey(interp, objv[idx], &pass_len, command_opts[fn], 0, FALSE);
	    pass = Util_GetKey(interp, objv[idx], &pass_len, (char *) command_opts[fn], 0, 0);
	    break;
	case _opt_salt:
	    GET_OPT_BYTE_ARRAY(objv[idx], salt, &salt_len);
	    break;
	case _opt_length:
	case _opt_size:
	    if (Util_GetInt(interp, objv[idx], &dk_len, command_opts[fn], 1, buf_len) != TCL_OK) {
	    if (Util_GetInt(interp, objv[idx], &dk_len, (char *) command_opts[fn], 1, buf_len) != TCL_OK) {
		return TCL_ERROR;
	    }
	    break;
	}
    }

    /* Validate options */
126
127
128
129
130
131
132
133

134
135
136
137
138
139
140
126
127
128
129
130
131
132

133
134
135
136
137
138
139
140







-
+







    } else {
	iklen = EVP_CIPHER_key_length(cipher);
	ivlen = EVP_CIPHER_iv_length(cipher);
	dk_len = iklen+ivlen;
    }

    /* Derive key */
    if (!PKCS5_PBKDF2_HMAC(pass, (int) pass_len, salt, (int) salt_len, iter, md, dk_len, tmpkeyiv)) {
    if (!PKCS5_PBKDF2_HMAC((const char *) pass, (int) pass_len, salt, (int) salt_len, iter, md, dk_len, tmpkeyiv)) {
	Tcl_AppendResult(interp, "Key derivation failed: ", GET_ERR_REASON(), (char *) NULL);
	return TCL_ERROR;
    }

   /* Set result to key and iv */
    if (cipher == NULL) {
	Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(tmpkeyiv, (Tcl_Size) dk_len));
202
203
204
205
206
207
208
209

210
211
212
213
214
215
216
217
218
219

220
221
222
223
224
225
226
227
228

229
230
231
232
233
234
235
202
203
204
205
206
207
208

209
210
211
212
213
214
215
216
217
218

219
220
221
222
223
224
225
226
227

228
229
230
231
232
233
234
235







-
+









-
+








-
+







	    Tcl_AppendResult(interp, "No value for option \"", command_opts[fn], "\"", (char *) NULL);
	    return TCL_ERROR;
	}

	switch(fn) {
	case _opt_digest:
	case _opt_hash:
	    if ((md = Util_GetDigest(interp, objv[idx], TRUE)) == NULL) {
	    if ((md = Util_GetDigest(interp, objv[idx], 1)) == NULL) {
		goto error;
	    }
	    break;
	case _opt_info:
	    /* Max 1024/2048 */
	    GET_OPT_BYTE_ARRAY(objv[idx], info, &info_len);
	    break;
	case _opt_key:
	case _opt_password:
	    if ((key = Util_GetKey(interp, objv[idx], &key_len, command_opts[fn], 0, 1)) == NULL) {
	    if ((key = Util_GetKey(interp, objv[idx], &key_len, (char *) command_opts[fn], 0, 1)) == NULL) {
		goto error;
	    }
	    break;
	case _opt_salt:
	    GET_OPT_BYTE_ARRAY(objv[idx], salt, &salt_len);
	    break;
	case _opt_length:
	case _opt_size:
	    if (Util_GetInt(interp, objv[idx], &dk_len, command_opts[fn], 1, 0) != TCL_OK) {
	    if (Util_GetInt(interp, objv[idx], &dk_len, (char *) command_opts[fn], 1, 0) != TCL_OK) {
		goto error;
	    }
	    break;
	}
    }

    if (md == NULL) {
319
320
321
322
323
324
325
326

327
328
329
330
331
332
333
319
320
321
322
323
324
325

326
327
328
329
330
331
332
333







-
+







 */
static int KDF_Scrypt(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]) {
    EVP_PKEY_CTX *pctx = NULL;
    unsigned char *salt = NULL, *pass = NULL, *out = NULL;
    Tcl_Size salt_len = 0, pass_len = 0;
    int dk_len = 64, res = TCL_OK;
    Tcl_Size fn;
    uint64_t N = 0, p = 0, r = 0, maxmem = 0;
    Tcl_WideInt N = 0, p = 0, r = 0, maxmem = 0;
    size_t out_len;
    Tcl_Obj *resultObj;
    (void) clientData;

    dprintf("Called");

    /* Clear errors */
359
360
361
362
363
364
365
366

367
368
369
370
371
372
373
359
360
361
362
363
364
365

366
367
368
369
370
371
372
373







-
+







	    GET_OPT_BYTE_ARRAY(objv[idx], pass, &pass_len);
	    break;
	case _opt_salt:
	    GET_OPT_BYTE_ARRAY(objv[idx], salt, &salt_len);
	    break;
	case _opt_length:
	case _opt_size:
	    if (Util_GetInt(interp, objv[idx], &dk_len, command_opts[fn], 1, 0) != TCL_OK) {
	    if (Util_GetInt(interp, objv[idx], &dk_len, (char *) command_opts[fn], 1, 0) != TCL_OK) {
		goto error;
	    }
	    break;
	case _opt_N:
	case _opt_n:
	    GET_OPT_WIDE(objv[idx], &N);
	    break;
399
400
401
402
403
404
405
406

407
408
409
410
411
412
413
414

415
416
417
418

419
420
421
422

423
424
425
426
427
428
429
399
400
401
402
403
404
405

406
407
408
409
410
411
412
413

414
415
416
417

418
419
420
421

422
423
424
425
426
427
428
429







-
+







-
+



-
+



-
+








    if (EVP_PKEY_derive_init(pctx) < 1) {
	Tcl_AppendResult(interp, "Initialize failed: ", GET_ERR_REASON(), (char *) NULL);
	goto error;
    }

    /* Set config parameters */
    if (EVP_PKEY_CTX_set1_pbe_pass(pctx, pass, (int) pass_len) < 1) {
    if (EVP_PKEY_CTX_set1_pbe_pass(pctx, (const char *) pass, (int) pass_len) < 1) {
	Tcl_AppendResult(interp, "Set key failed: ", GET_ERR_REASON(), (char *) NULL);
	goto error;
    }
    if (EVP_PKEY_CTX_set1_scrypt_salt(pctx, salt, (int) salt_len) < 1) {
	Tcl_AppendResult(interp, "Set salt failed: ", GET_ERR_REASON(), (char *) NULL);
	goto error;
    }
    if (N != 0 && EVP_PKEY_CTX_set_scrypt_N(pctx, N) < 1) {
    if (N != 0 && EVP_PKEY_CTX_set_scrypt_N(pctx, (uint64_t) N) < 1) {
	Tcl_AppendResult(interp, "Set cost parameter (N) failed: ", GET_ERR_REASON(), (char *) NULL);
	goto error;
    }
    if (r != 0 && EVP_PKEY_CTX_set_scrypt_r(pctx, r) < 1) {
    if (r != 0 && EVP_PKEY_CTX_set_scrypt_r(pctx, (uint64_t) r) < 1) {
	Tcl_AppendResult(interp, "Set lock size parameter (r) failed: ", GET_ERR_REASON(), (char *) NULL);
	goto error;
   }
    if (p != 0 && EVP_PKEY_CTX_set_scrypt_p(pctx, p) < 1) {
    if (p != 0 && EVP_PKEY_CTX_set_scrypt_p(pctx, (uint64_t) p) < 1) {
	Tcl_AppendResult(interp, "Set Parallelization parameter (p) failed: ", GET_ERR_REASON(), (char *) NULL);
	goto error;
    }
    if (maxmem != 0 && EVP_PKEY_CTX_set_scrypt_maxmem_bytes(pctx, maxmem) < 1) {
	Tcl_AppendResult(interp, "Set max memory failed: ", GET_ERR_REASON(), (char *) NULL);
	goto error;
    }
58
59
60
61
62
63
64
65

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80

81
82
83

84
85
86

87
88
89

90
91
92
93
94
95
96
58
59
60
61
62
63
64

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

80
81
82

83
84
85

86
87
88

89
90
91
92
93
94
95
96







-
+














-
+


-
+


-
+


-
+







    const STACK_OF(X509_EXTENSION) *exts;
    Tcl_Obj *listPtr = Tcl_NewListObj(0, NULL);

    if (listPtr == NULL) {
	return NULL;
    }

    if (exts = X509_get0_extensions(cert)) {
    if ((exts = X509_get0_extensions(cert)) != NULL) {
	for (int i=0; i < X509_get_ext_count(cert); i++) {
	    X509_EXTENSION *ex = sk_X509_EXTENSION_value(exts, i);
	    ASN1_OBJECT *obj = X509_EXTENSION_get_object(ex);
	    /* ASN1_OCTET_STRING *data = X509_EXTENSION_get_data(ex); */
	    int critical = X509_EXTENSION_get_critical(ex);
	    LAPPEND_BOOL(interp, listPtr, OBJ_nid2ln(OBJ_obj2nid(obj)), critical);
	}
    }
    return listPtr;
}

/*
 * Get Authority and Subject Key Identifiers
 */
Tcl_Obj *Tls_x509Identifier(ASN1_OCTET_STRING *astring) {
Tcl_Obj *Tls_x509Identifier(const ASN1_OCTET_STRING *astring) {
    Tcl_Obj *resultPtr = NULL;
    int len = 0;
    char buffer[1024];
    unsigned char buffer[1024];

    if (astring != NULL) {
	len = String_to_Hex(ASN1_STRING_get0_data(astring),
	len = String_to_Hex((unsigned char *) ASN1_STRING_get0_data(astring),
	    ASN1_STRING_length(astring), buffer, 1024);
    }
    resultPtr = Tcl_NewStringObj(buffer, (Tcl_Size) len);
    resultPtr = Tcl_NewStringObj((char *) &buffer[0], (Tcl_Size) len);
    return resultPtr;
}

/*
 * Get Key Usage
 */
Tcl_Obj *Tls_x509KeyUsage(Tcl_Interp *interp, X509 *cert, uint32_t xflags) {
199
200
201
202
203
204
205
206

207
208
209
210

211
212
213
214
215
216
217
199
200
201
202
203
204
205

206
207
208
209

210
211
212
213
214
215
216
217







-
+



-
+







    int len;
    char buffer[1024];

    if (listPtr == NULL) {
	return NULL;
    }

    if (names = X509_get_ext_d2i(cert, nid, NULL, NULL)) {
    if ((names = X509_get_ext_d2i(cert, nid, NULL, NULL)) != NULL) {
	for (int i=0; i < sk_GENERAL_NAME_num(names); i++) {
	    const GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);

	    len = BIO_to_Buffer(name && GENERAL_NAME_print(bio, name), bio, buffer, 1024);
	    len = BIO_to_Buffer(name && GENERAL_NAME_print(bio, (GENERAL_NAME *) name), bio, buffer, 1024);
	    LAPPEND_STR(interp, listPtr, NULL, buffer, (Tcl_Size) len);
	}
	sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
    }
    return listPtr;
}

269
270
271
272
273
274
275
276

277
278
279
280
281
282
283
284
285
286
287
288

289
290
291
292
293
294
295
296
297

298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317

318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336

337
338
339
340
341
342

343
344
345
346
347
348
349
269
270
271
272
273
274
275

276
277
278
279
280
281
282
283
284
285
286
287

288
289
290
291
292
293
294
295
296

297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335

336
337
338
339
340
341

342
343
344
345
346
347
348
349







-
+











-
+








-
+



















-
+


















-
+





-
+







    STACK_OF(DIST_POINT) *crl;
    Tcl_Obj *listPtr = Tcl_NewListObj(0, NULL);

    if (listPtr == NULL) {
	return NULL;
    }

    if (crl = X509_get_ext_d2i(cert, NID_crl_distribution_points, NULL, NULL)) {
    if ((crl = X509_get_ext_d2i(cert, NID_crl_distribution_points, NULL, NULL)) != NULL) {
	for (int i=0; i < sk_DIST_POINT_num(crl); i++) {
	    DIST_POINT *dp = sk_DIST_POINT_value(crl, i);
	    DIST_POINT_NAME *distpoint = dp->distpoint;

	    if (distpoint->type == 0) {
		/* full-name GENERALIZEDNAME */
		for (int j = 0; j < sk_GENERAL_NAME_num(distpoint->name.fullname); j++) {
		    GENERAL_NAME *gen = sk_GENERAL_NAME_value(distpoint->name.fullname, j);
		    int type;
		    ASN1_STRING *uri = GENERAL_NAME_get0_value(gen, &type);
		    if (type == GEN_URI) {
			LAPPEND_STR(interp, listPtr, NULL, ASN1_STRING_get0_data(uri), (Tcl_Size) ASN1_STRING_length(uri));
			LAPPEND_STR(interp, listPtr, (char *) NULL, (char *) ASN1_STRING_get0_data(uri), (Tcl_Size) ASN1_STRING_length(uri));
		    }
		}
	    } else if (distpoint->type == 1) {
		/* relative-name X509NAME */
		STACK_OF(X509_NAME_ENTRY) *sk_relname = distpoint->name.relativename;
		for (int j = 0; j < sk_X509_NAME_ENTRY_num(sk_relname); j++) {
		    X509_NAME_ENTRY *e = sk_X509_NAME_ENTRY_value(sk_relname, j);
		    ASN1_STRING *d = X509_NAME_ENTRY_get_data(e);
		    LAPPEND_STR(interp, listPtr, NULL, ASN1_STRING_data(d), (Tcl_Size) ASN1_STRING_length(d));
		    LAPPEND_STR(interp, listPtr, (char *) NULL, (char *) ASN1_STRING_data(d), (Tcl_Size) ASN1_STRING_length(d));
		}
	    }
	}
	CRL_DIST_POINTS_free(crl);
    }
    return listPtr;
}

/*
 * Get On-line Certificate Status Protocol (OSCP) URL
 */
Tcl_Obj *Tls_x509Oscp(Tcl_Interp *interp, X509 *cert) {
    STACK_OF(OPENSSL_STRING) *ocsp;
    Tcl_Obj *listPtr = Tcl_NewListObj(0, NULL);

    if (listPtr == NULL) {
	return NULL;
    }

    if (ocsp = X509_get1_ocsp(cert)) {
    if ((ocsp = X509_get1_ocsp(cert)) != NULL) {
	for (int i = 0; i < sk_OPENSSL_STRING_num(ocsp); i++) {
	    LAPPEND_STR(interp, listPtr, NULL, sk_OPENSSL_STRING_value(ocsp, i), -1);
	}
	X509_email_free(ocsp);
    }
    return listPtr;
}

/*
 * Get Certificate Authority (CA) Issuers URL
 */
Tcl_Obj *Tls_x509CaIssuers(Tcl_Interp *interp, X509 *cert) {
    STACK_OF(ACCESS_DESCRIPTION) *ads;
    ACCESS_DESCRIPTION *ad;
    Tcl_Obj *listPtr = Tcl_NewListObj(0, NULL);
    unsigned char *buf;
    int len;

    if (ads = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL)) {
    if ((ads = X509_get_ext_d2i(cert, NID_info_access, NULL, NULL)) != NULL) {
	for (int i = 0; i < sk_ACCESS_DESCRIPTION_num(ads); i++) {
	    ad = sk_ACCESS_DESCRIPTION_value(ads, i);
	    if (OBJ_obj2nid(ad->method) == NID_ad_ca_issuers && ad->location) {
		if (ad->location->type == GEN_URI) {
		    len = ASN1_STRING_to_UTF8(&buf, ad->location->d.uniformResourceIdentifier);
		    Tcl_ListObjAppendElement(interp, listPtr, Tcl_NewStringObj(buf, (Tcl_Size) len));
		    Tcl_ListObjAppendElement(interp, listPtr, Tcl_NewStringObj((char *) buf, (Tcl_Size) len));
		    OPENSSL_free(buf);
		    break;
		}
	    }
	}
	/* sk_ACCESS_DESCRIPTION_pop_free(ads, ACCESS_DESCRIPTION_free); */
	AUTHORITY_INFO_ACCESS_free(ads);
371
372
373
374
375
376
377

378
379
380
381
382
383
384
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385







+







 */

Tcl_Obj*
Tls_NewX509Obj(Tcl_Interp *interp, X509 *cert) {
    Tcl_Obj *certPtr = Tcl_NewListObj(0, NULL);
    BIO *bio = BIO_new(BIO_s_mem());
    int mdnid, pknid, bits, len;
    unsigned int ulen;
    uint32_t xflags;
    char buffer[BUFSIZ];
    unsigned char md[EVP_MAX_MD_SIZE];
    unsigned long flags = XN_FLAG_RFC2253 | ASN1_STRFLGS_UTF8_CONVERT;
    flags &= ~ASN1_STRFLGS_ESC_MSB;

    if (interp == NULL || cert == NULL || bio == NULL || certPtr == NULL) {
394
395
396
397
398
399
400
401

402
403
404
405
406
407
408
395
396
397
398
399
400
401

402
403
404
405
406
407
408
409







-
+







	const ASN1_BIT_STRING *sig;
	int sig_nid;

	X509_get0_signature(&sig, &sig_alg, cert);
	/* sig_nid = X509_get_signature_nid(cert) */
	sig_nid = OBJ_obj2nid(sig_alg->algorithm);
	LAPPEND_STR(interp, certPtr, "signatureAlgorithm", OBJ_nid2ln(sig_nid), -1);
	len = (sig_nid != NID_undef) ? String_to_Hex(sig->data, sig->length, buffer, BUFSIZ) : 0;
	len = (sig_nid != NID_undef) ? String_to_Hex(sig->data, sig->length, (unsigned char *) buffer, BUFSIZ) : 0;
	LAPPEND_STR(interp, certPtr, "signatureValue", buffer, (Tcl_Size) len);
    }

    /* Version of the encoded certificate - RFC 5280 section 4.1.2.1 */
    LAPPEND_LONG(interp, certPtr, "version", X509_get_version(cert)+1);

    /* Unique number assigned by CA to certificate - RFC 5280 section 4.1.2.2 */
429
430
431
432
433
434
435
436
437
438



439
440
441
442
443
444



445
446
447
448
449
450
451
452
453
454
455
456
457
458

459
460
461
462
463

464
465
466
467
468
469
470

471
472
473
474
475
476
477
430
431
432
433
434
435
436



437
438
439
440
441
442



443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458

459
460
461
462
463

464
465
466
467
468
469
470

471
472
473
474
475
476
477
478







-
-
-
+
+
+



-
-
-
+
+
+













-
+




-
+






-
+








    /* Subject identifies the entity associated with the public key stored in
	the subject public key field. RFC 5280 section 4.1.2.6 */
    len = BIO_to_Buffer(X509_NAME_print_ex(bio, X509_get_subject_name(cert), 0, flags), bio, buffer, BUFSIZ);
    LAPPEND_STR(interp, certPtr, "subject", buffer, (Tcl_Size) len);

    /* SHA1 Digest (Fingerprint) of cert - DER representation */
    if (X509_digest(cert, EVP_sha1(), md, &len)) {
	len = String_to_Hex(md, len, buffer, BUFSIZ);
	LAPPEND_STR(interp, certPtr, "sha1_hash", buffer, (Tcl_Size) len);
    if (X509_digest(cert, EVP_sha1(), md, &ulen)) {
	len = String_to_Hex(md, len, (unsigned char *) buffer, BUFSIZ);
	LAPPEND_STR(interp, certPtr, "sha1_hash", buffer, (Tcl_Size) ulen);
    }

    /* SHA256 Digest (Fingerprint) of cert - DER representation */
    if (X509_digest(cert, EVP_sha256(), md, &len)) {
	len = String_to_Hex(md, len, buffer, BUFSIZ);
	LAPPEND_STR(interp, certPtr, "sha256_hash", buffer, (Tcl_Size) len);
    if (X509_digest(cert, EVP_sha256(), md, &ulen)) {
	len = String_to_Hex(md, len, (unsigned char *) buffer, BUFSIZ);
	LAPPEND_STR(interp, certPtr, "sha256_hash", buffer, (Tcl_Size) ulen);
    }

    /* Subject Public Key Info specifies the public key and identifies the
	algorithm with which the key is used. RFC 5280 section 4.1.2.7 */
    if (X509_get_signature_info(cert, &mdnid, &pknid, &bits, &xflags)) {
	ASN1_BIT_STRING *key;
	unsigned int n;

	LAPPEND_STR(interp, certPtr, "signingDigest", OBJ_nid2ln(mdnid), -1);
	LAPPEND_STR(interp, certPtr, "publicKeyAlgorithm", OBJ_nid2ln(pknid), -1);
	LAPPEND_INT(interp, certPtr, "bits", bits); /* Effective security bits */

	key = X509_get0_pubkey_bitstr(cert);
	len = String_to_Hex(key->data, key->length, buffer, BUFSIZ);
	len = String_to_Hex(key->data, key->length, (unsigned char *) buffer, BUFSIZ);
	LAPPEND_STR(interp, certPtr, "publicKey", buffer, (Tcl_Size) len);

	len = 0;
	if (X509_pubkey_digest(cert, EVP_get_digestbynid(pknid), md, &n)) {
	    len = String_to_Hex(md, (int)n, buffer, BUFSIZ);
	    len = String_to_Hex(md, (int) n, (unsigned char *) buffer, BUFSIZ);
	}
	LAPPEND_STR(interp, certPtr, "publicKeyHash", buffer, (Tcl_Size) len);

	/* digest of the DER representation of the certificate */
	len = 0;
	if (X509_digest(cert, EVP_get_digestbynid(mdnid), md, &n)) {
	    len = String_to_Hex(md, (int)n, buffer, BUFSIZ);
	    len = String_to_Hex(md, (int) n, (unsigned char *) buffer, BUFSIZ);
	}
	LAPPEND_STR(interp, certPtr, "signatureHash", buffer, (Tcl_Size) len);
    }

    /* Certificate Purpose. Call before checking for extensions. */
    LAPPEND_STR(interp, certPtr, "purpose", Tls_x509Purpose(cert), -1);
    LAPPEND_OBJ(interp, certPtr, "certificatePurpose", Tls_x509Purposes(interp, cert));
491
492
493
494
495
496
497
498

499
500
501
502
503
504
505

506
507
508
509
510
511
512
492
493
494
495
496
497
498

499
500
501
502
503
504
505

506
507
508
509
510
511
512
513







-
+






-
+







	and/or issuer names over time. RFC 5280 section 4.1.2.8 */
    {
	const ASN1_BIT_STRING *iuid, *suid;
	X509_get0_uids(cert, &iuid, &suid);

	Tcl_ListObjAppendElement(interp, certPtr, Tcl_NewStringObj("issuerUniqueId", -1));
	if (iuid != NULL) {
	    Tcl_ListObjAppendElement(interp, certPtr, Tcl_NewByteArrayObj((char *)iuid->data, (Tcl_Size) iuid->length));
	    Tcl_ListObjAppendElement(interp, certPtr, Tcl_NewByteArrayObj((const unsigned char *)iuid->data, (Tcl_Size) iuid->length));
	} else {
	    Tcl_ListObjAppendElement(interp, certPtr, Tcl_NewStringObj("", -1));
	}

	Tcl_ListObjAppendElement(interp, certPtr, Tcl_NewStringObj("subjectUniqueId", -1));
	if (suid != NULL) {
	    Tcl_ListObjAppendElement(interp, certPtr, Tcl_NewByteArrayObj((char *)suid->data, (Tcl_Size) suid->length));
	    Tcl_ListObjAppendElement(interp, certPtr, Tcl_NewByteArrayObj((const unsigned char *)suid->data, (Tcl_Size) suid->length));
	} else {
	    Tcl_ListObjAppendElement(interp, certPtr, Tcl_NewStringObj("", -1));
	}
    }

    /* X509 v3 Extensions - RFC 5280 section 4.1.2.9 */
    LAPPEND_INT(interp, certPtr, "extCount", X509_get_ext_count(cert));
584
585
586
587
588
589
590
591
592




593
594
595
596
597
598
599
585
586
587
588
589
590
591


592
593
594
595
596
597
598
599
600
601
602







-
-
+
+
+
+








    /* Subject Information Access - RFC 5280 section 4.2.2.2, NID_sinfo_access */

    /* Certificate Alias. If uses a PKCS#12 structure, alias will reflect the
	friendlyName attribute (RFC 2985). */
    {
	len = 0;
        char *string = X509_alias_get0(cert, &len);
	LAPPEND_STR(interp, certPtr, "alias", string, (Tcl_Size) len);
        unsigned char *string = X509_alias_get0(cert, &len);
	LAPPEND_STR(interp, certPtr, "alias", (char *) string, (Tcl_Size) len);
	string = X509_keyid_get0 (cert, &len);
	LAPPEND_STR(interp, certPtr, "keyId", (char *) string, (Tcl_Size) len);
    }

    /* Certificate and dump all data */
    {
	char certStr[CERT_STR_SIZE];

	/* Get certificate */
1
2
3
4
5
6
7
8

9
10
11
12
13
14
15
1
2
3
4
5
6
7

8
9
10
11
12
13
14
15







-
+







# Group,Name,Constraints,Setup,Body,Cleanup,Match,Result,Output,Error Output,Return Codes
command,package require tls,,,,,,,,,
,,,,,,,,,,
command,# Find default CA certificates directory,,,,,,,,,
command,if {[info exists ::env(SSL_CERT_FILE)]} {set ::cafile $::env(SSL_CERT_FILE)} else {set ::cafile [file normalize {C:\Users\Brian\Documents\Source\Build\SSL-1.1\certs\cacert.pem}]},,,,,,,,,
,,,,,,,,,,
command,# Constraints,,,,,,,,,
command,source common.tcl,,,,,,,,,
command,source [file join [file dirname [info script]] common.tcl],,,,,,,,,
,,,,,,,,,,
command,# Helper functions,,,,,,,,,
command,"proc badssl {url} {set port 443;lassign [split $url "":""] url port;if {$port eq """"} {set port 443};set ch [tls::socket -autoservername 1 -require 1 -cafile $::cafile $url $port];if {[catch {tls::handshake $ch} err]} {close $ch;return -code error $err} else {close $ch}}",,,,,,,,,
,,,,,,,,,,
command,# BadSSL.com Tests,,,,,,,,,
BadSSL,1000-sans,,,badssl 1000-sans.badssl.com,,,handshake failed: certificate verify failed due to: certificate has expired,,,1
BadSSL,10000-sans,,,badssl 10000-sans.badssl.com,,,handshake failed: excessive message size,,,1
10
11
12
13
14
15
16
17

18
19
20
21
22
23
24
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24







-
+








package require tls

# Find default CA certificates directory
if {[info exists ::env(SSL_CERT_FILE)]} {set ::cafile $::env(SSL_CERT_FILE)} else {set ::cafile [file normalize {C:\Users\Brian\Documents\Source\Build\SSL-1.1\certs\cacert.pem}]}

# Constraints
source common.tcl
source [file join [file dirname [info script]] common.tcl]

# Helper functions
proc badssl {url} {set port 443;lassign [split $url ":"] url port;if {$port eq ""} {set port 443};set ch [tls::socket -autoservername 1 -require 1 -cafile $::cafile $url $port];if {[catch {tls::handshake $ch} err]} {close $ch;return -code error $err} else {close $ch}}

# BadSSL.com Tests


1
2
3
4
5

6
7
8
9
10
11
12
13
14
15
16
17
18
19

20
21
22
23
24
25
26
27

28
29
30
31
32
33
34
35
36

37
38
39
40
41
42
43
44
45

46
47
48
49
50
51
52
53
54

55
56
57
58
59
60
61

62
63
64
65
66
67
68
69
70

71
72
73
74
75
76
77
1
2
3
4

5
6
7
8
9
10
11
12
13
14
15
16
17
18

19
20
21
22
23
24
25
26

27
28
29
30
31
32
33
34
35

36
37
38
39
40
41
42
43
44

45
46
47
48
49
50
51
52
53

54
55
56
57
58
59
60

61
62
63
64
65
66
67
68
69

70
71
72
73
74
75
76
77




-
+













-
+







-
+








-
+








-
+








-
+






-
+








-
+







# Group,Name,Constraints,Setup,Body,Cleanup,Match,Result,Output,Error Output,Return Codes
command,package require tls,,,,,,,,,
,,,,,,,,,,
command,# Constraints,,,,,,,,,
command,source common.tcl,,,,,,,,,
command,::tcltest::testConstraint md4 [expr {"md4" in [::tls::digests]}],,,,,,,,,
,,,,,,,,,,
command,# Helper functions - See common.tcl,,,,,,,,,
command,proc digest_read_chan {cmd filename args} {;set ch [open $filename rb];set bsize [fconfigure $ch -buffersize];set new [$cmd {*}$args -chan $ch];while {![eof $new]} {set md [read $new $bsize]};close $new;return $md},,,,,,,,,
command,proc digest_write_chan {cmd filename data args} {;set ch [open $filename wb];set new [$cmd {*}$args -chan $ch];puts -nonewline $new $data;flush $new;close $new;set ch [open $filename rb];set md [read $ch];close $ch;return $md},,,,,,,,,
command,proc digest_accumulate {string args} {;set cmd [{*}$args -command dcmd]; $cmd update [string range $string 0 20];$cmd update [string range $string 21 end];return [$cmd finalize]},$cmd update [string range $string 0 20];$cmd update [string range $string 21 end];return [$cmd finalize]},,,,,,,,
,,,,,,,,,,
command,"set test_data ""Example string for message digest tests.\n""",,,,,,,,,
command,"set test_file ""md_data.dat""",,,,,,,,,
command,"set test_alt_file ""md_alt_data.dat""",,,,,,,,,
command,"set test_key ""Example key""",,,,,,,,,
command,::tcltest::makeFile $test_data $test_file,,,,,,,,,
,,,,,,,,,,
command,# Test short-cut commands,,,,,,,,,
Shortcut Cmds,md4 cmd,,,::tls::md4 $test_data,,,793399f792eca2752c6af3234ba70858,,,
Shortcut Cmds,md4 cmd,md4,,::tls::md4 $test_data,,,793399f792eca2752c6af3234ba70858,,,
Shortcut Cmds,md5 cmd,,,::tls::md5 $test_data,,,962bf0803b4232ec23bd8427bb94ea09,,,
Shortcut Cmds,sha1 cmd,,,::tls::sha1 $test_data,,,4fe03b7f2568551dfafb98ca6004e65c4b71aa7d,,,
Shortcut Cmds,sha256 cmd,,,::tls::sha256 $test_data,,,9d3578fc138205cf0ee4b4cef35fe101bb4ecac7b1614c18e6fa48b5c7f95e19,,,
Shortcut Cmds,sha512 cmd,,,::tls::sha512 $test_data,,,d178e759dc59127071588d2fad173c06238d87e800a6403c0a30daa4faaf05d0e7ce04916afaa6a58a30cbeb597dacb01c62f9fb9d89bab9da630c699e4816f1,,,
,,,,,,,,,,
,,,,,,,,,,
command,# Test MD command for read channel,,,,,,,,,
MD Chan Read,md4,,,digest_read_chan ::tls::md $test_file -digest md4,,,793399f792eca2752c6af3234ba70858,,,
MD Chan Read,md4,md4,,digest_read_chan ::tls::md $test_file -digest md4,,,793399f792eca2752c6af3234ba70858,,,
MD Chan Read,md5,,,digest_read_chan ::tls::md $test_file -digest md5,,,962bf0803b4232ec23bd8427bb94ea09,,,
MD Chan Read,sha1,,,digest_read_chan ::tls::md $test_file -digest sha1,,,4fe03b7f2568551dfafb98ca6004e65c4b71aa7d,,,
MD Chan Read,sha256,,,digest_read_chan ::tls::md $test_file -digest sha256,,,9d3578fc138205cf0ee4b4cef35fe101bb4ecac7b1614c18e6fa48b5c7f95e19,,,
MD Chan Read,sha512,,,digest_read_chan ::tls::md $test_file -digest sha512,,,d178e759dc59127071588d2fad173c06238d87e800a6403c0a30daa4faaf05d0e7ce04916afaa6a58a30cbeb597dacb01c62f9fb9d89bab9da630c699e4816f1,,,
MD Chan Read,md5 bin,,,binary encode hex [digest_read_chan ::tls::md $test_file -bin -digest md5],,,962bf0803b4232ec23bd8427bb94ea09,,,
MD Chan Read,md5 hex,,,digest_read_chan ::tls::md $test_file -hex -digest md5,,,962bf0803b4232ec23bd8427bb94ea09,,,
,,,,,,,,,,
command,# Test MD command for write channel,,,,,,,,,
MD Chan Write,md4,,,digest_write_chan ::tls::md $test_alt_file $test_data -digest md4,,,793399f792eca2752c6af3234ba70858,,,
MD Chan Write,md4,md4,,digest_write_chan ::tls::md $test_alt_file $test_data -digest md4,,,793399f792eca2752c6af3234ba70858,,,
MD Chan Write,md5,,,digest_write_chan ::tls::md $test_alt_file $test_data -digest md5,,,962bf0803b4232ec23bd8427bb94ea09,,,
MD Chan Write,sha1,,,digest_write_chan ::tls::md $test_alt_file $test_data -digest sha1,,,4fe03b7f2568551dfafb98ca6004e65c4b71aa7d,,,
MD Chan Write,sha256,,,digest_write_chan ::tls::md $test_alt_file $test_data -digest sha256,,,9d3578fc138205cf0ee4b4cef35fe101bb4ecac7b1614c18e6fa48b5c7f95e19,,,
MD Chan Write,sha512,,,digest_write_chan ::tls::md $test_alt_file $test_data -digest sha512,,,d178e759dc59127071588d2fad173c06238d87e800a6403c0a30daa4faaf05d0e7ce04916afaa6a58a30cbeb597dacb01c62f9fb9d89bab9da630c699e4816f1,,,
MD Chan Write,md5 bin,,,binary encode hex [digest_write_chan ::tls::md $test_alt_file $test_data -bin -digest md5],,,962bf0803b4232ec23bd8427bb94ea09,,,
MD Chan Write,md5 hex,,,digest_write_chan ::tls::md $test_alt_file $test_data -hex -digest md5,,,962bf0803b4232ec23bd8427bb94ea09,,,
,,,,,,,,,,
command,# Test MD command for object command,,,,,,,,,
MD Command,md4,,,digest_accumulate $test_data ::tls::md -digest md4,,,793399f792eca2752c6af3234ba70858,,,
MD Command,md4,md4,,digest_accumulate $test_data ::tls::md -digest md4,,,793399f792eca2752c6af3234ba70858,,,
MD Command,md5,,,digest_accumulate $test_data ::tls::md -digest md5,,,962bf0803b4232ec23bd8427bb94ea09,,,
MD Command,sha1,,,digest_accumulate $test_data ::tls::md -digest sha1,,,4fe03b7f2568551dfafb98ca6004e65c4b71aa7d,,,
MD Command,sha256,,,digest_accumulate $test_data ::tls::md -digest sha256,,,9d3578fc138205cf0ee4b4cef35fe101bb4ecac7b1614c18e6fa48b5c7f95e19,,,
MD Command,sha512,,,digest_accumulate $test_data ::tls::md -digest sha512,,,d178e759dc59127071588d2fad173c06238d87e800a6403c0a30daa4faaf05d0e7ce04916afaa6a58a30cbeb597dacb01c62f9fb9d89bab9da630c699e4816f1,,,
MD Command,md5 bin,,,binary encode hex [digest_accumulate $test_data ::tls::md -digest md5 -bin],,,962bf0803b4232ec23bd8427bb94ea09,,,
MD Command,md5 hex,,,digest_accumulate $test_data ::tls::md -digest md5 -hex,,,962bf0803b4232ec23bd8427bb94ea09,,,
,,,,,,,,,,
command,# Test MD command for data shortcut,,,,,,,,,
MD Shortcut,md4,,,::tls::md md4 $test_data,,,793399f792eca2752c6af3234ba70858,,,
MD Shortcut,md4,md4,,::tls::md md4 $test_data,,,793399f792eca2752c6af3234ba70858,,,
MD Shortcut,md5,,,::tls::md md5 $test_data,,,962bf0803b4232ec23bd8427bb94ea09,,,
MD Shortcut,sha1,,,::tls::md sha1 $test_data,,,4fe03b7f2568551dfafb98ca6004e65c4b71aa7d,,,
MD Shortcut,sha256,,,::tls::md sha256 $test_data,,,9d3578fc138205cf0ee4b4cef35fe101bb4ecac7b1614c18e6fa48b5c7f95e19,,,
MD Shortcut,sha512,,,::tls::md sha512 $test_data,,,d178e759dc59127071588d2fad173c06238d87e800a6403c0a30daa4faaf05d0e7ce04916afaa6a58a30cbeb597dacb01c62f9fb9d89bab9da630c699e4816f1,,,
,,,,,,,,,,
command,# Test MD command for data,,,,,,,,,
MD Data,md4,,,::tls::md -digest md4 -data $test_data,,,793399f792eca2752c6af3234ba70858,,,
MD Data,md4,md4,,::tls::md -digest md4 -data $test_data,,,793399f792eca2752c6af3234ba70858,,,
MD Data,md5,,,::tls::md -digest md5 -data $test_data,,,962bf0803b4232ec23bd8427bb94ea09,,,
MD Data,sha1,,,::tls::md -digest sha1 -data $test_data,,,4fe03b7f2568551dfafb98ca6004e65c4b71aa7d,,,
MD Data,sha256,,,::tls::md -digest sha256 -data $test_data,,,9d3578fc138205cf0ee4b4cef35fe101bb4ecac7b1614c18e6fa48b5c7f95e19,,,
MD Data,sha512,,,::tls::md -digest sha512 -data $test_data,,,d178e759dc59127071588d2fad173c06238d87e800a6403c0a30daa4faaf05d0e7ce04916afaa6a58a30cbeb597dacb01c62f9fb9d89bab9da630c699e4816f1,,,
MD Data,md5 bin,,,binary encode hex [::tls::md -digest md5 -data $test_data -bin],,,962bf0803b4232ec23bd8427bb94ea09,,,
MD Data,md5 hex,,,::tls::md -digest md5 -data $test_data -hex,,,962bf0803b4232ec23bd8427bb94ea09,,,
,,,,,,,,,,
command,# Test MD command for file,,,,,,,,,
MD File,md4,,,::tls::md -digest md4 -file $test_file,,,793399f792eca2752c6af3234ba70858,,,
MD File,md4,md4,,::tls::md -digest md4 -file $test_file,,,793399f792eca2752c6af3234ba70858,,,
MD File,md5,,,::tls::md -digest md5 -file $test_file,,,962bf0803b4232ec23bd8427bb94ea09,,,
MD File,sha1,,,::tls::md -digest sha1 -file $test_file,,,4fe03b7f2568551dfafb98ca6004e65c4b71aa7d,,,
MD File,sha256,,,::tls::md -digest sha256 -file $test_file,,,9d3578fc138205cf0ee4b4cef35fe101bb4ecac7b1614c18e6fa48b5c7f95e19,,,
MD File,sha512,,,::tls::md -digest sha512 -file $test_file,,,d178e759dc59127071588d2fad173c06238d87e800a6403c0a30daa4faaf05d0e7ce04916afaa6a58a30cbeb597dacb01c62f9fb9d89bab9da630c699e4816f1,,,
MD File,md5 bin,,,binary encode hex [::tls::md -digest md5 -file $test_file -bin],,,962bf0803b4232ec23bd8427bb94ea09,,,
MD File,md5 hex,,,::tls::md -digest md5 -file $test_file -hex,,,962bf0803b4232ec23bd8427bb94ea09,,,
,,,,,,,,,,
1
2
3
4
5
6
7
8
9
10
11
12
13
14

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

31
32
33
34
35
36
37
1
2
3
4
5
6
7
8
9
10
11
12
13

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

30
31
32
33
34
35
36
37













-
+















-
+







# Auto generated test cases for digest.csv

# Load Tcl Test package
if {[lsearch [namespace children] ::tcltest] == -1} {
	package require tcltest
	namespace import ::tcltest::*
}

set auto_path [concat [list [file dirname [file dirname [info script]]]] $auto_path]

package require tls

# Constraints
source common.tcl
::tcltest::testConstraint md4 [expr {"md4" in [::tls::digests]}]

# Helper functions - See common.tcl
proc digest_read_chan {cmd filename args} {;set ch [open $filename rb];set bsize [fconfigure $ch -buffersize];set new [$cmd {*}$args -chan $ch];while {![eof $new]} {set md [read $new $bsize]};close $new;return $md}
proc digest_write_chan {cmd filename data args} {;set ch [open $filename wb];set new [$cmd {*}$args -chan $ch];puts -nonewline $new $data;flush $new;close $new;set ch [open $filename rb];set md [read $ch];close $ch;return $md}
proc digest_accumulate {string args} {;set cmd [{*}$args -command dcmd]; $cmd update [string range $string 0 20];$cmd update [string range $string 21 end];return [$cmd finalize]}

set test_data "Example string for message digest tests.\n"
set test_file "md_data.dat"
set test_alt_file "md_alt_data.dat"
set test_key "Example key"
::tcltest::makeFile $test_data $test_file

# Test short-cut commands


test Shortcut_Cmds-1.1 {md4 cmd} -body {
test Shortcut_Cmds-1.1 {md4 cmd} -constraints {md4} -body {
	::tls::md4 $test_data
    } -result {793399f792eca2752c6af3234ba70858}

test Shortcut_Cmds-1.2 {md5 cmd} -body {
	::tls::md5 $test_data
    } -result {962bf0803b4232ec23bd8427bb94ea09}

47
48
49
50
51
52
53
54

55
56
57
58
59
60
61
47
48
49
50
51
52
53

54
55
56
57
58
59
60
61







-
+







	::tls::sha512 $test_data
    } -result {d178e759dc59127071588d2fad173c06238d87e800a6403c0a30daa4faaf05d0e7ce04916afaa6a58a30cbeb597dacb01c62f9fb9d89bab9da630c699e4816f1}


# Test MD command for read channel


test MD_Chan_Read-2.1 {md4} -body {
test MD_Chan_Read-2.1 {md4} -constraints {md4} -body {
	digest_read_chan ::tls::md $test_file -digest md4
    } -result {793399f792eca2752c6af3234ba70858}

test MD_Chan_Read-2.2 {md5} -body {
	digest_read_chan ::tls::md $test_file -digest md5
    } -result {962bf0803b4232ec23bd8427bb94ea09}

78
79
80
81
82
83
84
85

86
87
88
89
90
91
92
78
79
80
81
82
83
84

85
86
87
88
89
90
91
92







-
+







test MD_Chan_Read-2.7 {md5 hex} -body {
	digest_read_chan ::tls::md $test_file -hex -digest md5
    } -result {962bf0803b4232ec23bd8427bb94ea09}

# Test MD command for write channel


test MD_Chan_Write-3.1 {md4} -body {
test MD_Chan_Write-3.1 {md4} -constraints {md4} -body {
	digest_write_chan ::tls::md $test_alt_file $test_data -digest md4
    } -result {793399f792eca2752c6af3234ba70858}

test MD_Chan_Write-3.2 {md5} -body {
	digest_write_chan ::tls::md $test_alt_file $test_data -digest md5
    } -result {962bf0803b4232ec23bd8427bb94ea09}

109
110
111
112
113
114
115
116

117
118
119
120
121
122
123
109
110
111
112
113
114
115

116
117
118
119
120
121
122
123







-
+







test MD_Chan_Write-3.7 {md5 hex} -body {
	digest_write_chan ::tls::md $test_alt_file $test_data -hex -digest md5
    } -result {962bf0803b4232ec23bd8427bb94ea09}

# Test MD command for object command


test MD_Command-4.1 {md4} -body {
test MD_Command-4.1 {md4} -constraints {md4} -body {
	digest_accumulate $test_data ::tls::md -digest md4
    } -result {793399f792eca2752c6af3234ba70858}

test MD_Command-4.2 {md5} -body {
	digest_accumulate $test_data ::tls::md -digest md5
    } -result {962bf0803b4232ec23bd8427bb94ea09}

140
141
142
143
144
145
146
147

148
149
150
151
152
153
154
140
141
142
143
144
145
146

147
148
149
150
151
152
153
154







-
+







test MD_Command-4.7 {md5 hex} -body {
	digest_accumulate $test_data ::tls::md -digest md5 -hex
    } -result {962bf0803b4232ec23bd8427bb94ea09}

# Test MD command for data shortcut


test MD_Shortcut-5.1 {md4} -body {
test MD_Shortcut-5.1 {md4} -constraints {md4} -body {
	::tls::md md4 $test_data
    } -result {793399f792eca2752c6af3234ba70858}

test MD_Shortcut-5.2 {md5} -body {
	::tls::md md5 $test_data
    } -result {962bf0803b4232ec23bd8427bb94ea09}

163
164
165
166
167
168
169
170

171
172
173
174
175
176
177
163
164
165
166
167
168
169

170
171
172
173
174
175
176
177







-
+







test MD_Shortcut-5.5 {sha512} -body {
	::tls::md sha512 $test_data
    } -result {d178e759dc59127071588d2fad173c06238d87e800a6403c0a30daa4faaf05d0e7ce04916afaa6a58a30cbeb597dacb01c62f9fb9d89bab9da630c699e4816f1}

# Test MD command for data


test MD_Data-6.1 {md4} -body {
test MD_Data-6.1 {md4} -constraints {md4} -body {
	::tls::md -digest md4 -data $test_data
    } -result {793399f792eca2752c6af3234ba70858}

test MD_Data-6.2 {md5} -body {
	::tls::md -digest md5 -data $test_data
    } -result {962bf0803b4232ec23bd8427bb94ea09}

194
195
196
197
198
199
200
201

202
203
204
205
206
207
208
194
195
196
197
198
199
200

201
202
203
204
205
206
207
208







-
+







test MD_Data-6.7 {md5 hex} -body {
	::tls::md -digest md5 -data $test_data -hex
    } -result {962bf0803b4232ec23bd8427bb94ea09}

# Test MD command for file


test MD_File-7.1 {md4} -body {
test MD_File-7.1 {md4} -constraints {md4} -body {
	::tls::md -digest md4 -file $test_file
    } -result {793399f792eca2752c6af3234ba70858}

test MD_File-7.2 {md5} -body {
	::tls::md -digest md5 -file $test_file
    } -result {962bf0803b4232ec23bd8427bb94ea09}

1
2
3
4
5
6
7
8
9
10
11
12
13
1
2
3



4
5
6
7
8
9
10



-
-
-







# Group,Name,Constraints,Setup,Body,Cleanup,Match,Result,Output,Error Output,Return Codes
command,package require tls,,,,,,,,,
,,,,,,,,,,
command,# Constraints,,,,,,,,,
command,source common.tcl,,,,,,,,,
,,,,,,,,,,
command,# Helper functions - See common.tcl,,,,,,,,,
command,"proc read_chan {filename args} {set ch [open $filename rb];set bsize [fconfigure $ch -buffersize];set new [{*}$args -chan $ch];set dat """";while {![eof $new]} {append dat [read $new $bsize]};close $new;return $dat}",,,,,,,,,
command,proc write_chan {filename data args} {set ch [open $filename wb];set new [{*}$args -chan $ch];puts -nonewline $new $data;flush $new;close $new;set ch [open $filename rb];set dat [read $ch];close $ch;return $dat},,,,,,,,,
command,"proc accumulate {string args} {set cmd [{*}$args -command dcmd];set ::dat """";append ::dat [$cmd update [string range $string 0 20]];append ::dat [$cmd update [string range $string 21 end]];append ::dat [$cmd finalize]}",$cmd update [string range $string 0 20];$cmd update [string range $string 21 end];return [$cmd finalize]},,,,,,,,
command,proc get_file_hex {filename} {set ch [open $filename rb];set data [read $ch];close $ch;return [binary encode hex $data]},,,,,,,,,
command,proc get_file_text {filename} {set ch [open $filename r];set data [read $ch];close $ch;return $data},,,,,,,,,
,,,,,,,,,,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1
2
3
4
5
6
7
8
9
10
11
12



13
14
15
16
17
18
19












-
-
-







# Auto generated test cases for encrypt.csv

# Load Tcl Test package
if {[lsearch [namespace children] ::tcltest] == -1} {
	package require tcltest
	namespace import ::tcltest::*
}

set auto_path [concat [list [file dirname [file dirname [info script]]]] $auto_path]

package require tls

# Constraints
source common.tcl

# Helper functions - See common.tcl
proc read_chan {filename args} {set ch [open $filename rb];set bsize [fconfigure $ch -buffersize];set new [{*}$args -chan $ch];set dat "";while {![eof $new]} {append dat [read $new $bsize]};close $new;return $dat}
proc write_chan {filename data args} {set ch [open $filename wb];set new [{*}$args -chan $ch];puts -nonewline $new $data;flush $new;close $new;set ch [open $filename rb];set dat [read $ch];close $ch;return $dat}
proc accumulate {string args} {set cmd [{*}$args -command dcmd];set ::dat "";append ::dat [$cmd update [string range $string 0 20]];append ::dat [$cmd update [string range $string 21 end]];append ::dat [$cmd finalize]}
proc get_file_hex {filename} {set ch [open $filename rb];set data [read $ch];close $ch;return [binary encode hex $data]}
proc get_file_text {filename} {set ch [open $filename r];set data [read $ch];close $ch;return $data}

1
2
3
4
5
6
7
8

9
10
11
12
13
14
15
1
2
3
4
5
6
7

8
9
10
11
12
13
14
15







-
+







# Group,Name,Constraints,Setup,Body,Cleanup,Match,Result,Output,Error Output,Return Codes
command,package require tls,,,,,,,,,
,,,,,,,,,,
command,# Make sure path includes location of OpenSSL executable,,,,,,,,,
command,"if {[info exists ::env(OPENSSL)]} {set ::env(path) [string cat [file join $::env(OPENSSL) bin] "";"" $::env(path)]}",,,,,,,,,
,,,,,,,,,,
command,# Constraints,,,,,,,,,
command,source common.tcl,,,,,,,,,
command,source [file join [file dirname [info script]] common.tcl],,,,,,,,,
,,,,,,,,,,
command,# Helper functions,,,,,,,,,
command,"proc lcompare {list1 list2} {set m """";set u """";foreach i $list1 {if {$i ni $list2} {lappend m $i}};foreach i $list2 {if {$i ni $list1} {lappend u $i}};return [list ""missing"" $m ""unexpected"" $u]}",,,,,,,,,
command,proc exec_get {delim args} {return [split [exec openssl {*}$args] $delim]},,,,,,,,,
command,"proc exec_get_ciphers {} {set list [list];set data [exec openssl list -cipher-algorithms];foreach line [split $data ""\n""] {foreach {cipher null alias} [split [string trim $line]] {lappend list [string tolower $cipher]}};return [lsort -unique $list]}",,,,,,,,,
command,"proc exec_get_digests {} {set list [list];set data [exec openssl dgst -list];foreach line [split $data ""\n""] {foreach digest $line {if {[string match ""-*"" $digest]} {lappend list [string trimleft $digest ""-""]}}};return [lsort $list]}",,,,,,,,,
command,"proc exec_get_pkeys {} {set list [list];set data [exec openssl list -public-key-methods];foreach line [split $data ""\n""] {if {![string match ""*Type:*"" $line]} {lappend list [string trim $line]}};return $list}",,,,,,,,,
10
11
12
13
14
15
16
17

18
19
20
21
22
23
24
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24







-
+








package require tls

# Make sure path includes location of OpenSSL executable
if {[info exists ::env(OPENSSL)]} {set ::env(path) [string cat [file join $::env(OPENSSL) bin] ";" $::env(path)]}

# Constraints
source common.tcl
source [file join [file dirname [info script]] common.tcl]

# Helper functions
proc lcompare {list1 list2} {set m "";set u "";foreach i $list1 {if {$i ni $list2} {lappend m $i}};foreach i $list2 {if {$i ni $list1} {lappend u $i}};return [list "missing" $m "unexpected" $u]}
proc exec_get {delim args} {return [split [exec openssl {*}$args] $delim]}
proc exec_get_ciphers {} {set list [list];set data [exec openssl list -cipher-algorithms];foreach line [split $data "\n"] {foreach {cipher null alias} [split [string trim $line]] {lappend list [string tolower $cipher]}};return [lsort -unique $list]}
proc exec_get_digests {} {set list [list];set data [exec openssl dgst -list];foreach line [split $data "\n"] {foreach digest $line {if {[string match "-*" $digest]} {lappend list [string trimleft $digest "-"]}}};return [lsort $list]}
proc exec_get_pkeys {} {set list [list];set data [exec openssl list -public-key-methods];foreach line [split $data "\n"] {if {![string match "*Type:*" $line]} {lappend list [string trim $line]}};return $list}