Comparison

util-src/crypto.c @ 12714:82bca7191f13

util.crypto: Use stack space buffers Removes assumption that LUAL_BUFFERSIZE is known at pre-processing time, which it is not in Lua 5.3 and 5.4, where it is a computed macro based on sizeof. Allocation of stack space is safer and faster, no need to worry about luaL_prepbuffer failing to allocate memory and skipping free()
author Kim Alvefur <zash@zash.se>
date Mon, 11 Jul 2022 17:01:55 +0200
parent 12702:f63176781940
child 12715:5dd00f806e32
comparison
equal deleted inserted replaced
12713:52eead170bb8 12714:82bca7191f13
432 static int Lparse_ecdsa_signature(lua_State *L) { 432 static int Lparse_ecdsa_signature(lua_State *L) {
433 ECDSA_SIG *sig; 433 ECDSA_SIG *sig;
434 size_t sig_der_len; 434 size_t sig_der_len;
435 const unsigned char *sig_der = (unsigned char*)luaL_checklstring(L, 1, &sig_der_len); 435 const unsigned char *sig_der = (unsigned char*)luaL_checklstring(L, 1, &sig_der_len);
436 const BIGNUM *r, *s; 436 const BIGNUM *r, *s;
437 luaL_Buffer rb, sb; 437 unsigned char rb[32];
438 unsigned char sb[32];
438 int rlen, slen; 439 int rlen, slen;
439 440
440 sig = d2i_ECDSA_SIG(NULL, &sig_der, sig_der_len); 441 sig = d2i_ECDSA_SIG(NULL, &sig_der, sig_der_len);
441 442
442 if(sig == NULL) { 443 if(sig == NULL) {
447 ECDSA_SIG_get0(sig, &r, &s); 448 ECDSA_SIG_get0(sig, &r, &s);
448 449
449 rlen = BN_num_bytes(r); 450 rlen = BN_num_bytes(r);
450 slen = BN_num_bytes(s); 451 slen = BN_num_bytes(s);
451 452
452 // COMPAT w/ Lua 5.1 453 if (rlen > 32 || slen > 32) {
453 #if LUAL_BUFFERSIZE < 32 454 ECDSA_SIG_free(sig);
454 #error Configured LUAL_BUFFERSIZE is too small for this operation 455 luaL_error(L, "unexpectedly large signature integers");
455 #endif 456 }
456 457
457 luaL_buffinit(L, &rb); 458 BN_bn2bin(r, rb);
458 BN_bn2bin(r, (unsigned char*)luaL_prepbuffer(&rb)); 459 BN_bn2bin(s, sb);
459 luaL_addsize(&rb, rlen);
460 luaL_pushresult(&rb);
461
462 luaL_buffinit(L, &sb);
463 BN_bn2bin(s, (unsigned char*)luaL_prepbuffer(&sb));
464 luaL_addsize(&sb, slen);
465 luaL_pushresult(&sb);
466 460
467 ECDSA_SIG_free(sig); 461 ECDSA_SIG_free(sig);
462
463 lua_pushlstring(L, (const char*)rb, rlen);
464 lua_pushlstring(L, (const char*)sb, slen);
468 465
469 return 2; 466 return 2;
470 } 467 }
471 468
472 /* sig_der = build_ecdsa_signature(r, s) */ 469 /* sig_der = build_ecdsa_signature(r, s) */