1 /* fides.cc - Light-weight, decentralised trust and authorisation management
2 Copyright (C) 2008-2009 Guus Sliepen <guus@tinc-vpn.org>
4 Fides is free software; you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of
7 the License, or (at your option) any later version.
9 Fides is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <sys/types.h>
25 #include <botan/types.h>
26 #include <botan/botan.h>
27 #include <botan/ecdsa.h>
28 #include <botan/look_pk.h>
29 #include <botan/lookup.h>
30 #include <botan/filters.h>
31 #include <botan/sha2_32.h>
40 Botan::AutoSeeded_RNG fides::rng;
42 // Public key functions
44 fides::publickey::publickey(): pub(0), trust(0) {
47 fides::publickey::~publickey() {
51 void fides::publickey::load(istream &in) {
53 Botan::DataSource_Stream source(in);
54 pub = dynamic_cast<Botan::ECDSA_PublicKey *>(Botan::X509::load_key(source));
55 } catch(Botan::Exception &e) {
56 throw exception(e.what());
60 void fides::publickey::load(const std::string &filename) {
61 ifstream in(filename.c_str());
65 void fides::publickey::save(ostream &out) const {
69 void fides::publickey::save(const std::string &filename) const {
70 ofstream out(filename.c_str());
74 void fides::publickey::from_string(const std::string &in) {
76 Botan::DataSource_Memory source(in);
77 pub = dynamic_cast<Botan::ECDSA_PublicKey *>(Botan::X509::load_key(source));
78 } catch(Botan::Exception &e) {
79 throw exception(e.what());
83 string fides::publickey::to_string() const {
84 return Botan::X509::PEM_encode(*pub);
87 string fides::publickey::fingerprint(unsigned int bits) const {
88 // TODO: find out if there is a standard way to get a hash of an ECDSA public key
89 Botan::SHA_256 sha256;
90 Botan::SecureVector<Botan::byte> hash = sha256.process(Botan::X509::PEM_encode(*pub));
91 return string((const char *)hash.begin(), bits / 8);
94 bool fides::publickey::verify(const std::string &statement, const std::string &signature) const {
95 auto_ptr<Botan::PK_Verifier> verifier(Botan::get_pk_verifier(*pub, "EMSA1(SHA-512)"));
96 verifier->update((const Botan::byte *)statement.data(), statement.size());
97 Botan::SecureVector<Botan::byte> sig;
98 sig.set((const Botan::byte *)signature.data(), signature.size());
99 return verifier->check_signature(sig);
102 // Private key functions
104 fides::privatekey::privatekey(): priv(0) {
107 fides::privatekey::~privatekey() {
112 void fides::privatekey::generate(const std::string &field) {
113 Botan::EC_Domain_Params domain = Botan::get_EC_Dom_Pars_by_oid(field);
114 pub = priv = new Botan::ECDSA_PrivateKey(rng, domain);
117 void fides::privatekey::generate(unsigned int bits) {
119 case 112: return generate("1.3.132.0.6");
120 case 128: return generate("1.3.132.0.28");
121 case 160: return generate("1.3.132.0.9");
122 case 192: return generate("1.3.132.0.31");
123 case 224: return generate("1.3.132.0.32");
124 case 256: return generate("1.3.132.0.10");
125 case 384: return generate("1.3.132.0.34");
126 case 521: return generate("1.3.132.0.35");
127 default: throw exception("Unsupported number of bits for private key");
131 void fides::privatekey::load_private(istream &in) {
133 Botan::DataSource_Stream stream(in);
134 pub = priv = dynamic_cast<Botan::ECDSA_PrivateKey *>(Botan::PKCS8::load_key(stream, rng, ""));
135 } catch(Botan::Exception &e) {
136 throw exception(e.what());
140 void fides::privatekey::load_private(const std::string &filename) {
141 ifstream in(filename.c_str());
145 void fides::privatekey::save_private(ostream &out) const {
146 out << Botan::PKCS8::PEM_encode(*priv);
149 void fides::privatekey::save_private(const std::string &filename) const {
150 ofstream out(filename.c_str());
154 string fides::privatekey::sign(const std::string &statement) const {
155 auto_ptr<Botan::PK_Signer> signer(Botan::get_pk_signer(*priv, "EMSA1(SHA-512)"));
156 Botan::SecureVector<Botan::byte> sig = signer->sign_message((const Botan::byte *)statement.data(), statement.size(), rng);
157 return string((const char *)sig.begin(), (size_t)sig.size());
160 // Base64 and hex encoding/decoding functions
162 string fides::hexencode(const string &in) {
163 Botan::Pipe pipe(new Botan::Hex_Encoder);
164 pipe.process_msg((Botan::byte *)in.data(), in.size());
165 return pipe.read_all_as_string();
168 string fides::hexdecode(const string &in) {
169 Botan::Pipe pipe(new Botan::Hex_Decoder);
170 pipe.process_msg((Botan::byte *)in.data(), in.size());
171 return pipe.read_all_as_string();
174 string fides::b64encode(const string &in) {
175 Botan::Pipe pipe(new Botan::Base64_Encoder);
176 pipe.process_msg((Botan::byte *)in.data(), in.size());
177 return pipe.read_all_as_string();
180 string fides::b64decode(const string &in) {
181 Botan::Pipe pipe(new Botan::Base64_Decoder);
182 pipe.process_msg((Botan::byte *)in.data(), in.size());
183 return pipe.read_all_as_string();
186 // Certificate functions
188 fides::certificate::certificate(const publickey *key, struct timeval timestamp, const std::string &statement, const std::string &signature): signer(key), timestamp(timestamp), statement(statement), signature(signature) {}
190 bool fides::certificate::validate() const {
191 string data = signer->fingerprint(256);
192 data += string((const char *)×tamp, sizeof timestamp);
194 return signer->verify(data, signature);
197 fides::certificate::certificate(const privatekey *key, struct timeval timestamp, const std::string &statement): signer(key), timestamp(timestamp), statement(statement) {
198 string data = signer->fingerprint(256);
199 data += string((const char *)×tamp, sizeof timestamp);
201 signature = key->sign(data);
204 string fides::certificate::fingerprint(unsigned int bits) const {
205 return signature.substr(signature.size() - bits / 8);
208 string fides::certificate::to_string() const {
209 string data = fides::hexencode(signer->fingerprint());
212 snprintf(ts, sizeof ts, "%lu.%06lu", timestamp.tv_sec, timestamp.tv_usec);
215 data += fides::b64encode(signature);
223 static vector<string> dirlist(const string &path) {
224 vector<string> files;
226 DIR *dir = opendir(path.c_str());
230 struct dirent entry, *result = &entry;
233 readdir_r(dir, &entry, &result);
237 if(result->d_type == DT_UNKNOWN) {
238 if(stat((path + "/" + result->d_name).c_str(), &st))
240 if(S_ISREG(st.st_mode))
241 files.push_back(result->d_name);
242 } else if(result->d_type == DT_REG) {
243 files.push_back(result->d_name);
252 void fides::certificate_save(const certificate *cert, const string &filename) const {
253 ofstream file(filename.c_str());
254 file << cert->to_string() << '\n';
257 fides::certificate *fides::certificate_load(const string &filename) {
258 ifstream file(filename.c_str());
261 return certificate_from_string(data);
264 fides::certificate *fides::certificate_from_string(const string &data) {
266 e = data.find(' ', 0);
267 if(e == string::npos)
268 throw exception("Invalid certificate");
269 string fingerprint = hexdecode(data.substr(0, e));
270 const publickey *signer = find_key(fingerprint);
272 throw exception("Unknown public key");
274 e = data.find('.', b);
275 if(e == string::npos)
276 throw exception("Invalid certificate");
277 struct timeval timestamp;
278 timestamp.tv_sec = atol(data.c_str() + b);
280 timestamp.tv_usec = atol(data.c_str() + b);
281 e = data.find(' ', b);
282 if(e == string::npos)
283 throw exception("Invalid certificate");
285 e = data.find(' ', b);
286 if(e == string::npos)
287 throw exception("Invalid certificate");
288 string signature = fides::b64decode(data.substr(b, e - b));
290 string statement = data.substr(b);
292 return new certificate(signer, timestamp, statement, signature);
295 // Fides main functions
297 fides::fides(const string &dir): homedir(dir) {
298 cerr << "Fides initialising\n";
300 // Set homedir to provided directory, or $FIDES_HOME, or $HOME/.fides, or as a last resort $PWD/.fides
302 homedir = getenv("FIDES_HOME") ?: "";
303 if(homedir.empty()) {
305 homedir = getenv("HOME") ?: getcwd(cwd, sizeof cwd);
306 homedir += "/.fides";
309 // Derived directories
311 certdir = homedir + "certs/";
312 keydir = homedir + "keys/";
313 obsoletedir = homedir + ".obsolete_certs/";
315 // Ensure the homedir and its subdirectories exist
316 mkdir(homedir.c_str(), 0700);
317 mkdir(certdir.c_str(), 0700);
318 mkdir(keydir.c_str(), 0700);
319 mkdir(obsoletedir.c_str(), 0700);
322 mykey.load_private(homedir + "priv");
324 } catch(fides::exception &e) {
325 cerr << "Fides generating keypair\n";
327 mykey.save_private(homedir + "priv");
328 mykey.save(keydir + hexencode(mykey.fingerprint()));
331 vector<string> files = dirlist(keydir);
332 for(size_t i = 0; i < files.size(); ++i) {
333 cerr << "Loading key " << files[i] << '\n';
335 publickey *key = new publickey();
336 key->load(keydir + files[i]);
337 keys[hexdecode(files[i])] = key;
340 keys[mykey.fingerprint()] = &mykey;
342 files = dirlist(certdir);
343 for(size_t i = 0; i < files.size(); ++i) {
344 cerr << "Loading certificate " << files[i] << '\n';
345 certificate *cert = certificate_load(certdir + files[i]);
346 if(false && !cert->validate()) {
347 cerr << "Bad certificate!\n";
350 certs[hexdecode(files[i])] = cert;
353 // TODO: save and load this value
361 cerr << "Fides exitting\n";
362 for(map<string, certificate *>::const_iterator i = certs.begin(); i != certs.end(); ++i)
364 for(map<string, publickey *>::const_iterator i = keys.begin(); i != keys.end(); ++i)
365 if(i->second != &mykey)
369 bool fides::fsck() const {
372 for(map<string, certificate *>::const_iterator i = certs.begin(); i != certs.end(); ++i) {
373 if(!i->second->validate()) {
374 cerr << "Validation of certificate failed: " << i->second->to_string() << '\n';
379 cerr << errors << " errors in " << certs.size() << " certificates\n";
383 string fides::get_homedir() const {
387 bool fides::is_firstrun() const {
391 fides::publickey *fides::find_key(const string &fingerprint) const {
392 map<string, publickey *>::const_iterator i;
393 i = keys.find(fingerprint);
400 vector<const fides::certificate *> fides::find_certificates(const publickey *signer, const string ®ex) const {
401 vector<const certificate *> found;
402 map<string, certificate *>::const_iterator i;
403 regexp regexp(regex);
404 for(i = certs.begin(); i != certs.end(); ++i) {
406 cerr << "No certificate for " << hexencode(i->first) << '\n';
409 if(i->second->signer == signer)
410 if(regexp.match(i->second->statement))
411 found.push_back(i->second);
416 vector<const fides::certificate *> fides::find_certificates(const string ®ex) const {
417 vector<const certificate *> found;
418 map<string, certificate *>::const_iterator i;
419 regexp regexp(regex);
420 for(i = certs.begin(); i != certs.end(); ++i)
421 if(regexp.match(i->second->statement))
422 found.push_back(i->second);
426 vector<const fides::certificate *> fides::find_certificates(const publickey *signer) const {
427 vector<const certificate *> found;
428 map<string, certificate *>::const_iterator i;
429 for(i = certs.begin(); i != certs.end(); ++i)
430 if(i->second->signer == signer)
431 found.push_back(i->second);
435 void fides::import_all(istream &in) {
439 while(getline(in, line)) {
443 if(is_pem || !line.compare(0, 11, "-----BEGIN ")) {
445 if(!line.compare(0, 9, "-----END ")) {
446 fides::publickey *key = new publickey();
447 key->from_string(pem);
448 cerr << "Imported key " << hexencode(key->fingerprint()) << '\n';
457 fides::certificate *cert = certificate_from_string(line);
458 cerr << "Importing certificate " << hexencode(cert->fingerprint()) << '\n';
463 void fides::export_all(ostream &out) const {
464 for(map<string, publickey *>::const_iterator i = keys.begin(); i != keys.end(); ++i)
465 out << i->second->to_string();
466 for(map<string, certificate *>::const_iterator i = certs.begin(); i != certs.end(); ++i)
467 out << i->second->to_string() << '\n';
470 void fides::trust(const publickey *key) {
471 string full = "t+ " + hexencode(key->fingerprint());
475 void fides::distrust(const publickey *key) {
476 string full = "t- " + hexencode(key->fingerprint());
480 void fides::dctrust(const publickey *key) {
481 string full = "t0 " + hexencode(key->fingerprint());
485 void fides::update_trust() {
486 // clear trust on all keys
487 for(map<string, publickey *>::const_iterator i = keys.begin(); i != keys.end(); ++i)
488 i->second->trust = 0;
490 // Start by checking all trust certificates from ourself.
491 // If another key is positively or negatively trusted, update its trust score
492 // and add it to the the list of new keys to check.
493 // Then add our own key to the list of already checked keys.
494 // Then check all the trust certificates of those on the tocheck list, etc.
495 // Already checked keys are never updated anymore (TODO: is that smart?)
496 // Certificates of keys with a zero or negative trust score are not processed.
498 set<publickey *> checked;
499 set<publickey *> tocheck;
500 set<publickey *> newkeys;
501 set<publickey *>::iterator i;
504 tocheck.insert(&mykey);
506 while(tocheck.size()) {
508 checked.insert(tocheck.begin(), tocheck.end());
511 // loop over all keys whose certificates need to be checked
513 for(i = tocheck.begin(); i != tocheck.end(); ++i) {
514 cerr << "Trust for key " << hexencode((*i)->fingerprint()) << " set to " << (*i)->trust << '\n';
516 // except if this key is not trusted
521 // find all non-zero trust certificates of this key
523 vector<const certificate *> matches = find_certificates(*i, "^t[+-] ");
525 // update trust value of those keys
527 for(size_t j = 0; j < matches.size(); j++) {
528 publickey *other = find_key(hexdecode(matches[j]->statement.substr(3)));
531 cerr << "Trust certificate for unknown key: " << matches[j]->to_string() << '\n';
535 // except for keys we already checked
537 if(checked.find(other) != checked.end()) {
538 cerr << "Skipping trust certificate for already checked key: " << matches[j]->to_string() << '\n';
544 if(matches[j]->statement[1] == '+')
549 newkeys.insert(other);
557 void fides::merge(publickey *key) {
558 if(keys.find(key->fingerprint()) != keys.end()) {
559 cerr << "Key already known\n";
563 keys[key->fingerprint()] = key;
564 key->save(keydir + hexencode(key->fingerprint()));
567 void fides::merge(certificate *cert) {
568 // TODO: check if cert is already in database
569 // TODO: check if cert obsoletes other certs
571 // If we already know this certificate, drop it.
572 if(certs.find(cert->fingerprint()) != certs.end()) {
573 cerr << "Certificate already known\n";
577 // If the certificate does not validate, drop it.
578 if(!cert->validate()) {
579 // TODO: this should not happen, be wary of DoS attacks
580 cerr << "Certificate invalid\n";
584 // TODO: move these regexps to the class?
585 regexp authexp("^a[+0-] ");
586 regexp trustexp("^t[+0-] ");
587 vector<const certificate *> others;
589 // Is this an authorisation cert?
590 if(authexp.match(cert->statement)) {
591 // Find certs identical except for the +/-/0
592 // TODO: escape statement in regexp
593 others = find_certificates(cert->signer, string("^a[+0-] ") + cert->statement.substr(3) + '$');
595 if(timercmp(&others[0]->timestamp, &cert->timestamp, >)) {
596 cerr << "Certificate is overruled by a newer certificate\n";
599 if(timercmp(&others[0]->timestamp, &cert->timestamp, ==)) {
600 // TODO: this should not happen, be wary of DoS attacks
601 cerr << "Certificate has same timestamp as another timestamp!\n";
604 cerr << "Certificate overrules an older certificate!\n";
605 // save new cert first
606 certificate_save(cert, certdir + hexencode(cert->fingerprint()));
607 certs[cert->fingerprint()] = cert;
610 rename((certdir + hexencode(others[0]->fingerprint())).c_str(), (obsoletedir + hexencode(others[0]->fingerprint())).c_str());
611 certs.erase(others[0]->fingerprint());
617 // Is this a trust cert?
618 // TODO: it's just the same as above!
619 if(trustexp.match(cert->statement)) {
620 // Find certs identical except for the +/-/0
621 // TODO: escape statement in regexp
622 others = find_certificates(cert->signer, string("^t[+0-] ") + cert->statement.substr(3) + '$');
624 if(timercmp(&others[0]->timestamp, &cert->timestamp, >)) {
625 cerr << "Certificate is overruled by a newer certificate\n";
628 if(timercmp(&others[0]->timestamp, &cert->timestamp, ==)) {
629 // TODO: this should not happen, be wary of DoS attacks
630 cerr << "Certificate has same timestamp as another timestamp!\n";
633 cerr << "Certificate overrules an older certificate!\n";
635 rename((certdir + hexencode(others[0]->fingerprint())).c_str(), (obsoletedir + hexencode(others[0]->fingerprint())).c_str());
636 certs.erase(others[0]->fingerprint());
638 certs[cert->fingerprint()] = cert;
639 certificate_save(cert, certdir + hexencode(cert->fingerprint()));
644 // Did somebody sign the exact same statement twice?
645 // Could happen if there is a different, conflicting statement between this new and the corresponding old one.
646 others = find_certificates(cert->signer, string("^") + cert->statement + '$');
648 if(timercmp(&others[0]->timestamp, &cert->timestamp, >)) {
649 cerr << "Certificate is overruled by a newer certificate\n";
652 if(timercmp(&others[0]->timestamp, &cert->timestamp, ==)) {
653 // TODO: this should not happen, be wary of DoS attacks
654 cerr << "Certificate has same timestamp as another timestamp!\n";
657 cerr << "Certificate overrules an older certificate!\n";
659 rename((certdir + hexencode(others[0]->fingerprint())).c_str(), (obsoletedir + hexencode(others[0]->fingerprint())).c_str());
660 certs.erase(others[0]->fingerprint());
662 certs[cert->fingerprint()] = cert;
663 certificate_save(cert, certdir + hexencode(cert->fingerprint()));
667 cerr << "Certificate is new\n";
668 certs[cert->fingerprint()] = cert;
669 certificate_save(cert, certdir + hexencode(cert->fingerprint()));
672 void fides::auth_stats(const string &statement, int &self, int &trusted, int &all) const {
673 self = trusted = all = 0;
674 vector<const certificate *> matches = find_certificates(string("^a[+0-] ") + statement + '$');
675 for(size_t i = 0; i < matches.size(); ++i) {
676 char code = matches[i]->statement[1];
682 if(matches[i]->signer == &mykey)
684 if(matches[i]->signer->trust > 0)
690 bool fides::is_trusted(const publickey *key) const {
691 return key->trust > 0;
694 bool fides::is_distrusted(const publickey *key) const {
695 return key->trust < 0;
698 bool fides::is_allowed(const string &statement, const publickey *key) const {
699 int self, trusted, all;
702 auth_stats(hexencode(key->fingerprint()) + " " + statement, self, trusted, all);
704 auth_stats(statement, self, trusted, all);
714 bool fides::is_denied(const string &statement, const publickey *key) const {
715 int self, trusted, all;
718 auth_stats(hexencode(key->fingerprint()) + " " + statement, self, trusted, all);
720 auth_stats(statement, self, trusted, all);
730 void fides::sign(const string &statement) {
731 // Try to set "latest" to now, but ensure monoticity
733 gettimeofday(&now, 0);
734 if(timercmp(&latest, &now, >=)) {
736 if(latest.tv_usec >= 1000000) {
738 latest.tv_usec -= 1000000;
744 // Create a new certificate and merge it with our database
745 merge(new certificate(&mykey, latest, statement));
748 void fides::allow(const string &statement, const publickey *key) {
751 full += hexencode(key->fingerprint()) + ' ';
756 void fides::dontcare(const string &statement, const publickey *key) {
759 full += hexencode(key->fingerprint()) + ' ';
764 void fides::deny(const string &statement, const publickey *key) {
767 full += hexencode(key->fingerprint()) + ' ';