From 713d956882dffbde61f0b173193f4af12e613603 Mon Sep 17 00:00:00 2001 From: drbob Date: Fri, 25 Jun 2010 22:10:21 +0000 Subject: [PATCH] NETWORK REWORK (cont) * removing old tests and unused code. git-svn-id: http://svn.code.sf.net/p/retroshare/code/trunk@3220 b45a01b8-16f6-495d-af2f-9b41ad6348cc --- libretroshare/src/pqi/conn_test.cc | 362 ---- libretroshare/src/pqi/dht_test.cc | 310 --- libretroshare/src/pqi/gpgme_tst.c | 76 - libretroshare/src/pqi/net_test.cc | 264 --- libretroshare/src/pqi/net_test1.cc | 268 --- libretroshare/src/pqi/netiface_test.cc | 63 - libretroshare/src/pqi/pqi_base.cc | 413 ---- libretroshare/src/pqi/sslcert.cc | 2031 ------------------- libretroshare/src/pqi/sslcert.h | 195 -- libretroshare/src/pqi/xpgp_id.cc | 44 - libretroshare/src/pqi/xpgpcert.cc | 2569 ------------------------ libretroshare/src/pqi/xpgpcert.h | 221 -- 12 files changed, 6816 deletions(-) delete mode 100644 libretroshare/src/pqi/conn_test.cc delete mode 100644 libretroshare/src/pqi/dht_test.cc delete mode 100644 libretroshare/src/pqi/gpgme_tst.c delete mode 100644 libretroshare/src/pqi/net_test.cc delete mode 100644 libretroshare/src/pqi/net_test1.cc delete mode 100644 libretroshare/src/pqi/netiface_test.cc delete mode 100644 libretroshare/src/pqi/pqi_base.cc delete mode 100644 libretroshare/src/pqi/sslcert.cc delete mode 100644 libretroshare/src/pqi/sslcert.h delete mode 100644 libretroshare/src/pqi/xpgp_id.cc delete mode 100644 libretroshare/src/pqi/xpgpcert.cc delete mode 100644 libretroshare/src/pqi/xpgpcert.h diff --git a/libretroshare/src/pqi/conn_test.cc b/libretroshare/src/pqi/conn_test.cc deleted file mode 100644 index 7ca8043a4..000000000 --- a/libretroshare/src/pqi/conn_test.cc +++ /dev/null @@ -1,362 +0,0 @@ - - -#include "pqi/p3connmgr.h" - - -/***** Test for the new DHT system *****/ - - -#include "util/rsnet.h" -#include "util/rsthreads.h" -#include "util/rsprint.h" -#include "pqi/p3dhtmgr.h" -#include "pqi/p3connmgr.h" -#include "pqi/pqisecurity.h" -#include "pqi/pqipersongrp.h" - -#include -#include - -#include "tcponudp/udpsorter.h" - -/***** Test Framework *****/ - -const int NumOfPeers = 10; -std::string peerIds[NumOfPeers] = - {"PEER01", - "PEER02", /* Always online, no notify */ - "PEER03", /* notify/online at 20sec */ - "PEER04", /* Always online, notify at 30 sec */ - "PEER05", - "PEER06", /* notify/online at 50sec */ - "PEER07", - "PEER08", - "PEER09", /* notify/online at 80sec */ - "PEER10"}; - -#define STUN_PORT 7777 - -std::string ownId = "OWNID-AAAA"; -time_t ownPublishTs; - -RsMutex frmMtx; -std::list searchIds; -std::list searchModes; - -std::map onlineMap; -std::map notifyMap; - -void initTestData() -{ - ownPublishTs = 0; - /* setup Peers that are online always */ - bool online; - uint32_t ts; - for(int i = 0; i < NumOfPeers; i++) - { - online = false; - if ((i == 1) || (i == 3)) - { - online = true; - } - onlineMap[peerIds[i]] = online; - - if ((i == 2) || (i == 3) || - (i == 5) || (i == 8)) - { - ts = i * 10; - notifyMap[ts] = peerIds[i]; - } - } -} - -void respondPublish() -{ - frmMtx.lock(); /* LOCK TEST FRAMEWORK MUTEX */ - if (!ownPublishTs) - { - std::cerr << "Own ID first published!" << std::endl; - ownPublishTs = time(NULL); - } - frmMtx.unlock(); /* UNLOCK TEST FRAMEWORK MUTEX */ -} - -void respondSearch(p3DhtMgr *mgr, std::string id, uint32_t mode) -{ - std::cerr << "Checking for Search Results" << std::endl; - time_t now = time(NULL); - bool doNotify = false; - bool doOnline = false; - std::string notifyId; - - frmMtx.lock(); /* LOCK TEST FRAMEWORK MUTEX */ - if ((mode == DHT_MODE_NOTIFY) && (ownPublishTs)) - { - /* */ - std::map::iterator it; - uint32_t delta_t = now - ownPublishTs; - it = notifyMap.begin(); - if (it != notifyMap.end()) - { - if (it->first <= delta_t) - { - notifyId = it->second; - onlineMap[notifyId] = true; - notifyMap.erase(it); - doNotify = true; - } - } - } - else if (mode == DHT_MODE_SEARCH) - { - - /* translate */ - std::map::iterator mit; - for(mit = onlineMap.begin(); (mit != onlineMap.end()) && - (RsUtil::HashId(mit->first, false) != id); mit++); - - if (mit != onlineMap.end()) - { - doOnline = mit->second; - } - } - - frmMtx.unlock(); /* UNLOCK TEST FRAMEWORK MUTEX */ - - uint32_t type = 0; - - struct sockaddr_in laddr; - inet_aton("10.0.0.129", &(laddr.sin_addr)); - laddr.sin_port = htons(7812); - laddr.sin_family = AF_INET; - - struct sockaddr_in raddr; - inet_aton("127.0.0.1", &(raddr.sin_addr)); - raddr.sin_port = htons(STUN_PORT); - raddr.sin_family = AF_INET; - - if (doNotify) - { - std::cerr << "Responding to Notify: id:" << notifyId << std::endl; - mgr->dhtResultNotify(RsUtil::HashId(notifyId, true)); - } - - if (doOnline) - { - std::cerr << "Responding to Search" << std::endl; - mgr->dhtResultSearch(id, laddr, raddr, type, ""); - } - -} - - -/***** Test Framework *****/ - -class DhtMgrTester: public p3DhtMgr -{ - - /* Implementation */ - public: - - DhtMgrTester(std::string id, pqiConnectCb *cb) - :p3DhtMgr(id, cb) - { - return; - } - - - - - - /* Blocking calls (only from thread) */ -virtual bool dhtPublish(std::string id, - struct sockaddr_in &laddr, struct sockaddr_in &raddr, - uint32_t type, std::string sign) -{ - std::cerr << "DhtMgrTester::dhtPublish() id: " << RsUtil::BinToHex(id); - std::cerr << " laddr: " << inet_ntoa(laddr.sin_addr) << " lport: " << ntohs(laddr.sin_port); - std::cerr << " raddr: " << inet_ntoa(raddr.sin_addr) << " rport: " << ntohs(raddr.sin_port); - std::cerr << " type: " << type << " sign: " << sign; - std::cerr << std::endl; - - respondPublish(); - - return true; -} - -virtual bool dhtNotify(std::string peerid, std::string ownid, std::string sign) -{ - std::cerr << "DhtMgrTester::dhtNotify() id: " << RsUtil::BinToHex(peerid) << ", ownId: " << RsUtil::BinToHex(ownId); - std::cerr << " sign: " << sign; - std::cerr << std::endl; - - return true; -} - -virtual bool dhtSearch(std::string id, uint32_t mode) -{ - std::cerr << "DhtMgrTester::dhtSearch(id: " << RsUtil::BinToHex(id) << ", mode: " << mode << ")" << std::endl; - - frmMtx.lock(); /* LOCK TEST FRAMEWORK MUTEX */ - searchIds.push_back(id); - searchModes.push_back(mode); - frmMtx.unlock(); /* LOCK TEST FRAMEWORK MUTEX */ - - return true; -} - -}; - - -/* OVERLOAD THE ConnMgr - to insert peers */ -class p3TestConnMgr: public p3ConnectMgr -{ - public: - p3TestConnMgr(int mode) - :p3ConnectMgr(new p3DummyAuthMgr()), mTestMode(mode) { return; } - - protected: - /* must be virtual for testing */ -virtual void loadConfiguration() -{ - - /* setup own address */ - ownState.id = ownId; - ownState.name = "SELF NAME"; - ownState.localaddr.sin_family = AF_INET; - inet_aton("127.0.0.1", &(ownState.localaddr.sin_addr)); - ownState.localaddr.sin_port = htons(7812); - ownState.netMode = RS_NET_MODE_UDP; - ownState.visState = RS_VIS_STATE_STD; - - /* others not important */ - //ownState.state = 0; - //ownState.actions = 0; - - - if (mTestMode == 1) /* Add to Stun List */ - { - for(int i = 0; i < NumOfPeers; i++) - { - mStunList.push_back(peerIds[i]); - } - } - else if (mTestMode == 2) /* add to peers */ - { - /* add in as peers */ - //addPeer(); - for(int i = 0; i < NumOfPeers; i++) - { - if (i < 5) - { - mStunList.push_back(RsUtil::HashId(peerIds[i])); - } - else - { - addFriend(peerIds[i]); - } - } - } -} - - protected: - - uint32_t mTestMode; -}; - - -int main() -{ - time_t startTime = time(NULL); - /* setup system */ - initTestData(); - - /* setup a Stunner to respond to ConnMgr */ - - struct sockaddr_in saddr; - saddr.sin_family = AF_INET; - inet_aton("127.0.0.1", &(saddr.sin_addr)); - saddr.sin_port = htons(STUN_PORT); - UdpSorter stunner(saddr); /* starts a receiving thread */ - - p3TestConnMgr connMgr(2); - DhtMgrTester dhtTester(ownId, &connMgr); - - /* now add in some peers */ - connMgr.setDhtMgr(&dhtTester); - connMgr.setUpnpMgr(NULL); - - /************ ADD pqipersongrp as pqimonitor *****************/ - - SecurityPolicy *pol = secpolicy_create(); - unsigned long flags = 0; - pqipersongrp *pqipg = new pqipersongrpDummy(pol, flags); - - connMgr.addMonitor(pqipg); - - /************ ADD pqipersongrp as pqimonitor *****************/ - - - /* startup dht */ - std::cerr << "Starting up DhtTester()" << std::endl; - dhtTester.start(); - - /* wait for a little before switching on */ -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ -#ifndef WINDOWS_SYS - sleep(1); -#else - Sleep(1000); -#endif -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ - - std::cerr << "Switching on DhtTester()" << std::endl; - dhtTester.setDhtOn(true); - - /* wait loop */ - while(1) - { -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ -#ifndef WINDOWS_SYS - sleep(1); -#else - Sleep(1000); -#endif -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ - - connMgr.tick(); - pqipg->tick(); - - /* handle async search */ - frmMtx.lock(); /* LOCK TEST FRAMEWORK MUTEX */ - - std::string id; - uint32_t mode; - bool doRespond = false; - if (searchIds.size() > 0) - { - id = searchIds.front(); - mode = searchModes.front(); - doRespond = true; - searchIds.pop_front(); - searchModes.pop_front(); - } - - frmMtx.unlock(); /* UNLOCK TEST FRAMEWORK MUTEX */ - - if (doRespond) - { - respondSearch(&dhtTester, id, mode); - } - } -}; - - - - - - - - - - diff --git a/libretroshare/src/pqi/dht_test.cc b/libretroshare/src/pqi/dht_test.cc deleted file mode 100644 index 20cb05cb8..000000000 --- a/libretroshare/src/pqi/dht_test.cc +++ /dev/null @@ -1,310 +0,0 @@ - - -/***** Test for the new DHT system *****/ - - -#include "pqi/pqinetwork.h" - -#include "util/rsnet.h" -#include "util/rsthreads.h" -#include "util/rsprint.h" - -#include "pqi/p3dhtmgr.h" - -#include -#include - - -/***** Test Framework *****/ - -const int NumOfPeers = 10; -std::string peerIds[NumOfPeers] = - {"PEER01", - "PEER02", /* Always online, no notify */ - "PEER03", /* notify/online at 20sec */ - "PEER04", /* Always online, notify at 30 sec */ - "PEER05", - "PEER06", /* notify/online at 50sec */ - "PEER07", - "PEER08", - "PEER09", /* notify/online at 80sec */ - "PEER10"}; - -std::string ownId = "AAAA"; -time_t ownPublishTs; - -RsMutex frmMtx; -std::list searchIds; -std::list searchModes; - -std::map onlineMap; -std::map notifyMap; - -void initTestData() -{ - ownPublishTs = 0; - /* setup Peers that are online always */ - bool online; - uint32_t ts; - for(int i = 0; i < NumOfPeers; i++) - { - online = false; - if ((i == 1) || (i == 3)) - { - online = true; - } - onlineMap[peerIds[i]] = online; - - if ((i == 2) || (i == 3) || - (i == 5) || (i == 8)) - { - ts = i * 10; - notifyMap[ts] = peerIds[i]; - } - } -} - -void respondPublish() -{ - frmMtx.lock(); /* LOCK TEST FRAMEWORK MUTEX */ - if (!ownPublishTs) - { - std::cerr << "Own ID first published!" << std::endl; - ownPublishTs = time(NULL); - } - frmMtx.unlock(); /* UNLOCK TEST FRAMEWORK MUTEX */ -} - -void respondSearch(p3DhtMgr *mgr, std::string id, uint32_t mode) -{ - std::cerr << "Checking for Search Results" << std::endl; - time_t now = time(NULL); - bool doNotify = false; - bool doOnline = false; - std::string notifyId; - - frmMtx.lock(); /* LOCK TEST FRAMEWORK MUTEX */ - if ((mode == DHT_MODE_NOTIFY) && (ownPublishTs)) - { - /* */ - std::map::iterator it; - uint32_t delta_t = now - ownPublishTs; - it = notifyMap.begin(); - if (it != notifyMap.end()) - { - if (it->first <= delta_t) - { - notifyId = it->second; - onlineMap[notifyId] = true; - notifyMap.erase(it); - doNotify = true; - } - } - } - else if (mode == DHT_MODE_SEARCH) - { - /* translate */ - std::map::iterator mit; - for(mit = onlineMap.begin(); (mit != onlineMap.end()) && - (RsUtil::HashId(mit->first, false) != id); mit++); - - if (mit != onlineMap.end()) - { - doOnline = mit->second; - } - } - - frmMtx.unlock(); /* UNLOCK TEST FRAMEWORK MUTEX */ - - uint32_t type = 0; - - struct sockaddr_in laddr; - inet_aton("10.0.0.129", &(laddr.sin_addr)); - laddr.sin_port = htons(7812); - laddr.sin_family = AF_INET; - - struct sockaddr_in raddr; - inet_aton("10.0.0.19", &(raddr.sin_addr)); - raddr.sin_port = htons(7812); - raddr.sin_family = AF_INET; - - if (doNotify) - { - std::cerr << "Responding to Notify" << std::endl; - mgr->dhtResultNotify(RsUtil::HashId(notifyId, true)); - } - - if (doOnline) - { - std::cerr << "Responding to Search" << std::endl; - mgr->dhtResultSearch(id, laddr, raddr, type, ""); - } -} - - - - - - -/***** Test Framework *****/ - - - - -class DhtMgrTester: public p3DhtMgr -{ - - /* Implementation */ - public: - - DhtMgrTester(std::string id, pqiConnectCb *cb) - :p3DhtMgr(id, cb) - { - return; - } - - - /* Blocking calls (only from thread) */ -virtual bool dhtPublish(std::string id, - struct sockaddr_in &laddr, struct sockaddr_in &raddr, - uint32_t type, std::string sign) -{ - std::cerr << "DhtMgrTester::dhtPublish() id: " << RsUtil::BinToHex(id); - std::cerr << " laddr: " << inet_ntoa(laddr.sin_addr) << " lport: " << ntohs(laddr.sin_port); - std::cerr << " raddr: " << inet_ntoa(raddr.sin_addr) << " rport: " << ntohs(raddr.sin_port); - std::cerr << " type: " << type << " sign: " << sign; - std::cerr << std::endl; - - respondPublish(); - - return true; -} - -virtual bool dhtNotify(std::string peerid, std::string ownid, std::string sign) -{ - std::cerr << "DhtMgrTester::dhtNotify() id: " << RsUtil::BinToHex(peerid) << ", ownId: " << RsUtil::BinToHex(ownId); - std::cerr << " sign: " << sign; - std::cerr << std::endl; - - return true; -} - -virtual bool dhtSearch(std::string id, uint32_t mode) -{ - std::cerr << "DhtMgrTester::dhtSearch(id: " << RsUtil::BinToHex(id) << ", mode: " << mode << ")" << std::endl; - - frmMtx.lock(); /* LOCK TEST FRAMEWORK MUTEX */ - searchIds.push_back(id); - searchModes.push_back(mode); - frmMtx.unlock(); /* LOCK TEST FRAMEWORK MUTEX */ - - return true; -} - -}; - -int main() -{ - time_t startTime = time(NULL); - bool haveOwnAddress = false; - /* setup system */ - initTestData(); - - pqiConnectCbDummy cbTester; - DhtMgrTester dhtTester(ownId, &cbTester); - - /* now add in some peers */ - - /* startup dht */ - std::cerr << "Starting up DhtTester()" << std::endl; - dhtTester.start(); - - /* wait for a little before switching on */ -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ -#ifndef WINDOWS_SYS - sleep(1); -#else - Sleep(1000); -#endif -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ - - std::cerr << "Switching on DhtTester()" << std::endl; - dhtTester.enable(true); - - std::cerr << "Adding a List of Peers" << std::endl; - for(int i = 0; i < NumOfPeers; i++) - { - dhtTester.findPeer(peerIds[i]); - } - - - /* wait loop */ - while(1) - { - std::cerr << "Main waiting..." << std::endl; -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ -#ifndef WINDOWS_SYS - sleep(3); -#else - Sleep(3000); -#endif -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ - - - /* handle async search */ - frmMtx.lock(); /* LOCK TEST FRAMEWORK MUTEX */ - - std::string id; - uint32_t mode; - bool doRespond = false; - if (searchIds.size() > 0) - { - id = searchIds.front(); - mode = searchModes.front(); - doRespond = true; - searchIds.pop_front(); - searchModes.pop_front(); - } - - frmMtx.unlock(); /* UNLOCK TEST FRAMEWORK MUTEX */ - - if (doRespond) - { - respondSearch(&dhtTester, id, mode); - } - - if (!haveOwnAddress) - { - if (time(NULL) - startTime > 20) - { - std::cerr << "Setting Own Address!" << std::endl; - haveOwnAddress = true; - - uint32_t type = DHT_ADDR_UDP; - - struct sockaddr_in laddr; - inet_aton("10.0.0.111", &(laddr.sin_addr)); - laddr.sin_port = htons(7812); - laddr.sin_family = AF_INET; - - struct sockaddr_in raddr; - inet_aton("10.0.0.11", &(raddr.sin_addr)); - raddr.sin_port = htons(7812); - raddr.sin_family = AF_INET; - - dhtTester.setExternalInterface(laddr, raddr, type); - } - } - - } -}; - - - - - - - - - - diff --git a/libretroshare/src/pqi/gpgme_tst.c b/libretroshare/src/pqi/gpgme_tst.c deleted file mode 100644 index ec88a8439..000000000 --- a/libretroshare/src/pqi/gpgme_tst.c +++ /dev/null @@ -1,76 +0,0 @@ - -#include "pqi/authgpg.h" - -const std::string key_path("./tmp/privkey.pem"); -const std::string passwd("8764"); -const std::string gpg_passwd("aaaa"); -const std::string name("Test X509"); -const std::string email("test@email.com"); -const std::string org("Org"); -const std::string loc("Loc"); -const std::string state("State"); -const std::string country("GB"); - -int main() -{ - /* Init the auth manager */ - - GPGAuthMgr mgr; - - - /* Select which GPG Keys we use */ - - /* print all keys */ - mgr.printKeys(); - - std::list idList; - mgr.availablePGPCertificates(idList); - - if (idList.size() < 1) - { - fprintf(stderr, "No GPG Certificate to use!\n"); - exit(1); - } - std::string id = idList.front(); - fprintf(stderr, "Using GPG Certificate:%s \n", id.c_str()); - - std::string noname; - mgr.GPGInit(id); - mgr.LoadGPGPassword(gpg_passwd); - - /* Init SSL library */ - mgr.InitAuth(NULL, NULL, NULL); - - /* then try to generate and sign a X509 certificate */ - int nbits_in = 2048; - std::string errString; - - /* Generate a Certificate Request */ - X509_REQ *req = GenerateX509Req(key_path, passwd, name, email, org, - loc, state, country, nbits_in, errString); - - // setup output. - BIO *bio_out = NULL; - bio_out = BIO_new(BIO_s_file()); - BIO_set_fp(bio_out,stdout,BIO_NOCLOSE); - - /* Print it out */ - int nmflag = 0; - int reqflag = 0; - - X509_REQ_print_ex(bio_out, req, nmflag, reqflag); - - X509 *x509 = mgr.SignX509Req(req, 100, gpg_passwd); - - X509_print_ex(bio_out, x509, nmflag, reqflag); - - BIO_flush(bio_out); - BIO_free(bio_out); - - /* now try to validate it */ - mgr.AuthX509(x509); - - //sleep(10); -} - - diff --git a/libretroshare/src/pqi/net_test.cc b/libretroshare/src/pqi/net_test.cc deleted file mode 100644 index 8842c330a..000000000 --- a/libretroshare/src/pqi/net_test.cc +++ /dev/null @@ -1,264 +0,0 @@ -/* - * libretroshare/src/pqi net_test.cc - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -/****** - * NETWORKING Test to check Big/Little Endian behaviour - * as well as socket behaviour - * - */ - -#include "pqi/pqinetwork.h" -#include "util/rsnet.h" -#include -#include - - -bool test_byte_manipulation(); -bool test_address_manipulation(); -bool test_address_listen(); - -int main(int argc, char **argv) -{ - - test_byte_manipulation(); - test_address_manipulation(); - test_address_listen(); - return 1; -} - - /* test 1: byte manipulation */ -bool test_byte_manipulation() -{ - uint64_t num1 = 0x0000000000000000ffULL; /* 255 */ - uint64_t num2 = 0x00000000000000ff00ULL; /* */ - - uint64_t n_num1 = htonll(num1); - uint64_t n_num2 = htonll(num2); - - uint64_t h_num1 = ntohll(n_num1); - uint64_t h_num2 = ntohll(n_num2); - - std::ostringstream out; - out << std::hex; - out << "num1: " << num1 << " netOrder: " << n_num1 << " hostOrder: " << h_num1 << std::endl; - out << "num2: " << num2 << " netOrder: " << n_num2 << " hostOrder: " << h_num2 << std::endl; - - std::cerr << out.str(); - - return true; -} - -const char * loopback_addrstr = "127.0.0.1"; -const char * localnet1_addrstr = "192.168.0.1"; -const char * localnet2_addrstr = "10.0.0.1"; -const char * localnet3_addrstr = "10.5.63.78"; -const char * localnet4_addrstr = "192.168.74.91"; - - /* test 2: address manipulation */ -bool test_address_manipulation() -{ - struct sockaddr_in loopback_addr; - struct sockaddr_in localnet1_addr; - struct sockaddr_in localnet2_addr; - struct sockaddr_in localnet3_addr; - struct sockaddr_in localnet4_addr; - - /* setup some addresses */ - inet_aton(loopback_addrstr, &(loopback_addr.sin_addr)); - inet_aton(localnet1_addrstr, &(localnet1_addr.sin_addr)); - inet_aton(localnet2_addrstr, &(localnet2_addr.sin_addr)); - inet_aton(localnet3_addrstr, &(localnet3_addr.sin_addr)); - inet_aton(localnet4_addrstr, &(localnet4_addr.sin_addr)); - - - std::cerr << "Loopback Addr" << inet_ntoa(loopback_addr.sin_addr); - std::cerr << std::endl; - - std::cerr << "Localnet1 Addr" << inet_ntoa(localnet1_addr.sin_addr); - std::cerr << std::endl; - std::cerr << "Localnet2 Addr" << inet_ntoa(localnet2_addr.sin_addr); - std::cerr << std::endl; - std::cerr << "Localnet3 Addr" << inet_ntoa(localnet3_addr.sin_addr); - std::cerr << std::endl; - std::cerr << "Localnet4 Addr" << inet_ntoa(localnet4_addr.sin_addr); - std::cerr << std::endl; - std::cerr << std::endl; - - std::cerr << "Test 1a - networks"; - std::cerr << std::endl; - - struct sockaddr_in addr_ans, addr1, addr2; - - inet_aton("127.0.0.0", &(addr_ans.sin_addr)); - addr1.sin_addr.s_addr = inet_netof(loopback_addr.sin_addr); - addr2.sin_addr.s_addr = inet_network(loopback_addrstr); - - std::cerr << "Loopback Net(expected): 127.0.0.0 ->" << inet_ntoa(addr_ans.sin_addr); - std::cerr << " Net(1):" << inet_ntoa(addr1.sin_addr); - std::cerr << " Net(2):" << inet_ntoa(addr2.sin_addr); - std::cerr << std::endl; - - inet_aton("192.168.0.0", &(addr_ans.sin_addr)); - addr1.sin_addr.s_addr = inet_netof(localnet1_addr.sin_addr); - addr2.sin_addr.s_addr = inet_network(localnet1_addrstr); - - std::cerr << "Localnet1 Net(expected): 192.168.0.0 ->" << inet_ntoa(addr_ans.sin_addr); - std::cerr << " Net(1):" << inet_ntoa(addr1.sin_addr); - std::cerr << " Net(2):" << inet_ntoa(addr2.sin_addr); - std::cerr << std::endl; - - inet_aton("10.0.0.0", &(addr_ans.sin_addr)); - addr1.sin_addr.s_addr = inet_netof(localnet2_addr.sin_addr); - addr2.sin_addr.s_addr = inet_network(localnet2_addrstr); - - std::cerr << "Localnet2 Net(expected): 10.0.0.0 ->" << inet_ntoa(addr_ans.sin_addr); - std::cerr << " Net(1):" << inet_ntoa(addr1.sin_addr); - std::cerr << " Net(2):" << inet_ntoa(addr2.sin_addr); - std::cerr << std::endl; - - - inet_aton("10.0.0.0", &(addr_ans.sin_addr)); - addr1.sin_addr.s_addr = inet_netof(localnet3_addr.sin_addr); - addr2.sin_addr.s_addr = inet_network(localnet3_addrstr); - - std::cerr << "Localnet3 Net(expected): 10.0.0.0 ->" << inet_ntoa(addr_ans.sin_addr); - std::cerr << " Net(1):" << inet_ntoa(addr1.sin_addr); - std::cerr << " Net(2):" << inet_ntoa(addr2.sin_addr); - std::cerr << std::endl; - - - inet_aton("192.168.0.0", &(addr_ans.sin_addr)); - addr1.sin_addr.s_addr = inet_netof(localnet4_addr.sin_addr); - addr2.sin_addr.s_addr = inet_network(localnet4_addrstr); - - std::cerr << "Localnet4 Net(expected): 192.168.0.0 -> " << inet_ntoa(addr_ans.sin_addr); - std::cerr << " Net(1):" << inet_ntoa(addr1.sin_addr); - std::cerr << " Net(2):" << inet_ntoa(addr2.sin_addr); - std::cerr << std::endl; - - return true; -} - - - -#if 0 - -std::ostream &showSocketError(std::ostream &out); - -std::string socket_errorType(int err); -int sockaddr_cmp(struct sockaddr_in &addr1, struct sockaddr_in &addr2 ); -int inaddr_cmp(struct sockaddr_in addr1, struct sockaddr_in addr1 ); -int inaddr_cmp(struct sockaddr_in addr1, unsigned long); - -std::list getLocalInterfaces(); // returns all possible addrs. -bool isExternalNet(struct in_addr *addr); // if Valid & is not Private or Loopback. -bool isPrivateNet(struct in_addr *addr); // if inside 10.0.0.0 or - // other then firewalled. -bool isLoopbackNet(struct in_addr *addr); -bool sameNet(struct in_addr *addr, struct in_addr *addr2); -bool isValidNet(struct in_addr *addr); - - // checks (addr1 & 255.255.255.0) == (addr2 & 255.255.255.0) -bool isSameSubnet(struct in_addr *addr1, struct in_addr *addr2); - - -struct in_addr getPreferredInterface(); // returns best addr. - -in_addr_t pqi_inet_netof(struct in_addr addr); // our implementation. - -bool LookupDNSAddr(std::string name, struct sockaddr_in &addr); - -/* universal socket interface */ - -int unix_close(int sockfd); -int unix_socket(int domain, int type, int protocol); -int unix_fcntl_nonblock(int sockfd); -int unix_connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen); -int unix_getsockopt_error(int sockfd, int *err); - -#endif - - -bool test_bind_addr(struct sockaddr_in addr); - -bool test_address_listen() -{ - struct sockaddr_in addr1, addr2, addr3; - - sockaddr_clear(&addr1); - addr1.sin_family = AF_INET; - inet_aton(loopback_addrstr, &(addr1.sin_addr)); - addr1.sin_port = htons(12345); - - sockaddr_clear(&addr2); - addr2.sin_family = AF_INET; - addr2.sin_addr = getPreferredInterface(); // returns best addr. - addr2.sin_port = htons(13245); - - sockaddr_clear(&addr3); - addr3.sin_family = AF_INET; - addr3.sin_addr = getPreferredInterface(); // returns best addr. - addr3.sin_port = htons(23451); - - /* test bind to loopback, and preferred interfaces */ - test_bind_addr(addr1); - test_bind_addr(addr2); - test_bind_addr(addr3); - - return true; -} - -bool test_bind_addr(struct sockaddr_in addr) -{ - - int err; - - std::cerr << "test_bind_addr()"; - std::cerr << std::endl; - - std::cerr << "\tAddress Family: " << (int) addr.sin_family; - std::cerr << std::endl; - std::cerr << "\tAddress: " << inet_ntoa(addr.sin_addr); - std::cerr << std::endl; - std::cerr << "\tPort: " << ntohs(addr.sin_port); - std::cerr << std::endl; - - int sockfd = unix_socket(PF_INET, SOCK_STREAM, 0); - - if (0 != (err = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr)))) - { - std::cerr << " Failed to Bind to Local Address!" << std::endl; - showSocketError(std::cerr); - - return false; - } - - std::cerr << " Successfully Bound Socket to Address" << std::endl; - unix_close(sockfd); - - return true; -} - - diff --git a/libretroshare/src/pqi/net_test1.cc b/libretroshare/src/pqi/net_test1.cc deleted file mode 100644 index fd953a37f..000000000 --- a/libretroshare/src/pqi/net_test1.cc +++ /dev/null @@ -1,268 +0,0 @@ -/* - * libretroshare/src/pqi net_test.cc - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -/****** - * NETWORKING Test to check Big/Little Endian behaviour - * as well as socket behaviour - * - */ - -#include "pqi/pqinetwork.h" -#include "util/rsnet.h" -#include -#include -#include "util/utest.h" - -const char * loopback_addrstr = "127.0.0.1"; - -const char * localnet1_addrstr = "10.0.0.1"; -const char * localnet2_addrstr = "169.254.0.1"; -const char * localnet3_addrstr = "172.16.0.1"; -const char * localnet4_addrstr = "192.168.1.1"; - -const char * localnet5_addrstr = "10.4.28.34"; -const char * localnet6_addrstr = "169.254.1.81"; -const char * localnet7_addrstr = "172.20.9.201"; -const char * localnet8_addrstr = "192.168.1.254"; - -const char * external_addrstr = "74.125.19.99"; /* google */ -const char * invalid_addrstr = "AAA.BBB.256.256"; - -int test_isExternalNet(); -int test_isPrivateNet(); -int test_isLoopbackNet(); -int test_sameNet(); -int test_isValidNet(); -int test_isSameSubnet(); -int test_pqi_inet_netof(); - -INITTEST(); - -int main(int argc, char **argv) -{ - std::cerr << "net_test1" << std::endl; - - test_isExternalNet(); - test_isPrivateNet(); - test_isLoopbackNet(); - test_sameNet(); - test_isValidNet(); - test_isSameSubnet(); - test_pqi_inet_netof(); - - FINALREPORT("net_test1"); - - return TESTRESULT(); -} - -int test_isExternalNet() -{ - struct in_addr loopback_addr; - struct in_addr localnet1_addr; - struct in_addr localnet2_addr; - struct in_addr localnet3_addr; - struct in_addr localnet4_addr; - struct in_addr external_addr; - struct in_addr invalid_addr; - struct in_addr invalid_addr2; - - inet_aton(loopback_addrstr, &loopback_addr); - inet_aton(localnet1_addrstr, &localnet1_addr); - inet_aton(localnet2_addrstr, &localnet2_addr); - inet_aton(localnet3_addrstr, &localnet3_addr); - inet_aton(localnet4_addrstr, &localnet4_addr); - inet_aton(external_addrstr, &external_addr); - invalid_addr.s_addr = 0; - invalid_addr2.s_addr = -1; - - CHECK(isExternalNet(&loopback_addr)==false); - CHECK(isExternalNet(&localnet1_addr)==false); - CHECK(isExternalNet(&localnet2_addr)==false); - CHECK(isExternalNet(&localnet3_addr)==false); - CHECK(isExternalNet(&localnet4_addr)==false); - CHECK(isExternalNet(&external_addr)==true); - CHECK(isExternalNet(&invalid_addr)==false); - CHECK(isExternalNet(&invalid_addr2)==false); - - REPORT("isExternalNet()"); - - return 1; -} - -int test_isPrivateNet() -{ - struct in_addr loopback_addr; - struct in_addr localnet1_addr; - struct in_addr localnet2_addr; - struct in_addr localnet3_addr; - struct in_addr localnet4_addr; - struct in_addr external_addr; - - inet_aton(loopback_addrstr, &loopback_addr); - inet_aton(localnet1_addrstr, &localnet1_addr); - inet_aton(localnet2_addrstr, &localnet2_addr); - inet_aton(localnet3_addrstr, &localnet3_addr); - inet_aton(localnet4_addrstr, &localnet4_addr); - inet_aton(external_addrstr, &external_addr); - - CHECK(isPrivateNet(&loopback_addr)==false); //loopback not considered a "private network" - CHECK(isPrivateNet(&localnet1_addr)==true); - CHECK(isPrivateNet(&localnet2_addr)==true); - CHECK(isPrivateNet(&localnet3_addr)==true); - CHECK(isPrivateNet(&localnet4_addr)==true); - CHECK(isPrivateNet(&external_addr)==false); - - REPORT("isPrivateNet()"); - - return 1; -} - -int test_isLoopbackNet() -{ - struct in_addr loopback_addr; - struct in_addr localnet1_addr; - struct in_addr external_addr; - - inet_aton(loopback_addrstr, &loopback_addr); - inet_aton(localnet1_addrstr, &localnet1_addr); - inet_aton(external_addrstr, &external_addr); - - CHECK(isLoopbackNet(&loopback_addr)==true); - CHECK(isLoopbackNet(&localnet1_addr)==false); - CHECK(isLoopbackNet(&external_addr)==false); - - REPORT("isLoopbackNet()"); - - return 1; -} - -int test_sameNet() -{ - struct in_addr localnet1_addr; - struct in_addr localnet2_addr; - struct in_addr localnet3_addr; - struct in_addr localnet4_addr; - struct in_addr localnet5_addr; - struct in_addr localnet6_addr; - struct in_addr localnet7_addr; - struct in_addr localnet8_addr; - struct in_addr external_addr; - - inet_aton(localnet1_addrstr, &localnet1_addr); - inet_aton(localnet2_addrstr, &localnet2_addr); - inet_aton(localnet3_addrstr, &localnet3_addr); - inet_aton(localnet4_addrstr, &localnet4_addr); - inet_aton(localnet5_addrstr, &localnet5_addr); - inet_aton(localnet6_addrstr, &localnet6_addr); - inet_aton(localnet7_addrstr, &localnet7_addr); - inet_aton(localnet8_addrstr, &localnet8_addr); - inet_aton(external_addrstr, &external_addr); - - CHECK(sameNet(&localnet1_addr, &localnet5_addr)==true); - CHECK(sameNet(&localnet2_addr, &localnet6_addr)==true); - CHECK(sameNet(&localnet3_addr, &localnet7_addr)==true); - CHECK(sameNet(&localnet4_addr, &localnet8_addr)==true); - CHECK(sameNet(&localnet1_addr, &external_addr)==false); - CHECK(sameNet(&localnet2_addr, &external_addr)==false); - CHECK(sameNet(&localnet3_addr, &external_addr)==false); - CHECK(sameNet(&localnet4_addr, &external_addr)==false); - - REPORT("sameNet()"); - - return 1; -} - -int test_isValidNet() -{ - struct in_addr localnet1_addr; - struct in_addr invalid_addr; - - inet_aton(localnet1_addrstr, &localnet1_addr); - CHECK(isValidNet(&localnet1_addr)==true); - - CHECK(inet_aton(invalid_addrstr, &invalid_addr)==0); - std::cerr << inet_ntoa(invalid_addr) << std::endl; - //CHECK(isValidNet(&invalid_addr)==false); - - REPORT("isValidNet()"); - - return 1; -} - -int test_isSameSubnet() -{ - struct in_addr localnet1_addr; - struct in_addr classc1_addr; - struct in_addr classc2_addr; - - inet_aton(localnet1_addrstr, &localnet1_addr); - //random class C addresses - inet_aton("197.67.28.93", &classc1_addr); - inet_aton("197.67.28.3", &classc2_addr); - - CHECK(isSameSubnet(&localnet1_addr, &classc1_addr)==false); - CHECK(isSameSubnet(&classc1_addr, &classc2_addr)==true); - - REPORT("isSameSubnet()"); - - return 1; -} - -int test_pqi_inet_netof() -{ - struct in_addr localnet1_addr; - struct in_addr localnet2_addr; - struct in_addr localnet3_addr; - struct in_addr localnet4_addr; - struct in_addr localnet5_addr; - struct in_addr localnet6_addr; - struct in_addr localnet7_addr; - struct in_addr localnet8_addr; - struct in_addr external_addr; - - inet_aton(localnet1_addrstr, &localnet1_addr); - inet_aton(localnet2_addrstr, &localnet2_addr); - inet_aton(localnet3_addrstr, &localnet3_addr); - inet_aton(localnet4_addrstr, &localnet4_addr); - inet_aton(localnet5_addrstr, &localnet5_addr); - inet_aton(localnet6_addrstr, &localnet6_addr); - inet_aton(localnet7_addrstr, &localnet7_addr); - inet_aton(localnet8_addrstr, &localnet8_addr); - inet_aton(external_addrstr, &external_addr); - - CHECK(pqi_inet_netof(localnet1_addr)==htonl(10<<24)); - CHECK(pqi_inet_netof(localnet2_addr)==htonl(169<<24 | 254<<16)); - CHECK(pqi_inet_netof(localnet3_addr)==htonl(172<<24 | 16<<16)); - CHECK(pqi_inet_netof(localnet4_addr)==htonl(192<<24 | 168<<16 | 1<<8)); - CHECK(pqi_inet_netof(localnet5_addr)==htonl(10<<24)); - CHECK(pqi_inet_netof(localnet6_addr)==htonl(169<<24 | 254<<16)); - CHECK(pqi_inet_netof(localnet7_addr)==htonl(172<<24 | 20<<16)); - CHECK(pqi_inet_netof(localnet8_addr)==htonl(192<<24 | 168<<16 | 1<<8)); - CHECK(pqi_inet_netof(external_addr)==htonl(74<<24)); - - REPORT("pqi_inet_netof()"); - - return 1; -} diff --git a/libretroshare/src/pqi/netiface_test.cc b/libretroshare/src/pqi/netiface_test.cc deleted file mode 100644 index a3f6fa985..000000000 --- a/libretroshare/src/pqi/netiface_test.cc +++ /dev/null @@ -1,63 +0,0 @@ -/* - * libretroshare/src/pqi net_test.cc - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2007-2008 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -/****** - * NETWORKING Test to check Big/Little Endian behaviour - * as well as socket behaviour - * - */ - -#include "pqi/pqinetwork.h" -#include "util/rsnet.h" -#include -#include - - -bool test_iface(); - -int main(int argc, char **argv) -{ - - test_iface(); - return 1; -} - - /* test 1: byte manipulation */ -bool test_iface() -{ - struct in_addr pref_iface = getPreferredInterface(); - std::list ifaces = getLocalInterfaces(); - std::list::iterator it; - std::cerr << "test_iface()" << std::endl; - for(it = ifaces.begin(); it != ifaces.end(); it++) - { - std::cerr << "available iface: " << *it << std::endl; - } - std::cerr << "preferred " << inet_ntoa(pref_iface) << std::endl; - - return true; -} - - diff --git a/libretroshare/src/pqi/pqi_base.cc b/libretroshare/src/pqi/pqi_base.cc deleted file mode 100644 index 69291c094..000000000 --- a/libretroshare/src/pqi/pqi_base.cc +++ /dev/null @@ -1,413 +0,0 @@ -/* - * "$Id: pqi_base.cc,v 1.17 2007-03-31 09:41:32 rmf24 Exp $" - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2004-2006 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - - - -#include "pqi/pqi_base.h" - -#include - -// local functions. -int pqiroute_setshift(ChanId *item, int chan); -int pqiroute_getshift(ChanId *item); - -// these ones are also exported! -int pqicid_clear(ChanId *cid); -int pqicid_copy(const ChanId *cid, ChanId *newcid); -int pqicid_cmp(const ChanId *cid1, ChanId *cid2); - -// Helper functions for the PQInterface. - -static int next_search_id = 1; - -int getPQIsearchId() -{ - return next_search_id++; -} - - -// CHANID Operations. -int pqicid_clear(ChanId *cid) -{ - for(int i = 0; i < 10; i++) - { - cid -> route[i] = 0; - } - return 1; -} - -int pqicid_copy(const ChanId *cid, ChanId *newcid) -{ - for(int i = 0; i < 10; i++) - { - (newcid -> route)[i] = (cid -> route)[i]; - } - return 1; -} - -int pqicid_cmp(const ChanId *cid1, ChanId *cid2) -{ - int ret = 0; - for(int i = 0; i < 10; i++) - { - ret = cid1->route[i] - cid2->route[i]; - if (ret != 0) - { - return ret; - } - } - return 0; -} - - - - -int pqiroute_getshift(ChanId *id) -{ - int *array = id -> route; - int next = array[0]; - - // shift. - for(int i = 0; i < 10 - 1; i++) - { - array[i] = array[i+1]; - } - array[10 - 1] = 0; - - return next; -} - -int pqiroute_setshift(ChanId *id, int chan) -{ - int *array = id -> route; - - // shift. - for(int i = 10 - 1; i > 0; i--) - { - array[i] = array[i-1]; - } - array[0] = chan; - - return 1; -} - -/****************** PERSON DETAILS ***********************/ - -Person::Person() - :dhtFound(false), dhtFlags(0), - lc_timestamp(0), lr_timestamp(0), - nc_timestamp(0), nc_timeintvl(5), - name("Unknown"), status(PERSON_STATUS_MANUAL) - - - { - for(int i = 0; i < (signed) sizeof(lastaddr); i++) - { - ((unsigned char *) (&lastaddr))[i] = 0; - ((unsigned char *) (&localaddr))[i] = 0; - ((unsigned char *) (&serveraddr))[i] = 0; - ((unsigned char *) (&dhtaddr))[i] = 0; - } - pqicid_clear(&cid); - - - return; - } - -Person::~Person() - { - } - - -int Person::cidpop() -{ - return pqiroute_getshift(&cid); -} - -void Person::cidpush(int id) -{ - pqiroute_setshift(&cid, id); - return; -} - -bool Person::Group(std::string in) - { - std::list::iterator it; - for(it = groups.begin(); it != groups.end(); it++) - { - if (in == (*it)) - { - return true; - } - } - return false; - } - - -int Person::addGroup(std::string in) - { - groups.push_back(in); - return 1; - } - -int Person::removeGroup(std::string in) - { - std::list::iterator it; - for(it = groups.begin(); it != groups.end(); it++) - { - if (in == (*it)) - { - groups.erase(it); - return 1; - } - } - return 0; - } - - - -bool Person::Valid() - { - return (status & PERSON_STATUS_VALID); - } - -void Person::Valid(bool b) - { - if (b) - status |= PERSON_STATUS_VALID; - else - status &= ~PERSON_STATUS_VALID; - } - -bool Person::Accepted() - { - return (status & PERSON_STATUS_ACCEPTED); - } - -void Person::Accepted(bool b) - { - if (b) - status |= PERSON_STATUS_ACCEPTED; - else - status &= ~PERSON_STATUS_ACCEPTED; - } - -bool Person::InUse() - { - return (status & PERSON_STATUS_INUSE); - } - -void Person::InUse(bool b) - { - if (b) - status |= PERSON_STATUS_INUSE; - else - status &= ~(PERSON_STATUS_INUSE); - } - - -bool Person::Listening() - { - return (status & PERSON_STATUS_LISTENING); - } - -void Person::Listening(bool b) - { - if (b) - status |= PERSON_STATUS_LISTENING; - else - status &= ~PERSON_STATUS_LISTENING; - } - -bool Person::Connected() - { - return (status & PERSON_STATUS_CONNECTED); - } - -void Person::Connected(bool b) - { - if (b) - status |= PERSON_STATUS_CONNECTED; - else - status &= ~PERSON_STATUS_CONNECTED; - } - -bool Person::WillListen() - { - return (status & PERSON_STATUS_WILL_LISTEN); - } - -void Person::WillListen(bool b) - { - if (b) - status |= PERSON_STATUS_WILL_LISTEN; - else - status &= ~PERSON_STATUS_WILL_LISTEN; - } - -bool Person::WillConnect() - { - return (status & PERSON_STATUS_WILL_CONNECT); - } - -void Person::WillConnect(bool b) - { - if (b) - status |= PERSON_STATUS_WILL_CONNECT; - else - status &= ~PERSON_STATUS_WILL_CONNECT; - } - -bool Person::Manual() - { - return (status & PERSON_STATUS_MANUAL); - } - -void Person::Manual(bool b) - { - if (b) - status |= PERSON_STATUS_MANUAL; - else - status &= ~PERSON_STATUS_MANUAL; - } - -bool Person::Firewalled() - { - return (status & PERSON_STATUS_FIREWALLED); - } - -void Person::Firewalled(bool b) - { - if (b) - status |= PERSON_STATUS_FIREWALLED; - else - status &= ~PERSON_STATUS_FIREWALLED; - } - -bool Person::Forwarded() - { - return (status & PERSON_STATUS_FORWARDED); - } - -void Person::Forwarded(bool b) - { - if (b) - status |= PERSON_STATUS_FORWARDED; - else - status &= ~PERSON_STATUS_FORWARDED; - } - -bool Person::Local() - { - return (status & PERSON_STATUS_LOCAL); - } - -void Person::Local(bool b) - { - if (b) - status |= PERSON_STATUS_LOCAL; - else - status &= ~PERSON_STATUS_LOCAL; - } - - -bool Person::Trusted() - { - return (status & PERSON_STATUS_TRUSTED); - } - -void Person::Trusted(bool b) - { - if (b) - status |= PERSON_STATUS_TRUSTED; - else - status &= ~PERSON_STATUS_TRUSTED; - } - - -unsigned int Person::Status() - { - return status; - } - - -void Person::Status(unsigned int s) - { - status = s; - } - -std::string Person::Name() - { - return name; - } - - -void Person::Name(std::string n) - { - name = n; - } - - /* Dynamic Address Foundation */ -bool Person::hasDHT() -{ - return dhtFound; -} - -void Person::setDHT(struct sockaddr_in addr, unsigned int flags) -{ - dhtFound = true; - dhtFlags = flags; - dhtaddr = addr; -} - -/* GUI Flags */ -bool Person::InChat() - { - return (status & PERSON_STATUS_INCHAT); - } - -void Person::InChat(bool b) - { - if (b) - status |= PERSON_STATUS_INCHAT; - else - status &= ~PERSON_STATUS_INCHAT; - } - -bool Person::InMessage() - { - return (status & PERSON_STATUS_INMSG); - } - -void Person::InMessage(bool b) - { - if (b) - status |= PERSON_STATUS_INMSG; - else - status &= ~PERSON_STATUS_INMSG; - } - - diff --git a/libretroshare/src/pqi/sslcert.cc b/libretroshare/src/pqi/sslcert.cc deleted file mode 100644 index 2c2db8bae..000000000 --- a/libretroshare/src/pqi/sslcert.cc +++ /dev/null @@ -1,2031 +0,0 @@ -/* - * Core PQI networking: sslcert.cc - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2004-2006 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - -#include "sslcert.h" - -#include "pqi.h" -#include "pqinetwork.h" - -#include -#include -#include - -#include -#include - -#include "pqidebug.h" - -const int pqisslrootzone = 1211; - - -// other fns -std::string getCertName(cert *c) -{ - std::string name = c -> certificate -> name; - // strip out bad chars. - for(int i = 0; i < (signed) name.length(); i++) - { - if ((name[i] == '/') || (name[i] == ' ') || (name[i] == '=') || - (name[i] == '\\') || (name[i] == '\t') || (name[i] == '\n')) - { - name[i] = '_'; - } - } - return name; -} - - - -int pem_passwd_cb(char *buf, int size, int rwflag, void *password) -{ - strncpy(buf, (char *)(password), size); - buf[size - 1] = '\0'; - return(strlen(buf)); -} - - -/* This class handles openssl library init/destruct. - * only one of these... handles - * the CTX and setup? - * - * it will also handle the certificates..... - * mantaining a library of recieved certs, - * and ip addresses that the connections come from... - * - */ - -// the single instance of this. -static sslroot instance_sslroot; - -sslroot *getSSLRoot() -{ - return &instance_sslroot; -} - -sslroot::sslroot() - :sslctx(NULL), init(0), certsChanged(1), - certsMajorChanged(1), pkey(NULL) -{ -} - -int sslroot::active() -{ - return init; -} - -// args: server cert, server private key, trusted certificates. - -int sslroot::initssl(const char *cert_file, const char *priv_key_file, - const char *CA_FILE, const char *passwd) -{ -static int initLib = 0; - if (!initLib) - { - initLib = 1; - SSL_load_error_strings(); - SSL_library_init(); - } - - - if (init == 1) - { - return 1; - } - - if ((cert_file == NULL) || - (priv_key_file == NULL) || - (passwd == NULL)) - { - fprintf(stderr, "sslroot::initssl() missing parameters!\n"); - return 0; - } - - - SSL_load_error_strings(); - SSL_library_init(); - // XXX TODO - // actions_to_seed_PRNG(); - - pqioutput(PQL_WARNING, pqisslrootzone, "SSL Library Init!"); - - // setup connection method - sslctx = SSL_CTX_new(SSLv23_method()); - - // setup cipher lists. - SSL_CTX_set_cipher_list(sslctx, "DEFAULT"); - - // certificates (Set Local Server Certificate). - FILE *ownfp = fopen(cert_file, "r"); - if (ownfp == NULL) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "Couldn't open Own Certificate!"); - return -1; - } - - X509 *x509 = PEM_read_X509(ownfp, NULL, NULL, NULL); - fclose(ownfp); - if (x509 != NULL) - { - SSL_CTX_use_certificate(sslctx, x509); - own_cert = makeCertificate(x509); - if (own_cert == NULL) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "Failed to Make Own Cert!"); - return -1; - } - addCertificate(own_cert); - } - else - { - return -1; - } - - - // SSL_CTX_use_certificate_chain_file(sslctx, cert_file_chain); - - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, "SSL Set Chain File"); - - SSL_CTX_load_verify_locations(sslctx, CA_FILE, 0); - - // enable verification of certificates (PEER) - SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER | - SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); - - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, "SSL Verification Set"); - - // setup private key - FILE *pkfp = fopen(priv_key_file, "rb"); - if (pkfp == NULL) - { - pqioutput(PQL_ALERT, pqisslrootzone, "Couldn't Open PrivKey File!"); - closessl(); - return -1; - } - - pkey = PEM_read_PrivateKey(pkfp, NULL, NULL, (void *) passwd); - - SSL_CTX_use_PrivateKey(sslctx, pkey); - - if (1 != SSL_CTX_check_private_key(sslctx)) - { - std::ostringstream out; - out << "Issues With Private Key! - Doesn't match your Cert" << std::endl; - out << "Check your input key/certificate:" << std::endl; - out << priv_key_file << " & " << cert_file; - out << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - - closessl(); - return -1; - } - - - // Load CA for clients. - STACK_OF(X509_NAME) *cert_names; - cert_names = SSL_load_client_CA_file(CA_FILE); - - if (cert_names != NULL) - { - SSL_CTX_set_client_CA_list(sslctx, cert_names); - } - else - { - std::ostringstream out; - out << "Couldn't Load Client CA files!" << std::endl; - out << "Check That (" << CA_FILE << ") is valid"; - out << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - closessl(); - return -1; - } - - /* configure basics on the certificate. */ - std::string tagname; // = "LOCL:"; - own_cert -> Name(tagname + getX509CNString(own_cert -> certificate -> cert_info -> subject)); - - init = 1; - return 1; -} - - - -int sslroot::closessl() -{ - SSL_CTX_free(sslctx); - - // clean up private key.... - // remove certificates etc -> opposite of initssl. - init = 0; - return 1; -} - -/* Context handling */ -SSL_CTX *sslroot::getCTX() -{ - return sslctx; -} - -int sslroot::setConfigDirs(const char *cdir, const char *ndir) -{ - certdir = cdir; - neighbourdir = ndir; - return 1; -} - -static const unsigned int OPT_LEN = 16; -static const unsigned int VAL_LEN = 1000; - -int sslroot::saveCertificates() -{ - if (certfile.length() > 1) - return saveCertificates(certfile.c_str()); - return -1; -} - - -int sslroot::saveCertificates(const char *fname) -{ - // construct file name. - // - // create the file in memory - hash + sign. - // write out data to a file. - - std::string neighdir = certdir + "/" + neighbourdir + "/"; - std::string configname = certdir + "/"; - configname += fname; - - std::map::iterator mit; - - - std::string conftxt; - std::string empty(""); - unsigned int i; - - std::list::iterator it; - for(it = peercerts.begin(); it != peercerts.end(); it++) - { - std::string neighfile = neighdir + getCertName(*it) + ".pqi"; - savecertificate((*it), neighfile.c_str()); - conftxt += "CERT "; - conftxt += getCertName(*it); - conftxt += "\n"; - conftxt += (*it) -> Hash(); - conftxt += "\n"; - } - - // Now add the options. - for(mit = settings.begin(); mit != settings.end(); mit++) - { - // only save the nonempty settings. - if (mit -> second != empty) { - conftxt += "OPT "; - for(i = 0; (i < OPT_LEN) && (i < mit -> first.length()); i++) - { - conftxt += mit -> first[i]; - } - conftxt += "\n"; - for(i = 0; i < VAL_LEN; i++) - { - if (i < mit -> second.length()) - { - conftxt += mit -> second[i]; - } - else - { - conftxt += '\0'; - } - } - conftxt += "\n"; - } - } - - // now work out signature of it all. This relies on the - // EVP library of openSSL..... We are going to use signing - // for the moment. - - unsigned int signlen = EVP_PKEY_size(pkey); - unsigned char signature[signlen]; - - //OpenSSL_add_all_digests(); - - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_SignInit_ex(mdctx, EVP_sha1(), NULL)) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "EVP_SignInit Failure!"); - } - - if (0 == EVP_SignUpdate(mdctx, conftxt.c_str(), conftxt.length())) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "EVP_SignUpdate Failure!"); - } - - - if (0 == EVP_SignFinal(mdctx, signature, &signlen, pkey)) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "EVP_SignFinal Failure!"); - } - - { - std::ostringstream out; - out << "Conf Signature is(" << signlen << "): "; - for(i = 0; i < signlen; i++) - { - out << std::hex << std::setw(2) << (int) signature[i]; - conftxt += signature[i]; - } - out << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - FILE *cfd = fopen(configname.c_str(), "wb"); - int wrec; - if (1 != (wrec = fwrite(conftxt.c_str(), conftxt.length(), 1, cfd))) - { - std::ostringstream out; - out << "Error writing: " << configname << std::endl; - out << "Wrote: " << wrec << "/" << 1 << " Records" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - EVP_MD_CTX_destroy(mdctx); - fclose(cfd); - - return 1; -} - -int sslroot::loadCertificates(const char *conf_fname) -{ - // open the configuration file. - // - // read in CERT + Hash. - - // construct file name. - // - // create the file in memory - hash + sign. - // write out data to a file. - - std::string neighdir = certdir + "/" + neighbourdir + "/"; - std::string configname = certdir + "/"; - configname += conf_fname; - - // save name for later save attempts. - certfile = conf_fname; - - std::string conftxt; - - unsigned int maxnamesize = 1024; - char name[maxnamesize]; - - int c; - unsigned int i; - - FILE *cfd = fopen(configname.c_str(), "rb"); - if (cfd == NULL) - { - std::ostringstream out; - out << "Unable to Load Configuration File!" << std::endl; - out << "File: " << configname << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - return -1; - } - - std::list fnames; - std::list hashes; - std::map::iterator mit; - std::map tmpsettings; - - unsigned int signlen = EVP_PKEY_size(pkey); - unsigned char conf_signature[signlen]; - char *ret = NULL; - - for(ret = fgets(name, maxnamesize, cfd); - ((ret != NULL) && (!strncmp(name, "CERT ", 5))); - ret = fgets(name, maxnamesize, cfd)) - { - for(i = 5; (name[i] != '\n') && (i < (unsigned) maxnamesize); i++); - - if (name[i] == '\n') - { - name[i] = '\0'; - } - - // so the name is first.... - std::string fname = &(name[5]); - - // now read the - std::string hash; - std::string signature; - - for(i = 0; i < signlen; i++) - { - if (EOF == (c = fgetc(cfd))) - { - std::ostringstream out; - out << "Error Reading Signature of: "; - out << fname; - out << std::endl; - out << "ABorting Load!"; - out << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - return -1; - } - unsigned char uc = (unsigned char) c; - signature += (unsigned char) uc; - } - if ('\n' != (c = fgetc(cfd))) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "Warning Mising seperator"); - } - - { - std::ostringstream out; - out << "Read fname:" << fname << std::endl; - out << "Signature:" << std::endl; - for(i = 0; i < signlen; i++) - { - out << std::hex << std::setw(2) << (int) signature[i]; - } - out << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - // push back..... - fnames.push_back(fname); - hashes.push_back(signature); - - conftxt += "CERT "; - conftxt += fname; - conftxt += "\n"; - conftxt += signature; - conftxt += "\n"; - - // be sure to write over a bit... - name[0] = 'N'; - name[1] = 'O'; - } - - // string already waiting! - for(; ((ret != NULL) && (!strncmp(name, "OPT ", 4))); - ret = fgets(name, maxnamesize, cfd)) - { - for(i = 4; (name[i] != '\n') && (i < OPT_LEN); i++); - // terminate the string. - name[i] = '\0'; - - // so the name is first.... - std::string opt = &(name[4]); - - // now read the - std::string val; // cleaned up value. - std::string valsign; // value in the file. - - for(i = 0; i < VAL_LEN; i++) - { - if (EOF == (c = fgetc(cfd))) - { - std::ostringstream out; - out << "Error Reading Value of: "; - out << opt; - out << std::endl; - out << "ABorting Load!"; - out << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - return -1; - } - // remove zeros on strings... - if (c != '\0') - { - val += (unsigned char) c; - } - valsign += (unsigned char) c; - } - if ('\n' != (c = fgetc(cfd))) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "Warning Mising seperator"); - } - - { - std::ostringstream out; - out << "Read OPT:" << opt; - out << " Val:" << val << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - // push back..... - tmpsettings[opt] = val; - - conftxt += "OPT "; - conftxt += opt; - conftxt += "\n"; - conftxt += valsign; - conftxt += "\n"; - - // be sure to write over a bit... - name[0] = 'N'; - name[1] = 'O'; - } - - // only read up to the first newline symbol.... - // continue... - for(i = 0; (name[i] != '\n') && (i < signlen); i++); - - //printf("Stepping over [%d] %0x\n", i, name[i]); - - - if (i != signlen) - { - for(i++; i < signlen; i++) - { - c = fgetc(cfd); - if (c == EOF) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "Error Reading Conf Signature:"); - return 1; - } - unsigned char uc = (unsigned char) c; - name[i] = uc; - } - } - - { - std::ostringstream out; - out << "Configuration File Signature: " << std::endl; - for(i = 0; i < signlen; i++) - { - out << std::hex << std::setw(2) << (int) name[i]; - } - out << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - - // when we get here - should have the final signature in the buffer. - // check. - // - // compare signatures. - // instead of verifying with the public key.... - // we'll sign it again - and compare .... FIX LATER... - - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_SignInit(mdctx, EVP_sha1())) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignInit Failure!"); - } - - if (0 == EVP_SignUpdate(mdctx, conftxt.c_str(), conftxt.length())) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignUpdate Failure!"); - } - - if (0 == EVP_SignFinal(mdctx, conf_signature, &signlen, pkey)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignFinal Failure!"); - } - - EVP_MD_CTX_destroy(mdctx); - fclose(cfd); - - { - std::ostringstream out; - out << "Recalced File Signature: " << std::endl; - for(i = 0; i < signlen; i++) - { - out << std::hex << std::setw(2) << (int) conf_signature[i]; - } - out << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - bool same = true; - for(i = 0; i < signlen; i++) - { - if ((unsigned char) name[i] != conf_signature[i]) - { - same = false; - } - } - - if (same == false) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "ERROR VALIDATING CONFIGURATION! -- PLEASE FIX!"); - return -1; - } - std::list::iterator it; - std::list::iterator it2; - for(it = fnames.begin(), it2 = hashes.begin(); it != fnames.end(); it++, it2++) - { - std::string neighfile = neighdir + (*it) + ".pqi"; - cert *nc = loadcertificate(neighfile.c_str(), (*it2)); - if (nc != NULL) - { - if (0 > addCertificate(nc)) - { - // cleanup. - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "Updated Certificate....but no need for addition"); - // X509_free(nc -> certificate); - //delete nc; - } - } - } - for(mit = tmpsettings.begin(); mit != tmpsettings.end(); mit++) - { - settings[mit -> first] = mit -> second; - } - return 1; -} - - -int sslroot::savecertificate(cert *c, const char *fname) -{ - // load certificates from file. - FILE *setfp = fopen(fname, "wb"); - if (setfp == NULL) - { - std::ostringstream out; - out << "sslroot::savecertificate() Bad File: " << fname; - out << " Cannot be Written!" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - return -1; - } - - { - std::ostringstream out; - out << "Writing out Cert...:" << c -> Name() << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - PEM_write_X509(setfp, c -> certificate); - - // writing out details.... - - // read in a line..... - int size = 1024; - char line[size]; - std::list::iterator it; - - int i; - - // This will need to be made portable..... - - struct sockaddr_in *addr_inet; - struct sockaddr_in *addr_inet2; - struct sockaddr_in *addr_inet3; - - int pos_status = 0; - int pos_addr = sizeof(int); - int pos_addr2 = pos_addr + sizeof(*addr_inet); - int pos_addr3 = pos_addr2 + sizeof(*addr_inet2); - - int pos_lcts = pos_addr3 + sizeof(*addr_inet3); - int pos_lrts = pos_lcts + sizeof(int); - int pos_ncts = pos_lrts + sizeof(int); - int pos_ncvl = pos_ncts + sizeof(int); - int pos_name = pos_ncvl + sizeof(int); - int pos_end = pos_name + 20; // \n. for readability. - - int *status = (int *) &(line[pos_status]); - addr_inet = (struct sockaddr_in *) &(line[pos_addr]); - addr_inet2 = (struct sockaddr_in *) &(line[pos_addr2]); - addr_inet3 = (struct sockaddr_in *) &(line[pos_addr3]); - int *lcts = (int *) &(line[pos_lcts]); - int *lrts = (int *) &(line[pos_lrts]); - char *ncts = &(line[pos_ncts]); - char *ncvl = &(line[pos_ncvl]); - char *name = &(line[pos_name]); - char *end = &(line[pos_end]); - - for(i = 0; i < 1024; i++) - line[i] = 0; - - *status = c -> Status(); - *addr_inet = c -> lastaddr; - *addr_inet2 = c -> localaddr; - *addr_inet3 = c -> serveraddr; - - *lcts = c -> lc_timestamp; - *lrts = c -> lr_timestamp; - *ncts = c -> nc_timestamp; - *ncvl = c -> nc_timeintvl; - - std::string tmpname = c -> Name(); - for(i = 0; (i < (signed) tmpname.length()) && (i < 20 - 1); i++) - { - name[i] = tmpname[i]; - } - name[20 - 1] = '\0'; - end[0] = '\n'; - - - if (1 != fwrite(line, size,1, setfp)) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "Error Writing Peer Record!"); - return -1; - } - fclose(setfp); - - // then reopen to generate hash. - setfp = fopen(fname, "rb"); - if (setfp == NULL) - { - std::ostringstream out; - out << "sslroot::savecertificate() Bad File: " << fname; - out << " Opened for ReHash!" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - return -1; - } - - unsigned int signlen = EVP_PKEY_size(pkey); - unsigned char signature[signlen]; - - int maxsize = 10240; - int rbytes; - char inall[maxsize]; - if (0 == (rbytes = fread(inall, 1, maxsize, setfp))) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "Error Writing Peer Record!"); - return -1; - } - - { - std::ostringstream out; - out << "Read " << rbytes << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - // so we read rbytes. - // hash. - //OpenSSL_add_all_digests(); - - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_SignInit_ex(mdctx, EVP_sha1(), NULL)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignInit Failure!"); - } - - if (0 == EVP_SignUpdate(mdctx, inall, rbytes)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignUpdate Failure!"); - } - - if (0 == EVP_SignFinal(mdctx, signature, &signlen, pkey)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignFinal Failure!"); - } - - std::string signstr; - { - std::ostringstream out; - out << "Cert + Setting Signature is(" << signlen << "): "; - for(i = 0; i < (signed) signlen; i++) - { - out << std::hex << std::setw(2) << (int) signature[i]; - signstr += signature[i]; - } - out << std::dec << std::endl; - - c -> Hash(signstr); - out << "Stored Hash Length: " << (c -> Hash()).length() << std::endl; - out << "Real Hash Length: " << signlen << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - fclose(setfp); - - EVP_MD_CTX_destroy(mdctx); - - return 1; -} - -cert *sslroot::loadcertificate(const char *fname, std::string hash) -{ - // if there is a hash - check that the file matches it before loading. - FILE *pcertfp; - if (hash.length() > 1) - { - pcertfp = fopen(fname, "rb"); - // load certificates from file. - if (pcertfp == NULL) - { - std::ostringstream out; - out << "sslroot::loadcertificate() Bad File: " << fname; - out << " Cannot be Hashed!" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - return NULL; - } - - unsigned int signlen = EVP_PKEY_size(pkey); - unsigned char signature[signlen]; - - int maxsize = 10240; - int rbytes; - char inall[maxsize]; - if (0 == (rbytes = fread(inall, 1, maxsize, pcertfp))) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "Error Reading Peer Record!"); - return NULL; - } - - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_SignInit_ex(mdctx, EVP_sha1(), NULL)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignInit Failure!"); - } - - if (0 == EVP_SignUpdate(mdctx, inall, rbytes)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignUpdate Failure!"); - } - - if (0 == EVP_SignFinal(mdctx, signature, &signlen, pkey)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignFinal Failure!"); - } - - fclose(pcertfp); - EVP_MD_CTX_destroy(mdctx); - - bool same = true; - if (signlen != hash.length()) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "Different Length Signatures... Cannot Load Cert!"); - return NULL; - } - - for(int i = 0; i < (signed) signlen; i++) - { - if (signature[i] != (unsigned char) hash[i]) - { - same = false; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "Invalid Signature... Cannot Load Certificate!"); - return NULL; - } - } - - { - std::ostringstream out; - out << "Verified Signature for: " << fname; - out << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - - } - else - { - pqioutput(PQL_ALERT, pqisslrootzone, "Not checking cert signature"); - } - - pcertfp = fopen(fname, "rb"); - - // load certificates from file. - if (pcertfp == NULL) - { - std::ostringstream out; - out << "sslroot::loadcertificate() Bad File: " << fname; - out << " Cannot be Read!" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - return NULL; - } - - - X509 *pc; - cert *npc = NULL; - - if ((pc = PEM_read_X509(pcertfp, NULL, NULL, NULL)) != NULL) - { - // read a certificate. - std::ostringstream out; - out << "Loaded Certificate: "; - out << pc -> name << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - - npc = makeCertificate(pc); - if (npc == NULL) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, "Failed to Create Cert!"); - return NULL; - } - } - else // (pc == NULL) - { - unsigned long err = ERR_get_error(); - std::ostringstream out; - out << "Read Failed .... CODE(" << err << ")" << std::endl; - out << ERR_error_string(err, NULL) << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - return NULL; - } - - // Now we try to read in 1024 bytes..... - // if successful, then have settings! - - // read in a line..... - int size = 1024; - char line[size]; - - // Data arrangment. - // so far - // ------------ - // 4 - (int) status - // 8 - sockaddr - // 8 - sockaddr - // 8 - sockaddr - // 4 - lc_timestamp - // 4 - lr_timestamp - // 4 - nc_timestamp - // 4 - nc_timeintvl - // 20 - name. - // 1 - end - - // This will need to be made portable..... - - struct sockaddr_in *addr_inet; - struct sockaddr_in *addr_inet2; - struct sockaddr_in *addr_inet3; - - //int pos_status = 0; - int pos_addr = sizeof(int); - int pos_addr2 = pos_addr + sizeof(*addr_inet); - int pos_addr3 = pos_addr2 + sizeof(*addr_inet2); - int pos_lcts = pos_addr3 + sizeof(*addr_inet3); - - int pos_lrts = pos_lcts + sizeof(int); - int pos_ncts = pos_lrts + sizeof(int); - int pos_ncvl = pos_ncts + sizeof(int); - int pos_name = pos_ncvl + sizeof(int); - //int pos_end = pos_name + 20; // \n. for readability. - - int *status = (int *) line; - addr_inet = (struct sockaddr_in *) &(line[pos_addr]); - addr_inet2 = (struct sockaddr_in *) &(line[pos_addr2]); - addr_inet3 = (struct sockaddr_in *) &(line[pos_addr3]); - int *lcts = (int *) &(line[pos_lcts]); - int *lrts = (int *) &(line[pos_lrts]); - char *ncts = &(line[pos_ncts]); - char *ncvl = &(line[pos_ncvl]); - char *name = &(line[pos_name]); - //char *end = &(line[pos_end]); - - // end of data structures.... - - if (1 != (signed) fread(line, size,1, pcertfp)) - { - pqioutput(PQL_WARNING, pqisslrootzone, - "Error Reading Setting: Only Cert Retrieved"); - return npc; - } - - - // fill in the data. - cert *c = npc; - c -> Status(*status); - // but ensure that inUse is not set. - c -> InUse(false); - - c -> lastaddr = *addr_inet; - c -> localaddr = *addr_inet2; - c -> serveraddr = *addr_inet3; - - c -> lc_timestamp = *lcts; - c -> lr_timestamp = *lrts; - c -> nc_timestamp = *ncts; - c -> nc_timeintvl = *ncvl; - - - name[20 - 1] = '\0'; - c -> Name(std::string(name)); - - // save the hash. - c -> Hash(hash); - - fclose(pcertfp); - - // small hack - as the timestamps seem wrong..... - // could be a saving thing - or a bug.... - c -> lc_timestamp = 0; - c -> lr_timestamp = 0; - - // reset these. as well. - c -> nc_timestamp = 0; - c -> nc_timeintvl = 5; - - return c; -} - - -int sslroot::printCertificate(cert *c, std::ostream &out) -{ - out << "Cert Name:" << (c -> certificate) -> name << std::endl; - //X509_print_fp(stderr, c -> certificate); - return 1; -} - -// This function will clean up X509 *c if necessary. - -cert *sslroot::makeCertificate(X509 *c) -{ - if (c == NULL) - { - return NULL; - } - - // At this point we check to see if there is a duplicate. - cert *dup = checkDuplicateX509(c); - cert *npc = NULL; - if (dup == NULL) - { - npc = new cert(); - npc -> certificate = c; - if (!addtosignmap(npc)) // only allow the cert if no dup - { - - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::makeCertificate() Failed to Get Signature - Not Allowed!"); - - // failed!... cannot add it!. - delete npc; - return NULL; - } - - allcerts.push_back(npc); - { - std::ostringstream out; - out << "sslroot::makeCertificate() For " << c -> name; - out << " A-Okay!" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - // at this point we need to add to the signaturelist.... - - } - else if (c == dup -> certificate) - { - // identical - so okay. - npc = dup; - std::ostringstream out; - out << "sslroot::makeCertificate() For " << c -> name; - out << " Found Identical - A-Okay!" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - else - { - std::ostringstream out; - out << "sslroot::makeCertificate() For " << c -> name; - out << " Cleaning up other X509!" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - // clean up c. - X509_free(c); - npc = dup; - } - return npc; -} - - -cert *sslroot::checkDuplicateX509(X509 *x) -{ - if (x == NULL) - return NULL; - - // loop through and print - then check. - std::list::iterator it; - for(it = allcerts.begin(); it != allcerts.end(); it++) - { - if (0 == X509_cmp((*it) -> certificate, x)) - { - return (*it); - } - } - return NULL; -} - - -cert *sslroot::checkPeerX509(X509 *x) -{ - if (x == NULL) - return NULL; - - // loop through and print - then check. - std::list::iterator it; - for(it = peercerts.begin(); it != peercerts.end(); it++) - { - if (0 == X509_cmp((*it) -> certificate, x)) - { - return (*it); - } - } - return NULL; -} - - - -cert *sslroot::findpeercert(const char *name) -{ - // loop through and print - then check. - //std::cerr << "Checking Certs for: " << name << std::endl; - std::list::iterator it; - for(it = peercerts.begin(); it != peercerts.end(); it++) - { - char *certname = ((*it) -> certificate) -> name; - //std::cerr << "Cert Name:" << certname << std::endl; - if (strstr(certname, name) != NULL) - { - //std::cerr << "Matches!" << std::endl; - return (*it); - } - } - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::findpeercert() Failed!"); - return NULL; -} - -// returns zero for the same. -int sslroot::compareCerts(cert *a, cert *b) -{ - // std::cerr << "Comparing Certificates:" << std::endl; - //printCertificate(a); - //printCertificate(b); - //X509_print_fp(stderr, a -> certificate); - //X509_print_fp(stderr, b -> certificate); - - int val = X509_cmp(a -> certificate, b -> certificate); - - { - std::ostringstream out; - out << "Certificate Comparison Returned: " << val << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - return val; -} - -cert * sslroot::registerCertificate(X509 *nc, struct sockaddr_in raddr, bool in) -{ - if (nc == NULL) - return NULL; - - // shoud check all certs. - cert *c = checkDuplicateX509(nc); - if (c != NULL) - { - if (c -> certificate == nc) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::registerCertificate() Found Identical X509 cert"); - } - else - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::registerCertificate() Found Same X509 cert/diff mem - Clean"); - X509_free(nc); - } - - if (!c -> Connected()) - { - c -> lastaddr = raddr; - - if (in == true) - { - c -> lr_timestamp = time(NULL); - // likely to be server address - // (with default port) - // if null! - if (!isValidNet(&(c -> serveraddr.sin_addr))) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "Guessing Default Server Addr!"); - - c -> serveraddr = raddr; - c -> serveraddr.sin_port = - htons(PQI_DEFAULT_PORT); - } - } - else - { - c -> lc_timestamp = time(NULL); - // also likely to be servera address, - // but we can check and see if its local. - // can flag local - if (0 == inaddr_cmp(c -> localaddr, raddr)) - { - c -> Local(true); - // don't set serveraddr -> just ignore - } - else - { - c -> serveraddr = raddr; - c -> Firewalled(false); - } - } - } - else - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "WARNING: attempt to reg CONNECTED Cert!"); - } - return c; - } - - { - std::ostringstream out; - out << "sslroot::registerCertificate() Certificate Not Found!" << std::endl; - out << "Saving :" << nc -> name << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - cert *npc = makeCertificate(nc); - if (npc == NULL) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "Failed to Make Certificate"); - return NULL; - } - - npc -> Name(nc -> name); - - npc -> lastaddr = raddr; - if (in == true) - { - npc -> lr_timestamp = time(NULL); - // likely to be server address (with default port) - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, "Guessing Default Server Addr!"); - npc -> serveraddr = raddr; - npc -> serveraddr.sin_port = htons(PQI_DEFAULT_PORT); - } - else - { - npc -> lc_timestamp = time(NULL); - - // as it is a new cert... all fields are - // null and the earlier tests must be - // delayed until the discovery packets. - - // also likely to be server. - npc -> serveraddr = raddr; - } - - // push back onto collected. - npc -> nc_timestamp = 0; - collectedcerts.push_back(npc); - - // return NULL to indicate that it dosen't yet exist in dbase. - return NULL; -} - -cert * sslroot::getCollectedCert() -{ - if (collectedcerts.size() < 1) - return NULL; - - cert *c = collectedcerts.front(); - collectedcerts.pop_front(); - return c; -} - -bool sslroot::collectedCerts() -{ - return (collectedcerts.size() > 0); -} - - -int sslroot::removeCertificate(cert *c) -{ - if (c -> InUse()) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::removeCertificate() Failed: cert is in use."); - return -1; - } - - std::list::iterator it; - for(it = peercerts.begin(); it != peercerts.end(); it++) - { - if (c == (*it)) - { - peercerts.erase(it); - - c -> InUse(false); - c -> Accepted(false); - - - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::removeCertificate() Success! Moved to Coll Certs"); - - collectedcerts.push_back(c); - - certsChanged.IndicateChanged(); - certsMajorChanged.IndicateChanged(); - return 1; - } - } - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::removeCertificate() Failed to Match Cert!"); - - return 0; -} - - -int sslroot::addCertificate(cert *c) -{ - c -> InUse(false); - // let most flags through. - //c -> Accepted(false); - //c -> WillConnect(false); - if (c -> certificate == NULL) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::addCertificate() certificate==NULL, Not Adding"); - return 0; - } - - cert *dup = checkPeerX509(c -> certificate); - if (dup != NULL) - { - std::ostringstream out; - out << "sslroot::addCertificate() Not Adding"; - out << "Certificate with duplicate...." << std::endl; - out << "\t\tTry RegisterCertificate() " << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - - return -1; - } - - // else put in in the list. - peercerts.push_back(c); - - certsChanged.IndicateChanged(); - certsMajorChanged.IndicateChanged(); - - return 1; -} - - -int sslroot::addUntrustedCertificate(cert *c) -{ - // blank it all. - c -> Status(PERSON_STATUS_MANUAL); - // set Tag to be their X509CN. - c -> Name(getX509CNString(c -> certificate -> cert_info -> subject)); - - return addCertificate(c); -} - - - -int sslroot::validateCertificate(cert *c) -{ - std::ostringstream out; - out << "sslroot::validateCertificate() Why Not!" << std::endl; - c -> Valid(true); - out << "Cert Status: " << c -> Status() << std::endl; - pqioutput(PQL_ALERT, pqisslrootzone, out.str()); - return 1; -} - -/***** REMOVED! - * - * -std::list sslroot::listCertificates() -{ - std::list names; - std::list::iterator it; - for(it = peercerts.begin(); it != peercerts.end(); it++) - { - names.push_back(((*it) -> certificate) -> name); - } - return names; -} - * - * - *****/ - - -bool sslroot::CertsChanged() -{ - return certsChanged.Changed(0); -} - -bool sslroot::CertsMajorChanged() -{ - return certsMajorChanged.Changed(0); -} - -void sslroot::IndicateCertsChanged() -{ - certsChanged.IndicateChanged(); -} - - -std::list &sslroot::getCertList() -{ - return peercerts; -} - -std::string sslroot::getSetting(std::string opt) -{ - std::map::iterator it; - if (settings.end() != (it = settings.find(opt))) - { - // found setting. - std::ostringstream out; - out << "sslroot::getSetting(" << opt << ") = "; - out << it -> second << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - return it -> second; - } - // else return empty string. - - { - std::ostringstream out; - out << "sslroot::getSetting(" << opt; - out << ") Not There!" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - std::string empty(""); - return empty; -} - -void sslroot::setSetting(std::string opt, std::string val) -{ - // check settings.. - std::ostringstream out; - out << "sslroot::saveSetting(" << opt << ", "; - out << val << ")" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - - settings[opt] = val; - return; -} - -cert *sslroot::getOwnCert() -{ - return own_cert; -} - -int sslroot::checkNetAddress() -{ - std::list addrs = getLocalInterfaces(); - std::list::iterator it; - - bool found = false; - for(it = addrs.begin(); (!found) && (it != addrs.end()); it++) - { - if ((*it) == inet_ntoa(own_cert -> localaddr.sin_addr)) - { - found = true; - } - } - /* check that we didn't catch 0.0.0.0 - if so go for prefered */ - if ((found) && (own_cert -> localaddr.sin_addr.s_addr == 0)) - { - found = false; - } - - if (!found) - { - own_cert -> localaddr.sin_addr = getPreferredInterface(); - } - if ((isPrivateNet(&(own_cert -> localaddr.sin_addr))) || - (isLoopbackNet(&(own_cert -> localaddr.sin_addr)))) - { - own_cert -> Firewalled(true); - } - else - { - //own_cert -> Firewalled(false); - } - - int port = ntohs(own_cert -> localaddr.sin_port); - if ((port < PQI_MIN_PORT) || (port > PQI_MAX_PORT)) - { - own_cert -> localaddr.sin_port = htons(PQI_DEFAULT_PORT); - } - - /* if localaddr = serveraddr, then ensure that the ports - * are the same (modify server)... this mismatch can - * occur when the local port is changed.... - */ - - if (own_cert -> localaddr.sin_addr.s_addr == - own_cert -> serveraddr.sin_addr.s_addr) - { - own_cert -> serveraddr.sin_port = - own_cert -> localaddr.sin_port; - } - - // ensure that address family is set, otherwise windows Barfs. - own_cert -> localaddr.sin_family = AF_INET; - own_cert -> serveraddr.sin_family = AF_INET; - own_cert -> lastaddr.sin_family = AF_INET; - - return 1; -} - - - - -/********** SSL ERROR STUFF ******************************************/ - -int printSSLError(SSL *ssl, int retval, int err, unsigned long err2, - std::ostream &out) -{ - std::string reason; - - std::string mainreason = std::string("UNKNOWN ERROR CODE"); - if (err == SSL_ERROR_NONE) - { - mainreason = std::string("SSL_ERROR_NONE"); - } - else if (err == SSL_ERROR_ZERO_RETURN) - { - mainreason = std::string("SSL_ERROR_ZERO_RETURN"); - } - else if (err == SSL_ERROR_WANT_READ) - { - mainreason = std::string("SSL_ERROR_WANT_READ"); - } - else if (err == SSL_ERROR_WANT_WRITE) - { - mainreason = std::string("SSL_ERROR_WANT_WRITE"); - } - else if (err == SSL_ERROR_WANT_CONNECT) - { - mainreason = std::string("SSL_ERROR_WANT_CONNECT"); - } - else if (err == SSL_ERROR_WANT_ACCEPT) - { - mainreason = std::string("SSL_ERROR_WANT_ACCEPT"); - } - else if (err == SSL_ERROR_WANT_X509_LOOKUP) - { - mainreason = std::string("SSL_ERROR_WANT_X509_LOOKUP"); - } - else if (err == SSL_ERROR_SYSCALL) - { - mainreason = std::string("SSL_ERROR_SYSCALL"); - } - else if (err == SSL_ERROR_SSL) - { - mainreason = std::string("SSL_ERROR_SSL"); - } - out << "RetVal(" << retval; - out << ") -> SSL Error: " << mainreason << std::endl; - out << "\t + ERR Error: " << ERR_error_string(err2, NULL) << std::endl; - return 1; -} - -cert::cert() - :certificate(NULL), hash("") -{ - return; -} - -cert::~cert() -{ - return; -} - -std::string cert::Signature() -{ - if (certificate == NULL) - { - return Name(); - } - else - { - // get signature from cert.... - return Name(); - } -} - - -std::string cert::Hash() -{ - return hash; -} - - -void cert::Hash(std::string h) -{ - hash = h; - return; -} - - - -/********************* signature stuff *********************/ - -bool certsign::operator<(const certsign &ref) const -{ - //compare the signature. - if (0 > strncmp(data, ref.data, CERTSIGNLEN)) - return true; - return false; -} - - -bool certsign::operator==(const certsign &ref) const -{ - //compare the signature. - return (0 == strncmp(data, ref.data, CERTSIGNLEN)); -} - - -/* Fns for relating cert signatures to structures */ -cert *sslroot::findcertsign(certsign &sign) -{ - std::map::iterator it; - - std::ostringstream out; - out << "sslroot::findcertsign()" << std::endl; - for (it = signmap.begin(); it != signmap.end(); it++) - { - out << "Checking Vs " << it -> second -> Name(); - if (sign == it -> first) - { - out << "Match!"; - } - out << std::endl; - } - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - - if (signmap.end() != (it = signmap.find(sign))) - { - return it -> second; - } - return NULL; -} - -int sslroot::getcertsign(cert *c, certsign &sign) -{ - if ((c == NULL) || (c->certificate == NULL)) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::getcertsign() ERROR: NULL c || c->certificate"); - return 0; - } - - // get the signature from the cert, and copy to the array. - ASN1_BIT_STRING *signature = c -> certificate -> signature; - int signlen = ASN1_STRING_length(signature); - if (signlen < CERTSIGNLEN) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::getcertsign() ERROR: short Signature"); - return 0; - } - // else copy in the first CERTSIGNLEN. - unsigned char *signdata = ASN1_STRING_data(signature); - memcpy(sign.data, signdata, CERTSIGNLEN); - - return 1; -} - -int sslroot::addtosignmap(cert *c) -{ - certsign cs; - if (!getcertsign(c, cs)) - { - // error. - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::addsigntomap() ERROR: Fail to getcertsign()"); - return 0; - } - cert *c2 = findcertsign(cs); - if (c2 == NULL) - { - // add, and return okay. - signmap[cs] = c; - return 1; - } - if (c2 != c) - { - // error. - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::addsigntomap() ERROR: Duplicate Entry()"); - return 0; - } - - // else already exists. - return 1; -} - - - - -int sslroot::hashFile(std::string fname, unsigned char *hash, unsigned int hlen) -{ - // open the file. - // setup the hash. - - // pipe the file through. - - - return 1; -} - -int sslroot::hashDigest(char *data, unsigned int dlen, - unsigned char *hash, unsigned int hlen) -{ - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_DigestInit_ex(mdctx, EVP_sha1(), NULL)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_DigestInit Failure!"); - return -1; - } - - if (0 == EVP_DigestUpdate(mdctx, data, dlen)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_DigestUpdate Failure!"); - return -1; - } - - unsigned int signlen = hlen; - if (0 == EVP_DigestFinal_ex(mdctx, hash, &signlen)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_DigestFinal Failure!"); - return -1; - } - - EVP_MD_CTX_destroy(mdctx); - return signlen; -} - - - -int sslroot::signDigest(EVP_PKEY *key, char *data, unsigned int dlen, - unsigned char *sign, unsigned int slen) -{ - unsigned int signlen = EVP_PKEY_size(key); - - { - std::ostringstream out; - out << "sslroot::signDigest(" << (void *) key; - out << ", " << (void *) data << ", " << dlen << ", "; - out << (void *) sign << ", " << slen << ")" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - if (signlen > slen) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::signDigest() Sign Length too short"); - return -1; - } - - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_SignInit_ex(mdctx, EVP_sha1(), NULL)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignInit Failure!"); - return -1; - } - - if (0 == EVP_SignUpdate(mdctx, data, dlen)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignUpdate Failure!"); - return -1; - } - - signlen = slen; - if (0 == EVP_SignFinal(mdctx, sign, &signlen, key)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_SignFinal Failure!"); - return -1; - } - - EVP_MD_CTX_destroy(mdctx); - return signlen; -} - - -int sslroot::verifyDigest(EVP_PKEY *key, char *data, unsigned int dlen, - unsigned char *enc, unsigned int elen) -{ - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_VerifyInit_ex(mdctx, EVP_sha1(), NULL)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_VerifyInit Failure!"); - return -1; - } - - if (0 == EVP_VerifyUpdate(mdctx, data, dlen)) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_VerifyUpdate Failure!"); - return -1; - } - - int vv; - if (0 > (vv = EVP_VerifyFinal(mdctx, enc, elen, key))) - { - pqioutput(PQL_ALERT, pqisslrootzone, "EVP_VerifyFinal Failure!"); - return -1; - } - if (vv == 1) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, "Verified Signature OKAY"); - } - else - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, "Failed Verification!"); - } - - EVP_MD_CTX_destroy(mdctx); - return vv; -} - -// Think both will fit in the one Structure. -int sslroot::generateKeyPair(EVP_PKEY *keypair, unsigned int keylen) -{ - RSA *rsa = RSA_generate_key(2048, 65537, NULL, NULL); - EVP_PKEY_assign_RSA(keypair, rsa); - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, "sslroot::generateKeyPair()"); - return 1; -} - - -std::string getX509NameString(X509_NAME *name) -{ - std::string namestr; - for(int i = 0; i < X509_NAME_entry_count(name); i++) - { - X509_NAME_ENTRY *entry = X509_NAME_get_entry(name, i); - ASN1_STRING *entry_data = X509_NAME_ENTRY_get_data(entry); - ASN1_OBJECT *entry_obj = X509_NAME_ENTRY_get_object(entry); - - namestr += "\t"; - namestr += OBJ_nid2ln(OBJ_obj2nid(entry_obj)); - namestr += " : "; - - //namestr += entry_obj -> flags; - //namestr += entry_data -> length; - //namestr += entry_data -> type; - - //namestr += entry_data -> flags; - //entry -> set; - - if (entry_data -> data != NULL) - { - namestr += (char *) entry_data -> data; - } - else - { - namestr += "NULL"; - } - - if (i + 1 < X509_NAME_entry_count(name)) - { - namestr += "\n"; - } - - } - return namestr; -} - - -std::string getX509CNString(X509_NAME *name) -{ - std::string namestr; - for(int i = 0; i < X509_NAME_entry_count(name); i++) - { - X509_NAME_ENTRY *entry = X509_NAME_get_entry(name, i); - ASN1_STRING *entry_data = X509_NAME_ENTRY_get_data(entry); - ASN1_OBJECT *entry_obj = X509_NAME_ENTRY_get_object(entry); - - if (0 == strncmp("CN", OBJ_nid2sn(OBJ_obj2nid(entry_obj)), 2)) - { - if (entry_data -> data != NULL) - { - namestr += (char *) entry_data -> data; - } - else - { - namestr += "Unknown"; - } - return namestr; - } - } - return namestr; -} - - -std::string getX509TypeString(X509_NAME *name, char *type, int len) -{ - std::string namestr; - for(int i = 0; i < X509_NAME_entry_count(name); i++) - { - X509_NAME_ENTRY *entry = X509_NAME_get_entry(name, i); - ASN1_STRING *entry_data = X509_NAME_ENTRY_get_data(entry); - ASN1_OBJECT *entry_obj = X509_NAME_ENTRY_get_object(entry); - - if (0 == strncmp(type, OBJ_nid2sn(OBJ_obj2nid(entry_obj)), len)) - { - if (entry_data -> data != NULL) - { - namestr += (char *) entry_data -> data; - } - else - { - namestr += "Unknown"; - } - return namestr; - } - } - return namestr; -} - -std::string getX509LocString(X509_NAME *name) -{ - return getX509TypeString(name, "L", 2); -} - -std::string getX509OrgString(X509_NAME *name) -{ - return getX509TypeString(name, "O", 2); -} - - -std::string getX509CountryString(X509_NAME *name) -{ - return getX509TypeString(name, "C", 2); -} - - -std::string convert_to_str(certsign &sign) -{ - std::ostringstream id; - for(int i = 0; i < CERTSIGNLEN; i++) - { - id << std::hex << std::setw(2) << std::setfill('0') - << (uint16_t) (((uint8_t *) (sign.data))[i]); - } - return id.str(); -} - -bool convert_to_certsign(std::string id, certsign &sign) -{ - char num[3]; - if (id.length() < CERTSIGNLEN * 2) - { - return false; - } - - for(int i = 0; i < CERTSIGNLEN; i++) - { - num[0] = id[i * 2]; - num[1] = id[i * 2 + 1]; - num[2] = '\0'; - int32_t val; - if (1 != sscanf(num, "%x", &val)) - { - return false; - } - sign.data[i] = (uint8_t) val; - } - return true; -} - - diff --git a/libretroshare/src/pqi/sslcert.h b/libretroshare/src/pqi/sslcert.h deleted file mode 100644 index b352e187c..000000000 --- a/libretroshare/src/pqi/sslcert.h +++ /dev/null @@ -1,195 +0,0 @@ -#ifndef MRK_SSL_CERT_HEADER -#define MRK_SSL_CERT_HEADER - -/* - * Core PQI networking: sslcert.h - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2004-2006 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - -#include -#include - -#include -#include - -#include "pqi_base.h" -#include "pqinetwork.h" - -#include "pqiindic.h" - - -// helper fns. -int printSSLError(SSL *ssl, int retval, int err, unsigned long err2, std::ostream &out); -std::string getX509NameString(X509_NAME *name); -std::string getX509CNString(X509_NAME *name); - -std::string getX509OrgString(X509_NAME *name); -std::string getX509LocString(X509_NAME *name); -std::string getX509CountryString(X509_NAME *name); - - -/* definitions -> functions to be defined */ -std::string convert_to_str(certsign &sign); -bool convert_to_certsign(std::string id, certsign &sign); - -class sslroot; - -class cert: public Person -{ - public: - cert(); -virtual ~cert(); - -virtual std::string Signature(); -std::string Hash(); -void Hash(std::string); - - X509 *certificate; - std::string hash; -}; - - -// returns pointer to static variable. -// which must be inited.. -sslroot *getSSLRoot(); - -class sslroot -{ - public: - sslroot(); -int active(); -int setcertdir(char *path); -int initssl(const char *srvr_cert, const char *priv_key, - const char *CA_file, const char *passwd); -int closessl(); - -/* Context handling */ -SSL_CTX *getCTX(); - -/* Certificate handling */ -int compareCerts(cert *a, cert *b); - - // network interface. - - // program interface. -int addCertificate(cert *c); -int addUntrustedCertificate(cert *c); -int removeCertificate(cert *); - - // Creation of Certificates.... (From X509) - // Core functions.... -cert *checkDuplicateX509(X509 *x); -cert *checkPeerX509(X509 *x); -cert *makeCertificate(X509 *c); -cert *registerCertificate(X509 *nc, struct sockaddr_in, bool in); - -int validateCertificate(cert *c); - -// depreciated... -cert *findpeercert(const char *name); -//int loadpeercert(const char *fname); -//int savepeercert(const char *fname); - -// Configuration Handling... -int setConfigDirs(const char *cdir, const char *ndir); - -// these save both the certificates + the settings. -int saveCertificates(const char *fname); -int saveCertificates(); -int loadCertificates(const char *fname); - - // with a hash check/recalc in there for good measure. -cert * loadcertificate(const char* fname, std::string hash); -int savecertificate(cert *c, const char* fname); - -// digest hashing /signing or encrypting interface. -int hashFile(std::string fname, unsigned char *hash, unsigned int hlen); -int hashDigest(char *data, unsigned int dlen, unsigned char *hash, unsigned int hlen); -int signDigest(EVP_PKEY *key, char *data, unsigned int dlen, unsigned char *hash, unsigned int hlen); -int verifyDigest(EVP_PKEY *key, char *data, unsigned int dlen, unsigned char *enc, unsigned int elen); -int generateKeyPair(EVP_PKEY *keypair, unsigned int keylen); - - - -int printCertificate(cert *, std::ostream &out); - /****** REMOVED! - * - * -std::list listCertificates(); - * - * - ****/ - -std::list &getCertList(); - -cert * getOwnCert(); -int checkNetAddress(); - - // extra list for certs that aren't in main list. -cert * getCollectedCert(); -bool collectedCerts(); - -bool CertsChanged(); -bool CertsMajorChanged(); -void IndicateCertsChanged(); - -std::string getSetting(std::string opt); -void setSetting(std::string opt, std::string val); - - -/* Fns for relating cert signatures to structures */ -cert *findcertsign(certsign &sign); -int getcertsign(cert *c, certsign &sign); -int addtosignmap(cert *); - - private: /* data */ -std::list peercerts; -std::list allcerts; -std::list collectedcerts; - -// whenever a cert is added, it should also be put in the map. -std::map signmap; - - - -// General Configuration System -// easy it put it here - so it can be signed easily. -std::map settings; - -std::string certdir; -std::string neighbourdir; -std::string certfile; - -SSL_CTX *sslctx; -int init; - -Indicator certsChanged; -Indicator certsMajorChanged; - -EVP_PKEY *pkey; - -cert *own_cert; - -}; - -#endif // MRK_SSL_CERT_HEADER diff --git a/libretroshare/src/pqi/xpgp_id.cc b/libretroshare/src/pqi/xpgp_id.cc deleted file mode 100644 index c122d401f..000000000 --- a/libretroshare/src/pqi/xpgp_id.cc +++ /dev/null @@ -1,44 +0,0 @@ - - -/***** Extract XPGP Id *****/ - -#include "pqi/authxpgp.h" - -#include -#include - -int main(int argc, char **argv) -{ - if (argc < 2) - { - std::cerr << "Usage: " << argv[0] << " "; - std::cerr << std::endl; - exit(1); - } - - std::string userName, userId; - - if (LoadCheckXPGPandGetName(argv[1], userName, userId)) - { - std::cerr << "Cert Ok: name: " << userName; - std::cerr << std::endl; - std::cerr << "id = \"" << userId << "\""; - std::cerr << std::endl; - } - else - { - std::cerr << "Cert Check Failed"; - std::cerr << std::endl; - } -} - - - - - - - - - - - diff --git a/libretroshare/src/pqi/xpgpcert.cc b/libretroshare/src/pqi/xpgpcert.cc deleted file mode 100644 index 9449c5960..000000000 --- a/libretroshare/src/pqi/xpgpcert.cc +++ /dev/null @@ -1,2569 +0,0 @@ -/* - * "$Id: xpgpcert.cc,v 1.18 2007-04-15 18:45:18 rmf24 Exp $" - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2004-2006 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - - - -#include "xpgpcert.h" - -#include "pqinetwork.h" - -#include -#include -#include - -#include -#include - -#include "pqidebug.h" - -const int pqisslrootzone = 1211; - -/** XPGP keyring interface ************ -int XPGP_add_certificate(XPGP_KEYRING *kr, XPGP *x); -int XPGP_auth_certficate(XPGP_KEYRING *kr, XPGP *x); -int XPGP_sign_certificate(XPGP_KEYRING *kr, XPGP *subj, XPGP *issuer); - -int XPGP_check_valid_certificate(XPGP *x); - -int XPGP_signer_trusted(XPGP_KEYRING *kr, XPGP *trusted); -int XPGP_signer_untrusted(XPGP_KEYRING *kr, XPGP *untrusted); - - int XPGP_copy_known_signatures(XPGP_KEYRING *kr, XPGP *dest, XPGP *src); - - * - * - */ - -unsigned char convertHexToChar(unsigned char a, unsigned char b); - - -// other fns -std::string getCertName(cert *c) -{ - std::string name = c -> certificate -> name; - // strip out bad chars. - for(int i = 0; i < (signed) name.length(); i++) - { - if ((name[i] == '/') || (name[i] == ' ') || (name[i] == '=') || - (name[i] == '\\') || (name[i] == '\t') || (name[i] == '\n')) - { - name[i] = '_'; - } - } - return name; -} - - - -int pem_passwd_cb(char *buf, int size, int rwflag, void *password) -{ - strncpy(buf, (char *)(password), size); - buf[size - 1] = '\0'; - return(strlen(buf)); -} - - -/* This class handles openssl library init/destruct. - * only one of these... handles - * the CTX and setup? - * - * it will also handle the certificates..... - * mantaining a library of recieved certs, - * and ip addresses that the connections come from... - * - */ - -// the single instance of this. -static sslroot instance_sslroot; - -sslroot *getSSLRoot() -{ - return &instance_sslroot; -} - -sslroot::sslroot() - :sslctx(NULL), init(0), certsChanged(1), - certsMajorChanged(1), pkey(NULL) -{ -} - -int sslroot::active() -{ - return init; -} - -// args: server cert, server private key, trusted certificates. - -int sslroot::initssl(const char *cert_file, const char *priv_key_file, - const char *passwd) -{ -static int initLib = 0; - if (!initLib) - { - initLib = 1; - SSL_load_error_strings(); - SSL_library_init(); - } - - - if (init == 1) - { - return 1; - } - - if ((cert_file == NULL) || - (priv_key_file == NULL) || - (passwd == NULL)) - { - fprintf(stderr, "sslroot::initssl() missing parameters!\n"); - return 0; - } - - - // XXX TODO - // actions_to_seed_PRNG(); - - std::cerr << "SSL Library Init!" << std::endl; - - // setup connection method - sslctx = SSL_CTX_new(PGPv1_method()); - - // setup cipher lists. - SSL_CTX_set_cipher_list(sslctx, "DEFAULT"); - - // certificates (Set Local Server Certificate). - FILE *ownfp = fopen(cert_file, "r"); - if (ownfp == NULL) - { - std::cerr << "Couldn't open Own Certificate!" << std::endl; - return -1; - } - - - - // get xPGP certificate. - XPGP *xpgp = PEM_read_XPGP(ownfp, NULL, NULL, NULL); - fclose(ownfp); - - if (xpgp == NULL) - { - return -1; - } - SSL_CTX_use_pgp_certificate(sslctx, xpgp); - - // get private key - FILE *pkfp = fopen(priv_key_file, "rb"); - if (pkfp == NULL) - { - std::cerr << "Couldn't Open PrivKey File!" << std::endl; - closessl(); - return -1; - } - - pkey = PEM_read_PrivateKey(pkfp, NULL, NULL, (void *) passwd); - fclose(pkfp); - - if (pkey == NULL) - { - return -1; - } - SSL_CTX_use_pgp_PrivateKey(sslctx, pkey); - - if (1 != SSL_CTX_check_pgp_private_key(sslctx)) - { - std::cerr << "Issues With Private Key! - Doesn't match your Cert" << std::endl; - std::cerr << "Check your input key/certificate:" << std::endl; - std::cerr << priv_key_file << " & " << cert_file; - std::cerr << std::endl; - closessl(); - return -1; - } - - // make keyring. - pgp_keyring = createPGPContext(xpgp, pkey); - SSL_CTX_set_XPGP_KEYRING(sslctx, pgp_keyring); - - - // Setup the certificate. (after keyring is made!). - - own_cert = makeCertificateXPGP(xpgp); - if (own_cert == NULL) - { - std::cerr << "Failed to Make Own Cert!" << std::endl; - return -1; - } - addCertificate(own_cert); - - // enable verification of certificates (PEER) - SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER | - SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); - - std::cerr << "SSL Verification Set" << std::endl; - - - - /* configure basics on the certificate. */ - own_cert -> Name(getX509CNString(own_cert -> certificate -> subject -> subject)); - - init = 1; - return 1; -} - - - -int sslroot::closessl() -{ - SSL_CTX_free(sslctx); - - // clean up private key.... - // remove certificates etc -> opposite of initssl. - init = 0; - return 1; -} - -/* Context handling */ -SSL_CTX *sslroot::getCTX() -{ - return sslctx; -} - -int sslroot::setConfigDirs(const char *cdir, const char *ndir) -{ - certdir = cdir; - neighbourdir = ndir; - return 1; -} - -static const unsigned int OPT_LEN = 16; -static const unsigned int VAL_LEN = 1000; - -int sslroot::saveCertificates() -{ - if (certfile.length() > 1) - return saveCertificates(certfile.c_str()); - return -1; -} - - -int sslroot::saveCertificates(const char *fname) -{ - // construct file name. - // - // create the file in memory - hash + sign. - // write out data to a file. - - std::string neighdir = certdir + "/" + neighbourdir + "/"; - std::string configname = certdir + "/"; - configname += fname; - - std::map::iterator mit; - - - std::string conftxt; - std::string empty(""); - unsigned int i; - - std::list::iterator it; - for(it = peercerts.begin(); it != peercerts.end(); it++) - { - std::string neighfile = neighdir + getCertName(*it) + ".pqi"; - savecertificate((*it), neighfile.c_str()); - conftxt += "CERT "; - conftxt += getCertName(*it); - conftxt += "\n"; - conftxt += (*it) -> Hash(); - conftxt += "\n"; - std::cerr << std::endl; - } - - // Now add the options. - for(mit = settings.begin(); mit != settings.end(); mit++) - { - // only save the nonempty settings. - if (mit -> second != empty) { - conftxt += "OPT "; - for(i = 0; (i < OPT_LEN) && (i < mit -> first.length()); i++) - { - conftxt += mit -> first[i]; - } - conftxt += "\n"; - for(i = 0; i < VAL_LEN; i++) - { - if (i < mit -> second.length()) - { - conftxt += mit -> second[i]; - } - else - { - conftxt += '\0'; - } - } - conftxt += "\n"; - std::cerr << std::endl; - } - } - - // now work out signature of it all. This relies on the - // EVP library of openSSL..... We are going to use signing - // for the moment. - - unsigned int signlen = EVP_PKEY_size(pkey); - unsigned char signature[signlen]; - - //OpenSSL_add_all_digests(); - - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_SignInit_ex(mdctx, EVP_sha1(), NULL)) - { - std::cerr << "EVP_SignInit Failure!" << std::endl; - } - - if (0 == EVP_SignUpdate(mdctx, conftxt.c_str(), conftxt.length())) - { - std::cerr << "EVP_SignUpdate Failure!" << std::endl; - } - - - if (0 == EVP_SignFinal(mdctx, signature, &signlen, pkey)) - { - std::cerr << "EVP_SignFinal Failure!" << std::endl; - } - - std::cerr << "Conf Signature is(" << signlen << "): "; - for(i = 0; i < signlen; i++) - { - fprintf(stderr, "%02x", signature[i]); - conftxt += signature[i]; - } - std::cerr << std::endl; - - FILE *cfd = fopen(configname.c_str(), "wb"); - int wrec; - if (1 != (wrec = fwrite(conftxt.c_str(), conftxt.length(), 1, cfd))) - { - std::cerr << "Error writing: " << configname << std::endl; - std::cerr << "Wrote: " << wrec << "/" << 1 << " Records" << std::endl; - } - - EVP_MD_CTX_destroy(mdctx); - fclose(cfd); - - return 1; -} - -int sslroot::loadCertificates(const char *conf_fname) -{ - // open the configuration file. - // - // read in CERT + Hash. - - // construct file name. - // - // create the file in memory - hash + sign. - // write out data to a file. - - std::string neighdir = certdir + "/" + neighbourdir + "/"; - std::string configname = certdir + "/"; - configname += conf_fname; - - // save name for later save attempts. - certfile = conf_fname; - - std::string conftxt; - - unsigned int maxnamesize = 1024; - char name[maxnamesize]; - - int c; - unsigned int i; - - FILE *cfd = fopen(configname.c_str(), "rb"); - if (cfd == NULL) - { - std::cerr << "Unable to Load Configuration File!" << std::endl; - std::cerr << "File: " << configname << std::endl; - return -1; - } - - std::list fnames; - std::list hashes; - std::map::iterator mit; - std::map tmpsettings; - - unsigned int signlen = EVP_PKEY_size(pkey); - unsigned char conf_signature[signlen]; - char *ret = NULL; - - for(ret = fgets(name, maxnamesize, cfd); - ((ret != NULL) && (!strncmp(name, "CERT ", 5))); - ret = fgets(name, maxnamesize, cfd)) - { - for(i = 5; (name[i] != '\n') && (i < (unsigned) maxnamesize); i++); - - if (name[i] == '\n') - { - name[i] = '\0'; - } - - // so the name is first.... - std::string fname = &(name[5]); - - // now read the - std::string hash; - std::string signature; - - for(i = 0; i < signlen; i++) - { - if (EOF == (c = fgetc(cfd))) - { - std::cerr << "Error Reading Signature of: "; - std::cerr << fname; - std::cerr << std::endl; - std::cerr << "ABorting Load!"; - std::cerr << std::endl; - return -1; - } - unsigned char uc = (unsigned char) c; - signature += (unsigned char) uc; - } - if ('\n' != (c = fgetc(cfd))) - { - std::cerr << "Warning Mising seperator" << std::endl; - } - - std::cerr << "Read fname:" << fname << std::endl; - std::cerr << "Signature:" << std::endl; - for(i = 0; i < signlen; i++) - { - fprintf(stderr, "%02x", (unsigned char) signature[i]); - } - std::cerr << std::endl; - std::cerr << std::endl; - - // push back..... - fnames.push_back(fname); - hashes.push_back(signature); - - conftxt += "CERT "; - conftxt += fname; - conftxt += "\n"; - conftxt += signature; - conftxt += "\n"; - - // be sure to write over a bit... - name[0] = 'N'; - name[1] = 'O'; - } - - // string already waiting! - for(; ((ret != NULL) && (!strncmp(name, "OPT ", 4))); - ret = fgets(name, maxnamesize, cfd)) - { - for(i = 4; (name[i] != '\n') && (i < OPT_LEN); i++); - // terminate the string. - name[i] = '\0'; - - // so the name is first.... - std::string opt = &(name[4]); - - // now read the - std::string val; // cleaned up value. - std::string valsign; // value in the file. - for(i = 0; i < VAL_LEN; i++) - { - if (EOF == (c = fgetc(cfd))) - { - std::cerr << "Error Reading Value of: "; - std::cerr << opt; - std::cerr << std::endl; - std::cerr << "ABorting Load!"; - std::cerr << std::endl; - return -1; - } - // remove zeros on strings... - if (c != '\0') - { - val += (unsigned char) c; - } - valsign += (unsigned char) c; - } - if ('\n' != (c = fgetc(cfd))) - { - std::cerr << "Warning Mising seperator" << std::endl; - } - - std::cerr << "Read OPT:" << opt; - std::cerr << " Val:" << val << std::endl; - - // push back..... - tmpsettings[opt] = val; - - conftxt += "OPT "; - conftxt += opt; - conftxt += "\n"; - conftxt += valsign; - conftxt += "\n"; - - // be sure to write over a bit... - name[0] = 'N'; - name[1] = 'O'; - } - - // only read up to the first newline symbol.... - // continue... - for(i = 0; (name[i] != '\n') && (i < signlen); i++); - - //printf("Stepping over [%d] %0x\n", i, name[i]); - - - if (i != signlen) - { - for(i++; i < signlen; i++) - { - c = fgetc(cfd); - if (c == EOF) - { - std::cerr << "Error Reading Conf Signature:"; - std::cerr << std::endl; - return 1; - } - unsigned char uc = (unsigned char) c; - name[i] = uc; - } - } - - std::cerr << "Configuration File Signature: " << std::endl; - for(i = 0; i < signlen; i++) - { - fprintf(stderr, "%02x", (unsigned char) name[i]); - } - std::cerr << std::endl; - - - // when we get here - should have the final signature in the buffer. - // check. - // - // compare signatures. - // instead of verifying with the public key.... - // we'll sign it again - and compare .... FIX LATER... - - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_SignInit(mdctx, EVP_sha1())) - { - std::cerr << "EVP_SignInit Failure!" << std::endl; - } - - if (0 == EVP_SignUpdate(mdctx, conftxt.c_str(), conftxt.length())) - { - std::cerr << "EVP_SignUpdate Failure!" << std::endl; - } - - if (0 == EVP_SignFinal(mdctx, conf_signature, &signlen, pkey)) - { - std::cerr << "EVP_SignFinal Failure!" << std::endl; - } - - EVP_MD_CTX_destroy(mdctx); - fclose(cfd); - - std::cerr << "Recalced File Signature: " << std::endl; - for(i = 0; i < signlen; i++) - { - fprintf(stderr, "%02x", conf_signature[i]); - } - std::cerr << std::endl; - - bool same = true; - for(i = 0; i < signlen; i++) - { - if ((unsigned char) name[i] != conf_signature[i]) - { - same = false; - } - } - - if (same == false) - { - std::cerr << "ERROR VALIDATING CONFIGURATION!" << std::endl; - std::cerr << "PLEASE FIX!" << std::endl; - return -1; - } - std::list::iterator it; - std::list::iterator it2; - for(it = fnames.begin(), it2 = hashes.begin(); it != fnames.end(); it++, it2++) - { - std::string neighfile = neighdir + (*it) + ".pqi"; - cert *nc = loadcertificate(neighfile.c_str(), (*it2)); - if (nc != NULL) - { - if (0 > addCertificate(nc)) - { - // cleanup. - std::cerr << "Updated Certificate....but no"; - std::cerr << " need for addition"; - std::cerr << std::endl; - // X509_free(nc -> certificate); - //delete nc; - } - } - } - for(mit = tmpsettings.begin(); mit != tmpsettings.end(); mit++) - { - settings[mit -> first] = mit -> second; - } - return 1; -} - - -const int PQI_SSLROOT_CERT_CONFIG_SIZE = 1024; - -int sslroot::savecertificate(cert *c, const char *fname) -{ - // load certificates from file. - FILE *setfp = fopen(fname, "wb"); - if (setfp == NULL) - { - std::cerr << "sslroot::savecertificate() Bad File: " << fname; - std::cerr << " Cannot be Written!" << std::endl; - return -1; - } - - std::cerr << "Writing out Cert...:" << c -> Name() << std::endl; - PEM_write_XPGP(setfp, c -> certificate); - - // writing out details.... - - // read in a line..... - int size = PQI_SSLROOT_CERT_CONFIG_SIZE; - char line[size]; - std::list::iterator it; - - int i; - - // This will need to be made portable..... - - struct sockaddr_in *addr_inet; - struct sockaddr_in *addr_inet2; - struct sockaddr_in *addr_inet3; - - int pos_status = 0; - int pos_addr = sizeof(int); - int pos_addr2 = pos_addr + sizeof(*addr_inet); - int pos_addr3 = pos_addr2 + sizeof(*addr_inet2); - - int pos_lcts = pos_addr3 + sizeof(*addr_inet3); - int pos_lrts = pos_lcts + sizeof(int); - int pos_ncts = pos_lrts + sizeof(int); - int pos_ncvl = pos_ncts + sizeof(int); - int pos_name = pos_ncvl + sizeof(int); - int pos_end = pos_name + 20; // \n. for readability. - - int *status = (int *) &(line[pos_status]); - addr_inet = (struct sockaddr_in *) &(line[pos_addr]); - addr_inet2 = (struct sockaddr_in *) &(line[pos_addr2]); - addr_inet3 = (struct sockaddr_in *) &(line[pos_addr3]); - int *lcts = (int *) &(line[pos_lcts]); - int *lrts = (int *) &(line[pos_lrts]); - int *ncts = (int *) &(line[pos_ncts]); - int *ncvl = (int *) &(line[pos_ncvl]); - char *name = &(line[pos_name]); - char *end = &(line[pos_end]); - - for(i = 0; i < 1024; i++) - line[i] = 0; - - *status = c -> Status(); - *addr_inet = c -> lastaddr; - *addr_inet2 = c -> localaddr; - *addr_inet3 = c -> serveraddr; - - *lcts = c -> lc_timestamp; - *lrts = c -> lr_timestamp; - *ncts = c -> nc_timestamp; - *ncvl = c -> nc_timeintvl; - - std::string tmpname = c -> Name(); - for(i = 0; (i < (signed) tmpname.length()) && (i < 20 - 1); i++) - { - name[i] = tmpname[i]; - } - name[20 - 1] = '\0'; - end[0] = '\n'; - - /* now convert it to hex */ - char config_hex[2 * size]; - for(i = 0; i < size; i++) - { - sprintf(&(config_hex[i * 2]), "%02x", - (unsigned int) ((unsigned char *) line)[i]); - } - - if (1 != fwrite(config_hex, size * 2,1, setfp)) - { - std::cerr << "Error Writing Peer Record!" << std::endl; - return -1; - } - fclose(setfp); - - // then reopen to generate hash. - setfp = fopen(fname, "rb"); - if (setfp == NULL) - { - std::cerr << "sslroot::savecertificate() Bad File: " << fname; - std::cerr << " Opened for ReHash!" << std::endl; - return -1; - } - - unsigned int signlen = EVP_PKEY_size(pkey); - unsigned char signature[signlen]; - - int maxsize = 20480; - int rbytes; - char inall[maxsize]; - if (0 == (rbytes = fread(inall, 1, maxsize, setfp))) - { - std::cerr << "Error Writing Peer Record!" << std::endl; - return -1; - } - std::cerr << "Read " << rbytes << std::endl; - - // so we read rbytes. - // hash. - //OpenSSL_add_all_digests(); - - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_SignInit_ex(mdctx, EVP_sha1(), NULL)) - { - std::cerr << "EVP_SignInit Failure!" << std::endl; - } - - if (0 == EVP_SignUpdate(mdctx, inall, rbytes)) - { - std::cerr << "EVP_SignUpdate Failure!" << std::endl; - } - - if (0 == EVP_SignFinal(mdctx, signature, &signlen, pkey)) - { - std::cerr << "EVP_SignFinal Failure!" << std::endl; - } - - std::cerr << "Saved Cert: " << c -> Name() << " Status: "; - std::cerr << std::hex << (unsigned int) c->Status() << std::dec << std::endl; - - std::cerr << "Cert + Setting Signature is(" << signlen << "): "; - std::string signstr; - for(i = 0; i < (signed) signlen; i++) - { - fprintf(stderr, "%02x", signature[i]); - signstr += signature[i]; - } - std::cerr << std::endl; - - c -> Hash(signstr); - std::cerr << "Stored Hash Length: " << (c -> Hash()).length() << std::endl; - std::cerr << "Real Hash Length: " << signlen << std::endl; - - fclose(setfp); - - EVP_MD_CTX_destroy(mdctx); - - return 1; -} - -cert *sslroot::loadcertificate(const char *fname, std::string hash) -{ - // if there is a hash - check that the file matches it before loading. - FILE *pcertfp; - - /* We only check a signature's hash if - * we are loading from a configuration file. - * Therefore we saved the file and it should be identical. - * and a direct load + verify will work. - * - * If however it has been transported by email.... - * Then we might have to correct the data (strip out crap) - * from the configuration at the end. (XPGP load should work!) - */ - - if (hash.length() > 1) - { - pcertfp = fopen(fname, "rb"); - // load certificates from file. - if (pcertfp == NULL) - { - std::cerr << "sslroot::loadcertificate() Bad File: " << fname; - std::cerr << " Cannot be Hashed!" << std::endl; - return NULL; - } - - unsigned int signlen = EVP_PKEY_size(pkey); - unsigned char signature[signlen]; - - int maxsize = 20480; /* should be enough for about 50 signatures */ - int rbytes; - char inall[maxsize]; - if (0 == (rbytes = fread(inall, 1, maxsize, pcertfp))) - { - std::cerr << "Error Reading Peer Record!" << std::endl; - return NULL; - } - //std::cerr << "Read " << rbytes << std::endl; - - - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_SignInit_ex(mdctx, EVP_sha1(), NULL)) - { - std::cerr << "EVP_SignInit Failure!" << std::endl; - } - - if (0 == EVP_SignUpdate(mdctx, inall, rbytes)) - { - std::cerr << "EVP_SignUpdate Failure!" << std::endl; - } - - if (0 == EVP_SignFinal(mdctx, signature, &signlen, pkey)) - { - std::cerr << "EVP_SignFinal Failure!" << std::endl; - } - - fclose(pcertfp); - EVP_MD_CTX_destroy(mdctx); - - bool same = true; - if (signlen != hash.length()) - { - std::cerr << "Different Length Signatures... "; - std::cerr << "Cannot Load Certificate!" << std::endl; - return NULL; - } - - for(int i = 0; i < (signed) signlen; i++) - { - if (signature[i] != (unsigned char) hash[i]) - { - same = false; - std::cerr << "Invalid Signature... "; - std::cerr << "Cannot Load Certificate!" << std::endl; - return NULL; - } - } - std::cerr << "Verified Signature for: " << fname; - std::cerr << std::endl; - - - } - else - { - std::cerr << "Not checking cert signature" << std::endl; - } - - pcertfp = fopen(fname, "rb"); - - // load certificates from file. - if (pcertfp == NULL) - { - std::cerr << "sslroot::loadcertificate() Bad File: " << fname; - std::cerr << " Cannot be Read!" << std::endl; - return NULL; - } - - - XPGP *pc; - cert *npc = NULL; - - if ((pc = PEM_read_XPGP(pcertfp, NULL, NULL, NULL)) != NULL) - { - // read a certificate. - std::cerr << "Loaded Certificate: "; - std::cerr << pc -> name << std::endl; - - npc = makeCertificateXPGP(pc); - if (npc == NULL) - { - std::cerr << "Failed to Create Cert!" << std::endl; - return NULL; - } - } - else // (pc == NULL) - { - unsigned long err = ERR_get_error(); - std::cerr << "Read Failed .... CODE(" << err << ")" << std::endl; - std::cerr << ERR_error_string(err, NULL) << std::endl; - return NULL; - } - - // Now we try to read in 1024 bytes..... - // if successful, then have settings! - - // read in a line..... - int size = PQI_SSLROOT_CERT_CONFIG_SIZE; - char config_hex[PQI_SSLROOT_CERT_CONFIG_SIZE * 4]; /* double for extra space */ - char line[PQI_SSLROOT_CERT_CONFIG_SIZE]; - - /* load as much as possible into the config_hex. - */ - - int rbytes = fread(config_hex, 1, size * 4, pcertfp); - bool configLoaded = false; - int i, j; - - if (rbytes < size * 2) - { - if ((hash.size() > 1) && (rbytes >= size)) - { - /* old format certificate (already verified) */ - std::cerr << "Loading Old Style Cert Config" << std::endl; - memcpy(line, config_hex, size); - configLoaded = true; - } - else - { - std::cerr << "Error Reading Setting: Only Cert Retrieved" << std::endl; - return npc; - } - } - - /* if there was no hash then we need to check it */ - if (hash.size() <= 1) - { - std::cerr << "Checking Cert Configuration for spam char" << std::endl; - for(i = 0, j = 0; i < rbytes; i++) - { - if (isxdigit(config_hex[i])) - { - config_hex[j++] = config_hex[i]; - } - else - { - std::cerr << "Stripped out:" << config_hex[i] << " or " - << (int) config_hex[i] << "@" << i - << " j:" << j << std::endl; - } - - } - if (j < size * 2) - { - std::cerr << "Error Cert Config wrong size" << std::endl; - return npc; - } - std::cerr << "Stripped out " << i - j << " spam chars" << std::endl; - } - - /* now convert the hex into binary */ - if (!configLoaded) - { - for(i = 0; i < size; i++) - { - ((unsigned char *) line)[i] = convertHexToChar( - config_hex[2 * i], config_hex[2 * i + 1]); - } - configLoaded = true; - } - - // Data arrangment. - // so far - // ------------ - // 4 - (int) status - // 8 - sockaddr - // 8 - sockaddr - // 8 - sockaddr - // 4 - lc_timestamp - // 4 - lr_timestamp - // 4 - nc_timestamp - // 4 - nc_timeintvl - // 20 - name. - // 1 - end - - // This will need to be made portable..... - - struct sockaddr_in *addr_inet; - struct sockaddr_in *addr_inet2; - struct sockaddr_in *addr_inet3; - - //int pos_status = 0; - int pos_addr = sizeof(int); - int pos_addr2 = pos_addr + sizeof(*addr_inet); - int pos_addr3 = pos_addr2 + sizeof(*addr_inet2); - int pos_lcts = pos_addr3 + sizeof(*addr_inet3); - - int pos_lrts = pos_lcts + sizeof(int); - int pos_ncts = pos_lrts + sizeof(int); - int pos_ncvl = pos_ncts + sizeof(int); - int pos_name = pos_ncvl + sizeof(int); - //int pos_end = pos_name + 20; // \n. for readability. - - int *status = (int *) line; - addr_inet = (struct sockaddr_in *) &(line[pos_addr]); - addr_inet2 = (struct sockaddr_in *) &(line[pos_addr2]); - addr_inet3 = (struct sockaddr_in *) &(line[pos_addr3]); - int *lcts = (int *) &(line[pos_lcts]); - int *lrts = (int *) &(line[pos_lrts]); - int *ncts = (int *) &(line[pos_ncts]); - int *ncvl = (int *) &(line[pos_ncvl]); - char *name = &(line[pos_name]); - //char *end = &(line[pos_end]); - - // end of data structures.... - - - - // fill in the data. - cert *c = npc; - c -> Status(*status); - - std::cerr << "Loaded Cert: " << c -> Name() << " Prev Status: "; - std::cerr << std::hex << (unsigned int) c->Status() << std::dec << std::endl; - - // but ensure that inUse is not set. - c -> InUse(false); - - c -> lastaddr = *addr_inet; - c -> localaddr = *addr_inet2; - c -> serveraddr = *addr_inet3; - - c -> lc_timestamp = *lcts; - c -> lr_timestamp = *lrts; - c -> nc_timestamp = *ncts; - c -> nc_timeintvl = *ncvl; - - - name[20 - 1] = '\0'; - c -> Name(std::string(name)); - - // save the hash. - c -> Hash(hash); - - fclose(pcertfp); - - // small hack - as the timestamps seem wrong..... - // could be a saving thing - or a bug.... - c -> lc_timestamp = 0; - c -> lr_timestamp = 0; - - // reset these. as well. - c -> nc_timestamp = 0; - c -> nc_timeintvl = 5; - - return c; -} - - // for sending stuff as text - // cert * loadCertFromString(std::string pem); - // std::string saveCertAsString(cert *c); - // - -std::string sslroot::saveCertAsString(cert *c) -{ - // save certificate to a string, - // must use a BIO. - std::string certstr; - BIO *bp = BIO_new(BIO_s_mem()); - - std::cerr << "saveCertAsString:" << c -> Name() << std::endl; - PEM_write_bio_XPGP(bp, c -> certificate); - - /* translate the bp data to a string */ - char *data; - int len = BIO_get_mem_data(bp, &data); - for(int i = 0; i < len; i++) - { - certstr += data[i]; - } - - BIO_free(bp); - - return certstr; -} - -cert *sslroot::loadCertFromString(std::string pem) -{ - /* Put the data into a mem BIO */ - char *certstr = strdup(pem.c_str()); - - BIO *bp = BIO_new_mem_buf(certstr, -1); - - XPGP *pc; - cert *npc = NULL; - - pc = PEM_read_bio_XPGP(bp, NULL, NULL, NULL); - - BIO_free(bp); - free(certstr); - - if (pc != NULL) - { - // read a certificate. - std::cerr << "loadCertFromString: "; - std::cerr << pc -> name << std::endl; - - npc = makeCertificateXPGP(pc); - if (npc == NULL) - { - std::cerr << "Failed to Create Cert!" << std::endl; - return NULL; - } - } - else // (pc == NULL) - { - unsigned long err = ERR_get_error(); - std::cerr << "Read Failed .... CODE(" << err << ")" << std::endl; - std::cerr << ERR_error_string(err, NULL) << std::endl; - return NULL; - } - - // small hack - as the timestamps seem wrong..... - // could be a saving thing - or a bug.... - npc -> lc_timestamp = 0; - npc -> lr_timestamp = 0; - - // reset these. as well. - npc -> nc_timestamp = 0; - npc -> nc_timeintvl = 5; - - return npc; -} - - -unsigned char convertHexToChar(unsigned char a, unsigned char b) -{ - int num1 = 0; - int num2 = 0; - if (('0' <= a) && ('9' >= a)) - { - num1 = a - '0'; - } - else if (('a' <= a) && ('f' >= a)) - { - num1 = 10 + a - 'a'; - } - else if (('A' <= a) && ('F' >= a)) - { - num1 = 10 + a - 'A'; - } - - if (('0' <= b) && ('9' >= b)) - { - num2 = b - '0'; - } - else if (('a' <= b) && ('f' >= b)) - { - num2 = 10 + b - 'a'; - } - else if (('A' <= b) && ('F' >= b)) - { - num2 = 10 + b - 'A'; - } - - num1 *= 16; - num1 += num2; - - return (unsigned char) num1; -} - -int sslroot::printCertificate(cert *c, std::ostream &out) -{ - out << "Cert Name:" << (c -> certificate) -> name << std::endl; - //X509_print_fp(stderr, c -> certificate); - return 1; -} - -// This function will clean up X509 *c if necessary. -// This fn will also collate the signatures.... -// that are received via p3disc. -// (connections -> registerCertificate, which does similar sign merging) -// -cert *sslroot::makeCertificateXPGP(XPGP *c) -{ - if (c == NULL) - { - return NULL; - } - - // At this point we check to see if there is a duplicate. - cert *dup = checkDuplicateXPGP(c); - cert *npc = NULL; - if (dup == NULL) - { - npc = new cert(); - npc -> certificate = c; - if (!addtosignmap(npc)) // only allow the cert if no dup - { - std::cerr << "sslroot::makeCertificate()"; - std::cerr << "Failed to Get Signature - Not Allowed!"; - std::cerr << std::endl; - - // failed!... cannot add it!. - delete npc; - return NULL; - } - - /* setup the defaults */ - npc -> Status(PERSON_STATUS_MANUAL); - npc -> trustLvl = -1; - // set Tag to be their X509CN. - npc -> Name(getX509CNString(npc->certificate-> - subject->subject)); - - allcerts.push_back(npc); - std::cerr << "sslroot::makeCertificate() For " << c -> name; - std::cerr << " A-Okay!" << std::endl; - // at this point we need to add to the signaturelist.... - - } - else if (c == dup -> certificate) - { - // identical - so okay. - npc = dup; - std::cerr << "sslroot::makeCertificate() For " << c -> name; - std::cerr << " Found Identical - A-Okay!" << std::endl; - } - else - { - std::cerr << "sslroot::makeCertificate() For " << c -> name; - std::cerr << " Cleaning up other XPGP!" << std::endl; - std::cerr << " Also moving new signatures ... " << std::endl; - // clean up c. - XPGP_copy_known_signatures(pgp_keyring, dup -> certificate, c); - XPGP_free(c); - npc = dup; - } - return npc; -} - - -cert *sslroot::checkDuplicateXPGP(XPGP *x) -{ - if (x == NULL) - return NULL; - - // loop through and print - then check. - std::list::iterator it; - for(it = allcerts.begin(); it != allcerts.end(); it++) - { - if (0 == XPGP_cmp((*it) -> certificate, x)) - { - return (*it); - } - } - return NULL; -} - - -cert *sslroot::checkPeerXPGP(XPGP *x) -{ - if (x == NULL) - return NULL; - - // loop through and print - then check. - std::list::iterator it; - for(it = peercerts.begin(); it != peercerts.end(); it++) - { - if (0 == XPGP_cmp((*it) -> certificate, x)) - { - return (*it); - } - } - return NULL; -} - - - -cert *sslroot::findpeercert(const char *name) -{ - // loop through and print - then check. - //std::cerr << "Checking Certs for: " << name << std::endl; - std::list::iterator it; - for(it = peercerts.begin(); it != peercerts.end(); it++) - { - char *certname = ((*it) -> certificate) -> name; - //std::cerr << "Cert Name:" << certname << std::endl; - if (strstr(certname, name) != NULL) - { - //std::cerr << "Matches!" << std::endl; - return (*it); - } - } - std::cerr << "sslroot::findpeercert() Failed!" << std::endl; - return NULL; -} - -// returns zero for the same. -int sslroot::compareCerts(cert *a, cert *b) -{ - // std::cerr << "Comparing Certificates:" << std::endl; - //printCertificate(a); - //printCertificate(b); - //X509_print_fp(stderr, a -> certificate); - //X509_print_fp(stderr, b -> certificate); - - int val = XPGP_cmp(a -> certificate, b -> certificate); - - std::cerr << "Certificate Comparison Returned: " << val << std::endl; - - return val; -} - -cert * sslroot::registerCertificateXPGP(XPGP *nc, struct sockaddr_in raddr, bool in) -{ - if (nc == NULL) - return NULL; - - // shoud check all certs. - cert *c = checkDuplicateXPGP(nc); - if (c != NULL) - { - if (c -> certificate == nc) - { - std::cerr << "sslroot::registerCertificate()"; - std::cerr << " Found Identical XPGP cert"; - std::cerr << std::endl; - } - else - { - std::cerr << "sslroot::registerCertificate()"; - std::cerr << " Found Same XPGP cert/diff mem - Clean"; - std::cerr << std::endl; - std::cerr << "sslroot::registerCertificate()"; - std::cerr << " Copying New Signatures before deleting"; - std::cerr << std::endl; - /* copy across the signatures -> if necessary */ - XPGP_copy_known_signatures(pgp_keyring, c->certificate, nc); - XPGP_free(nc); - } - - if (!c -> Connected()) - { - c -> lastaddr = raddr; - - if (in == true) - { - c -> lr_timestamp = time(NULL); - // likely to be server address - // (with default port) - // if null! - if (!isValidNet(&(c -> serveraddr.sin_addr))) - { - std::cerr << "Guessing Default Server Addr!"; - std::cerr << std::endl; - c -> serveraddr = raddr; - c -> serveraddr.sin_port = - htons(PQI_DEFAULT_PORT); - } - } - else - { - c -> lc_timestamp = time(NULL); - // also likely to be servera address, - // but we can check and see if its local. - // can flag local - if (0 == inaddr_cmp(c -> localaddr, raddr)) - { - c -> Local(true); - // don't set serveraddr -> just ignore - } - else - { - c -> serveraddr = raddr; - c -> Firewalled(false); - } - } - } - else - { - std::cerr << "WARNING: attempt to reg CONNECTED Cert!"; - std::cerr << std::endl; - } - return c; - } - - std::cerr << "sslroot::registerCertificate() Certificate Not Found!" << std::endl; - std::cerr << "Saving :" << nc -> name << std::endl; - std::cerr << std::endl; - - cert *npc = makeCertificateXPGP(nc); - if (npc == NULL) - { - std::cerr << "Failed to Make Certificate"; - std::cerr << std::endl; - return NULL; - } - - npc -> Name(nc -> name); - - npc -> lastaddr = raddr; - if (in == true) - { - npc -> lr_timestamp = time(NULL); - // likely to be server address (with default port) - std::cerr << "Guessing Default Server Addr!"; - std::cerr << std::endl; - npc -> serveraddr = raddr; - npc -> serveraddr.sin_port = htons(PQI_DEFAULT_PORT); - } - else - { - npc -> lc_timestamp = time(NULL); - - // as it is a new cert... all fields are - // null and the earlier tests must be - // delayed until the discovery packets. - - // also likely to be server. - npc -> serveraddr = raddr; - } - - // push back onto collected. - npc -> nc_timestamp = 0; - collectedcerts.push_back(npc); - - // return NULL to indicate that it dosen't yet exist in dbase. - return NULL; -} - -cert * sslroot::getCollectedCert() -{ - if (collectedcerts.size() < 1) - return NULL; - - cert *c = collectedcerts.front(); - collectedcerts.pop_front(); - return c; -} - -bool sslroot::collectedCerts() -{ - return (collectedcerts.size() > 0); -} - - -int sslroot::removeCertificate(cert *c) -{ - if (c -> InUse()) - { - std::cerr << "sslroot::removeCertificate() Failed" << std::endl; - std::cerr << "\t a cert is in use." << std::endl; - return -1; - } - - std::list::iterator it; - for(it = peercerts.begin(); it != peercerts.end(); it++) - { - if (c == (*it)) - { - peercerts.erase(it); - - c -> InUse(false); - c -> Accepted(false); - - std::cerr << "sslroot::removeCertificate() "; - std::cerr << "Success!" << std::endl; - std::cerr << "\tMoved to Collected Certs" << std::endl; - - /* remove from the keyring */ - XPGP_remove_certificate(pgp_keyring, c->certificate); - - collectedcerts.push_back(c); - - certsChanged.IndicateChanged(); - certsMajorChanged.IndicateChanged(); - return 1; - } - } - std::cerr << "sslroot::removeCertificate() "; - std::cerr << "Failed to Match Cert!" << std::endl; - - return 0; -} - - -int sslroot::addCertificate(cert *c) -{ - std::cerr << "sslroot::addCertificate()" << std::endl; - c -> InUse(false); - // let most flags through. - //c -> Accepted(false); - //c -> WillConnect(false); - if (c -> certificate == NULL) - { - std::cerr << "sslroot::addCertificate() certificate==NULL" << std::endl; - std::cerr << "\tNot Adding Certificate!" << std::endl; - return 0; - } - - cert *dup = checkPeerXPGP(c -> certificate); - if (dup != NULL) - { - std::cerr << "sslroot::addCertificate() Not Adding"; - std::cerr << "Certificate with duplicate...." << std::endl; - std::cerr << "\t\tTry RegisterCertificate() " << std::endl; - - return -1; - } - - // else put in in the list. - peercerts.push_back(c); - - /* add to keyring */ - XPGP_add_certificate(pgp_keyring, c->certificate); - - /* if this should be a trusted cert... setup */ - if (c-> Trusted()) - { - if (XPGP_signer_trusted(pgp_keyring, c -> certificate)) - { - c -> Trusted(true); - } - else - { - c -> Trusted(false); - } - } - - c -> trustLvl = XPGP_auth_certificate(pgp_keyring, c->certificate); - - certsChanged.IndicateChanged(); - certsMajorChanged.IndicateChanged(); - - return 1; -} - - -int sslroot::addUntrustedCertificate(cert *c) -{ - // blank it all. - c -> Status(PERSON_STATUS_MANUAL); - // set Tag to be their X509CN. - c -> Name(getX509CNString(c -> certificate -> subject -> subject)); - - return addCertificate(c); -} - - -int sslroot::addCollectedCertificate(cert *c) -{ - // blank it all. - c -> Status(PERSON_STATUS_MANUAL); - // set Tag to be their X509CN. - c -> Name(getX509CNString(c -> certificate -> subject -> subject)); - - // put in the collected certs ... - collectedcerts.push_back(c); - return 1; -} - - - -int sslroot::validateCertificateXPGP(cert *c) -{ - std::cerr << "sslroot::validateCertificate() Why Not!" << std::endl; - if (XPGP_check_valid_certificate(c->certificate)) - { - c -> Valid(true); - } - else - { - c -> Valid(false); - } - std::cerr << "Cert Status: " << c -> Status() << std::endl; - return 1; -} - - -/* this redoes the trust calculations */ -int sslroot::checkAuthCertificate(cert *xpgp) -{ - std::cerr << "sslroot::checkAuthCertificate()" << std::endl; - if ((xpgp == NULL) || (xpgp -> certificate == NULL)) - { - return -1; - } - - /* reevaluate the auth of the xpgp */ - xpgp -> trustLvl = XPGP_auth_certificate(pgp_keyring, xpgp->certificate); - - /* this also merges the signature into the keyring */ - certsChanged.IndicateChanged(); - certsMajorChanged.IndicateChanged(); - return 1; -} - - -int sslroot::signCertificate(cert *xpgp) -{ - std::cerr << "sslroot::signCertificate()" << std::endl; - cert *own = getOwnCert(); - - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::signCertificate()"); - - /* check that cert is suitable */ - /* sign it */ - XPGP_sign_certificate(pgp_keyring, xpgp -> certificate, own -> certificate); - - /* reevaluate the auth of the xpgp */ - xpgp -> trustLvl = XPGP_auth_certificate(pgp_keyring, xpgp->certificate); - - /* this also merges the signature into the keyring */ - certsChanged.IndicateChanged(); - certsMajorChanged.IndicateChanged(); - return 1; -} - -int sslroot::trustCertificate(cert *c, bool totrust) -{ - std::cerr << "sslroot::trustCertificate()" << std::endl; - /* check auth status of certificate */ - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::trustCertificate()"); - - /* if trusted -> untrust */ - if (!totrust) - { - XPGP_signer_untrusted(pgp_keyring, c -> certificate); - c -> Trusted(false); - } - else - { - /* if auth then we can trust them */ - if (XPGP_signer_trusted(pgp_keyring, c -> certificate)) - { - c -> Trusted(true); - } - } - - /* reevaluate the auth of the xpgp */ - c -> trustLvl = XPGP_auth_certificate(pgp_keyring, c->certificate); - - certsChanged.IndicateChanged(); - certsMajorChanged.IndicateChanged(); - - return 1; -} - -int sslroot::superNodeMode() -{ -# -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ -#ifndef WINDOWS_SYS // UNIX only. - - XPGP_supernode(pgp_keyring); -#endif -/********************************** WINDOWS/UNIX SPECIFIC PART ******************/ - return 1; -} - -/***** REMOVED!!! - * - * -std::list sslroot::listCertificates() -{ - std::list names; - std::list::iterator it; - for(it = peercerts.begin(); it != peercerts.end(); it++) - { - names.push_back(((*it) -> certificate) -> name); - } - return names; -} - * - * - * - */ - - -bool sslroot::CertsChanged() -{ - return certsChanged.Changed(0); -} - -bool sslroot::CertsMajorChanged() -{ - return certsMajorChanged.Changed(0); -} - -void sslroot::IndicateCertsChanged() -{ - certsChanged.IndicateChanged(); -} - - -std::list &sslroot::getCertList() -{ - return peercerts; -} - -std::string sslroot::getSetting(std::string opt) -{ - std::map::iterator it; - if (settings.end() != (it = settings.find(opt))) - { - // found setting. - std::cerr << "sslroot::getSetting(" << opt << ") = "; - std::cerr << it -> second << std::endl; - return it -> second; - } - // else return empty string. - std::cerr << "sslroot::getSetting(" << opt; - std::cerr << ") Not There!" << std::endl; - - std::string empty(""); - return empty; -} - -void sslroot::setSetting(std::string opt, std::string val) -{ - // check settings.. - std::cerr << "sslroot::saveSetting(" << opt << ", "; - std::cerr << val << ")" << std::endl; - - settings[opt] = val; - return; -} - -cert *sslroot::getOwnCert() -{ - return own_cert; -} - -int sslroot::checkNetAddress() -{ - std::list addrs = getLocalInterfaces(); - std::list::iterator it; - - bool found = false; - for(it = addrs.begin(); (!found) && (it != addrs.end()); it++) - { - if ((*it) == inet_ntoa(own_cert -> localaddr.sin_addr)) - { - found = true; - } - } - /* check that we didn't catch 0.0.0.0 - if so go for prefered */ - if ((found) && (own_cert -> localaddr.sin_addr.s_addr == 0)) - { - found = false; - } - - if (!found) - { - own_cert -> localaddr.sin_addr = getPreferredInterface(); - } - if ((isPrivateNet(&(own_cert -> localaddr.sin_addr))) || - (isLoopbackNet(&(own_cert -> localaddr.sin_addr)))) - { - own_cert -> Firewalled(true); - } - else - { - //own_cert -> Firewalled(false); - } - - int port = ntohs(own_cert -> localaddr.sin_port); - if ((port < PQI_MIN_PORT) || (port > PQI_MAX_PORT)) - { - own_cert -> localaddr.sin_port = htons(PQI_DEFAULT_PORT); - } - - /* if localaddr = serveraddr, then ensure that the ports - * are the same (modify server)... this mismatch can - * occur when the local port is changed.... - */ - - if (own_cert -> localaddr.sin_addr.s_addr == - own_cert -> serveraddr.sin_addr.s_addr) - { - own_cert -> serveraddr.sin_port = - own_cert -> localaddr.sin_port; - } - - // ensure that address family is set, otherwise windows Barfs. - own_cert -> localaddr.sin_family = AF_INET; - own_cert -> serveraddr.sin_family = AF_INET; - own_cert -> lastaddr.sin_family = AF_INET; - - return 1; -} - - - - -/********** SSL ERROR STUFF ******************************************/ - -int printSSLError(SSL *ssl, int retval, int err, unsigned long err2, - std::ostream &out) -{ - std::string reason; - - std::string mainreason = std::string("UNKNOWN ERROR CODE"); - if (err == SSL_ERROR_NONE) - { - mainreason = std::string("SSL_ERROR_NONE"); - } - else if (err == SSL_ERROR_ZERO_RETURN) - { - mainreason = std::string("SSL_ERROR_ZERO_RETURN"); - } - else if (err == SSL_ERROR_WANT_READ) - { - mainreason = std::string("SSL_ERROR_WANT_READ"); - } - else if (err == SSL_ERROR_WANT_WRITE) - { - mainreason = std::string("SSL_ERROR_WANT_WRITE"); - } - else if (err == SSL_ERROR_WANT_CONNECT) - { - mainreason = std::string("SSL_ERROR_WANT_CONNECT"); - } - else if (err == SSL_ERROR_WANT_ACCEPT) - { - mainreason = std::string("SSL_ERROR_WANT_ACCEPT"); - } - else if (err == SSL_ERROR_WANT_X509_LOOKUP) - { - mainreason = std::string("SSL_ERROR_WANT_X509_LOOKUP"); - } - else if (err == SSL_ERROR_SYSCALL) - { - mainreason = std::string("SSL_ERROR_SYSCALL"); - } - else if (err == SSL_ERROR_SSL) - { - mainreason = std::string("SSL_ERROR_SSL"); - } - out << "RetVal(" << retval; - out << ") -> SSL Error: " << mainreason << std::endl; - out << "\t + ERR Error: " << ERR_error_string(err2, NULL) << std::endl; - return 1; -} - -cert::cert() - :certificate(NULL), hash("") -{ - return; -} - -cert::~cert() -{ - return; -} - -std::string cert::Signature() -{ - if (certificate == NULL) - { - return Name(); - } - else - { - std::ostringstream out; - certsign cs; - getSSLRoot() -> getcertsign(this, cs); - - out << std::hex; - for(int i = 0; i < CERTSIGNLEN; i++) - { - - unsigned char n = cs.data[i]; - out << std::hex << std::setw(2) << std::setfill('0') - << std::setprecision(2) << (unsigned int) n; - } - return out.str(); - } -} - -std::string cert::Hash() -{ - return hash; -} - - -void cert::Hash(std::string h) -{ - hash = h; - return; -} - - - -/********************* signature stuff *********************/ - -bool certsign::operator<(const certsign &ref) const -{ - //compare the signature. - if (0 > memcmp(data, ref.data, CERTSIGNLEN)) - return true; - return false; -} - - -bool certsign::operator==(const certsign &ref) const -{ - //compare the signature. - return (0 == memcmp(data, ref.data, CERTSIGNLEN)); -} - - -/* Fns for relating cert signatures to structures */ -cert *sslroot::findPeerId(std::string id) -{ - certsign sign; - if (!convert_to_certsign(id, sign)) - { - pqioutput(PQL_WARNING, pqisslrootzone, - "sslroot::findPeerId() ERROR: Failed to Convert to certsign"); - return NULL; - } - - return findcertsign(sign); -} - -cert *sslroot::findcertsign(certsign &sign) -{ - std::map::iterator it; - - std::ostringstream out; - out << "sslroot::findcertsign()" << std::endl; - for (it = signmap.begin(); it != signmap.end(); it++) - { - out << "Checking Vs " << it -> second -> Name(); - if (sign == it -> first) - { - out << "Match!"; - } - out << std::endl; - } - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - - if (signmap.end() != (it = signmap.find(sign))) - { - return it -> second; - } - pqioutput(PQL_WARNING, pqisslrootzone, - "sslroot::findcertsign() ERROR: No Matching Entry"); - return NULL; -} - -int sslroot::getcertsign(cert *c, certsign &sign) -{ - // bug ... segv a couple of times here! - if ((c == NULL) || (c->certificate == NULL)) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::getcertsign() ERROR: NULL c || c->certificate"); - return 0; - } - - // a Bit of a hack here..... - // get the first signature.... - if (sk_XPGP_SIGNATURE_num(c->certificate->signs) < 1) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::getcertsign() ERROR: No Signatures"); - return 0; - } - XPGP_SIGNATURE *xpgpsign = sk_XPGP_SIGNATURE_value(c->certificate->signs, 0); - - // get the signature from the cert, and copy to the array. - ASN1_BIT_STRING *signature = xpgpsign->signature; - int signlen = ASN1_STRING_length(signature); - if (signlen < CERTSIGNLEN) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::getcertsign() ERROR: short Signature"); - return 0; - } - // else copy in the first CERTSIGNLEN. - unsigned char *signdata = ASN1_STRING_data(signature); - memcpy(sign.data, signdata, CERTSIGNLEN); - - return 1; -} - -int sslroot::addtosignmap(cert *c) -{ - certsign cs; - if (!getcertsign(c, cs)) - { - // error. - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::addsigntomap() ERROR: Fail to getcertsign()"); - return 0; - } - cert *c2 = findcertsign(cs); - if (c2 == NULL) - { - // add, and return okay. - signmap[cs] = c; - return 1; - } - if (c2 != c) - { - // error. - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::addsigntomap() ERROR: Duplicate Entry()"); - return 0; - } - - // else already exists. - return 1; -} - - - - -int sslroot::hashFile(std::string fname, unsigned char *hash, unsigned int hlen) -{ - // open the file. - // setup the hash. - - // pipe the file through. - - - return 1; -} - -int sslroot::hashDigest(char *data, unsigned int dlen, - unsigned char *hash, unsigned int hlen) -{ - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_DigestInit_ex(mdctx, EVP_sha1(), NULL)) - { - std::cerr << "EVP_DigestInit Failure!" << std::endl; - return -1; - } - - if (0 == EVP_DigestUpdate(mdctx, data, dlen)) - { - std::cerr << "EVP_DigestUpdate Failure!" << std::endl; - return -1; - } - - unsigned int signlen = hlen; - if (0 == EVP_DigestFinal_ex(mdctx, hash, &signlen)) - { - std::cerr << "EVP_DigestFinal Failure!" << std::endl; - return -1; - } - - EVP_MD_CTX_destroy(mdctx); - return signlen; -} - - - -int sslroot::signDigest(EVP_PKEY *key, char *data, unsigned int dlen, - unsigned char *sign, unsigned int slen) -{ - unsigned int signlen = EVP_PKEY_size(key); - - { - std::ostringstream out; - out << "sslroot::signDigest(" << (void *) key; - out << ", " << (void *) data << ", " << dlen << ", "; - out << (void *) sign << ", " << slen << ")" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - } - - if (signlen > slen) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::signDigest() Sign Length too short"); - return -1; - } - - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_SignInit_ex(mdctx, EVP_sha1(), NULL)) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::signDigest() EVP_SignInit Failure!"); - return -1; - } - - if (0 == EVP_SignUpdate(mdctx, data, dlen)) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::signDigest() EVP_SignUpdate Failure!"); - return -1; - } - - signlen = slen; - if (0 == EVP_SignFinal(mdctx, sign, &signlen, key)) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::signDigest() EVP_SignFinal Failure!"); - return -1; - } - - { - // display signed data - std::ostringstream out; - out << "sslroot::signDigest() Data Display" << std::endl; - out << "Data To Sign (" << dlen << "):::::::::::::" << std::hex; - for(unsigned int i = 0; i < dlen; i++) - { - if (i % 16 == 0) - { - out << std::endl; - out << std::setw(4) << i << " : "; - } - out << std::setw(2) << (unsigned int) ((unsigned char *) data)[i] << " "; - } - out << std::endl; - out << "Signature (" << std::dec << slen << "):::::::::::::" << std::hex; - for(unsigned int i = 0; i < slen; i++) - { - if (i % 16 == 0) - { - out << std::endl; - out << std::setw(4) << i << " : "; - } - out << std::setw(2) << (unsigned int) ((unsigned char *) sign)[i] << " "; - } - out << std::endl; - out << "::::::::::::::::::::::::::::::::::::::::::::::" << std::endl; - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, out.str()); - - } - - - EVP_MD_CTX_destroy(mdctx); - return signlen; -} - - -int sslroot::verifyDigest(EVP_PKEY *key, char *data, unsigned int dlen, - unsigned char *sign, unsigned int slen) -{ - EVP_MD_CTX *mdctx = EVP_MD_CTX_create(); - - if (0 == EVP_VerifyInit_ex(mdctx, EVP_sha1(), NULL)) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::verifyDigest() EVP_VerifyInit Failure!"); - return -1; - } - - if (0 == EVP_VerifyUpdate(mdctx, data, dlen)) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::verifyDigest() EVP_VerifyUpdate Failure!"); - return -1; - } - - int vv; - if (0 > (vv = EVP_VerifyFinal(mdctx, sign, slen, key))) - { - pqioutput(PQL_ALERT, pqisslrootzone, - "sslroot::verifyDigest() EVP_VerifyFinale Failure!"); - return -1; - } - if (vv == 1) - { - pqioutput(PQL_DEBUG_BASIC, pqisslrootzone, - "sslroot::verifyDigest() Verified Signature OKAY"); - } - else - { - std::ostringstream out; - out << "sslroot::verifyDigest() Failed Verification!" << std::endl; - out << "Data To Verify (" << dlen << "):::::::::::::" << std::hex; - for(unsigned int i = 0; i < dlen; i++) - { - if (i % 16 == 0) - { - out << std::endl; - out << std::setw(4) << i << " : "; - } - out << std::setw(2) << (unsigned int) ((unsigned char *) data)[i] << " "; - } - out << std::endl; - out << "Signature (" << std::dec << slen << "):::::::::::::" << std::hex; - for(unsigned int i = 0; i < slen; i++) - { - if (i % 16 == 0) - { - out << std::endl; - out << std::setw(4) << i << " : "; - } - out << std::setw(2) << (unsigned int) ((unsigned char *) sign)[i] << " "; - } - out << std::endl; - out << "::::::::::::::::::::::::::::::::::::::::::::::" << std::endl; - out << "sslroot::verifyDigest() Should Clear SSL Error!"; - - pqioutput(PQL_ALERT, pqisslrootzone, out.str()); - } - - EVP_MD_CTX_destroy(mdctx); - return vv; -} - -// Think both will fit in the one Structure. -int sslroot::generateKeyPair(EVP_PKEY *keypair, unsigned int keylen) -{ - RSA *rsa = RSA_generate_key(2048, 65537, NULL, NULL); - EVP_PKEY_assign_RSA(keypair, rsa); - std::cerr << "sslroot::generateKeyPair()" << std::endl; - return 1; -} - -// Extra features for XPGP..... (for login window) - - - -// This fn installs and signs a trusted peer. -// It is limited to only working just after certificate creation. -// this is done by checking the timestamps. -// -// It should be called before the pqi handler is initiated, -// otherwise the connection will not be automatically started. - -int sslroot::loadInitialTrustedPeer(std::string tp_file) -{ - /* we will only do this if various conditions are met. - * (1) check validity of certificate - * (2) check that we don't have any other certificates loaded. - * (3) check that our certificate has just been created (timestamp) and only has one signature. - */ - - bool canLoad = true; - - std::string userName; - - /* check (1) valid cert */ - if (!LoadCheckXPGPandGetName(tp_file.c_str(),userName)) - { - std::cerr << "sslroot::loadInitialTrustedPeer() Failed TrustedPeer Checks!(1)"; - std::cerr << std::endl; - canLoad = false; - return 0; - } - - /* check (2) no other certificates loaded */ - if (peercerts.size() != 1) - { - /* too many certs loaded! */ - std::cerr << "sslroot::loadInitialTrustedPeer() Failed TrustedPeer Checks!(2a)"; - std::cerr << std::endl; - canLoad = false; - return 0; - } - - /* that one must be our own */ - cert *ourcert = getOwnCert(); - if ((!ourcert) || (ourcert != *(peercerts.begin())) || (!ourcert->certificate)) - { - /* too many certs loaded! */ - std::cerr << "sslroot::loadInitialTrustedPeer() Failed TrustedPeer Checks!(2b)"; - std::cerr << std::endl; - canLoad = false; - return 0; - } - - XPGP *xpgp = ourcert->certificate; - if (sk_XPGP_SIGNATURE_num(xpgp->signs) != 1) - { - /* too many certs loaded! */ - std::cerr << "sslroot::loadInitialTrustedPeer() Failed TrustedPeer Checks!(3a)"; - std::cerr << std::endl; - canLoad = false; - return 0; - } - - /* check own certificate timestamps */ - time_t cts = time(NULL); - X509_VAL *certv = xpgp->key->validity; - XPGP_SIGNATURE *ownsign = sk_XPGP_SIGNATURE_value(xpgp->signs, 0); - ASN1_TIME *signts = ownsign->timestamp; - ASN1_TIME *createts = certv->notBefore; - - /* compare timestamps - * Certificate timestamp should have been generated - * within the last 5 seconds, */ - time_t max_initts = cts - 5; - if ((0 > X509_cmp_time(createts, &max_initts)) || (0 > X509_cmp_time(signts, &max_initts))) - { - std::cerr << "sslroot::loadInitialTrustedPeer() Failed TrustedPeer Checks!(3b)"; - std::cerr << std::endl; - canLoad = false; - return 0; - } - - /* or if in the future! */ - if ((0 < X509_cmp_current_time(createts)) || (0 < X509_cmp_current_time(signts))) - { - std::cerr << "sslroot::loadInitialTrustedPeer() Failed TrustedPeer Checks!(3c)"; - std::cerr << std::endl; - canLoad = false; - return 0; - } - - /* if we get here - it has passed the tests, and we can sign it, and install it */ - cert *trusted_cert = loadcertificate(tp_file.c_str(), ""); /* no Hash! */ - if (!trusted_cert) - { - std::cerr << "sslroot::loadInitialTrustedPeer() Failed TrustedPeer Checks!(4a)"; - std::cerr << std::endl; - canLoad = false; - return 0; - } - - /* now add it */ - if (1 != addCertificate(trusted_cert)) - { - std::cerr << "sslroot::loadInitialTrustedPeer() Failed TrustedPeer Checks!(4b)"; - std::cerr << std::endl; - canLoad = false; - return 0; - } - - /* must set these flags completely - as they aren't changed */ - trusted_cert->Accepted(true); - trusted_cert->Manual(false); - trusted_cert->WillConnect(true); - trusted_cert->WillListen(true); - /* use existing firewall/forwarded flags */ - - /* sign it! (must be after add) */ - if (!signCertificate(trusted_cert)) - { - std::cerr << "sslroot::loadInitialTrustedPeer() Failed TrustedPeer Checks!(4c)"; - std::cerr << std::endl; - canLoad = false; - return 0; - } - - if (canLoad) - { - std::cerr << "sslroot::loadInitialTrustedPeer() Loaded: " << userName; - std::cerr << std::endl; - return 1; - } - return 0; -} - - - - - -// Not dependent on sslroot. load, and detroys the XPGP memory. - -int LoadCheckXPGPandGetName(const char *cert_file, std::string &userName) -{ - /* This function loads the XPGP certificate from the file, - * and checks the certificate - */ - - FILE *tmpfp = fopen(cert_file, "r"); - if (tmpfp == NULL) - { - std::cerr << "sslroot::LoadCheckAndGetXPGPName()"; - std::cerr << " Failed to open Certificate File:" << cert_file; - std::cerr << std::endl; - return 0; - } - - // get xPGP certificate. - XPGP *xpgp = PEM_read_XPGP(tmpfp, NULL, NULL, NULL); - fclose(tmpfp); - - // check the certificate. - bool valid = false; - if (xpgp) - { - valid = XPGP_check_valid_certificate(xpgp); - } - - if (valid) - { - // extract the name. - userName = getX509CNString(xpgp->subject->subject); - } - - // clean up. - XPGP_free(xpgp); - - if (valid) - { - // happy! - return 1; - } - else - { - // something went wrong! - return 0; - } -} - -std::string getX509NameString(X509_NAME *name) -{ - std::string namestr; - for(int i = 0; i < X509_NAME_entry_count(name); i++) - { - X509_NAME_ENTRY *entry = X509_NAME_get_entry(name, i); - ASN1_STRING *entry_data = X509_NAME_ENTRY_get_data(entry); - ASN1_OBJECT *entry_obj = X509_NAME_ENTRY_get_object(entry); - - namestr += "\t"; - namestr += OBJ_nid2ln(OBJ_obj2nid(entry_obj)); - namestr += " : "; - - //namestr += entry_obj -> flags; - //namestr += entry_data -> length; - //namestr += entry_data -> type; - - //namestr += entry_data -> flags; - //entry -> set; - - if (entry_data -> data != NULL) - { - namestr += (char *) entry_data -> data; - } - else - { - namestr += "NULL"; - } - - if (i + 1 < X509_NAME_entry_count(name)) - { - namestr += "\n"; - } - - } - return namestr; -} - - -std::string getX509CNString(X509_NAME *name) -{ - std::string namestr; - for(int i = 0; i < X509_NAME_entry_count(name); i++) - { - X509_NAME_ENTRY *entry = X509_NAME_get_entry(name, i); - ASN1_STRING *entry_data = X509_NAME_ENTRY_get_data(entry); - ASN1_OBJECT *entry_obj = X509_NAME_ENTRY_get_object(entry); - - if (0 == strncmp("CN", OBJ_nid2sn(OBJ_obj2nid(entry_obj)), 2)) - { - if (entry_data -> data != NULL) - { - namestr += (char *) entry_data -> data; - } - else - { - namestr += "Unknown"; - } - return namestr; - } - } - return namestr; -} - - -std::string getX509TypeString(X509_NAME *name, char *type, int len) -{ - std::string namestr; - for(int i = 0; i < X509_NAME_entry_count(name); i++) - { - X509_NAME_ENTRY *entry = X509_NAME_get_entry(name, i); - ASN1_STRING *entry_data = X509_NAME_ENTRY_get_data(entry); - ASN1_OBJECT *entry_obj = X509_NAME_ENTRY_get_object(entry); - - if (0 == strncmp(type, OBJ_nid2sn(OBJ_obj2nid(entry_obj)), len)) - { - if (entry_data -> data != NULL) - { - namestr += (char *) entry_data -> data; - } - else - { - namestr += "Unknown"; - } - return namestr; - } - } - return namestr; -} - - -std::string getX509LocString(X509_NAME *name) -{ - return getX509TypeString(name, "L", 2); -} - -std::string getX509OrgString(X509_NAME *name) -{ - return getX509TypeString(name, "O", 2); -} - - -std::string getX509CountryString(X509_NAME *name) -{ - return getX509TypeString(name, "C", 2); -} - - -std::string convert_to_str(certsign &sign) -{ - std::ostringstream id; - for(int i = 0; i < CERTSIGNLEN; i++) - { - id << std::hex << std::setw(2) << std::setfill('0') << (uint16_t) (((uint8_t *) (sign.data))[i]); - } - return id.str(); -} - -bool convert_to_certsign(std::string id, certsign &sign) -{ - char num[3]; - if (id.length() < CERTSIGNLEN * 2) - { - return false; - } - - for(int i = 0; i < CERTSIGNLEN; i++) - { - num[0] = id[i * 2]; - num[1] = id[i * 2 + 1]; - num[2] = '\0'; - int32_t val; - if (1 != sscanf(num, "%x", &val)) - { - return false; - } - sign.data[i] = (uint8_t) val; - } - return true; -} - - diff --git a/libretroshare/src/pqi/xpgpcert.h b/libretroshare/src/pqi/xpgpcert.h deleted file mode 100644 index b419cd655..000000000 --- a/libretroshare/src/pqi/xpgpcert.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * "$Id: xpgpcert.h,v 1.9 2007-04-15 18:45:18 rmf24 Exp $" - * - * 3P/PQI network interface for RetroShare. - * - * Copyright 2004-2006 by Robert Fernie. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License Version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 - * USA. - * - * Please report all bugs and problems to "retroshare@lunamutt.com". - * - */ - - - -#ifndef MRK_SSL_XPGP_CERT_HEADER -#define MRK_SSL_XPGP_CERT_HEADER - -/* This is the trial XPGP version - * - * It has to be compiled against XPGP ssl version. - * this is only a hacked up version, merging - * (so both can operate in parallel will happen later) - * - */ - -#include -#include - -#include -#include - -#include "pqi_base.h" -#include "pqinetwork.h" - -#include "pqiindic.h" - - -// helper fns. -int printSSLError(SSL *ssl, int retval, int err, unsigned long err2, std::ostream &out); -std::string getX509NameString(X509_NAME *name); -std::string getX509CNString(X509_NAME *name); - -std::string getX509OrgString(X509_NAME *name); -std::string getX509LocString(X509_NAME *name); -std::string getX509CountryString(X509_NAME *name); - -int LoadCheckXPGPandGetName(const char *cert_file, std::string &userName); - -std::string convert_to_str(certsign &sign); -bool convert_to_certsign(std::string id, certsign &sign); - -class sslroot; - -class cert: public Person -{ - public: - cert(); -virtual ~cert(); - -virtual std::string Signature(); -std::string Hash(); -void Hash(std::string); -std::string PeerId() { return Signature(); } - - XPGP *certificate; - std::string hash; - std::string peerid; -}; - - -// returns pointer to static variable. -// which must be inited.. -sslroot *getSSLRoot(); - -class sslroot -{ - public: - sslroot(); -int active(); -int setcertdir(char *path); -int initssl(const char *srvr_cert, const char *priv_key, - const char *passwd); -int closessl(); - -/* Context handling */ -SSL_CTX *getCTX(); - -/* Certificate handling */ -int compareCerts(cert *a, cert *b); - - // network interface. - - // program interface. -int addCertificate(cert *c); -int addUntrustedCertificate(cert *c); -int addCollectedCertificate(cert *c); - -int removeCertificate(cert *); - - // Creation of Certificates.... (From X509) - // Core functions.... -cert *checkDuplicateXPGP(XPGP *x); -cert *checkPeerXPGP(XPGP *x); -cert *makeCertificateXPGP(XPGP *c); -cert *registerCertificateXPGP(XPGP *nc, struct sockaddr_in, bool in); - -int validateCertificateXPGP(cert *c); - - /* Fns specific to XPGP */ -int checkAuthCertificate(cert *xpgp); -int signCertificate(cert *); -int trustCertificate(cert *, bool totrust); -int superNodeMode(); -int loadInitialTrustedPeer(std::string tp_file); - -// depreciated... -cert *findpeercert(const char *name); -//int loadpeercert(const char *fname); -//int savepeercert(const char *fname); - -// Configuration Handling... -int setConfigDirs(const char *cdir, const char *ndir); - -// these save both the certificates + the settings. -int saveCertificates(const char *fname); -int saveCertificates(); -int loadCertificates(const char *fname); - - // with a hash check/recalc in there for good measure. -cert * loadcertificate(const char* fname, std::string hash); -int savecertificate(cert *c, const char* fname); - - // for sending stuff as text -cert * loadCertFromString(std::string pem); -std::string saveCertAsString(cert *c); - -// digest hashing /signing or encrypting interface. -int hashFile(std::string fname, unsigned char *hash, unsigned int hlen); -int hashDigest(char *data, unsigned int dlen, unsigned char *hash, unsigned int hlen); -int signDigest(EVP_PKEY *key, char *data, unsigned int dlen, unsigned char *hash, unsigned int hlen); -int verifyDigest(EVP_PKEY *key, char *data, unsigned int dlen, unsigned char *enc, unsigned int elen); -int generateKeyPair(EVP_PKEY *keypair, unsigned int keylen); - - - -int printCertificate(cert *, std::ostream &out); -/* removing the list of certificate names - ambiguity! - * -std::list listCertificates(); - * - */ - -std::list &getCertList(); - -cert * getOwnCert(); -int checkNetAddress(); - - // extra list for certs that aren't in main list. -cert * getCollectedCert(); -bool collectedCerts(); - -bool CertsChanged(); -bool CertsMajorChanged(); -void IndicateCertsChanged(); - -std::string getSetting(std::string opt); -void setSetting(std::string opt, std::string val); - - -/* Fns for relating cert signatures to structures */ -cert *findPeerId(std::string id); -cert *findcertsign(certsign &sign); -int getcertsign(cert *c, certsign &sign); -int addtosignmap(cert *); - - private: /* data */ -std::list peercerts; -std::list allcerts; -std::list collectedcerts; - -// whenever a cert is added, it should also be put in the map. -std::map signmap; - - - -// General Configuration System -// easy it put it here - so it can be signed easily. -std::map settings; - -std::string certdir; -std::string neighbourdir; -std::string certfile; - -SSL_CTX *sslctx; -int init; - -Indicator certsChanged; -Indicator certsMajorChanged; - -EVP_PKEY *pkey; - -cert *own_cert; - -XPGP_KEYRING *pgp_keyring; - -}; - -#endif // MRK_SSL_XPGP_CERT_HEADER