LicenseManager.cc 17.4 KB
Newer Older
1
/*===========================================================================*\
Jan Möbius's avatar
Jan Möbius committed
2
3
*                                                                            *
*                              OpenFlipper                                   *
Jan Möbius's avatar
Jan Möbius committed
4
*      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen       *
Jan Möbius's avatar
Jan Möbius committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
*                           www.openflipper.org                              *
*                                                                            *
*--------------------------------------------------------------------------- *
*  This file is part of OpenFlipper.                                         *
*                                                                            *
*  OpenFlipper is free software: you can redistribute it and/or modify       *
*  it under the terms of the GNU Lesser General Public License as            *
*  published by the Free Software Foundation, either version 3 of            *
*  the License, or (at your option) any later version with the               *
*  following exceptions:                                                     *
*                                                                            *
*  If other files instantiate templates or use macros                        *
*  or inline functions from this file, or you compile this file and          *
*  link it with other files to produce an executable, this file does         *
*  not by itself cause the resulting executable to be covered by the         *
*  GNU Lesser General Public License. This exception does not however        *
*  invalidate any other reasons why the executable file might be             *
*  covered by the GNU Lesser General Public License.                         *
*                                                                            *
*  OpenFlipper 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 Lesser General Public License for more details.                       *
*                                                                            *
*  You should have received a copy of the GNU LesserGeneral Public           *
*  License along with OpenFlipper. If not,                                   *
*  see <http://www.gnu.org/licenses/>.                                       *
*                                                                            *
33
34
35
\*===========================================================================*/

/*===========================================================================*\
Jan Möbius's avatar
Jan Möbius committed
36
37
38
39
40
*                                                                            *
*   $Revision$                                                       *
*   $LastChangedBy$                                                *
*   $Date$                     *
*                                                                            *
41
\*===========================================================================*/
42

Jan Möbius's avatar
Jan Möbius committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59


/*
License File format:

0:    Signature     over all other entries
1:    Expiry date
2:    Plugin filename
3:    coreHash
4:    pluginHash
5:    cpuHash
6:    windowsProductId (Windows only otherwise filled with "-" before hashing)
7..?: mac Address hashes

*/


Jan Möbius's avatar
Jan Möbius committed
60
61
62
63
64
65
// Windows required to get network address infos
#ifdef WIN32
  #include <winsock2.h>
  #include <iphlpapi.h>
  #pragma comment(lib, "IPHLPAPI.lib")
#endif
Jan Möbius's avatar
Jan Möbius committed
66

Jan Möbius's avatar
Jan Möbius committed
67
68
69
70
#ifdef ARCH_DARWIN
  #include <sys/types.h>
  #include <sys/sysctl.h>
#endif
Jan Möbius's avatar
Jan Möbius committed
71
72


73
74
75
76
77
78
#include <OpenFlipper/LicenseManager/LicenseManager.hh>
#include <OpenFlipper/common/GlobalOptions.hh>
#include <QFile>
#include <QCryptographicHash>
#include <QNetworkInterface>

Jan Möbius's avatar
Jan Möbius committed
79

80
81


82
83
84
85
86
87
88
89
LicenseManager::~LicenseManager() 
{ 
  exit(0); 
}

LicenseManager::LicenseManager()
{
  authenticated_ = false;
Jan Möbius's avatar
Jan Möbius committed
90
91
  
  // On startup, block all signals by default until the plugin is authenticated!
92
93
94
  QObject::blockSignals( true );
}

Jan Möbius's avatar
Jan Möbius committed
95
96
// Override default block signals. Transparent if authenticated, otherwise
// the function will always block the signals automatically
97
void LicenseManager::blockSignals( bool _state) {
Jan Möbius's avatar
Jan Möbius committed
98

99
100
101
102
103
104
105
106
  if ( !authenticated() ) {
    QObject::blockSignals( true );
  } else {
    QObject::blockSignals(_state);
  }

}

Jan Möbius's avatar
Jan Möbius committed
107
// Plugin authentication function.
108
bool LicenseManager::authenticate() {
109

Jan Möbius's avatar
Jan Möbius committed
110
  // Construct license string (will be cleaned up if license valid)
111
112
  authstring_ = "==\n";
  authstring_ += "PluginName: " + pluginFileName() + "\n";
113
114
  
  // ===============================================================================================
Jan Möbius's avatar
Jan Möbius committed
115
  // Compute hash value of Core application binary
116
117
118
  // ===============================================================================================

  #ifdef WIN32
Jan Möbius's avatar
Jan Möbius committed
119
    QFile coreApp(OpenFlipper::Options::applicationDirStr() + QDir::separator() + "OpenFlipper.exe");
Jan Möbius's avatar
Jan Möbius committed
120
121
122
123
124
  #elif defined ARCH_DARWIN
    QFile coreApp(OpenFlipper::Options::applicationDirStr() + QDir::separator() + ".." + 
                                                              QDir::separator() + "MacOS"+
							      QDir::separator() + "OpenFlipper");
  #else 
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    QFile coreApp(OpenFlipper::Options::applicationDirStr() + QDir::separator() + "bin" + QDir::separator() + "OpenFlipper");
  #endif

  if ( ! coreApp.exists() ) {
    std::cerr << "Error finding core application for security check! : " << coreApp.fileName().toStdString() << std::endl;
    return false;
  }

  coreApp.open(QIODevice::ReadOnly);
  QCryptographicHash sha1sumCore( QCryptographicHash::Sha1 );
  sha1sumCore.addData(coreApp.readAll() );
  coreApp.close();

  QString coreHash = QString(sha1sumCore.result().toHex());
  

  // ===============================================================================================
Jan Möbius's avatar
Jan Möbius committed
142
  // Compute hash of Plugin binary
143
144
145
146
  // ===============================================================================================

  #ifdef WIN32
    QFile pluginFile(OpenFlipper::Options::pluginDirStr() + QDir::separator() + pluginFileName() + ".dll");
Jan Möbius's avatar
Jan Möbius committed
147
148
  #elif defined ARCH_DARWIN
    QFile pluginFile(OpenFlipper::Options::pluginDirStr() + QDir::separator() + "lib" + pluginFileName() + ".so");
149
  #else
Jan Möbius's avatar
Jan Möbius committed
150
    QFile pluginFile(OpenFlipper::Options::pluginDirStr() + QDir::separator() + "lib" + pluginFileName() + ".so");
151
152
153
154
  #endif

  if ( ! pluginFile.exists() ) {
    std::cerr << "Error finding plugin file for security check!" << std::endl;
Jan Möbius's avatar
Jan Möbius committed
155
    std::cerr << "Path: " << pluginFile.fileName().toStdString() << std::endl;
156
157
158
159
160
161
162
163
164
165
    return false;
  }

  pluginFile.open(QIODevice::ReadOnly);
  QCryptographicHash sha1sumPlugin( QCryptographicHash::Sha1 );
  sha1sumPlugin.addData(pluginFile.readAll());
  pluginFile.close();

  QString pluginHash = QString(sha1sumPlugin.result().toHex());

Jan Möbius's avatar
Jan Möbius committed
166
167
168
  // ===============================================================================================
  // Compute hash of network interfaces
  // ===============================================================================================  
169

Jan Möbius's avatar
Jan Möbius committed
170
  QStringList macHashes;
171

172
173
#ifdef WIN32

Jan Möbius's avatar
Jan Möbius committed
174
175
  #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
  #define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
176
177

  // Pointer for iterating over adapters
Jan Möbius's avatar
Jan Möbius committed
178
179
180
181
  PIP_ADAPTER_ADDRESSES pAddresses = NULL;

  // Length of the buffer to get information
  ULONG outBufLen = 0;
182
183

  // Allocate enough for one info struct
Jan Möbius's avatar
Jan Möbius committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
  outBufLen = sizeof (IP_ADAPTER_ADDRESSES);
  pAddresses = (IP_ADAPTER_ADDRESSES *) MALLOC(outBufLen);

  // default to unspecified address family ( get all interfaces .. 4 and 6)
  ULONG family = AF_UNSPEC;

  // Set the flags to pass to GetAdaptersAddresses
  ULONG flags = GAA_FLAG_INCLUDE_PREFIX;

  // Make an initial call to GetAdaptersAddresses to get the 
  // size needed into the outBufLen variable
  if (GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen) == ERROR_BUFFER_OVERFLOW) {
      FREE(pAddresses);
      pAddresses = (IP_ADAPTER_ADDRESSES *) MALLOC(outBufLen);
  }

  // If we allocated the required memory
  if (pAddresses != NULL) {
    
    // Get the required info
    DWORD dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);

    if (dwRetVal == NO_ERROR) {
        
      // pointer to iterate over all available structs .. initialize to first one
      PIP_ADAPTER_ADDRESSES pCurrAddresses = pAddresses;

      while (pCurrAddresses) {

        // Check if this device contains a mac
        if (pCurrAddresses->PhysicalAddressLength != 0) {
          QString currentMac = "";
          
          for (uint i = 0; i < pCurrAddresses->PhysicalAddressLength; i++) {
            
            currentMac += QString("%1").arg( (int) pCurrAddresses->PhysicalAddress[i] , 2 ,16,QChar('0'));
            
            if (i != (pCurrAddresses->PhysicalAddressLength - 1))
              currentMac +=":";
          }

Jan Möbius's avatar
Jan Möbius committed
225
226
227
228
          // Ignore non ethernet macs with more than 5 blocks
          // Only check ethernet and wireless interfaces
          if ( (currentMac.count(":") == 5) && 
               ( pCurrAddresses->IfType == IF_TYPE_IEEE80211 || pCurrAddresses->IfType == IF_TYPE_ETHERNET_CSMACD )  ) {
Jan Möbius's avatar
Jan Möbius committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
                // Cleanup and remember mac adress
                currentMac = currentMac.toAscii().toUpper();
                currentMac = currentMac.remove(":");
                macHashes.push_back(currentMac);
          }

        }

        // Next interface
        pCurrAddresses = pCurrAddresses->Next;
      }
      
    }

  }

  FREE(pAddresses);
246
247
248

#else

249
250
  // Get all Network Interfaces
  QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
Jan Möbius's avatar
Jan Möbius committed
251
  foreach ( QNetworkInterface netInterface, interfaces ) {
Jan Möbius's avatar
Jan Möbius committed
252
    
Jan Möbius's avatar
Jan Möbius committed
253
254
    // Ignore loopback interfaces
    if ( ( netInterface.flags() & QNetworkInterface::IsLoopBack ) ) {
255
      continue;
Jan Möbius's avatar
Jan Möbius committed
256
    }
257
    
Jan Möbius's avatar
Jan Möbius committed
258
259
260
261
262
263
264
265
    // Ignore non ethernet macs
    if ( netInterface.hardwareAddress().count(":") != 5 ) {
      continue;
    }

    // Cleanup mac adress
    QString currentMac = netInterface.hardwareAddress().toAscii().toUpper();
    currentMac = currentMac.remove(":");
Jan Möbius's avatar
Jan Möbius committed
266
    
Jan Möbius's avatar
Jan Möbius committed
267
    macHashes.push_back(currentMac);
268
  }
269

270
#endif
Jan Möbius's avatar
Jan Möbius committed
271
272


Jan Möbius's avatar
Jan Möbius committed
273
  // cleanup the list from duplicates (virtual interfaces on windows connected to an existing device ... )
Jan Möbius's avatar
Jan Möbius committed
274
  macHashes.removeDuplicates();
275

Jan Möbius's avatar
Jan Möbius committed
276
277
278
  // generate hashes
  for (int i = 0 ; i < macHashes.size(); ++i ) 
    macHashes[i] = QCryptographicHash::hash ( macHashes[i].toAscii() , QCryptographicHash::Sha1 ).toHex();  
279

280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
  // ===============================================================================================
  // Compute hash of processor information
  // ===============================================================================================  

  QString processor = "Unknown";

  #ifdef WIN32
    QSettings registryCPU("HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor", QSettings::NativeFormat);

    QStringList cpus = registryCPU.childGroups(); 
    if ( cpus.size() != 0 ) { 
      processor = registryCPU.value( cpus[0]+"/ProcessorNameString", "Unknown" ).toString();
    } 

  #elif defined ARCH_DARWIN 

    size_t lenCPU;
    char *pCPU;
    
    // First call to get required size
    sysctlbyname("machdep.cpu.brand_string", NULL, &lenCPU, NULL, 0);
    
    // allocate
    pCPU = (char * )malloc(lenCPU);
    
    // Second call to get data
    sysctlbyname("machdep.cpu.brand_string", pCPU, &lenCPU, NULL, 0);
    
    // Output
    processor = QString(pCPU);
    
    // free memory
    delete pCPU;

  #else
    QFile cpuinfo("/proc/cpuinfo");
    if ( cpuinfo.exists() ) {   
      cpuinfo.open(QFile::ReadOnly);
      QTextStream stream(&cpuinfo);
      QStringList splitted = stream.readAll().split("\n",QString::SkipEmptyParts);
      
Jan Möbius's avatar
Jan Möbius committed
321
      int position = splitted.indexOf ( QRegExp("^model name.*") );
322
323
      if ( position != -1 ){
        QString cpuModel = splitted[position].section(':', -1).simplified();
Jan Möbius's avatar
Jan Möbius committed
324
        processor = cpuModel;
325
326
327
328
329
330
      } 
    }
  #endif

  QString cpuHash = QCryptographicHash::hash ( processor.toAscii()  , QCryptographicHash::Sha1 ).toHex();

Jan Möbius's avatar
Jan Möbius committed
331
332
333
334
335
336
337
  // ===============================================================================================
  // Get windows product id
  // =============================================================================================== 
  
  QString productId = "-";
  
  #ifdef WIN32
338
    QSettings registryProduct("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", QSettings::NativeFormat);
Jan Möbius's avatar
Jan Möbius committed
339
340
341
342
    productId = registryProduct.value( "ProductId", "Unknown" ).toString();
  #endif
  
  QString productHash = QCryptographicHash::hash ( productId.toAscii()  , QCryptographicHash::Sha1 ).toHex();
343
344
345
346

  // ===============================================================================================
  // Check License or generate request
  // =============================================================================================== 
347

Jan Möbius's avatar
Jan Möbius committed
348
349
  QString saltPre;
  ADD_SALT_PRE(saltPre);
Jan Möbius's avatar
Jan Möbius committed
350
  
Jan Möbius's avatar
Jan Möbius committed
351
352
353
  QString saltPost;
  ADD_SALT_POST(saltPost);

Jan Möbius's avatar
Jan Möbius committed
354
  QString licenseFileName = OpenFlipper::Options::licenseDirStr() + QDir::separator() + pluginFileName() + ".lic";
Jan Möbius's avatar
Jan Möbius committed
355
356
357
  QFile file( licenseFileName );

  if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) {
Jan Möbius's avatar
Jan Möbius committed
358
    QMessageBox::critical(0,tr("Unable to find license File"),licenseFileName );
Jan Möbius's avatar
Jan Möbius committed
359
360
  } else {
    QString licenseContents = file.readAll();
361
    QStringList elements = licenseContents.split('\n',QString::SkipEmptyParts);
Jan Möbius's avatar
Jan Möbius committed
362

Jan Möbius's avatar
Jan Möbius committed
363
    // simplify license file entries
Jan Möbius's avatar
Jan Möbius committed
364
365
    for ( int i = 0 ; i < elements.size(); ++i )
      elements[i] = elements[i].simplified();
Jan Möbius's avatar
Jan Möbius committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
    
    // Check the signature of the file (excluding first element as this is the signature itself)
    QString license = saltPre;
    for ( int i = 1 ; i < elements.size(); ++i )
      license += elements[i];
    license += saltPost;
    QString licenseHash = QCryptographicHash::hash ( license.toAscii()  , QCryptographicHash::Sha1 ).toHex();
    bool signatureOk = licenseHash == elements[0];

    // Check expiry date
    QDate currentDate = QDate::currentDate();
    QDate expiryDate  = QDate::fromString(elements[1],Qt::ISODate);
    bool expired = (currentDate > expiryDate);
    
    // Get number of available mac adresses
    QStringList licensedMacs;
    for ( int i = 7 ; i < elements.size(); ++i ) {
      licensedMacs.push_back(elements[i]);
    }
    
    bool macFound = false;
    for ( int i = 0; i < macHashes.size(); ++i ) {
388
      if ( licensedMacs.contains(macHashes[i]) ) 
Jan Möbius's avatar
Jan Möbius committed
389
        macFound = true;
Jan Möbius's avatar
Jan Möbius committed
390
    }
Jan Möbius's avatar
Jan Möbius committed
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
    
    if ( !signatureOk ) {
      authstring_ += tr("License Error: The license file signature for Plugin \"") + name() + tr("\" is invalid!\n\n");
    } else if ( expired ) {
      authstring_ += tr("License Error: The license for plugin \"") + name() + tr("\" has expired on ") + elements[1] + "!\n\n";       
    } else if ( elements[2] != pluginFileName() ) {
      authstring_ += tr("License Error: The license file contains plugin name\"") + elements[2] + tr("\" but this is plugin \"") + name() + "\"!\n\n";
    } else if ( elements[3] != coreHash ) {
      authstring_ += tr("License Error: The license file for plugin \"") + name() + tr("\" is invalid for the currently running OpenFlipper Core!\n\n");
    } else if ( elements[4] != pluginHash ) {
      authstring_ += tr("License Error: The plugin \"") + name() + tr("\" is a different version than specified in license file!\n\n");
    } else if ( elements[5] != cpuHash ) {
      authstring_ += "License Error: The plugin \"" + name() + "\" is not allowed to run on the current system (Changed CPU?)!\n\n";       
    } else if ( elements[6] != productHash ) {
      authstring_ += "License Error: The plugin \"" + name() + "\" is not allowed to run on the current system (Changed OS?)!\n\n";       
    } else if ( !macFound ) {
      authstring_ += "License Error: The plugin \"" + name() + "\" is not allowed to run on the current system (Changed Network?)!\n\n";
    } else {
      authenticated_ = true;
    }
    
    // Clean it on success
    if (  authenticated_ ) 
      authstring_ = "";
      
Jan Möbius's avatar
Jan Möbius committed
416
417
  }

Jan Möbius's avatar
Jan Möbius committed
418
419
420
  if ( authenticated_ ) {
    blockSignals(false);
  } else {
421
422
423
424
425
426
427
    authstring_ += tr("Message: License check for plugin failed.\n");
    authstring_ += tr("Message: Please get a valid License!\n");
    authstring_ += tr("Message: Send the following Information to \n");
    authstring_ += tr("Contact mail: ") + CONTACTMAIL + "\n\n";
    authstring_ += pluginFileName() +"\n";
    authstring_ += coreHash +"\n";
    authstring_ += pluginHash +"\n";
428
    authstring_ += cpuHash +"\n";
Jan Möbius's avatar
Jan Möbius committed
429
430
431
432
    authstring_ += productHash +"\n";
    
    for ( int i = 0 ; i < macHashes.size(); ++i )  
      authstring_ += macHashes[i] +"\n";
Jan Möbius's avatar
Jan Möbius committed
433

Jan Möbius's avatar
Jan Möbius committed
434
    QString keyRequest = saltPre + pluginFileName() + coreHash + pluginHash + cpuHash + productHash + macHashes.join("") +  saltPost;
Jan Möbius's avatar
Jan Möbius committed
435
    QString requestSig = QCryptographicHash::hash ( keyRequest.toAscii()  , QCryptographicHash::Sha1 ).toHex();
436
    authstring_ += requestSig + "\n";
Jan Möbius's avatar
Jan Möbius committed
437

Jan Möbius's avatar
Jan Möbius committed
438
    authenticated_ = false;
439
440
441
442
443
  }

  return authenticated_;
}

444
445
446
447
QString LicenseManager::licenseError() {
  return authstring_;
}

448
bool LicenseManager::authenticated() {
Jan Möbius's avatar
Jan Möbius committed
449
  // Function to check if the plugin is authenticated
450
451
452
453
  return authenticated_;
}

void LicenseManager::connectNotify ( const char * /*signal*/ ) {
Jan Möbius's avatar
Jan Möbius committed
454
455
456

  // if the plugin is not authenticated and something wants to connect, we block all signals and force a direct disconnect
  // here, rendering all signal/slot connections useless.
457
458
  if ( !authenticated() ) {
    blockSignals(true);
Jan Möbius's avatar
Jan Möbius committed
459
    disconnect();
460
  }
Jan Möbius's avatar
Jan Möbius committed
461
  
462
463
464
}

QString LicenseManager::pluginFileName() {
Jan Möbius's avatar
Jan Möbius committed
465
466
467
468
  // FileName of the plugin. has to be set via the salt file
  QString pluginFileName;
  ADD_PLUGIN_FILENAME(pluginFileName);
  return pluginFileName;
469
470
}