// vault.inc - shared TOSV vault core: paths, DB, audit, rates, crypto. // Included by tosv.cpp and tosv-sftp.cpp (one TU per binary). // All state here is per-process by construction. Socket IO stays in mains. #pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static void wipe_mem(void*p,size_t n){volatile unsigned char*v=(volatile unsigned char*)p;for(size_t i=0;i> ATT; static std::string hexr(size_t n){std::random_device r;std::string s;const char* h="0123456789abcdef";while(s.size()>(k*4))&0xF];}return s;} static std::string __attribute__((unused)) uuid4(){ std::random_device r; unsigned char b[16]; for(int i=0;i<16;i++) b[i]=(unsigned char)(r()%256); b[6]=(b[6]&0x0F)|0x40; b[8]=(b[8]&0x3F)|0x80; char o[37]; snprintf(o,37,"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8],b[9],b[10],b[11],b[12],b[13],b[14],b[15]); return std::string(o); } // LEGACY FROZEN: hand-rolled hash kept byte-identical for v1 decrypt only. // It is NOT standard SHA-256 (T1/Ch read state words 3,4,5 instead of 4,5,6; // found 2026-10-31 by known-answer test). Never use for new data; v2 tags // use crypto_hash_sha256. Touching this breaks v1 blob readability. typedef uint32_t U; struct Leg256{ U h[8]; unsigned long long l; unsigned char b[64]; int n; }; #define LEGRR(x,y) ((x>>y)|(x<<(32-y))) static U KLEG[64]={0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2}; static void leg_init(Leg256*c){c->h[0]=0x6a09e667;c->h[1]=0xbb67ae85;c->h[2]=0x3c6ef372;c->h[3]=0xa54ff53a;c->h[4]=0x510e527f;c->h[5]=0x9b05688c;c->h[6]=0x1f83d9ab;c->h[7]=0x5be0cd19;c->l=0;c->n=0;} static void leg_blk(Leg256*c,unsigned char*p){U w[64];for(int i=0;i<16;i++)w[i]=(U(p[4*i])<<24)|(U(p[4*i+1])<<16)|(U(p[4*i+2])<<8)|U(p[4*i+3]);for(int i=16;i<64;i++){U s0=LEGRR(w[i-15],7)^LEGRR(w[i-15],18)^(w[i-15]>>3),s1=LEGRR(w[i-2],17)^LEGRR(w[i-2],19)^(w[i-2]>>10);w[i]=w[i-16]+s0+w[i-7]+s1;}U a=c->h[0],b=c->h[1],d=c->h[2],e=c->h[3],f=c->h[4],g=c->h[5],h=c->h[6],k=c->h[7];for(int i=0;i<64;i++){U S1=LEGRR(e,6)^LEGRR(e,11)^LEGRR(e,25),ch=(e&f)^(~e&g),t1=k+S1+ch+KLEG[i]+w[i],S0=LEGRR(a,2)^LEGRR(a,13)^LEGRR(a,22),mj=(a&b)^(a&d)^(b&d),t2=S0+mj;k=h;h=g;g=f;f=e;e=d+t1;d=b;b=a;a=t1+t2;}c->h[0]+=a;c->h[1]+=b;c->h[2]+=d;c->h[3]+=e;c->h[4]+=f;c->h[5]+=g;c->h[6]+=h;c->h[7]+=k;} static void leg_upd(Leg256*c,unsigned char*p,size_t n){c->l+=n;while(n){size_t t=64-c->n;if(t>n)t=n;memcpy(c->b+c->n,p,t);c->n+=t;p+=t;n-=t;if(c->n==64){leg_blk(c,c->b);c->n=0;}}} static void leg_fin(Leg256*c,unsigned char*o){unsigned long long bl=c->l*8;unsigned char q=0x80;leg_upd(c,&q,1);q=0;while(c->n!=56)leg_upd(c,&q,1);unsigned char L[8];for(int i=0;i<8;i++)L[i]=(bl>>((7-i)*8))&255;leg_upd(c,L,8);for(int i=0;i<8;i++){o[4*i]=c->h[i]>>24;o[4*i+1]=c->h[i]>>16;o[4*i+2]=c->h[i]>>8;o[4*i+3]=c->h[i];}} static std::vector leg_hash(const std::string& s){Leg256 c;leg_init(&c);leg_upd(&c,(unsigned char*)s.data(),s.size());unsigned char o[32];leg_fin(&c,o);return std::vector(o,o+32);} // ---- DB: simple key=value + grants, flock-guarded cross-process ---- struct Grant{ std::string gu,gp,gid,ips,frm,to; }; struct DB{ bool used=false; std::string su,sp,duress; bool tw=false; int layers=3; std::vector grants; }; static std::string escg(std::string s){std::string o;for(char c:s){if(c=='\\')o+="\\\\";else if(c=='|')o+="\\p";else if(c=='\n')o+="\\n";else if(c=='\r')o+="\\r";else o+=c;}return o;} static std::string unescg(std::string s){std::string o;for(size_t i=0;i0)raw.append(b,r);} flock(fd,LOCK_UN); close(fd); std::istringstream f(raw); std::string l; auto unesc=[](std::string s){std::string o;for(size_t i=0;i L(DBC.m);if(DBC.have&&DBC.missing==m1&&(m1||db_same(DBC.mt,t1)))return DBC.db;} DB d=load_db();struct timespec t2={0,0};bool m2=db_st(t2); if(m1!=m2||(!m1&&!db_same(t1,t2)))return d; {std::lock_guard L(DBC.m);DBC.db=d;DBC.have=true;DBC.missing=m1;DBC.mt=t1;} return d;} // ---- audit: one O_APPEND write per line, whole lines only ---- static void audit(std::string a,std::string ip="-"){for(char&ch:a)if(ch=='\n'||ch=='\r')ch='_';for(char&ch:ip)if(ch=='\n'||ch=='\r')ch='_';if(a.size()>3800)a="audit-overflow";std::lock_guard L(M);auto n=std::chrono::system_clock::now();std::time_t t=std::chrono::system_clock::to_time_t(n);char b[64];struct tm gt;gmtime_r(&t,>);strftime(b,64,"%FT%TZ",>);std::string line=std::string(b)+" "+ip+" "+a+"\n";int fd=open(AUDF().c_str(),O_WRONLY|O_CREAT|O_APPEND,0600);if(fd<0)return;size_t off=0;while(off L(M);long long n=std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count();if(ATT.size()>10000)ATT.erase(ATT.begin());auto&v=ATT[k];std::vector w;for(auto t:v)if(n-t BLK; static long long epoch_now(){return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count();} static bool is_blocked(std::string ip){std::lock_guard L(M);auto it=BLK.find(ip);return it!=BLK.end()&&epoch_now()second;} static void strike(std::string ip){long long n=epoch_now();std::lock_guard L(M);if(ATT.size()>10000)ATT.erase(ATT.begin());if(BLK.size()>10000)BLK.erase(BLK.begin());auto&v=ATT["blk:"+ip];std::vector w;for(auto t:v)if(n-t<300)w.push_back(t);w.push_back(n);v=w;if((int)v.size()>=20)BLK[ip]=n+3600;} static bool ip_ok(std::string allow,std::string ip){if(allow.empty())return true;unsigned char pb[16];int pf=ip.find(':')==std::string::npos?AF_INET:AF_INET6;if(inet_pton(pf,ip.c_str(),pb)!=1)return false;size_t pl=pf==AF_INET?4:16;int maxb=pf==AF_INET?32:128;std::stringstream ss(allow);std::string c;while(std::getline(ss,c,',')){while(!c.empty()&&c[0]==' ')c.erase(c.begin());while(!c.empty()&&c.back()==' ')c.pop_back();if(c.empty())continue;auto p=c.find('/');std::string host=p==std::string::npos?c:c.substr(0,p);int bits=-1;if(p!=std::string::npos){std::string bs=c.substr(p+1);long bv=-1;if(!bs.empty()&&bs.size()<=3){bv=0;for(char ch:bs){if(ch<'0'||ch>'9'){bv=-1;break;}bv=bv*10+(ch-'0');}if(bv>128)bv=-1;}if(bv<0)continue;bits=(int)bv;}unsigned char hb[16];int hf=host.find(':')==std::string::npos?AF_INET:AF_INET6;if(hf!=pf)continue;if(inet_pton(hf,host.c_str(),hb)!=1)continue;if(bits<0){if(memcmp(pb,hb,pl)==0)return true;continue;}if(bits>maxb)continue;int full=bits/8,rem=bits%8;if(full>0&&memcmp(pb,hb,(size_t)full)!=0)continue;if(rem){unsigned char m=(unsigned char)(0xFF<<(8-rem));if(((pb[full]^hb[full])&m)!=0)continue;}return true;}return false;} static std::string window_now(){time_t nt=time(0);char nb[32];strftime(nb,32,"%FT%H:%M",gmtime(&nt));return std::string(nb);} static bool __attribute__((unused)) valid_ts(std::string t){if(t.size()!=16||t[4]!='-'||t[7]!='-'||t[10]!='T'||t[13]!=':')return false;for(size_t i=0;i<16;i++){if(i==4||i==7||i==10||i==13)continue;if(t[i]<'0'||t[i]>'9')return false;}return true;} static bool __attribute__((unused)) fid_ok(std::string f){if(f.empty()||f.size()>64)return false;for(char c:f){bool ok=(c>='a'&&c<='z')||(c>='A'&&c<='Z')||(c>='0'&&c<='9')||c=='-'||c=='_';if(!ok)return false;}return true;} static bool store_full(){size_t bc=0;try{for(auto&p:fs::directory_iterator(STORED())){if(!p.is_regular_file())continue;std::string n=p.path().filename().string();if(n.size()>4&&n.substr(n.size()-4)==".tag")continue;if(n.size()>5&&n.find(".part.")!=std::string::npos)continue;if(++bc>100000)return true;}}catch(...){}return false;} static int tag_layers(std::string p,int fb){std::ifstream f(p+".tag");std::string h;int l=0;if(f>>h&&(f>>l)&&l>=1&&l<=8)return l;return fb;} struct LKeys{std::vector> v;~LKeys(){for(auto&k:v){wipe_mem(k.data(),k.size());munlock(k.data(),k.size());}}}; static LKeys derive(std::string auth,std::string memhex,int layers){ParamWipe _pw(auth);std::vector prev;for(size_t i=0;i>&ks,long long off){for(auto&k:ks){size_t kl=k.size();for(size_t i=0;i b(65536);while(f){f.read((char*)b.data(),65536);std::streamsize n=f.gcount();if(n>0)leg_upd(&c,b.data(),(size_t)n);}unsigned char o[32];leg_fin(&c,o);char h[65];for(int i=0;i<32;i++)snprintf(h+2*i,3,"%02x",o[i]);return std::string(h);} static int tag_check(std::string p,int lay){std::string t=p+".tag";std::string now=leg_fhash(p);std::ifstream f(t);std::string old;if(!(f>>old)){std::ofstream o(t);o< b(65536);while(f){f.read((char*)b.data(),65536);std::streamsize n=f.gcount();if(n>0)crypto_hash_sha256_update(&st,b.data(),(size_t)n);}unsigned char o[32];crypto_hash_sha256_final(&st,o);char h[65];for(int i=0;i<32;i++)snprintf(h+2*i,3,"%02x",o[i]);return std::string(h);} static int blob_ver(std::string p){std::ifstream f(p+".tag");std::string h;int l=0,v=1;if(f>>h){if(!(f>>l))return 1;if(!(f>>v))return 1;return v;}std::ifstream b(p,std::ios::binary);return b.get()==2?2:1;} static bool v2_plain_len(size_t fl,size_t&out){if(fl<58)return false;size_t body=fl-41,CS=65536,step=CS+17;size_t nf=body/step,rem=body%step;if(rem!=0&&rem<17)return false;out=(rem==0)?nf*CS:nf*CS+rem-17;return true;} static size_t dav_len(std::string p){size_t fl=0;try{fl=fs::file_size(p);}catch(...){return 0;}if(blob_ver(p)==2){size_t pl=0;if(v2_plain_len(fl,pl))return pl;}return fl;} struct VKey{unsigned char k[32];VKey(){mlock(k,32);}~VKey(){wipe_mem(k,32);munlock(k,32);}}; static std::mutex KDFM; // ---- v2 key cache: memoizes KDF only, never verification ---- // entry binds blob path plus header salt; TTL 300s, cap 128 LRU, // guarded sodium_malloc keys, wipe-on-evict, flush on duress wipe. // One instance per process; never shared across processes. struct KCEnt{unsigned char salt[16];unsigned char*key;long long last;std::list::iterator li;}; struct KeyCache{std::mutex m;std::map c;std::list l;static const int CAP=128,TTL=300; void free_ent(KCEnt&e){if(e.key){sodium_free(e.key);e.key=nullptr;}} void flush(){std::lock_guard L(m);for(auto&kv:c)free_ent(kv.second);c.clear();l.clear();} bool get(std::string p,unsigned char*salt,VKey&out){std::lock_guard L(m);auto it=c.find(p);if(it==c.end())return false;long long n=epoch_now();if(n-it->second.last>TTL||memcmp(it->second.salt,salt,16)!=0){free_ent(it->second);l.erase(it->second.li);c.erase(it);return false;}memcpy(out.k,it->second.key,32);it->second.last=n;l.erase(it->second.li);l.push_front(p);it->second.li=l.begin();return true;} void put(std::string p,unsigned char*salt,VKey&key){unsigned char*nk=(unsigned char*)sodium_malloc(32);if(!nk)return;memcpy(nk,key.k,32);std::lock_guard L(m);long long n=epoch_now();for(auto s=c.begin();s!=c.end();){if(n-s->second.last>TTL){free_ent(s->second);l.erase(s->second.li);s=c.erase(s);}else ++s;}auto it=c.find(p);if(it!=c.end()&&memcmp(it->second.salt,salt,16)==0){memcpy(key.k,it->second.key,32);it->second.last=n;l.erase(it->second.li);l.push_front(p);it->second.li=l.begin();sodium_free(nk);return;}if(it!=c.end()){free_ent(it->second);l.erase(it->second.li);c.erase(it);}KCEnt e;memcpy(e.salt,salt,16);e.key=nk;e.last=n;l.push_front(p);e.li=l.begin();c[p]=e;while((int)c.size()>CAP){auto b=l.back();auto bi=c.find(b);if(bi!=c.end()){free_ent(bi->second);c.erase(bi);}l.pop_back();}} }; static bool derive_v2(std::string auth,unsigned char*salt,VKey&out){ParamWipe _pw(auth);std::lock_guard L(KDFM);if(crypto_pwhash(out.k,32,auth.c_str(),auth.size(),salt,crypto_pwhash_OPSLIMIT_INTERACTIVE,crypto_pwhash_MEMLIMIT_INTERACTIVE,crypto_pwhash_ALG_DEFAULT)!=0){wipe_mem(out.k,32);return false;}return true;} // incremental sealer: powers store_v2 and SFTP uploads with one code path struct V2Push{crypto_secretstream_xchacha20poly1305_state st;std::ofstream f;bool ok=false;std::vector buf; bool open(std::string tmp,std::string auth){ParamWipe _pw(auth);unsigned char salt[16];randombytes_buf(salt,16);VKey key;if(!derive_v2(auth,salt,key))return false;unsigned char header[24];if(crypto_secretstream_xchacha20poly1305_init_push(&st,header,key.k)!=0)return false;f.open(tmp,std::ios::binary);if(!f)return false;unsigned char ver=2;f.write((char*)&ver,1);f.write((char*)salt,16);f.write((char*)header,24);if(!f)return false;ok=true;return true;} bool raw(const unsigned char*d,size_t n,bool last){std::vector ct(n+17);unsigned long long cl=0;if(crypto_secretstream_xchacha20poly1305_push(&st,ct.data(),&cl,d,n,NULL,0,last?crypto_secretstream_xchacha20poly1305_TAG_FINAL:0)!=0){ok=false;return false;}f.write((char*)ct.data(),(std::streamsize)cl);if(!f){ok=false;return false;}return true;} // secretstream has no self-framing: buffer to canonical 64KB MESSAGE chunks // regardless of caller write sizes, else the read side misframes (seen live). bool push(const unsigned char*d,size_t n){if(!ok)return false;if(n)buf.insert(buf.end(),d,d+n);const size_t CS=65536;while(buf.size()>CS){if(!raw(buf.data(),CS,false))return false;buf.erase(buf.begin(),buf.begin()+CS);}return true;} bool finish(){if(!ok)return false;if(!raw(buf.data(),buf.size(),true))return false;buf.clear();f.flush();if(!f)return false;f.close();ok=false;return true;} }; static bool __attribute__((unused)) store_v2(std::string p,const unsigned char*d,size_t n,std::string auth){ParamWipe _pw(auth);V2Push w;if(!w.open(p,auth))return false;const size_t CS=65536;size_t pos=0;while(pos ct(step),m(CS);bool ok=true;for(size_t i=0;i::eof())ok=false;unsigned char o[32];crypto_hash_sha256_final(&hs,o);char hh[65];for(int i=0;i<32;i++)snprintf(hh+2*i,3,"%02x",o[i]);std::ifstream tf(p+".tag");std::string old;bool have=(bool)(tf>>old);if(!ok)return 2;if(have&&old!=std::string(hh))return 1;if(!have){std::ofstream o2(p+".tag");o2<emit,bool&is_last){is_last=false;if(!ok||pos>=fl)return false;const size_t CS=65536,step=CS+17;size_t want=std::min(step,fl-pos);std::vector ct(want),m(CS);f.read((char*)ct.data(),want);if(f.gcount()!=(std::streamsize)want){ok=false;return false;}unsigned long long ml=0;unsigned char tag=0;if(crypto_secretstream_xchacha20poly1305_pull(&st,m.data(),&ml,&tag,ct.data(),want,NULL,0)!=0){ok=false;return false;}pos+=want;bool last=(pos>=fl);if(last){if(tag!=crypto_secretstream_xchacha20poly1305_TAG_FINAL){ok=false;return false;}}else if(tag!=0){ok=false;return false;}if(emit)emit(m.data(),(size_t)ml);is_last=last;return true;} }; static bool __attribute__((unused)) fetch_v2_stream(std::string p,std::string auth,KeyCache&kc,std::functionemit){V2Pull r;if(!r.open(p,auth,kc))return false;for(;;){bool last=false;if(!r.next(emit,last))return false;if(last)return true;}} static void ntp_once(std::string srv){std::string host=srv,port="123";auto c=srv.rfind(':');if(c!=std::string::npos&&srv.find(':')==c){host=srv.substr(0,c);port=srv.substr(c+1);}addrinfo H{};H.ai_socktype=SOCK_DGRAM;addrinfo*ai=0;if(getaddrinfo(host.c_str(),port.c_str(),&H,&ai)!=0||!ai)return;int s=socket(ai->ai_family,SOCK_DGRAM,0);if(s<0){freeaddrinfo(ai);return;}timeval tv{3,0};setsockopt(s,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof tv);unsigned char q[48]={0};q[0]=0x1B;sendto(s,q,48,0,ai->ai_addr,ai->ai_addrlen);unsigned char r[48];ssize_t n=recvfrom(s,r,48,0,(sockaddr*)0,0);close(s);freeaddrinfo(ai);if(n<48)return;uint32_t sec=((uint32_t)r[40]<<24)|((uint32_t)r[41]<<16)|((uint32_t)r[42]<<8)|r[43];long long skew=(long long)sec-2208988800LL-epoch_now();if(skew>60||skew<-60)audit("clock-skew "+std::to_string(skew)+"s","-");} static void ntp_loop(std::string srv){std::this_thread::sleep_for(std::chrono::seconds(5));for(;;){ntp_once(srv);std::this_thread::sleep_for(std::chrono::seconds(3600));}} static void wipe_store(KeyCache&kc){kc.flush();try{for(auto&p:fs::recursive_directory_iterator(STORED())){if(p.is_regular_file()){try{auto n=p.file_size();std::fstream f(p.path(),std::ios::in|std::ios::out|std::ios::binary);size_t wn=std::min(n,1048576);std::vector z(wn,0);f.write(z.data(),wn);f.flush();f.seekp(0);std::vector o(wn,(char)0xFF);f.write(o.data(),wn);f.flush();f.seekp(0);{std::random_device wr;for(size_t wi=0;wi