Upstream tarball 10114
[amule.git] / src / ClientCreditsList.cpp
blob4608b1225712ad4ebfb5c23b4219e20a0090cd5d
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2008 Merkur ( devs@emule-project.net / http://www.emule-project.net )
6 //
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
9 // respective authors.
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
20 //
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include "ClientCreditsList.h" // Interface declarations
29 #include <protocol/ed2k/Constants.h>
30 #include <common/Macros.h>
31 #include <common/DataFileVersion.h>
32 #include <common/FileFunctions.h> // Needed for GetFileSize
35 #include "GetTickCount.h" // Needed for GetTickCount
36 #include "Preferences.h" // Needed for thePrefs
37 #include "ClientCredits.h" // Needed for CClientCredits
38 #include "amule.h" // Needed for theApp
39 #include "CFile.h" // Needed for CFile
40 #include "Logger.h" // Needed for Add(Debug)LogLine
41 #include "CryptoPP_Inc.h" // Needed for Crypto functions
44 #define CLIENTS_MET_FILENAME wxT("clients.met")
45 #define CLIENTS_MET_BAK_FILENAME wxT("clients.met.BAK")
46 #define CRYPTKEY_FILENAME wxT("cryptkey.dat")
49 CClientCreditsList::CClientCreditsList()
51 m_nLastSaved = ::GetTickCount();
52 LoadList();
54 InitalizeCrypting();
58 CClientCreditsList::~CClientCreditsList()
60 DeleteContents(m_mapClients);
61 delete static_cast<CryptoPP::RSASSA_PKCS1v15_SHA_Signer *>(m_pSignkey);
65 void CClientCreditsList::LoadList()
67 CFile file;
68 CPath fileName = CPath(theApp->ConfigDir + CLIENTS_MET_FILENAME);
70 if (!fileName.FileExists()) {
71 return;
74 try {
75 file.Open(fileName, CFile::read);
77 if (file.ReadUInt8() != CREDITFILE_VERSION) {
78 AddDebugLogLineM( true, logCredits,
79 wxT("Creditfile is out of date and will be replaced") );
80 file.Close();
81 return;
84 // everything is ok, lets see if the backup exist...
85 CPath bakFileName = CPath(theApp->ConfigDir + CLIENTS_MET_BAK_FILENAME);
87 bool bCreateBackup = TRUE;
88 if (bakFileName.FileExists()) {
89 // Ok, the backup exist, get the size
90 CFile hBakFile(bakFileName);
91 if ( hBakFile.GetLength() > file.GetLength()) {
92 // the size of the backup was larger then the
93 // org. file, something is wrong here, don't
94 // overwrite old backup..
95 bCreateBackup = FALSE;
97 // else: backup is smaller or the same size as org.
98 // file, proceed with copying of file
101 //else: the backup doesn't exist, create it
102 if (bCreateBackup) {
103 file.Close(); // close the file before copying
104 if (!CPath::CloneFile(fileName, bakFileName, true)) {
105 AddDebugLogLineM(true, logCredits,
106 CFormat(wxT("Could not create backup file '%s'")) % fileName);
108 // reopen file
109 if (!file.Open(fileName, CFile::read)) {
110 AddDebugLogLineM( true, logCredits,
111 wxT("Failed to load creditfile") );
112 return;
115 file.Seek(1);
119 uint32 count = file.ReadUInt32();
121 const uint32 dwExpired = time(NULL) - 12960000; // today - 150 day
122 uint32 cDeleted = 0;
123 for (uint32 i = 0; i < count; i++){
124 CreditStruct* newcstruct = new CreditStruct();
126 newcstruct->key = file.ReadHash();
127 newcstruct->uploaded = file.ReadUInt32();
128 newcstruct->downloaded = file.ReadUInt32();
129 newcstruct->nLastSeen = file.ReadUInt32();
130 newcstruct->uploaded += static_cast<uint64>(file.ReadUInt32()) << 32;
131 newcstruct->downloaded += static_cast<uint64>(file.ReadUInt32()) << 32;
132 newcstruct->nReserved3 = file.ReadUInt16();
133 newcstruct->nKeySize = file.ReadUInt8();
134 file.Read(newcstruct->abySecureIdent, MAXPUBKEYSIZE);
136 if ( newcstruct->nKeySize > MAXPUBKEYSIZE ) {
137 // Oh dear, this is bad mojo, the file is most likely corrupt
138 // We can no longer assume that any of the clients in the file are valid
139 // and will have to discard it.
140 delete newcstruct;
142 DeleteContents(m_mapClients);
144 AddDebugLogLineM( true, logCredits,
145 wxT("WARNING: Corruptions found while reading Creditfile!") );
146 return;
149 if (newcstruct->nLastSeen < dwExpired){
150 cDeleted++;
151 delete newcstruct;
152 continue;
155 CClientCredits* newcredits = new CClientCredits(newcstruct);
156 m_mapClients[newcredits->GetKey()] = newcredits;
159 AddLogLineM(false, wxString::Format(wxPLURAL("Creditfile loaded, %u client is known", "Creditfile loaded, %u clients are known", count - cDeleted), count - cDeleted));
161 if (cDeleted) {
162 AddLogLineM(false, wxString::Format(wxPLURAL(" - Credits expired for %u client!", " - Credits expired for %u clients!", cDeleted), cDeleted));
164 } catch (const CSafeIOException& e) {
165 AddDebugLogLineM(true, logCredits, wxT("IO error while loading clients.met file: ") + e.what());
170 void CClientCreditsList::SaveList()
172 AddDebugLogLineM( false, logCredits, wxT("Saved Credit list"));
173 m_nLastSaved = ::GetTickCount();
175 wxString name(theApp->ConfigDir + CLIENTS_MET_FILENAME);
176 CFile file;
178 if ( !file.Create(name, true) ) {
179 AddDebugLogLineM( true, logCredits, wxT("Failed to create creditfile") );
180 return;
183 if ( file.Open(name, CFile::write) ) {
184 try {
185 uint32 count = 0;
187 file.WriteUInt8( CREDITFILE_VERSION );
188 // Temporary place-holder for number of stucts
189 file.WriteUInt32( 0 );
191 ClientMap::iterator it = m_mapClients.begin();
192 for ( ; it != m_mapClients.end(); ++it ) {
193 CClientCredits* cur_credit = it->second;
195 if ( cur_credit->GetUploadedTotal() || cur_credit->GetDownloadedTotal() ) {
196 const CreditStruct* const cstruct = cur_credit->GetDataStruct();
197 file.WriteHash(cstruct->key);
198 file.WriteUInt32(static_cast<uint32>(cstruct->uploaded));
199 file.WriteUInt32(static_cast<uint32>(cstruct->downloaded));
200 file.WriteUInt32(cstruct->nLastSeen);
201 file.WriteUInt32(static_cast<uint32>(cstruct->uploaded >> 32));
202 file.WriteUInt32(static_cast<uint32>(cstruct->downloaded >> 32));
203 file.WriteUInt16(cstruct->nReserved3);
204 file.WriteUInt8(cstruct->nKeySize);
205 // Doesn't matter if this saves garbage, will be fixed on load.
206 file.Write(cstruct->abySecureIdent, MAXPUBKEYSIZE);
207 count++;
211 // Write the actual number of structs
212 file.Seek( 1 );
213 file.WriteUInt32( count );
214 } catch (const CIOFailureException& e) {
215 AddDebugLogLineM(true, logCredits, wxT("IO failure while saving clients.met: ") + e.what());
217 } else {
218 AddDebugLogLineM(true, logCredits, wxT("Failed to open existing creditfile!"));
223 CClientCredits* CClientCreditsList::GetCredit(const CMD4Hash& key)
225 CClientCredits* result;
227 ClientMap::iterator it = m_mapClients.find( key );
230 if ( it == m_mapClients.end() ){
231 result = new CClientCredits(key);
232 m_mapClients[result->GetKey()] = result;
233 } else {
234 result = it->second;
237 result->SetLastSeen();
239 return result;
243 void CClientCreditsList::Process()
245 if (::GetTickCount() - m_nLastSaved > MIN2MS(13))
246 SaveList();
250 bool CClientCreditsList::CreateKeyPair()
252 try{
253 CryptoPP::AutoSeededX917RNG<CryptoPP::DES_EDE3> rng;
254 CryptoPP::InvertibleRSAFunction privkey;
255 privkey.Initialize(rng, RSAKEYSIZE);
257 // Nothing we can do against this filename2char :/
258 wxCharBuffer filename = filename2char(theApp->ConfigDir + CRYPTKEY_FILENAME);
259 CryptoPP::FileSink *fileSink = new CryptoPP::FileSink(filename);
260 CryptoPP::Base64Encoder *privkeysink = new CryptoPP::Base64Encoder(fileSink);
261 privkey.DEREncode(*privkeysink);
262 privkeysink->MessageEnd();
264 // Do not delete these pointers or it will blow in your face.
265 // cryptopp semantics is giving ownership of these objects.
267 // delete privkeysink;
268 // delete fileSink;
270 AddDebugLogLineM( true, logCredits, wxT("Created new RSA keypair"));
271 } catch(const CryptoPP::Exception& e) {
272 AddDebugLogLineM(true, logCredits,
273 wxString(wxT("Failed to create new RSA keypair: ")) +
274 char2unicode(e.what()));
275 wxFAIL;
276 return false;
279 return true;
283 void CClientCreditsList::InitalizeCrypting()
285 m_nMyPublicKeyLen = 0;
286 memset(m_abyMyPublicKey,0,80); // not really needed; better for debugging tho
287 m_pSignkey = NULL;
289 if (!thePrefs::IsSecureIdentEnabled()) {
290 return;
293 try {
294 // check if keyfile is there
295 if (wxFileExists(theApp->ConfigDir + CRYPTKEY_FILENAME)) {
296 off_t keySize = CPath::GetFileSize(theApp->ConfigDir + CRYPTKEY_FILENAME);
298 if (keySize == wxInvalidOffset) {
299 AddDebugLogLineM(true, logCredits, wxT("Cannot access 'cryptkey.dat', please check permissions."));
300 return;
301 } else if (keySize == 0) {
302 AddDebugLogLineM(true, logCredits, wxT("'cryptkey.dat' is empty, recreating keypair."));
303 CreateKeyPair();
305 } else {
306 AddLogLineM( false, _("No 'cryptkey.dat' file found, creating.") );
307 CreateKeyPair();
310 // load private key
311 CryptoPP::FileSource filesource(filename2char(theApp->ConfigDir + CRYPTKEY_FILENAME), true, new CryptoPP::Base64Decoder);
312 m_pSignkey = new CryptoPP::RSASSA_PKCS1v15_SHA_Signer(filesource);
313 // calculate and store public key
314 CryptoPP::RSASSA_PKCS1v15_SHA_Verifier pubkey(*static_cast<CryptoPP::RSASSA_PKCS1v15_SHA_Signer *>(m_pSignkey));
315 CryptoPP::ArraySink asink(m_abyMyPublicKey, 80);
316 pubkey.DEREncode(asink);
317 m_nMyPublicKeyLen = asink.TotalPutLength();
318 asink.MessageEnd();
319 } catch (const CryptoPP::Exception& e) {
320 delete static_cast<CryptoPP::RSASSA_PKCS1v15_SHA_Signer *>(m_pSignkey);
321 m_pSignkey = NULL;
323 AddDebugLogLineM(true, logCredits,
324 wxString(wxT("Error while initializing encryption keys: ")) +
325 char2unicode(e.what()));
330 uint8 CClientCreditsList::CreateSignature(CClientCredits* pTarget, byte* pachOutput, uint8 nMaxSize, uint32 ChallengeIP, uint8 byChaIPKind, void* sigkey)
332 CryptoPP::RSASSA_PKCS1v15_SHA_Signer* signer =
333 static_cast<CryptoPP::RSASSA_PKCS1v15_SHA_Signer *>(sigkey);
334 // signer param is used for debug only
335 if (signer == NULL)
336 signer = static_cast<CryptoPP::RSASSA_PKCS1v15_SHA_Signer *>(m_pSignkey);
338 // create a signature of the public key from pTarget
339 wxASSERT( pTarget );
340 wxASSERT( pachOutput );
342 if ( !CryptoAvailable() ) {
343 return 0;
346 try {
347 CryptoPP::SecByteBlock sbbSignature(signer->SignatureLength());
348 CryptoPP::AutoSeededX917RNG<CryptoPP::DES_EDE3> rng;
349 byte abyBuffer[MAXPUBKEYSIZE+9];
350 uint32 keylen = pTarget->GetSecIDKeyLen();
351 memcpy(abyBuffer,pTarget->GetSecureIdent(),keylen);
352 // 4 additional bytes random data send from this client
353 uint32 challenge = pTarget->m_dwCryptRndChallengeFrom;
354 wxASSERT ( challenge != 0 );
355 PokeUInt32(abyBuffer+keylen,challenge);
357 uint16 ChIpLen = 0;
358 if ( byChaIPKind != 0){
359 ChIpLen = 5;
360 PokeUInt32(abyBuffer+keylen+4, ChallengeIP);
361 PokeUInt8(abyBuffer+keylen+4+4,byChaIPKind);
363 signer->SignMessage(rng, abyBuffer ,keylen+4+ChIpLen , sbbSignature.begin());
364 CryptoPP::ArraySink asink(pachOutput, nMaxSize);
365 asink.Put(sbbSignature.begin(), sbbSignature.size());
367 return asink.TotalPutLength();
368 } catch (const CryptoPP::Exception& e) {
369 AddDebugLogLineM(true, logCredits, wxString(wxT("Error while creating signature: ")) + char2unicode(e.what()));
370 wxFAIL;
372 return 0;
377 bool CClientCreditsList::VerifyIdent(CClientCredits* pTarget, const byte* pachSignature, uint8 nInputSize, uint32 dwForIP, uint8 byChaIPKind)
379 wxASSERT( pTarget );
380 wxASSERT( pachSignature );
381 if ( !CryptoAvailable() ){
382 pTarget->SetIdentState(IS_NOTAVAILABLE);
383 return false;
385 bool bResult;
386 try {
387 CryptoPP::StringSource ss_Pubkey((byte*)pTarget->GetSecureIdent(),pTarget->GetSecIDKeyLen(),true,0);
388 CryptoPP::RSASSA_PKCS1v15_SHA_Verifier pubkey(ss_Pubkey);
389 // 4 additional bytes random data send from this client +5 bytes v2
390 byte abyBuffer[MAXPUBKEYSIZE+9];
391 memcpy(abyBuffer,m_abyMyPublicKey,m_nMyPublicKeyLen);
392 uint32 challenge = pTarget->m_dwCryptRndChallengeFor;
393 wxASSERT ( challenge != 0 );
394 PokeUInt32(abyBuffer+m_nMyPublicKeyLen, challenge);
396 // v2 security improvments (not supported by 29b, not used as default by 29c)
397 uint8 nChIpSize = 0;
398 if (byChaIPKind != 0){
399 nChIpSize = 5;
400 uint32 ChallengeIP = 0;
401 switch (byChaIPKind){
402 case CRYPT_CIP_LOCALCLIENT:
403 ChallengeIP = dwForIP;
404 break;
405 case CRYPT_CIP_REMOTECLIENT:
406 // Ignore local ip...
407 if (!theApp->GetPublicIP(true)) {
408 if (::IsLowID(theApp->GetED2KID())){
409 AddDebugLogLineM( false, logCredits, wxT("Warning: Maybe SecureHash Ident fails because LocalIP is unknown"));
410 // Fallback to local ip...
411 ChallengeIP = theApp->GetPublicIP();
412 } else {
413 ChallengeIP = theApp->GetED2KID();
415 } else {
416 ChallengeIP = theApp->GetPublicIP();
418 break;
419 case CRYPT_CIP_NONECLIENT: // maybe not supported in future versions
420 ChallengeIP = 0;
421 break;
423 PokeUInt32(abyBuffer+m_nMyPublicKeyLen+4, ChallengeIP);
424 PokeUInt8(abyBuffer+m_nMyPublicKeyLen+4+4, byChaIPKind);
426 //v2 end
428 bResult = pubkey.VerifyMessage(abyBuffer, m_nMyPublicKeyLen+4+nChIpSize, pachSignature, nInputSize);
429 } catch (const CryptoPP::Exception& e) {
430 AddDebugLogLineM(true, logCredits, wxString(wxT("Error while verifying identity: ")) + char2unicode(e.what()));
431 bResult = false;
434 if (!bResult){
435 if (pTarget->GetIdentState() == IS_IDNEEDED)
436 pTarget->SetIdentState(IS_IDFAILED);
437 } else {
438 pTarget->Verified(dwForIP);
441 return bResult;
445 bool CClientCreditsList::CryptoAvailable() const
447 return m_nMyPublicKeyLen > 0 && m_pSignkey != NULL;
451 #ifdef _DEBUG
452 bool CClientCreditsList::Debug_CheckCrypting(){
453 // create random key
454 CryptoPP::AutoSeededX917RNG<CryptoPP::DES_EDE3> rng;
456 CryptoPP::RSASSA_PKCS1v15_SHA_Signer priv(rng, 384);
457 CryptoPP::RSASSA_PKCS1v15_SHA_Verifier pub(priv);
459 byte abyPublicKey[80];
460 CryptoPP::ArraySink asink(abyPublicKey, 80);
461 pub.DEREncode(asink);
462 int8 PublicKeyLen = asink.TotalPutLength();
463 asink.MessageEnd();
464 uint32 challenge = rand();
465 // create fake client which pretends to be this emule
466 CreditStruct* newcstruct = new CreditStruct();
467 CClientCredits newcredits(newcstruct);
468 newcredits.SetSecureIdent(m_abyMyPublicKey,m_nMyPublicKeyLen);
469 newcredits.m_dwCryptRndChallengeFrom = challenge;
470 // create signature with fake priv key
471 byte pachSignature[200];
472 memset(pachSignature,0,200);
473 uint8 sigsize = CreateSignature(&newcredits,pachSignature,200,0,false, &priv);
476 // next fake client uses the random created public key
477 CreditStruct* newcstruct2 = new CreditStruct();
478 CClientCredits newcredits2(newcstruct2);
479 newcredits2.m_dwCryptRndChallengeFor = challenge;
481 // if you uncomment one of the following lines the check has to fail
482 //abyPublicKey[5] = 34;
483 //m_abyMyPublicKey[5] = 22;
484 //pachSignature[5] = 232;
486 newcredits2.SetSecureIdent(abyPublicKey,PublicKeyLen);
488 //now verify this signature - if it's true everything is fine
489 return VerifyIdent(&newcredits2,pachSignature,sigsize,0,0);
491 #endif
492 // File_checked_for_headers