Exemple #1
0
//============================================================
// Calculates and stores a signature for this SignatureInfo object
// Uses EstEID card to sign the info
// pSigInfo - signature info object
// nSigType - signature type code
// keyfile - RSA key file
// passwd - key password
// certfile - certificate file
//============================================================
EXP_OPTION int calculateSignatureWithEstID(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, 
                    int slot, const char* passwd)
{
  int err = ERR_OK, nKey;
  LIBHANDLE pLibrary = 0;
  CK_ULONG certLen, sigLen, padDigLen;
  CK_RV rv;
  CK_SLOT_ID slotids[20], slId = 0;
  CK_SESSION_HANDLE hSession = 0;
  CK_OBJECT_HANDLE hPrivateKey, hKeys[20], hCert;
  char keyId[20][20];
  CK_ULONG keyIdLen[20];
  CK_BYTE certData[2048];
  CK_BYTE sigDig[100], padDig[130];
  CK_BYTE signature[256];
  CK_BYTE padding[] = { 48, 33, 48, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0, 4, 20 };
	CK_BYTE padding256[] = { 48, 49, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
	//CK_BYTE padding256[] = { 48, 33, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
  char* buf1;
  int l1, l2;
  X509* x509;
  DigiDocMemBuf mbuf1;

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(pSigDoc);
  // try active driver driver first
  snprintf((char*)signature, sizeof(signature), "DIGIDOC_DRIVER_%d_FILE", 
	  ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1));
  for(l1 = 0; l1 < 20; l1++) 
    slotids[l1] = INVALID_SLOTIID; // initialize
  err = loadAndTestDriver(ConfigItem_lookup((const char*)signature),
			  &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot);
  ddocDebug(3, "calculateSignatureWithEstID", "Driver handle: %d err = %d slot: %d", 
	    pLibrary, err, slot);
  RETURN_IF_NOT(err == ERR_OK, err);
  // inittialize
  slId = INVALID_SLOTIID; // not found yet
  //err = ddocLocateSlotWithSignatureCert(pLibrary, slotids, 
  //					&slId, (char*)signature, sizeof(signature));
  
  // find suitable slotid
  
  for(l1 = 0; l1 < 20; l1++) {
    if(slotids[l1] != INVALID_SLOTIID)
      ddocDebug(3, "calculateSignatureWithEstID", 
		"Slot idx: %d = %d", l1, slotids[l1]);
    if(slotids[l1] != INVALID_SLOTIID && l1 == slot) {
      slId = slotids[l1];
      ddocDebug(3, "calculateSignatureWithEstID", 
		"Select idx: %d slot: %d", l1, slId);
    }
  }
  
  // open session
  if(slId != INVALID_SLOTIID) {
    hSession = OpenSession(slId, passwd);
    ddocDebug(3, "calculateSignatureWithEstID", 
	      "Open sess for slot: %d sess = %uld\n", slId, hSession);
    if (hSession == CK_INVALID_HANDLE) { err = ERR_PKCS_LOGIN; SET_LAST_ERROR(err); return err; }
    ddocDebug(3, "calculateSignatureWithEstID", "OpenSession ok, hSession = %d\n", (int)hSession);

    // get private key
    for(l1 = 0; l1 < 20; l1++) {
      memset(keyId[l1], 0, 20);
      keyIdLen[l1] = 0;
    }
    err = LocatePrivateKey(hSession, keyId, keyIdLen, hKeys);
    //ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %s", keyId);
    //if (hPrivateKey == CK_INVALID_HANDLE) { err = ERR_PKCS_PK; SET_LAST_ERROR(err); return err; }

    // get cert     
    memset(certData, 0, sizeof(certData));  
    certLen = sizeof(certData);
    hCert = LocateCertificate(hSession, certData, &certLen, keyId, keyIdLen, &nKey);
    hPrivateKey = hKeys[nKey];
    ddocDebug(3, "calculateSignatureWithEstID", "selected priv-key: %ld pos %d id: %s", hPrivateKey, nKey, keyId[nKey]);
    ddocDebug(3, "calculateSignatureWithEstID", "Cert-len: %ld", certLen);
    //printf("Cert: %s", certData);
    if (hCert == (CK_OBJECT_HANDLE)-1) { err = ERR_PKCS_CERT_LOC; SET_LAST_ERROR(err); return err; }

    // set cert data
    err = ddocDecodeX509Data(&x509, certData, certLen);
    if (!x509) { err = ERR_PKCS_CERT_DECODE;  }
	  // save cert in file
	  if(ConfigItem_lookup_int("DEBUG_LEVEL", 1) > 3)
	  saveCert(x509, "signer.pem", FILE_FORMAT_PEM);
		//AM 07.03.08 setSignatureCert for BDOC
		if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME)) { 
				setSignatureCertBDOC(pSigInfo, x509);
		}else{
				setSignatureCert(pSigInfo, x509);
		}

		//AM 12.03.08
		//VS 23.02.2010 - not necessary?
		/*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME)) { 
		findCAForCertificate(&ppCA, x509);
		err = bdocSigInfo_addCert(pSigInfo, ppCA, CERTID_TYPE_CA_CERTID);
		}*/ 

    // FIXME
    createTimestamp(pSigDoc, (char*)sigDig, sizeof(sigDig));
    setString((char**)&(pSigInfo->szTimeStamp), (const char*)sigDig, -1);

    // Signed properties digest
    buf1 = createXMLSignedProperties(pSigDoc, pSigInfo, 0);
    //dumpInFile("sigprop-sign1.txt", buf1);
    if (!buf1) { 
      err = ERR_NULL_POINTER; 
      SET_LAST_ERROR(err);
      return err;
    }
    mbuf1.pMem = canonicalizeXML((char*)buf1, strlen(buf1));
    mbuf1.nLen = strlen((const char*)mbuf1.pMem);
    ddocDebugWriteFile(4, "sigprop-signed.txt", &mbuf1);
    l2 = sizeof(sigDig);
	//AM 24.04.08
	if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME))
		err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, BDOC_DIGEST, sigDig, &l2);
	else
		err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    ddocMemBuf_free(&mbuf1);
    if (err != ERR_OK) {
      SET_LAST_ERROR(err);			
      return err;
    }
    ddocSigInfo_SetSigPropDigest(pSigInfo, (const char*)sigDig, l2);
    ddocSigInfo_SetSigPropRealDigest(pSigInfo, (const char*)sigDig, l2);
    // create signed info
	//AM 11.03.08 createXMLSignedInfo for BDOC
	if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME))
		buf1 = createXMLSignedInfoBDoc(pSigDoc, pSigInfo);
	else
		buf1 = createXMLSignedInfo(pSigDoc, pSigInfo);      
    if (!buf1) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err ;
    }
    // get digest
    l2 = sizeof(sigDig);
	/*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME))
		err = calculateDigest((const byte*)buf1, strlen(buf1),  BDOC_DIGEST, sigDig, &l2);
	else*/
		err = calculateDigest((const byte*)buf1, strlen(buf1),  DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    if (err != ERR_OK) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err;
    } 
    ddocSigInfo_SetSigInfoRealDigest(pSigInfo, (const char*)sigDig, l2);
    // sign data
    sigLen = sizeof(signature);
    memset(signature, 0, sizeof(signature));
    // pad PKCS#1 ver 1
    /*if(!strcmp(pSigDoc->szFormat, BDOC_XML_1_NAME) && BDOC_DIGEST==DIGEST_SHA256) {
		padDigLen = 51;
		memset(padDig, 0, sizeof(padDig));
		memcpy(padDig, padding256, 19);
		memcpy(padDig + 19, sigDig, l2);
	} else {*/
		padDigLen = 35;
		memset(padDig, 0, sizeof(padDig));
		memcpy(padDig, padding, 15);
		memcpy(padDig + 15, sigDig, l2);
	//}
    //rv = RSA_padding_add_PKCS1_type_1(padDig, padDigLen, sigDig, l2);
    //rv = RSA_padding_check_PKCS1_type_1(sigDig, l2, padDig, padDigLen, padDigLen+1);
    // checkErrors();
    // sign data
    rv = SignData(hSession, hPrivateKey, 
		  signature, &sigLen, padDig, padDigLen);    
    if (rv != CKR_OK) { 
      err = ERR_PKCS_SIGN_DATA;
      SET_LAST_ERROR(err);
      return err;
    }		

    // set signature value
    ddocSigInfo_SetSignatureValue(pSigInfo, (const char*)signature, (int)sigLen);
  } // if slotid found
    
  if(hSession)
    closePKCS11Library(pLibrary, hSession);
  return err;
}
Exemple #2
0
//============================================================
// Calculates and stores a signature for this SignatureInfo object
// Uses EstEID card to sign the info
// pSigInfo - signature info object
// nSigType - signature type code
// keyfile - RSA key file
// passwd - key password
// certfile - certificate file
//============================================================
EXP_OPTION int calculateSignatureWithEstID(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, 
                    int slot, const char* passwd)
{
  int err = ERR_OK, nKey;
  LIBHANDLE pLibrary = 0;
  CK_ULONG certLen, sigLen, padDigLen;
  CK_RV rv;
  CK_SLOT_ID slotids[20], slId = 0;
  CK_SESSION_HANDLE hSession = 0;
  CK_OBJECT_HANDLE hPrivateKey = 0, hKeys[20], hCert;
  char keyId[20][20], kId[20];
  CK_ULONG keyIdLen[20];
  CK_BYTE certData[2048];
  CK_BYTE sigDig[100], padDig[130];
  CK_BYTE signature[256];
  CK_BYTE padding[] = { 48, 33, 48, 9, 6, 5, 43, 14, 3, 2, 26, 5, 0, 4, 20 };
  //CK_BYTE padding256[] = { 48, 49, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
  //CK_BYTE padding256[] = { 48, 33, 48, 13, 6, 9, 96, 134, 72, 1 ,101, 3, 4, 2, 1, 5, 0, 4, 32};
  char* buf1;
  int l1, l2, kILen;
  X509* x509 = 0;
  DigiDocMemBuf mbuf1;

  RETURN_IF_NULL_PARAM(pSigInfo);
  RETURN_IF_NULL_PARAM(pSigDoc);
  // try active driver driver first
  snprintf((char*)signature, sizeof(signature), "DIGIDOC_DRIVER_%d_FILE", 
	  ConfigItem_lookup_int("DIGIDOC_DEFAULT_DRIVER", 1));
  for(l1 = 0; l1 < 20; l1++) 
    slotids[l1] = INVALID_SLOTIID; // initialize
  err = loadAndTestDriver(ConfigItem_lookup((const char*)signature),
			  &pLibrary, (CK_SLOT_ID*)slotids, 20, (CK_ULONG)slot);
  ddocDebug(3, "calculateSignatureWithEstID", "Driver handle: %d err = %d slot: %d", 
	    pLibrary, err, slot);
  RETURN_IF_NOT(err == ERR_OK, err);
  // inittialize
  slId = INVALID_SLOTIID; // not found yet  
  // try key-usage check
  if(ConfigItem_lookup_int("KEY_USAGE_CHECK", 1)) {
    kILen = sizeof(kId);
    ddocDebug(3, "calculateSignatureWithEstID", "Find slot by key-usage, slot: %d", slot);
    err = ddocLocateSlotWithSignatureCert(pLibrary, slotids, &slId, &x509, kId, &kILen, slot, &l1);
    ddocDebug(3, "calculateSignatureWithEstID", 
		"Select by key-usage slot idx: %d = %d err: %d key-id: %s, kid-len: %d", l1, slId, err, kId, kILen);
    if(err != ERR_OK || l1 < 0 || l1 >= 20) {
		SET_LAST_ERROR(ERR_SIGNERS_CERT_NON_REPU);
        return ERR_SIGNERS_CERT_NON_REPU;
	}
  } else {
    ddocDebug(3, "calculateSignatureWithEstID", "Find slot by slot idx: %d", slot);
    for(l1 = 0; (l1 < 20) && (slId == INVALID_SLOTIID); l1++) {
      if(slotids[l1] != INVALID_SLOTIID)
        ddocDebug(3, "calculateSignatureWithEstID", 
                        "Slot idx: %d = %d", l1, slotids[l1]);
      if(slotids[l1] != INVALID_SLOTIID && l1 == slot) {
        slId = slotids[l1];
        ddocDebug(3, "calculateSignatureWithEstID", 
                        "Select idx: %d slot: %d", l1, slId);
    } // if slotid
    } // for
  }
  // use default if not found by key-id or direct 
  if(slId == INVALID_SLOTIID) {
      l1 = ConfigItem_lookup_int("DIGIDOC_SIGNATURE_SLOT", 0);
      if(slotids[l1] != INVALID_SLOTIID) {
          ddocDebug(3, "calculateSignatureWithEstID", 
                    "Select default slot idx: %d = %d", l1, slotids[l1]);
          slId = slotids[l1];
      }
  }

  // open session
  if(slId != INVALID_SLOTIID) {
    hSession = OpenSession(slId, passwd);
    ddocDebug(3, "calculateSignatureWithEstID", 
	      "Open sess for slot: %d sess = %d", slId, hSession);
    if (hSession == CK_INVALID_HANDLE) { err = ERR_PKCS_LOGIN; SET_LAST_ERROR(err); return err; }
    ddocDebug(3, "calculateSignatureWithEstID", "OpenSession ok, hSession1 = %d", (int)hSession);

    if(!x509) {
		ddocDebug(3, "calculateSignatureWithEstID", "Cert ok");
      // get private key
      for(l1 = 0; l1 < 20; l1++) {
        memset(keyId[l1], 0, 20);
        keyIdLen[l1] = 0;
      }
      err = LocatePrivateKey(hSession, keyId, keyIdLen, hKeys);
      //ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %s", keyId);
      //

      // get cert  
      memset(certData, 0, sizeof(certData));  
      certLen = sizeof(certData);
      hCert = LocateCertificate(hSession, certData, &certLen, keyId, keyIdLen, &nKey);
      hPrivateKey = hKeys[nKey];
      ddocDebug(3, "calculateSignatureWithEstID", "selected priv-key: %ld pos %d id: %s", hPrivateKey, nKey, keyId[nKey]);
      ddocDebug(3, "calculateSignatureWithEstID", "Cert-len: %ld", certLen);
      //printf("Cert: %s", certData);
      if (hCert == (CK_OBJECT_HANDLE)-1) { err = ERR_PKCS_CERT_LOC; SET_LAST_ERROR(err); return err; }

      // set cert data
      err = ddocDecodeX509Data(&x509, certData, certLen);
      

    } else { // cert already found
		//kILen = sizeof(kId);
        ddocDebug(3, "calculateSignatureWithEstID", "Locate priv key2 id: %s, len: %d, hkey: %d", kId, kILen, hPrivateKey);
		err = LocatePrivateKeyWithId(hSession, (CK_BYTE_PTR)kId, kILen, &hPrivateKey);
		ddocDebug(3, "calculateSignatureWithEstID", "Priv key-id: %s len: %d hkey: %d err: %d", kId, kILen, hPrivateKey, err);
    }	 
	ddocDebug(3, "calculateSignatureWithEstID", "Priv key: %d err: %d", hPrivateKey, err);
    if (hPrivateKey == CK_INVALID_HANDLE) { err = ERR_PKCS_PK; SET_LAST_ERROR(err); return err; }
    if (!x509) { err = ERR_PKCS_CERT_DECODE;  }
      
   // save cert in file
   if(ConfigItem_lookup_int("DEBUG_LEVEL", 1) > 3) 
     saveCert(x509, "signer.pem", FILE_FORMAT_PEM);
   setSignatureCert(pSigInfo, x509);

    // FIXME
    createTimestamp(pSigDoc, (char*)sigDig, sizeof(sigDig));
    setString((char**)&(pSigInfo->szTimeStamp), (const char*)sigDig, -1);

    // Signed properties digest
    buf1 = createXMLSignedProperties(pSigDoc, pSigInfo, 0);
    //dumpInFile("sigprop-sign1.txt", buf1);
    if (!buf1) { 
      err = ERR_NULL_POINTER; 
      SET_LAST_ERROR(err);
      return err;
    }
    mbuf1.pMem = canonicalizeXML((char*)buf1, strlen(buf1));
    mbuf1.nLen = strlen((const char*)mbuf1.pMem);
    ddocDebugWriteFile(4, "sigprop-signed.txt", &mbuf1);
    l2 = sizeof(sigDig);
    err = calculateDigest((const byte*)mbuf1.pMem, mbuf1.nLen, DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    ddocMemBuf_free(&mbuf1);
    if (err != ERR_OK) {
      SET_LAST_ERROR(err);			
      return err;
    }
    ddocSigInfo_SetSigPropDigest(pSigInfo, (const char*)sigDig, l2);
    ddocSigInfo_SetSigPropRealDigest(pSigInfo, (const char*)sigDig, l2);
    // create signed info
    buf1 = createXMLSignedInfo(pSigDoc, pSigInfo);      
    if (!buf1) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err ;
    }
    // get digest
    l2 = sizeof(sigDig);
	err = calculateDigest((const byte*)buf1, strlen(buf1),  DIGEST_SHA1, sigDig, &l2);
    free(buf1);
    if (err != ERR_OK) {
      err = ERR_NULL_POINTER;
      SET_LAST_ERROR(err);
      return err;
    } 
    ddocSigInfo_SetSigInfoRealDigest(pSigInfo, (const char*)sigDig, l2);
    // sign data
    sigLen = sizeof(signature);
    memset(signature, 0, sizeof(signature));
    // pad PKCS#1 ver 1
	padDigLen = 35;
	memset(padDig, 0, sizeof(padDig));
	memcpy(padDig, padding, 15);
	memcpy(padDig + 15, sigDig, l2);
    //rv = RSA_padding_add_PKCS1_type_1(padDig, padDigLen, sigDig, l2);
    //rv = RSA_padding_check_PKCS1_type_1(sigDig, l2, padDig, padDigLen, padDigLen+1);
    // checkErrors();
    // sign data
    rv = SignData(hSession, hPrivateKey, 
		  signature, &sigLen, padDig, padDigLen);    
    if (rv != CKR_OK) { 
      err = ERR_PKCS_SIGN_DATA;
      SET_LAST_ERROR(err);
      return err;
    }		

    // set signature value
    ddocSigInfo_SetSignatureValue(pSigInfo, (const char*)signature, (int)sigLen);
	ddocDebug(3, "calculateSignatureWithEstID", "Sig-len: %ld", sigLen);
    
  } // if slotid found
    
  if(hSession)
    closePKCS11Library(pLibrary, hSession);
  return err;
}
void ConnectFriendWizard::initializePage(int id)
{
    switch ((Page) id) {
    case Page_Intro:
        ui->textRadioButton->setChecked(true);
        break;
    case Page_Text:
        connect(ui->userCertHelpButton, SIGNAL( clicked()), this, SLOT(showHelpUserCert()));
        connect(ui->userCertIncludeSignaturesButton, SIGNAL(clicked()), this, SLOT(toggleSignatureState()));
        connect(ui->userCertOldFormatButton, SIGNAL(clicked()), this, SLOT(toggleFormatState()));
        connect(ui->userCertCopyButton, SIGNAL(clicked()), this, SLOT(copyCert()));
        connect(ui->userCertSaveButton, SIGNAL(clicked()), this, SLOT(saveCert()));
        connect(ui->userCertMailButton, SIGNAL(clicked()), this, SLOT(runEmailClient()));
        connect(ui->friendCertEdit, SIGNAL(textChanged()), this, SLOT(friendCertChanged()));

        cleanfriendCertTimer = new QTimer(this);
        cleanfriendCertTimer->setSingleShot(true);
        cleanfriendCertTimer->setInterval(1000); // 1 second
        connect(cleanfriendCertTimer, SIGNAL(timeout()), this, SLOT(cleanFriendCert()));

        ui->userCertOldFormatButton->setChecked(true);

        toggleFormatState(false);
        toggleSignatureState(false);
        updateOwnCert();

        cleanFriendCert();

        break;
    case Page_Cert:
        connect(ui->userFileCreateButton, SIGNAL(clicked()), this, SLOT(generateCertificateCalled()));
        connect(ui->friendFileNameOpenButton, SIGNAL(clicked()), this, SLOT(loadFriendCert()));

        ui->friendFileNameEdit->setAcceptFile(true);

        ui->CertificatePage->registerField("friendCertificateFile*", ui->friendFileNameEdit);
        break;
    case Page_Foff:
        ui->userSelectionCB->addItem(tr("Any peer I've not signed"));
        ui->userSelectionCB->addItem(tr("Friends of my friends who already trust me"));
        ui->userSelectionCB->addItem(tr("Signed peers showing as denied"));

        ui->selectedPeersTW->setHorizontalHeaderItem(0, new QTableWidgetItem(tr("")));
        ui->selectedPeersTW->setHorizontalHeaderItem(1, new QTableWidgetItem(tr("Peer name")));
        ui->selectedPeersTW->setHorizontalHeaderItem(2, new QTableWidgetItem(tr("Also signed by")));
        ui->selectedPeersTW->setHorizontalHeaderItem(3, new QTableWidgetItem(tr("Peer id")));

        connect(ui->makeFriendButton, SIGNAL(clicked()), this, SLOT(signAllSelectedUsers()));
        connect(ui->userSelectionCB, SIGNAL(activated(int)), this, SLOT(updatePeersList(int)));

        updatePeersList(ui->userSelectionCB->currentIndex());

        ui->FofPage->setComplete(false);
        break;
    case Page_Rsid:
        ui->RsidPage->registerField("friendRSID*", ui->friendRsidEdit);
        break;
    case Page_Email:
        ui->EmailPage->registerField("addressEdit*", ui->addressEdit);
        ui->EmailPage->registerField("subjectEdit*", ui->subjectEdit);

        ui->subjectEdit->setText(tr("RetroShare Invitation"));
        ui->inviteTextEdit->setPlainText(GetStartedDialog::GetInviteText());

        break;
    case Page_ErrorMessage:
        break;
    case Page_Conclusion:
    {
        std::cerr << "Conclusion page id : " << peerDetails.id << "; gpg_id : " << peerDetails.gpg_id << std::endl;

        ui->_anonymous_routing_CB_2->setChecked(peerDetails.service_perm_flags & RS_SERVICE_PERM_TURTLE) ;
        ui->_discovery_CB_2        ->setChecked(peerDetails.service_perm_flags & RS_SERVICE_PERM_DISCOVERY) ;
        ui->_forums_channels_CB_2  ->setChecked(peerDetails.service_perm_flags & RS_SERVICE_PERM_DISTRIB) ;
        ui->_direct_transfer_CB_2  ->setChecked(peerDetails.service_perm_flags & RS_SERVICE_PERM_DIRECT_DL) ;

        RsPeerDetails tmp_det ;
        bool already_in_keyring = rsPeers->getPeerDetails(peerDetails.gpg_id, tmp_det) ;

        ui->addKeyToKeyring_CB->setChecked(true) ;
        ui->addKeyToKeyring_CB->setEnabled(!already_in_keyring) ;

        if(already_in_keyring)
            ui->addKeyToKeyring_CB->setToolTip(tr("This key is already in your keyring")) ;
        else
            ui->addKeyToKeyring_CB->setToolTip(tr("Check this to add the key to your keyring\nThis might be useful for sending\ndistant messages to this peer\neven if you don't make friends.")) ;

        //set the radio button to sign the GPG key
        if (peerDetails.accept_connection && !peerDetails.ownsign) {
            //gpg key connection is already accepted, don't propose to accept it again
            ui->signGPGCheckBox->setChecked(false);
            ui->acceptNoSignGPGCheckBox->hide();
            ui->acceptNoSignGPGCheckBox->setChecked(false);
        }
        if (!peerDetails.accept_connection && peerDetails.ownsign) {
            //gpg key is already signed, don't propose to sign it again
            ui->acceptNoSignGPGCheckBox->setChecked(true);
            ui->signGPGCheckBox->hide();
            ui->signGPGCheckBox->setChecked(false);
        }
        if (!peerDetails.accept_connection && !peerDetails.ownsign) {
            ui->acceptNoSignGPGCheckBox->setChecked(true);
            ui->signGPGCheckBox->show();
            ui->signGPGCheckBox->setChecked(false);
            ui->acceptNoSignGPGCheckBox->show();
        }
        if (peerDetails.accept_connection && peerDetails.ownsign) {
            ui->acceptNoSignGPGCheckBox->setChecked(false);
            ui->acceptNoSignGPGCheckBox->hide();
            ui->signGPGCheckBox->setChecked(false);
            ui->signGPGCheckBox->hide();
            ui->alreadyRegisteredLabel->show();
        } else {
            ui->alreadyRegisteredLabel->hide();
        }

        QString trustString;
        switch (peerDetails.validLvl) {
        case RS_TRUST_LVL_ULTIMATE:
            trustString = tr("Ultimate");
            break;
        case RS_TRUST_LVL_FULL:
            trustString = tr("Full");
            break;
        case RS_TRUST_LVL_MARGINAL:
            trustString = tr("Marginal");
            break;
        case RS_TRUST_LVL_NEVER:
            trustString = tr("None");
            break;
        default:
            trustString = tr("No Trust");
            break;
        }

        QString ts;
        std::list<std::string>::iterator it;
        for (it = peerDetails.gpgSigners.begin(); it != peerDetails.gpgSigners.end(); ++it) {
            {
                std::string peer_name = rsPeers->getPeerName(*it) ;

                // This is baaaad code. We should handle this kind of errors with proper exceptions.
                // This happens because signers from a unknown key cannt be found in the keyring, including
                // self-signatures.
                //
                if(peer_name == "[Unknown PGP Cert name]" && *it == peerDetails.gpg_id)
                    peer_name = peerDetails.name ;

                ts += QString("%1<%2>\n").arg(QString::fromUtf8(peer_name.c_str()), QString::fromStdString(*it));
            }
        }

        ui->nameEdit->setText(QString::fromUtf8(peerDetails.name.c_str()));
        ui->trustEdit->setText(trustString);
        ui->emailEdit->setText(QString::fromUtf8(peerDetails.email.c_str()));
        QString loc = QString::fromUtf8(peerDetails.location.c_str());
        if (!loc.isEmpty())
        {
            loc += " (";
            loc += QString::fromStdString(peerDetails.id);
            loc += ")";
        }
        else
        {
            if (!peerDetails.id.empty())
            {
                loc += QString::fromStdString(peerDetails.id);
            }
        }

        ui->locationEdit->setText(loc);
        ui->signersEdit->setPlainText(ts);

        fillGroups(this, ui->groupComboBox, groupId);
    }
    break;
    case Page_FriendRequest:
    {
        std::cerr << "Friend request page id : " << peerDetails.id << "; gpg_id : " << peerDetails.gpg_id << std::endl;

        ui->fr_avatar->setFrameType(AvatarWidget::NORMAL_FRAME);
        setPixmap(QWizard::LogoPixmap, QPixmap(":/images/user/user_request48.png"));

        //set the radio button to sign the GPG key
        if (peerDetails.accept_connection && !peerDetails.ownsign) {
            //gpg key connection is already accepted, don't propose to accept it again
            ui->fr_signGPGCheckBox->setChecked(false);
            ui->fr_acceptNoSignGPGCheckBox->hide();
            ui->fr_acceptNoSignGPGCheckBox->setChecked(false);
        }
        if (!peerDetails.accept_connection && peerDetails.ownsign) {
            //gpg key is already signed, don't propose to sign it again
            ui->fr_acceptNoSignGPGCheckBox->setChecked(true);
            ui->fr_signGPGCheckBox->hide();
            ui->fr_signGPGCheckBox->setChecked(false);
        }
        if (!peerDetails.accept_connection && !peerDetails.ownsign) {
            ui->fr_acceptNoSignGPGCheckBox->setChecked(true);
            ui->fr_signGPGCheckBox->show();
            ui->fr_signGPGCheckBox->setChecked(false);
            ui->fr_acceptNoSignGPGCheckBox->show();
        }
        if (peerDetails.accept_connection && peerDetails.ownsign) {
            ui->fr_acceptNoSignGPGCheckBox->setChecked(false);
            ui->fr_acceptNoSignGPGCheckBox->hide();
            ui->fr_signGPGCheckBox->setChecked(false);
            ui->fr_signGPGCheckBox->hide();
        }

        ui->fr_nameEdit->setText(QString::fromUtf8(peerDetails.name.c_str()));
        ui->fr_emailEdit->setText(QString::fromUtf8(peerDetails.email.c_str()));

        QString loc = QString::fromUtf8(peerDetails.location.c_str());
        if (!loc.isEmpty())
        {
            loc += " (";
            loc += QString::fromStdString(peerDetails.id);
            loc += ")";
        }
        else
        {
            if (!peerDetails.id.empty())
            {
                loc += QString::fromStdString(peerDetails.id);
            }
        }

        ui->fr_locationEdit->setText(loc);

        ui->fr_label->setText(tr("You have a friend request from") + " " + QString::fromUtf8(peerDetails.name.c_str()));

        fillGroups(this, ui->fr_groupComboBox, groupId);
    }
    break;
    case Page_FriendRecommendations:
        ui->frec_recommendList->setHeaderText(tr("Recommend friends"));
        ui->frec_recommendList->setModus(FriendSelectionWidget::MODUS_CHECK);
        ui->frec_recommendList->setShowType(FriendSelectionWidget::SHOW_GROUP | FriendSelectionWidget::SHOW_SSL);
        ui->frec_recommendList->start();

        ui->frec_toList->setHeaderText(tr("To"));
        ui->frec_toList->setModus(FriendSelectionWidget::MODUS_CHECK);
        ui->frec_toList->start();

        ui->frec_messageEdit->setText(MessageComposer::recommendMessage());
        break;
    }
}
Exemple #4
0
void LoginHandler::tlsStarted()
{
	QSslCertificate cert = m_server->hostCertificate();
	QString hostname = m_address.host();

	// Check if this is a trusted certificate
	QFileInfo trustedCertFile = getCertFile(TRUSTED_HOSTS, hostname);
	if(trustedCertFile.exists()) {
		QList<QSslCertificate> trustedcerts = QSslCertificate::fromPath(trustedCertFile.absoluteFilePath());

		if(trustedcerts.isEmpty() || trustedcerts.at(0).isNull()) {
			failLogin(tr("Invalid SSL certificate for host %1").arg(hostname));

		} else if(trustedcerts.at(0) != cert) {
			failLogin(tr("Certificate of a trusted server has changed!"));

		} else {
			// Certificate matches explicitly trusted one, proceed with login
			m_server->_securityLevel = Server::TRUSTED_HOST;
			tlsAccepted();
		}

		return;
	}

	// Check if we have seen this host certificate before
	QFileInfo certFile = getCertFile(KNOWN_HOSTS, hostname);
	if(certFile.exists()) {
		QList<QSslCertificate> knowncerts = QSslCertificate::fromPath(certFile.absoluteFilePath());

		if(knowncerts.isEmpty() || knowncerts.at(0).isNull()) {
			failLogin(tr("Invalid SSL certificate for host %1").arg(hostname));
			return;
		}

		if(knowncerts.at(0) != cert) {
			// Certificate mismatch!

			if(_selectorDialog)
				_selectorDialog->hide();

			_certDialog = new QMessageBox(_widgetParent);
			_certDialog->setWindowTitle(hostname);
			_certDialog->setWindowModality(Qt::WindowModal);
			_certDialog->setIcon(QMessageBox::Warning);
			_certDialog->setText(tr("The certificate of this server has changed!"));

			QAbstractButton *continueBtn = _certDialog->addButton(tr("Continue"), QMessageBox::AcceptRole);
			_certDialog->addButton(QMessageBox::Cancel);

			// WTF, accepted() and rejected() signals do not work correctly:
			// http://qt-project.org/forums/viewthread/21172
			// https://bugreports.qt-project.org/browse/QTBUG-23967
			connect(_certDialog.data(), &QMessageBox::finished, [this, cert, certFile, continueBtn]() {
				if(_certDialog->clickedButton() == continueBtn) {
					saveCert(certFile, cert);
					tlsAccepted();

				} else {
					cancelLogin();
				}
			});

			_certDialog->show();
			m_server->_securityLevel = TcpServer::NEW_HOST;

			return;

		} else {
			m_server->_securityLevel = TcpServer::KNOWN_HOST;
		}

	} else {
		// Host not encountered yet: rember the certificate for next time
		saveCert(certFile, cert);
		m_server->_securityLevel = TcpServer::NEW_HOST;
	}

	// Certificate is acceptable
	tlsAccepted();
}
void MainWindow::connectTheExternalSocket()
{
    //check the certificat
    {
        QDir datapack(QStandardPaths::writableLocation(QStandardPaths::DataLocation));
        datapack.mkpath(datapack.absolutePath());
        QFile certFile;
        certFile.setFileName(datapack.absolutePath()+QStringLiteral("/pub.key"));
        if(certFile.exists())
        {
            if(realSslSocket->mode()==QSslSocket::UnencryptedMode)
            {
                SslCert sslCert(this);
                sslCert.exec();
                if(sslCert.validated())
                    saveCert(certFile.fileName());
                else
                {
                    realSslSocket->disconnectFromHost();
                    return;
                }
            }
            else if(certFile.open(QIODevice::ReadOnly))
            {
                if(realSslSocket->peerCertificate().publicKey().toPem()!=certFile.readAll())
                {
                    SslCert sslCert(this);
                    sslCert.exec();
                    if(sslCert.validated())
                        saveCert(certFile.fileName());
                    else
                    {
                        realSslSocket->disconnectFromHost();
                        return;
                    }
                }
                certFile.close();
            }
        }
        else
        {
            if(realSslSocket->mode()!=QSslSocket::UnencryptedMode)
                saveCert(certFile.fileName());

        }
    }
    //continue the normal procedure
    socket=new CatchChallenger::ConnectedSocket(realSslSocket);
    CatchChallenger::Api_client_real::client=new CatchChallenger::Api_client_real(socket);
    if(!proxy_dns_or_ip.isEmpty())
    {
        QNetworkProxy proxy=realSslSocket->proxy();
        proxy.setType(QNetworkProxy::Socks5Proxy);
        proxy.setHostName(proxy_dns_or_ip);
        proxy.setPort(proxy_port);
        static_cast<CatchChallenger::Api_client_real *>(CatchChallenger::Api_client_real::client)->setProxy(proxy);
    }
    connect(CatchChallenger::Api_client_real::client,               &CatchChallenger::Api_protocol::protocol_is_good,   this,&MainWindow::protocol_is_good,Qt::QueuedConnection);
    connect(CatchChallenger::Api_client_real::client,               &CatchChallenger::Api_protocol::disconnected,       this,&MainWindow::disconnected);
    connect(CatchChallenger::Api_client_real::client,               &CatchChallenger::Api_protocol::message,            this,&MainWindow::message,Qt::QueuedConnection);
    connect(CatchChallenger::Api_client_real::client,               &CatchChallenger::Api_protocol::logged,             this,&MainWindow::logged,Qt::QueuedConnection);
    CatchChallenger::BaseWindow::baseWindow->connectAllSignals();
    CatchChallenger::BaseWindow::baseWindow->setMultiPlayer(true);
    QDir datapack(QStandardPaths::writableLocation(QStandardPaths::DataLocation)+QStringLiteral("/datapack/"));
    if(!datapack.exists())
        if(!datapack.mkpath(datapack.absolutePath()))
        {
            disconnected(tr("Not able to create the folder %1").arg(datapack.absolutePath()));
            return;
        }
    CatchChallenger::Api_client_real::client->setDatapackPath(datapack.absolutePath());
    MapController::mapController->setDatapackPath(CatchChallenger::Api_client_real::client->datapackPath());
    CatchChallenger::BaseWindow::baseWindow->stateChanged(QAbstractSocket::ConnectedState);
    CatchChallenger::Api_client_real::client->sendProtocol();
}