// TOSV in-tree TLS 1.3 server (SEC-11, ADR 0011). No external TLS library: only libsodium and mlkem-native,
// both already linked. Profile: TLS 1.3 only, TLS_CHACHA20_POLY1305_SHA256, key exchange X25519MLKEM768
// (hybrid post-quantum, codepoint 0x11EC), plain X25519 only when TOSV_TLS_ALLOW_CLASSICAL=1, Ed25519
// certificate (sigalg 0x0807), no client auth, no resumption, no 0-RTT, no HelloRetryRequest.
// Included once by tosv.cpp after vault.inc (needs wipe_mem, sodium.h, mlkem_native.h).
typedef std::vector<unsigned char> TBytes;
struct TlsId{TBytes certs;unsigned char sk[64]={0},pk[32]={0};bool ok=false;};
static void t_put(TBytes&o,const void*p,size_t n){const unsigned char*c=(const unsigned char*)p;o.insert(o.end(),c,c+n);}
static void t_u8(TBytes&o,unsigned v){o.push_back((unsigned char)v);}
static void t_u16(TBytes&o,unsigned v){o.push_back((unsigned char)(v>>8));o.push_back((unsigned char)v);}
static void t_u24(TBytes&o,size_t v){o.push_back((unsigned char)(v>>16));o.push_back((unsigned char)(v>>8));o.push_back((unsigned char)v);}
static TBytes t_hmac(const TBytes&key,const TBytes&d){TBytes o(32);crypto_auth_hmacsha256_state s;crypto_auth_hmacsha256_init(&s,key.data(),key.size());crypto_auth_hmacsha256_update(&s,d.data(),d.size());crypto_auth_hmacsha256_final(&s,o.data());return o;}
static TBytes t_label(const TBytes&secret,const std::string&label,const TBytes&ctx,size_t len){std::string l="tls13 "+label;TBytes info;t_u16(info,(unsigned)len);t_u8(info,(unsigned)l.size());t_put(info,l.data(),l.size());t_u8(info,(unsigned)ctx.size());t_put(info,ctx.data(),ctx.size());t_u8(info,1);TBytes o=t_hmac(secret,info);o.resize(len);return o;}
static TBytes t_sha(const TBytes&d){TBytes o(32);crypto_hash_sha256(o.data(),d.data(),d.size());return o;}
static bool t_b64(const std::string&in,TBytes&out){std::string c;for(char ch:in)if(ch!=' '&&ch!='\r'&&ch!='\n'&&ch!='\t')c+=ch;out.assign(c.size()+4,0);size_t n=0;if(sodium_base642bin(out.data(),out.size(),c.data(),c.size(),nullptr,&n,nullptr,sodium_base64_VARIANT_ORIGINAL)!=0)return false;out.resize(n);return true;}
static std::string t_pem(const TBytes&d,const char*tag){std::string b((d.size()+2)/3*4+1,0);sodium_bin2base64(&b[0],b.size(),d.data(),d.size(),sodium_base64_VARIANT_ORIGINAL);b.resize(strlen(b.c_str()));std::string o=std::string("-----BEGIN ")+tag+"-----\n";for(size_t i=0;i<b.size();i+=64)o+=b.substr(i,64)+"\n";return o+"-----END "+tag+"-----\n";}
static const unsigned char T_PKCS8[16]={0x30,0x2e,0x02,0x01,0x00,0x30,0x05,0x06,0x03,0x2b,0x65,0x70,0x04,0x22,0x04,0x20};
static bool t_slurp(const char*p,std::string&o){std::ifstream f(p,std::ios::binary);if(!f)return false;std::stringstream s;s<<f.rdbuf();o=s.str();return o.size()<=65536;}
// Loads PEM cert chain plus PKCS#8 Ed25519 key. Refuses anything that is not Ed25519 or does not match.
static bool tls_load_id(const char*certp,const char*keyp,TlsId&id,std::string&err){
std::string cp,kp;if(!t_slurp(certp,cp)||!t_slurp(keyp,kp)){err="cert or key unreadable";return false;}
size_t a=kp.find("-----BEGIN PRIVATE KEY-----"),b=kp.find("-----END PRIVATE KEY-----");TBytes kd;if(a==std::string::npos||b==std::string::npos||!t_b64(kp.substr(a+27,b-a-27),kd)||kd.size()!=48||memcmp(kd.data(),T_PKCS8,16)!=0){err="key must be an unencrypted PKCS#8 Ed25519 PEM";return false;}
crypto_sign_seed_keypair(id.pk,id.sk,kd.data()+16);sodium_memzero(kd.data(),kd.size());
TBytes list;size_t pos=0,count=0;bool first=true;while(true){size_t s=cp.find("-----BEGIN CERTIFICATE-----",pos);if(s==std::string::npos)break;size_t e=cp.find("-----END CERTIFICATE-----",s);if(e==std::string::npos)break;TBytes der;if(!t_b64(cp.substr(s+27,e-s-27),der)||der.size()<64||der.size()>16000){err="bad certificate PEM";return false;}
if(first){if(!memmem(der.data(),der.size(),id.pk,32)){err="certificate does not match key (Ed25519 only)";return false;}first=false;}
t_u24(list,der.size());t_put(list,der.data(),der.size());t_u16(list,0);pos=e+25;if(++count>4)break;}
if(!count){err="no certificate in file";return false;}
id.certs.clear();t_u8(id.certs,0);t_u24(id.certs,list.size());t_put(id.certs,list.data(),list.size());id.ok=true;return true;}
// ---- minimal self-signed Ed25519 certificate (DER), so TLS needs no external tool ----
static TBytes t_der(unsigned tag,const TBytes&c){TBytes o;t_u8(o,tag);if(c.size()<128)t_u8(o,(unsigned)c.size());else if(c.size()<256){t_u8(o,0x81);t_u8(o,(unsigned)c.size());}else{t_u8(o,0x82);t_u16(o,(unsigned)c.size());}t_put(o,c.data(),c.size());return o;}
static TBytes t_cat(std::initializer_list<TBytes> l){TBytes o;for(auto&x:l)t_put(o,x.data(),x.size());return o;}
static TBytes t_utc(time_t t){tm g;gmtime_r(&t,&g);char b[16];strftime(b,sizeof b,"%y%m%d%H%M%SZ",&g);TBytes c;t_put(c,b,13);return t_der(0x17,c);}
static bool tls_selfsign(const std::string&cn,const std::string&certp,const std::string&keyp,std::string&err){
if(cn.empty()||cn.size()>64||cn.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-")!=std::string::npos){err="name must be a hostname or IPv4 address";return false;}
if(access(certp.c_str(),F_OK)==0||access(keyp.c_str(),F_OK)==0){err="refusing to overwrite existing cert or key";return false;}
unsigned char seed[32],pk[32],sk[64];randombytes_buf(seed,32);crypto_sign_seed_keypair(pk,sk,seed);
TBytes oid={0x06,0x03,0x2b,0x65,0x70};TBytes alg=t_der(0x30,TBytes(oid));
TBytes cnb;t_put(cnb,cn.data(),cn.size());TBytes name=t_der(0x30,t_der(0x31,t_der(0x30,t_cat({TBytes{0x06,0x03,0x55,0x04,0x03},t_der(0x0c,cnb)}))));
TBytes ser(16);randombytes_buf(ser.data(),16);ser[0]=(unsigned char)((ser[0]&0x7f)|0x01);
time_t now=time(nullptr);TBytes val=t_der(0x30,t_cat({t_utc(now-86400),t_utc(now+86400*365)}));
TBytes pkb;t_u8(pkb,0);t_put(pkb,pk,32);TBytes spki=t_der(0x30,t_cat({alg,t_der(0x03,pkb)}));
struct in_addr ia;bool isip=inet_pton(AF_INET,cn.c_str(),&ia)==1;TBytes sanv;if(isip)t_put(sanv,&ia,4);else t_put(sanv,cn.data(),cn.size());
TBytes san=t_der(0x30,t_der(0x30,t_cat({TBytes{0x06,0x03,0x55,0x1d,0x11},t_der(0x04,t_der(0x30,t_der(isip?0x87:0x82,sanv)))})));
TBytes tbs=t_der(0x30,t_cat({TBytes{0xa0,0x03,0x02,0x01,0x02},t_der(0x02,ser),alg,name,val,name,spki,t_der(0xa3,san)}));
unsigned char sig[64];crypto_sign_detached(sig,nullptr,tbs.data(),tbs.size(),sk);TBytes sb;t_u8(sb,0);t_put(sb,sig,64);
TBytes cert=t_der(0x30,t_cat({tbs,alg,t_der(0x03,sb)}));
TBytes kd(T_PKCS8,T_PKCS8+16);t_put(kd,seed,32);
int kf=open(keyp.c_str(),O_WRONLY|O_CREAT|O_EXCL,0600);if(kf<0){err="cannot create key file";return false;}std::string kpem=t_pem(kd,"PRIVATE KEY");bool w=write(kf,kpem.data(),kpem.size())==(ssize_t)kpem.size();close(kf);
std::string cpem=t_pem(cert,"CERTIFICATE");std::ofstream cf(certp);cf<<cpem;if(!w||!cf.good()){err="write failed";return false;}
sodium_memzero(seed,32);sodium_memzero(sk,64);return true;}
// ---- connection ----
struct Tls13{
int fd;bool pq_only;const TlsId*id;crypto_hash_sha256_state th;TBytes rk,riv,wk,wiv,rsec,wsec;uint64_t rseq=0,wseq=0;bool renc=false,wenc=false;
std::chrono::steady_clock::time_point dl;
Tls13(int f,bool pq,const TlsId*i):fd(f),pq_only(pq),id(i){crypto_hash_sha256_init(&th);dl=std::chrono::steady_clock::now()+std::chrono::seconds(30);}
~Tls13(){for(TBytes*v:{&rk,&riv,&wk,&wiv,&rsec,&wsec})if(!v->empty())sodium_memzero(v->data(),v->size());}
bool rd(void*p,size_t n){unsigned char*c=(unsigned char*)p;size_t o=0;while(o<n){ssize_t r=recv(fd,c+o,n-o,0);if(r<=0)return false;o+=(size_t)r;}return true;}
bool wr(const void*p,size_t n){const char*c=(const char*)p;size_t o=0;while(o<n){ssize_t w=send(fd,c+o,n-o,MSG_NOSIGNAL);if(w<=0)return false;o+=(size_t)w;}return true;}
static TBytes nonce(const TBytes&iv,uint64_t s){TBytes n=iv;for(int i=0;i<8;i++)n[11-i]^=(unsigned char)(s>>(8*i));return n;}
bool send_rec(unsigned type,const TBytes&d){TBytes h;if(!wenc){if(d.size()>16384)return false;t_u8(h,type);t_u16(h,0x0303);t_u16(h,(unsigned)d.size());TBytes o=h;t_put(o,d.data(),d.size());return wr(o.data(),o.size());}
TBytes in=d;t_u8(in,type);t_u8(h,23);t_u16(h,0x0303);t_u16(h,(unsigned)in.size()+16);TBytes ct(in.size()+16);unsigned long long cl=0;TBytes n=nonce(wiv,wseq++);crypto_aead_chacha20poly1305_ietf_encrypt(ct.data(),&cl,in.data(),in.size(),h.data(),5,nullptr,n.data(),wk.data());sodium_memzero(in.data(),in.size());TBytes o=h;t_put(o,ct.data(),(size_t)cl);return wr(o.data(),o.size());}
// reads one record; returns inner type and plaintext. Skips compatibility CCS records.
bool read_rec(unsigned&type,TBytes&out){for(int skip=0;skip<4;skip++){if(std::chrono::steady_clock::now()>dl&&!renc)return false;unsigned char h[5];if(!rd(h,5))return false;size_t len=((size_t)h[3]<<8)|h[4];if(len>16384+256||len==0)return false;TBytes b(len);if(!rd(b.data(),len))return false;
if(h[0]==20){if(len==1&&b[0]==1)continue;return false;}
if(!renc){if(h[0]!=22&&h[0]!=21)return false;type=h[0];out=b;return true;}
if(h[0]!=23||len<17)return false;out.assign(len-16,0);unsigned long long ol=0;TBytes n=nonce(riv,rseq++);if(crypto_aead_chacha20poly1305_ietf_decrypt(out.data(),&ol,nullptr,b.data(),len,h,5,n.data(),rk.data())!=0)return false;out.resize((size_t)ol);while(!out.empty()&&out.back()==0)out.pop_back();if(out.empty())return false;type=out.back();out.pop_back();return true;}return false;}
void keys(const TBytes&sec,TBytes&k,TBytes&iv){TBytes e;k=t_label(sec,"key",e,32);iv=t_label(sec,"iv",e,12);}
TBytes thash(){crypto_hash_sha256_state c=th;TBytes o(32);crypto_hash_sha256_final(&c,o.data());return o;}
bool send_hs(unsigned type,const TBytes&body,TBytes*flight=nullptr){TBytes m;t_u8(m,type);t_u24(m,body.size());t_put(m,body.data(),body.size());crypto_hash_sha256_update(&th,m.data(),m.size());if(flight){t_put(*flight,m.data(),m.size());return true;}return send_rec(22,m);}
void alert(unsigned d){TBytes a={2,(unsigned char)d};send_rec(21,a);}
bool handshake(){
unsigned ty=0;TBytes ch;if(!read_rec(ty,ch)||ty!=22||ch.size()<42||ch[0]!=1)return false;size_t bl=((size_t)ch[1]<<16)|((size_t)ch[2]<<8)|ch[3];if(bl+4!=ch.size())return false;
TBytes sid;const unsigned char*kpq=nullptr;const unsigned char*kx=nullptr;bool ccs_sent=false;
for(int round=0;;round++){
crypto_hash_sha256_update(&th,ch.data(),ch.size());
size_t p=4,N=ch.size();auto u8=[&](size_t&v)->bool{if(p+1>N)return false;v=ch[p++];return true;};auto u16=[&](size_t&v)->bool{if(p+2>N)return false;v=((size_t)ch[p]<<8)|ch[p+1];p+=2;return true;};
size_t v;if(!u16(v))return false;p+=32;if(p>N)return false;size_t sl;if(!u8(sl)||sl>32||p+sl>N)return false;sid.assign(ch.begin()+p,ch.begin()+p+sl);p+=sl;
size_t cl;if(!u16(cl)||cl%2||p+cl>N)return false;bool suite=false;for(size_t i=0;i<cl;i+=2)if(ch[p+i]==0x13&&ch[p+i+1]==0x03)suite=true;p+=cl;
size_t ml;if(!u8(ml)||p+ml>N)return false;bool nullc=false;for(size_t i=0;i<ml;i++)if(ch[p+i]==0)nullc=true;p+=ml;if(!nullc)return false;
size_t el;if(!u16(el)||p+el!=N)return false;
bool v13=false,sig=false,gpq=false;kpq=nullptr;kx=nullptr;
while(p<N){size_t et,elen;if(!u16(et)||!u16(elen)||p+elen>N)return false;size_t q=p;p+=elen;
if(et==0x2b){if(elen<1||ch[q]+1u!=elen)return false;for(size_t i=1;i+1<elen;i+=2)if(ch[q+i]==3&&ch[q+i+1]==4)v13=true;}
else if(et==0x0a){if(elen<2)return false;for(size_t i=2;i+1<elen;i+=2)if(ch[q+i]==0x11&&ch[q+i+1]==0xec)gpq=true;}
else if(et==0x0d){if(elen<2)return false;for(size_t i=2;i+1<elen;i+=2)if(ch[q+i]==0x08&&ch[q+i+1]==0x07)sig=true;}
else if(et==0x33){if(elen<2)return false;size_t tl=((size_t)ch[q]<<8)|ch[q+1];if(tl+2!=elen)return false;size_t r=q+2;while(r+4<=q+elen){size_t g=((size_t)ch[r]<<8)|ch[r+1],gl=((size_t)ch[r+2]<<8)|ch[r+3];r+=4;if(r+gl>q+elen)return false;if(g==0x11ec&&gl==1184+32)kpq=&ch[r];else if(g==0x001d&&gl==32)kx=&ch[r];r+=gl;}}}
if(!v13){alert(70);return false;}if(!suite||!sig){alert(40);return false;}
if(!kpq&&!(kx&&!pq_only)&&gpq&&round==0){TBytes h1=thash();crypto_hash_sha256_init(&th);TBytes mh={254,0,0,32};t_put(mh,h1.data(),32);crypto_hash_sha256_update(&th,mh.data(),mh.size());
static const unsigned char HRR[32]={0xCF,0x21,0xAD,0x74,0xE5,0x9A,0x61,0x11,0xBE,0x1D,0x8C,0x02,0x1E,0x65,0xB8,0x91,0xC2,0xA2,0x11,0x16,0x7A,0xBB,0x8C,0x5E,0x07,0x9E,0x09,0xE2,0xC8,0xA8,0x33,0x9C};
TBytes hb;t_u16(hb,0x0303);t_put(hb,HRR,32);t_u8(hb,(unsigned)sid.size());t_put(hb,sid.data(),sid.size());t_u16(hb,0x1303);t_u8(hb,0);TBytes he;t_u16(he,0x002b);t_u16(he,2);t_u16(he,0x0304);t_u16(he,0x0033);t_u16(he,2);t_u16(he,0x11ec);t_u16(hb,(unsigned)he.size());t_put(hb,he.data(),he.size());
if(!send_hs(2,hb))return false;{TBytes h={20,3,3,0,1,1};if(!wr(h.data(),h.size()))return false;ccs_sent=true;}
if(!read_rec(ty,ch)||ty!=22||ch.size()<42||ch[0]!=1)return false;size_t bl2=((size_t)ch[1]<<16)|((size_t)ch[2]<<8)|ch[3];if(bl2+4!=ch.size())return false;continue;}
break;}
unsigned char xs[32],xp[32];randombytes_buf(xs,32);crypto_scalarmult_curve25519_base(xp,xs);unsigned char ss[64];TBytes share;unsigned grp;
if(kpq){unsigned char ct[MLKEM768_CIPHERTEXTBYTES];if(mlkem_enc(ct,ss,kpq)!=0||crypto_scalarmult_curve25519(ss+32,xs,kpq+1184)!=0){alert(47);return false;}t_put(share,ct,sizeof ct);t_put(share,xp,32);grp=0x11ec;}
else if(kx&&!pq_only){if(crypto_scalarmult_curve25519(ss,xs,kx)!=0){alert(47);return false;}t_put(share,xp,32);grp=0x001d;}
else{alert(40);return false;}
sodium_memzero(xs,32);
TBytes sh;t_u16(sh,0x0303);TBytes rnd(32);randombytes_buf(rnd.data(),32);t_put(sh,rnd.data(),32);t_u8(sh,(unsigned)sid.size());t_put(sh,sid.data(),sid.size());t_u16(sh,0x1303);t_u8(sh,0);
TBytes ext;t_u16(ext,0x002b);t_u16(ext,2);t_u16(ext,0x0304);t_u16(ext,0x0033);t_u16(ext,(unsigned)share.size()+4);t_u16(ext,grp);t_u16(ext,(unsigned)share.size());t_put(ext,share.data(),share.size());t_u16(sh,(unsigned)ext.size());t_put(sh,ext.data(),ext.size());
if(!send_hs(2,sh))return false;if(!ccs_sent){TBytes h={20,3,3,0,1,1};if(!wr(h.data(),h.size()))return false;}
TBytes e;TBytes zero(32,0);TBytes early=t_hmac(zero,zero);TBytes empty=t_sha(e);TBytes d1=t_label(early,"derived",empty,32);TBytes sharedv(ss,ss+(grp==0x11ec?64:32));sodium_memzero(ss,64);TBytes hs=t_hmac(d1,sharedv);sodium_memzero(sharedv.data(),sharedv.size());
TBytes h1=thash();TBytes chs=t_label(hs,"c hs traffic",h1,32),shs=t_label(hs,"s hs traffic",h1,32);
wsec=shs;keys(shs,wk,wiv);wenc=true;wseq=0;rsec=chs;keys(chs,rk,riv);renc=true;rseq=0;
TBytes flight;send_hs(8,TBytes{0,0},&flight);
send_hs(11,id->certs,&flight);
{TBytes th2=thash();TBytes c;for(int i=0;i<64;i++)c.push_back(0x20);const char*cs="TLS 1.3, server CertificateVerify";t_put(c,cs,strlen(cs));c.push_back(0);t_put(c,th2.data(),32);unsigned char sg[64];crypto_sign_detached(sg,nullptr,c.data(),c.size(),id->sk);TBytes cv;t_u16(cv,0x0807);t_u16(cv,64);t_put(cv,sg,64);send_hs(15,cv,&flight);}
{TBytes fk=t_label(shs,"finished",e,32);TBytes vd=t_hmac(fk,thash());sodium_memzero(fk.data(),32);send_hs(20,vd,&flight);}
TBytes d2=t_label(hs,"derived",empty,32);TBytes master=t_hmac(d2,zero);TBytes h2=thash();TBytes cap=t_label(master,"c ap traffic",h2,32),sap=t_label(master,"s ap traffic",h2,32);
for(size_t o=0;o<flight.size();o+=16000){size_t n=std::min<size_t>(16000,flight.size()-o);if(!send_rec(22,TBytes(flight.begin()+o,flight.begin()+o+n)))return false;}
// client Finished
TBytes cf;if(!read_rec(ty,cf)||ty!=22||cf.size()!=36||cf[0]!=20||cf[1]!=0||cf[2]!=0||cf[3]!=32)return false;
TBytes cfk=t_label(chs,"finished",e,32);TBytes exp=t_hmac(cfk,h2);sodium_memzero(cfk.data(),32);if(sodium_memcmp(exp.data(),cf.data()+4,32)!=0)return false;
rsec=cap;keys(cap,rk,riv);rseq=0;wsec=sap;keys(sap,wk,wiv);wseq=0;
for(TBytes*x:{&hs,&master,&chs,&shs,&cap,&sap})sodium_memzero(x->data(),x->size());
return true;}
// returns app data in out; false on close/error. Handles KeyUpdate; alerts end the stream.
int read_app(TBytes&out){unsigned ty;TBytes b;while(true){if(!read_rec(ty,b))return -1;if(ty==23){out=b;return 1;}if(ty==21)return 0;
if(ty==22){if(b.size()!=5||b[0]!=24||b[3]!=1||b[4]>1)return -1;TBytes e;rsec=t_label(rsec,"traffic upd",e,32);keys(rsec,rk,riv);rseq=0;if(b[4]==1){TBytes u={24,0,0,1,0};if(!send_rec(22,u))return -1;wsec=t_label(wsec,"traffic upd",e,32);keys(wsec,wk,wiv);wseq=0;}continue;}return -1;}}
};