bool VolumeHeader::Decrypt (const ConstBufferPtr &encryptedData, const VolumePassword &password, const Pkcs5KdfList &keyDerivationFunctions, const EncryptionAlgorithmList &encryptionAlgorithms, const EncryptionModeList &encryptionModes)
{
    if (password.Size() < 1)
        throw PasswordEmpty (SRC_POS);

    ConstBufferPtr salt (encryptedData.GetRange (SaltOffset, SaltSize));
    SecureBuffer header (EncryptedHeaderDataSize);
    SecureBuffer headerKey (GetLargestSerializedKeySize());

    foreach (shared_ptr <Pkcs5Kdf> pkcs5, keyDerivationFunctions)
    {
        pkcs5->DeriveKey (headerKey, password, salt);

        foreach (shared_ptr <EncryptionMode> mode, encryptionModes)
        {
            if (typeid (*mode) != typeid (EncryptionModeXTS))
                mode->SetKey (headerKey.GetRange (0, mode->GetKeySize()));

            foreach (shared_ptr <EncryptionAlgorithm> ea, encryptionAlgorithms)
            {
                if (!ea->IsModeSupported (mode))
                    continue;

                /*
                printf("trying %ls, %ls, %ls\n", pkcs5->GetName().c_str(),
                							mode->GetName().c_str(),
                							ea->GetName().c_str()
                							);
                							*/


                if (typeid (*mode) == typeid (EncryptionModeXTS))
                {
                    ea->SetKey (headerKey.GetRange (0, ea->GetKeySize()));

                    mode = mode->GetNew();
                    mode->SetKey (headerKey.GetRange (ea->GetKeySize(), ea->GetKeySize()));
                }
                else
                {
                    ea->SetKey (headerKey.GetRange (LegacyEncryptionModeKeyAreaSize, ea->GetKeySize()));
                }

                ea->SetMode (mode);

                header.CopyFrom (encryptedData.GetRange (EncryptedHeaderDataOffset, EncryptedHeaderDataSize));
                ea->Decrypt (header);

                if (Deserialize (header, ea, mode))
                {
                    EA = ea;
                    Pkcs5 = pkcs5;
                    return true;
                }
            }
        }
    }
Beispiel #2
0
/*************************************************
* SHARK Key Schedule                             *
*************************************************/
void SHARK::set_key(const byte key[], u32bit length) throw(InvalidKeyLength)
   {
   if(!valid_keylength(length))
      throw InvalidKeyLength(name(), length);
   SecureBuffer<byte, 56> subkeys;
   SecureBuffer<byte, 8> buffer;
   for(u32bit j = 0; j != 56; j++)
      subkeys[j] = key[j % length];
   EK.copy(TE0, 7); EK[6] = transform(EK[6]);
   for(u32bit j = 0; j != 7; j++)
      {
      encrypt(buffer);
      xor_buf(subkeys + 8*j, buffer, 8);
      buffer.copy(subkeys + 8*j, 8);
      }
   for(u32bit j = 0; j != 56; j++)
      EK[j/8] = (EK[j/8] << 8) + subkeys[j];
   DK[0] = EK[6] = transform(EK[6]);
   for(u32bit j = 1; j != 6; j++)
      DK[j] = transform(EK[6 - j]);
   DK[6] = EK[0];
   }
Beispiel #3
0
/*
* RC2 Key Schedule
*/
void RC2::key_schedule(const byte key[], u32bit length)
   {
   static const byte TABLE[256] = {
      0xD9, 0x78, 0xF9, 0xC4, 0x19, 0xDD, 0xB5, 0xED, 0x28, 0xE9, 0xFD, 0x79,
      0x4A, 0xA0, 0xD8, 0x9D, 0xC6, 0x7E, 0x37, 0x83, 0x2B, 0x76, 0x53, 0x8E,
      0x62, 0x4C, 0x64, 0x88, 0x44, 0x8B, 0xFB, 0xA2, 0x17, 0x9A, 0x59, 0xF5,
      0x87, 0xB3, 0x4F, 0x13, 0x61, 0x45, 0x6D, 0x8D, 0x09, 0x81, 0x7D, 0x32,
      0xBD, 0x8F, 0x40, 0xEB, 0x86, 0xB7, 0x7B, 0x0B, 0xF0, 0x95, 0x21, 0x22,
      0x5C, 0x6B, 0x4E, 0x82, 0x54, 0xD6, 0x65, 0x93, 0xCE, 0x60, 0xB2, 0x1C,
      0x73, 0x56, 0xC0, 0x14, 0xA7, 0x8C, 0xF1, 0xDC, 0x12, 0x75, 0xCA, 0x1F,
      0x3B, 0xBE, 0xE4, 0xD1, 0x42, 0x3D, 0xD4, 0x30, 0xA3, 0x3C, 0xB6, 0x26,
      0x6F, 0xBF, 0x0E, 0xDA, 0x46, 0x69, 0x07, 0x57, 0x27, 0xF2, 0x1D, 0x9B,
      0xBC, 0x94, 0x43, 0x03, 0xF8, 0x11, 0xC7, 0xF6, 0x90, 0xEF, 0x3E, 0xE7,
      0x06, 0xC3, 0xD5, 0x2F, 0xC8, 0x66, 0x1E, 0xD7, 0x08, 0xE8, 0xEA, 0xDE,
      0x80, 0x52, 0xEE, 0xF7, 0x84, 0xAA, 0x72, 0xAC, 0x35, 0x4D, 0x6A, 0x2A,
      0x96, 0x1A, 0xD2, 0x71, 0x5A, 0x15, 0x49, 0x74, 0x4B, 0x9F, 0xD0, 0x5E,
      0x04, 0x18, 0xA4, 0xEC, 0xC2, 0xE0, 0x41, 0x6E, 0x0F, 0x51, 0xCB, 0xCC,
      0x24, 0x91, 0xAF, 0x50, 0xA1, 0xF4, 0x70, 0x39, 0x99, 0x7C, 0x3A, 0x85,
      0x23, 0xB8, 0xB4, 0x7A, 0xFC, 0x02, 0x36, 0x5B, 0x25, 0x55, 0x97, 0x31,
      0x2D, 0x5D, 0xFA, 0x98, 0xE3, 0x8A, 0x92, 0xAE, 0x05, 0xDF, 0x29, 0x10,
      0x67, 0x6C, 0xBA, 0xC9, 0xD3, 0x00, 0xE6, 0xCF, 0xE1, 0x9E, 0xA8, 0x2C,
      0x63, 0x16, 0x01, 0x3F, 0x58, 0xE2, 0x89, 0xA9, 0x0D, 0x38, 0x34, 0x1B,
      0xAB, 0x33, 0xFF, 0xB0, 0xBB, 0x48, 0x0C, 0x5F, 0xB9, 0xB1, 0xCD, 0x2E,
      0xC5, 0xF3, 0xDB, 0x47, 0xE5, 0xA5, 0x9C, 0x77, 0x0A, 0xA6, 0x20, 0x68,
      0xFE, 0x7F, 0xC1, 0xAD };

   SecureBuffer<byte, 128> L;
   L.copy(key, length);

   for(u32bit j = length; j != 128; ++j)
      L[j] = TABLE[(L[j-1] + L[j-length]) % 256];
   L[128-length] = TABLE[L[128-length]];
   for(s32bit j = 127-length; j >= 0; --j)
      L[j] = TABLE[L[j+1] ^ L[j+length]];

   for(u32bit j = 0; j != 64; ++j)
      K[j] = load_le<u16bit>(L, j);
   }
Beispiel #4
0
	void FatFormatter::Format (WriteSectorCallback &writeSector, uint64 deviceSize, uint32 clusterSize, uint32 sectorSize)
	{
		fatparams fatParams;

#if TC_MAX_VOLUME_SECTOR_SIZE > 0xFFFF
#error TC_MAX_VOLUME_SECTOR_SIZE > 0xFFFF
#endif
		fatParams.sector_size = (uint16) sectorSize;

		if (deviceSize / fatParams.sector_size > 0xffffFFFF)
			throw ParameterIncorrect (SRC_POS);

		fatParams.num_sectors = (uint32) (deviceSize / fatParams.sector_size);
		fatParams.cluster_size = clusterSize / fatParams.sector_size;
		memcpy (fatParams.volume_name, "NO NAME    ", 11);
		GetFatParams (&fatParams); 
		fatparams *ft = &fatParams;

		SecureBuffer sector (ft->sector_size);
		uint32 sectorNumber = 0;

		/* Write the data area */

		sector.Zero();

		uint32 volumeId;
		RandomNumberGenerator::GetDataFast (BufferPtr ((byte *) &volumeId, sizeof (volumeId)));

		PutBoot (ft, (byte *) sector, volumeId);
		writeSector (sector); ++sectorNumber;

		/* fat32 boot area */
		if (ft->size_fat == 32)				
		{
			/* fsinfo */
			PutFSInfo((byte *) sector, ft);
			writeSector (sector); ++sectorNumber;

			/* reserved */
			while (sectorNumber < 6)
			{
				sector.Zero();
				sector[508+3] = 0xaa; /* TrailSig */
				sector[508+2] = 0x55;
				writeSector (sector); ++sectorNumber;
			}

			/* bootsector backup */
			sector.Zero();
			PutBoot (ft, (byte *) sector, volumeId);
			writeSector (sector); ++sectorNumber;

			PutFSInfo((byte *) sector, ft);
			writeSector (sector); ++sectorNumber;
		}

		/* reserved */
		while (sectorNumber < (uint32)ft->reserved)
		{
			sector.Zero();
			writeSector (sector); ++sectorNumber;
		}

		/* write fat */
		for (uint32 x = 1; x <= ft->fats; x++)
		{
			for (uint32 n = 0; n < ft->fat_length; n++)
			{
				sector.Zero();

				if (n == 0)
				{
					byte fat_sig[12];
					if (ft->size_fat == 32)
					{
						fat_sig[0] = (byte) ft->media;
						fat_sig[1] = fat_sig[2] = 0xff;
						fat_sig[3] = 0x0f;
						fat_sig[4] = fat_sig[5] = fat_sig[6] = 0xff;
						fat_sig[7] = 0x0f;
						fat_sig[8] = fat_sig[9] = fat_sig[10] = 0xff;
						fat_sig[11] = 0x0f;
						memcpy (sector, fat_sig, 12);
					}				
					else if (ft->size_fat == 16)
					{
						fat_sig[0] = (byte) ft->media;
						fat_sig[1] = 0xff;
						fat_sig[2] = 0xff;
						fat_sig[3] = 0xff;
						memcpy (sector, fat_sig, 4);
					}
					else if (ft->size_fat == 12)
					{
						fat_sig[0] = (byte) ft->media;
						fat_sig[1] = 0xff;
						fat_sig[2] = 0xff;
						fat_sig[3] = 0x00;
						memcpy (sector, fat_sig, 4);
					}
				}

				if (!writeSector (sector))
					return;
			}
		}

		/* write rootdir */
		for (uint32 x = 0; x < ft->size_root_dir / ft->sector_size; x++)
		{
			sector.Zero();
			if (!writeSector (sector))
				return;
		}
	}
        void connect(void *const handle, const string &host, const string &port,
                     const ProxyConfig &proxy, const string &userName,
                     const SecureBuffer &password, const string &userJID,
                     const string &xmppDomain, InBandRegister inbandRegistrationAction,
                     xmpp_connection_callback_t callback)
        {
            (void)inbandRegistrationAction;

#ifdef ENABLE_LIBSTROPHE
            auto xmlConnection = make_shared<XmppStropheConnection>(host, port);
#else
            auto remoteTcp = make_shared<TcpConnection>(host, port, proxy);

            auto xmlConnection = make_shared<XmppConnection>(
                                     static_pointer_cast<IStreamConnection>(remoteTcp));
#endif // ENABLE_LIBSTROPHE

            XmppConfig config(JabberID(userJID), xmppDomain);
            config.requireTLSNegotiation();

            config.setSaslConfig("SCRAM-SHA-1", SaslScramSha1::Params::create(userName, password));
            config.setSaslConfig("PLAIN", SaslPlain::Params::create(userName, password));

#ifndef DISABLE_SUPPORT_XEP0077
            if (inbandRegistrationAction != XMPP_NO_IN_BAND_REGISTER)
            {
                config.requestInBandRegistration();
                auto registrationParams = InBandRegistration::Params::create();
                registrationParams->setRegistrationParam("username", userName);
                string passwordStr((const char *)password.get(), password.size());
                registrationParams->setRegistrationParam("password", passwordStr);
                config.setExtensionConfig(InBandRegistration::extensionName(), registrationParams);
            }
#endif
            {
                lock_guard<recursive_mutex> lock(ContextWrapper::mutex());
                ContextWrapper::s_connectionParams[xmlConnection] = {handle, callback};
            }
            {
                lock_guard<recursive_mutex> lock(m_mutex);
                if (!m_client)
                {
                    m_client = XmppClient::create();

                    auto createdFunc =
                        // Note: We don't really need reference capturing, but there is a bug in C++
                        //       4.6 where static functions still require capturing this.
                        [&](XmppStreamCreatedEvent & e)
                    {
                        ConnectionParams params{};
                        {
                            lock_guard<recursive_mutex> lock(ContextWrapper::mutex());
                            auto f = ContextWrapper::s_connectionParams.find(e.remoteServer());
                            if (f == ContextWrapper::s_connectionParams.end())
                            {
                                return;
                            }
                            params = f->second;
                        }

                        auto stream = e.stream();
                        if (e.result().succeeded() && stream)
                        {
                            const void *streamHandle = stream.get();
                            {
                                lock_guard<recursive_mutex> lock(ContextWrapper::mutex());
                                ContextWrapper::s_streamsByHandle[streamHandle] = stream;
                            }

                            auto callback = params.m_callback;
                            auto streamConnectedFunc =
                                // Note: We don't really need reference capturing, but there is a
                                //       bug in C++ 4.6 where static functions still require
                                //       capturing this.
                                [&, stream, streamHandle, callback](XmppConnectedEvent & e)
                            {
                                // Send first presence message
                                postPresence(stream);

                                if (callback.on_connected)
                                {
                                    xmpp_connection_handle_t connectionHandle = {streamHandle};
                                    callback.on_connected(callback.param,
                                                          translateError(e.result()),
                                                          e.boundJID().c_str(),
                                                          connectionHandle);
                                }
                            };
                            typedef NotifySyncFunc<XmppConnectedEvent,
                                  decltype(streamConnectedFunc)> StreamConnectedFunc;
                            stream->onConnected() += make_shared<StreamConnectedFunc>(
                                                         streamConnectedFunc);

                            auto streamClosedFunc =
                                // Note: We don't really need reference capturing, but there is a
                                //       bug in C++ 4.6 where static functions still require
                                //       capturing this.
                                [&, streamHandle, callback](XmppClosedEvent & e)
                            {
                                if (callback.on_disconnected)
                                {
                                    xmpp_connection_handle_t connectionHandle = {streamHandle};
                                    callback.on_disconnected(callback.param,
                                                             translateError(e.result()),
                                                             connectionHandle);
                                }

                                {
                                    lock_guard<recursive_mutex> lock(ContextWrapper::mutex());
                                    ContextWrapper::s_streamsByHandle.erase(streamHandle);
                                }
                            };
                            typedef NotifySyncFunc<XmppClosedEvent,
                                  decltype(streamClosedFunc)> StreamClosedFunc;
                            stream->onClosed() += make_shared<StreamClosedFunc>(streamClosedFunc);
                        }
                        else
                        {
                            xmpp_error_code_t errorCode = translateError(e.result());
                            if (params.m_callback.on_connected && isValidWrapper(params.m_handle))
                            {
                                xmpp_connection_handle_t connectionHandle = {params.m_handle};
                                params.m_callback.on_connected(params.m_callback.param, errorCode,
                                                               nullptr, connectionHandle);
                            }
                        }


                        {
                            lock_guard<recursive_mutex> lock(mutex());
                            ContextWrapper::s_connectionParams.erase(e.remoteServer());
                        }

                    };

                    typedef NotifySyncFunc<XmppStreamCreatedEvent,
                          decltype(createdFunc)> StreamCreatedFunc;
                    m_client->onStreamCreated() += make_shared<StreamCreatedFunc>(createdFunc);
                }
            }

            m_client->initiateXMPP(config, xmlConnection);
        }
Beispiel #6
0
	static int fuse_service_read (const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi)
	{
		try
		{
			if (!FuseService::CheckAccessRights())
				return -EACCES;

			if (strcmp (path, FuseService::GetVolumeImagePath()) == 0)
			{
				try
				{
					// Test for read beyond the end of the volume
					if ((uint64) offset + size > FuseService::GetVolumeSize())
						size = FuseService::GetVolumeSize() - offset;

					size_t sectorSize = FuseService::GetVolumeSectorSize();
					if (size % sectorSize != 0 || offset % sectorSize != 0)
					{
						// Support for non-sector-aligned read operations is required by some loop device tools
						// which may analyze the volume image before attaching it as a device

						uint64 alignedOffset = offset - (offset % sectorSize);
						uint64 alignedSize = size + (offset % sectorSize);

						if (alignedSize % sectorSize != 0)
							alignedSize += sectorSize - (alignedSize % sectorSize);

						SecureBuffer alignedBuffer (alignedSize);

						FuseService::ReadVolumeSectors (alignedBuffer, alignedOffset);
						BufferPtr ((byte *) buf, size).CopyFrom (alignedBuffer.GetRange (offset % sectorSize, size));
					}
					else
					{
						FuseService::ReadVolumeSectors (BufferPtr ((byte *) buf, size), offset);
					}
				}
				catch (MissingVolumeData)
				{
					return 0;
				}

				return size;
			}

			if (strcmp (path, FuseService::GetControlPath()) == 0)
			{
				shared_ptr <Buffer> infoBuf = FuseService::GetVolumeInfo();
				BufferPtr outBuf ((byte *)buf, size);

				if (offset >= (off_t) infoBuf->Size())
					return 0;

				if (offset + size > infoBuf->Size())
					size = infoBuf->Size () - offset;

				outBuf.CopyFrom (infoBuf->GetRange (offset, size));
				return size;
			}
		}
		catch (...)
		{
			return FuseService::ExceptionToErrorCode();
		}

		return -ENOENT;
	}
	void KeyfileGeneratorDialog::OnGenerateButtonClick (wxCommandEvent& event)
	{
		try
		{
			int keyfilesCount = NumberOfKeyfiles->GetValue();
			int keyfilesSize = KeyfilesSize->GetValue();		
			bool useRandomSize = RandomSizeCheckBox->IsChecked();
			wxString keyfileBaseName = KeyfilesBaseName->GetValue();
			keyfileBaseName.Trim(true);
			keyfileBaseName.Trim(false);
			
			if (keyfileBaseName.IsEmpty())
			{
				Gui->ShowWarning("KEYFILE_EMPTY_BASE_NAME");
				return;
			}
			
			wxFileName baseFileName = wxFileName::FileName (keyfileBaseName);
			if (!baseFileName.IsOk())
			{
				Gui->ShowWarning("KEYFILE_INVALID_BASE_NAME");
				return;
			}
			
			DirectoryPath keyfilesDir = Gui->SelectDirectory (Gui->GetActiveWindow(), LangString["SELECT_KEYFILE_GENERATION_DIRECTORY"], false);
			if (keyfilesDir.IsEmpty())
				return;
				
			wxFileName dirFileName = wxFileName::DirName( wstring(keyfilesDir).c_str() );
			if (!dirFileName.IsDirWritable ())
			{
				Gui->ShowWarning(L"You don't have write permission on the selected directory");
				return;
			}
				
			wxBusyCursor busy;
			for (int i = 0; i < keyfilesCount; i++)
			{
				int bufferLen;
				if (useRandomSize)
				{
					SecureBuffer sizeBuffer (sizeof(int));
					RandomNumberGenerator::GetData (sizeBuffer, true);
					
					memcpy(&bufferLen, sizeBuffer.Ptr(), sizeof(int));

					/* since keyfilesSize < 1024 * 1024, we mask with 0x000FFFFF */
					bufferLen = (long) (((unsigned long) bufferLen) & 0x000FFFFF);

					bufferLen %= ((1024*1024 - 64) + 1);
					bufferLen += 64;								
				}
				else
					bufferLen = keyfilesSize;

				SecureBuffer keyfileBuffer (bufferLen);
				RandomNumberGenerator::GetData (keyfileBuffer, true);
								
				wstringstream convertStream;
				convertStream << i;
				wxString suffix = L"_";				
				suffix += convertStream.str().c_str();				
				
				wxFileName keyfileName;
				if (i == 0)
				{
					keyfileName.Assign(dirFileName.GetPath(), keyfileBaseName);
				}
				else
				{
					if (baseFileName.HasExt())
					{
						keyfileName.Assign(dirFileName.GetPath(), baseFileName.GetName() + suffix + L"." + baseFileName.GetExt());
					}
					else
					{
						keyfileName.Assign(dirFileName.GetPath(), keyfileBaseName + suffix);
					}
				}
				
				if (keyfileName.Exists())
				{
					wxString msg = wxString::Format(LangString["KEYFILE_ALREADY_EXISTS"], keyfileName.GetFullPath());
					if (!Gui->AskYesNo (msg, false, true))
						return;				
				}

				{
					FilePath keyfilePath((const wchar_t*) keyfileName.GetFullPath());
					File keyfile;
					keyfile.Open (keyfilePath, File::CreateWrite);
					keyfile.Write (keyfileBuffer);
				}

			}
			Gui->ShowInfo ("KEYFILE_CREATED");
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}