/* Copyright (c) 2008-2009 TrueCrypt Developers Association. All rights reserved. Governed by the TrueCrypt License 3.0 the full text of which is contained in the file License.txt included in TrueCrypt binary and source code distribution packages. */ #include "System.h" #ifdef TC_UNIX #include #include #include #include #include #include #include #include #include "Platform/Unix/Process.h" #endif #include "Common/SecurityToken.h" #include "Application.h" #include "GraphicUserInterface.h" #include "FatalErrorHandler.h" #include "Forms/DeviceSelectionDialog.h" #include "Forms/KeyfileGeneratorDialog.h" #include "Forms/MainFrame.h" #include "Forms/MountOptionsDialog.h" #include "Forms/RandomPoolEnrichmentDialog.h" #include "Forms/SecurityTokenKeyfilesDialog.h" namespace VeraCrypt { GraphicUserInterface::GraphicUserInterface () : ActiveFrame (nullptr), BackgroundMode (false), mMainFrame (nullptr), mWaitDialog (nullptr) { #ifdef TC_UNIX signal (SIGHUP, OnSignal); signal (SIGINT, OnSignal); signal (SIGQUIT, OnSignal); signal (SIGTERM, OnSignal); #endif #ifdef TC_MACOSX wxApp::s_macHelpMenuTitleName = _("&Help"); #endif } GraphicUserInterface::~GraphicUserInterface () { try { if (RandomNumberGenerator::IsRunning()) RandomNumberGenerator::Stop(); } catch (...) { } FatalErrorHandler::Deregister(); #ifdef TC_UNIX signal (SIGHUP, SIG_DFL); signal (SIGINT, SIG_DFL); signal (SIGQUIT, SIG_DFL); signal (SIGTERM, SIG_DFL); #endif } void GraphicUserInterface::AppendToListCtrl (wxListCtrl *listCtrl, const vector &itemFields, int imageIndex, void *itemDataPtr) const { InsertToListCtrl (listCtrl, listCtrl->GetItemCount(), itemFields, imageIndex, itemDataPtr); } wxMenuItem *GraphicUserInterface::AppendToMenu (wxMenu &menu, const wxString &label, wxEvtHandler *handler, wxObjectEventFunction handlerFunction, int itemId) const { wxMenuItem *item = new wxMenuItem (&menu, itemId, label); menu.Append (item); if (handler) handler->Connect (item->GetId(), wxEVT_COMMAND_MENU_SELECTED, handlerFunction); return item; } bool GraphicUserInterface::AskYesNo (const wxString &message, bool defaultYes, bool warning) const { return ShowMessage (message, wxYES_NO | (warning ? wxICON_EXCLAMATION : wxICON_QUESTION) | (defaultYes ? wxYES_DEFAULT : wxNO_DEFAULT) ) == wxYES; } void GraphicUserInterface::AutoDismountVolumes (VolumeInfoList mountedVolumes, bool alwaysForce) { size_t mountedVolumeCount = Core->GetMountedVolumes().size(); try { wxBusyCursor busy; DismountVolumes (mountedVolumes, alwaysForce ? true : GetPreferences().ForceAutoDismount, false); } catch (...) { } if (Core->GetMountedVolumes().size() < mountedVolumeCount) OnVolumesAutoDismounted(); } void GraphicUserInterface::BackupVolumeHeaders (shared_ptr volumePath) const { wxWindow *parent = GetActiveWindow(); if (!volumePath || volumePath->IsEmpty()) volumePath = make_shared (SelectVolumeFile (GetActiveWindow())); if (volumePath->IsEmpty()) throw UserAbort (SRC_POS); #ifdef TC_WINDOWS if (Core->IsVolumeMounted (*volumePath)) { ShowInfo ("DISMOUNT_FIRST"); return; } #endif #ifdef TC_UNIX // Temporarily take ownership of a device if the user is not an administrator UserId origDeviceOwner ((uid_t) -1); if (!Core->HasAdminPrivileges() && volumePath->IsDevice()) { origDeviceOwner = FilesystemPath (wstring (*volumePath)).GetOwner(); Core->SetFileOwner (*volumePath, UserId (getuid())); } finally_do_arg2 (FilesystemPath, *volumePath, UserId, origDeviceOwner, { if (finally_arg2.SystemId != (uid_t) -1) Core->SetFileOwner (finally_arg, finally_arg2); }); #endif ShowInfo ("EXTERNAL_VOL_HEADER_BAK_FIRST_INFO"); shared_ptr normalVolume; shared_ptr hiddenVolume; MountOptions normalVolumeMountOptions; MountOptions hiddenVolumeMountOptions; normalVolumeMountOptions.Path = volumePath; hiddenVolumeMountOptions.Path = volumePath; VolumeType::Enum volumeType = VolumeType::Normal; // Open both types of volumes while (true) { shared_ptr volume; MountOptions *options = (volumeType == VolumeType::Hidden ? &hiddenVolumeMountOptions : &normalVolumeMountOptions); MountOptionsDialog dialog (parent, *options, LangString[volumeType == VolumeType::Hidden ? "ENTER_HIDDEN_VOL_PASSWORD" : "ENTER_NORMAL_VOL_PASSWORD"], true); while (!volume) { dialog.Hide(); if (dialog.ShowModal() != wxID_OK) return; try { wxBusyCursor busy; OpenVolumeThreadRoutine routine( options->Path, options->PreserveTimestamps, options->Password, options->Pim, options->Kdf, false, options->Keyfiles, options->Protection, options->ProtectionPassword, options->ProtectionPim, options->ProtectionKdf, options->ProtectionKeyfiles, true, volumeType, options->UseBackupHeaders ); ExecuteWaitThreadRoutine (parent, &routine); volume = routine.m_pVolume; } catch (PasswordException &e) { ShowWarning (e); } } if (volumeType == VolumeType::Hidden) hiddenVolume = volume; else normalVolume = volume; // Ask whether a hidden volume is present if (volumeType == VolumeType::Normal) { wxArrayString choices; choices.Add (LangString["VOLUME_CONTAINS_HIDDEN"]); choices.Add (LangString["VOLUME_DOES_NOT_CONTAIN_HIDDEN"]); wxSingleChoiceDialog choiceDialog (parent, LangString["DOES_VOLUME_CONTAIN_HIDDEN"], Application::GetName(), choices); choiceDialog.SetSize (wxSize (Gui->GetCharWidth (&choiceDialog) * 60, -1)); choiceDialog.SetSelection (-1); if (choiceDialog.ShowModal() != wxID_OK) return; switch (choiceDialog.GetSelection()) { case 0: volumeType = VolumeType::Hidden; continue; case 1: break; default: return; } } break; } if (hiddenVolume) { if (typeid (*normalVolume->GetLayout()) == typeid (VolumeLayoutV1Normal)) throw ParameterIncorrect (SRC_POS); if (typeid (*normalVolume->GetLayout()) == typeid (VolumeLayoutV2Normal) && typeid (*hiddenVolume->GetLayout()) != typeid (VolumeLayoutV2Hidden)) throw ParameterIncorrect (SRC_POS); } // Ask user to select backup file path wxString confirmMsg = LangString["CONFIRM_VOL_HEADER_BAK"]; confirmMsg.Replace (L"%hs", L"%s"); if (!AskYesNo (wxString::Format (confirmMsg, wstring (*volumePath).c_str()), true)) return; FilePathList files = SelectFiles (parent, wxEmptyString, true, false); if (files.empty()) return; File backupFile; backupFile.Open (*files.front(), File::CreateWrite); RandomNumberGenerator::Start(); /* force the display of the random enriching interface */ RandomNumberGenerator::SetEnrichedByUserStatus (false); UserEnrichRandomPool (nullptr); { wxBusyCursor busy; // Re-encrypt volume header SecureBuffer newHeaderBuffer (normalVolume->GetLayout()->GetHeaderSize()); ReEncryptHeaderThreadRoutine routine(newHeaderBuffer, normalVolume->GetHeader(), normalVolumeMountOptions.Password, normalVolumeMountOptions.Pim, normalVolumeMountOptions.Keyfiles); ExecuteWaitThreadRoutine (parent, &routine); backupFile.Write (newHeaderBuffer); if (hiddenVolume) { // Re-encrypt hidden volume header ReEncryptHeaderThreadRoutine hiddenRoutine(newHeaderBuffer, hiddenVolume->GetHeader(), hiddenVolumeMountOptions.Password, hiddenVolumeMountOptions.Pim, hiddenVolumeMountOptions.Keyfiles); ExecuteWaitThreadRoutine (parent, &hiddenRoutine); } else { // Store random data in place of hidden volume header shared_ptr ea = normalVolume->GetEncryptionAlgorithm(); Core->RandomizeEncryptionAlgorithmKey (ea); ea->Encrypt (newHeaderBuffer); } backupFile.Write (newHeaderBuffer); } ShowWarning ("VOL_HEADER_BACKED_UP"); } void GraphicUserInterface::BeginInteractiveBusyState (wxWindow *window) { static auto_ptr arrowWaitCursor; if (arrowWaitCursor.get() == nullptr) arrowWaitCursor.reset (new wxCursor (wxCURSOR_ARROWWAIT)); window->SetCursor (*arrowWaitCursor); } void GraphicUserInterface::CreateKeyfile (shared_ptr keyfilePath) const { try { KeyfileGeneratorDialog dialog (GetActiveWindow()); dialog.ShowModal(); } catch (exception &e) { ShowError (e); } } void GraphicUserInterface::ClearListCtrlSelection (wxListCtrl *listCtrl) const { foreach (long item, GetListCtrlSelectedItems (listCtrl)) listCtrl->SetItemState (item, 0, wxLIST_STATE_SELECTED); } wxHyperlinkCtrl *GraphicUserInterface::CreateHyperlink (wxWindow *parent, const wxString &linkUrl, const wxString &linkText) const { wxHyperlinkCtrl *hyperlink = new wxHyperlinkCtrl (parent, wxID_ANY, linkText, linkUrl, wxDefaultPosition, wxDefaultSize, wxHL_DEFAULT_STYLE); wxColour color = wxSystemSettings::GetColour (wxSYS_COLOUR_WINDOWTEXT); hyperlink->SetHoverColour (color); hyperlink->SetNormalColour (color); hyperlink->SetVisitedColour (color); return hyperlink; } void GraphicUserInterface::DoShowError (const wxString &message) const { ShowMessage (message, wxOK | wxICON_ERROR); } void GraphicUserInterface::DoShowInfo (const wxString &message) const { ShowMessage (message, wxOK | wxICON_INFORMATION); } void GraphicUserInterface::DoShowString (const wxString &str) const { ShowMessage (str, wxOK); } void GraphicUserInterface::DoShowWarning (const wxString &message) const { ShowMessage (message, wxOK #ifndef TC_MACOSX | wxICON_EXCLAMATION #endif ); } void GraphicUserInterface::EndInteractiveBusyState (wxWindow *window) const { static auto_ptr arrowCursor; if (arrowCursor.get() == nullptr) arrowCursor.reset (new wxCursor (wxCURSOR_ARROW)); window->SetCursor (*arrowCursor); } wxTopLevelWindow *GraphicUserInterface::GetActiveWindow () const { #ifdef TC_WINDOWS return dynamic_cast (wxGetActiveWindow()); #endif #ifdef __WXGTK__ // GTK for some reason unhides a hidden window if it is a parent of a new window if (IsInBackgroundMode()) return nullptr; #endif if (wxTopLevelWindows.size() == 1) return dynamic_cast (wxTopLevelWindows.front()); #ifdef __WXGTK__ wxLongLong startTime = wxGetLocalTimeMillis(); do { #endif foreach (wxWindow *window, wxTopLevelWindows) { wxTopLevelWindow *topLevelWin = dynamic_cast (window); if (topLevelWin && topLevelWin->IsActive() && topLevelWin->IsShown()) return topLevelWin; } #ifdef __WXGTK__ Yield(); // GTK does a lot of operations asynchronously, which makes it prone to many race conditions } while (wxGetLocalTimeMillis() - startTime < 500); #endif return dynamic_cast (ActiveFrame ? ActiveFrame : GetTopWindow()); } shared_ptr GraphicUserInterface::GetAdminPasswordRequestHandler () { struct AdminPasswordRequestHandler : public GetStringFunctor { virtual void operator() (string &passwordStr) { wxString sValue; if (Gui->GetWaitDialog()) { Gui->GetWaitDialog()->RequestAdminPassword(sValue); if (sValue.IsEmpty()) throw UserAbort (SRC_POS); } else { wxPasswordEntryDialog dialog (Gui->GetActiveWindow(), _("Enter your user password or administrator password:"), _("Administrator privileges required")); if (dialog.ShowModal() != wxID_OK) throw UserAbort (SRC_POS); sValue = dialog.GetValue(); } wstring wPassword (sValue); // A copy of the password is created here by wxWidgets, which cannot be erased finally_do_arg (wstring *, &wPassword, { StringConverter::Erase (*finally_arg); }); StringConverter::ToSingle (wPassword, passwordStr); } }; return shared_ptr (new AdminPasswordRequestHandler); } int GraphicUserInterface::GetCharHeight (wxWindow *window) const { int width; int height; window->GetTextExtent (L"a", &width, &height); if (height < 1) return 14; return height; } int GraphicUserInterface::GetCharWidth (wxWindow *window) const { int width; int height; window->GetTextExtent (L"a", &width, &height); if (width < 1) return 7;
/*
 Derived from source code of TrueCrypt 7.1a, which is
 Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed
 by the TrueCrypt License 3.0.

 Modifications and additions to the original source code (contained in this file) 
 and all other portions of this file are Copyright (c) 2013-2015 IDRIX
 and are governed by the Apache License 2.0 the full text of which is
 contained in the file License.txt included in VeraCrypt binary and source
 code distribution packages.
*/

#include "System.h"
#include <wx/stackwalk.h>

#include "Main.h"
#include "Application.h"
#include "UserInterface.h"
#include "GraphicUserInterface.h"
#include "Volume/Crc32.h"

#ifdef TC_UNIX
#include <signal.h>
#endif

#ifdef TC_MACOSX
#	include <sys/ucontext.h>
#elif defined (TC_BSD)
#	include <ucontext.h>
#endif

#include "FatalErrorHandler.h"

namespace VeraCrypt
{
	static terminate_handler DefaultTerminateHandler;

	struct FatalErrorReport
	{
		bool UnhandledException;
	};

#ifdef TC_UNIX
	static void OnFatalProgramErrorSignal (int, siginfo_t *signalInfo, void *contextArg)
	{
		TC_UNUSED_VAR ucontext_t *context = (ucontext_t *) contextArg;
		uint64 faultingInstructionAddress = 0;

#ifdef TC_LINUX
#	ifdef REG_EIP
		faultingInstructionAddress = context->uc_mcontext.gregs[REG_EIP];
#	elif defined (REG_RIP)
		faultingInstructionAddress = context->uc_mcontext.gregs[REG_RIP];
#	endif

#elif defined (TC_MACOSX)
#	ifdef __x86_64__
		faultingInstructionAddress = context->uc_mcontext->__ss.__rip;
#	else
		faultingInstructionAddress = context->uc_mcontext->__ss.__eip;
#	endif

#endif
		wstringstream vars;

		vars << L"cpus=" << wxThread::GetCPUCount();
		vars << L"&cksum=" << hex << FatalErrorHandler::GetAppChecksum() << dec;
		vars << L"&err=" << signalInfo->si_signo;
		vars << L"&addr=" << hex << faultingInstructionAddress << dec;
		vars << FatalErrorHandler::GetCallStack (16);

		wxString url = Gui->GetHomepageLinkURL (L"err-report", true, vars.str());
		url.Replace (L"=0x", L"=");
		url.Replace (L"=0X0x", L"=0x");
		url.Replace (L"=0X", L"=0x");

		wxString msg = L"A critical error has occurred and VeraCrypt must be terminated. If this is caused by a bug in VeraCrypt, we would like to fix it. To help us, you can send us an automatically generated error report containing the following items:\n\n- Program version\n- Operating system version\n- Hardware architecture\n- Checksum of VeraCrypt executable\n- Error category\n- Error address\n";
#if wxUSE_STACKWALKER == 1
		msg += L"- VeraCrypt call stack\n";
#endif
		msg += L"\nIf you select 'Yes', the following URL (which contains the entire error report) will be opened in your default Internet browser.\n\n";

#ifdef __WXGTK__
		wxString fUrl = url;
		fUrl.Replace (L"&st", L" &st");
		msg += fUrl;
#else
		msg += url;
#endif

		msg += L"\n\nDo you want to send us the error report?";

		if (Gui->AskYesNo (msg, true))
			wxLaunchDefaultBrowser (url, wxBROWSER_NEW_WINDOW);

		_exit (1);
	}
#endif // TC_UNIX

	void FatalErrorHandler::Deregister()
	{
#ifdef TC_UNIX
		signal (SIGILL, SIG_DFL);
		signal (SIGFPE, SIG_DFL);
		signal (SIGSEGV, SIG_DFL);
		signal (SIGBUS, SIG_DFL);
		signal (SIGSYS, SIG_DFL);
#endif

#ifndef TC_WINDOWS
		std::set_terminate (DefaultTerminateHandler);
#endif
	}
	
	uint32 FatalErrorHandler::GetAppChecksum ()
	{
		uint32 checkSum = 0;
		try
		{
			File executable;
			executable.Open (Application::GetExecutablePath());

			Buffer executableData (executable.Length());
			executable.ReadCompleteBuffer (executableData);
			checkSum = Crc32::ProcessBuffer (executableData);
		}
		catch (...) { }

		return checkSum;
	}

	wstring FatalErrorHandler::GetCallStack (int depth)
	{	
#if wxUSE_STACKWALKER == 1

		class StackWalker : public wxStackWalker
		{
		public:
			StackWalker () : FrameCount (0) { }

			void OnStackFrame (const wxStackFrame &frame)
			{
				if (FrameCount >= 32)
					return;

				StackVars << L"&st" << FrameCount++ << L"=";

				wxString functionName = frame.GetName();
				if (!functionName.empty() && !frame.GetModule().empty())
				{
					int p = functionName.Find (L"(");
					if (p != wxNOT_FOUND)
						functionName = functionName.Mid (0, p);

					for (size_t i = 0; i < functionName.size(); ++i)
					{
						if (!isalnum (functionName[i]))
							functionName[i] = L'_';
					}

					while (functionName.Replace (L"__", L"_"));

					StackVars << wstring (functionName);
				}
				else
					StackVars << "0X" << hex << frame.GetAddress() << dec;
			}

			int FrameCount;
			wstringstream StackVars;
		};

		StackWalker stackWalker;
		stackWalker.Walk (2);

		return stackWalker.StackVars.str();

#else // wxUSE_STACKWALKER
		
		return wstring();

#endif // wxUSE_STACKWALKER
	}

	void FatalErrorHandler::OnTerminate ()
	{
		try
		{
			throw;
		}
		catch (UserAbort&)
		{
		}
		catch (Exception &e)
		{
			wxString vars;

			wxString exName = StringConverter::ToWide (StringConverter::GetTypeName (typeid (e)));
			if (exName.find (L"VeraCrypt::") != string::npos)
				exName = exName.Mid (11);

			wxString exPos = StringConverter::ToWide (e.what());
			if (exPos.find (L"VeraCrypt::") != string::npos)
				exPos = exPos.Mid (11);

			vars << L"cpus=" << wxThread::GetCPUCount();
			vars << wxString::Format (L"&cksum=%x", GetAppChecksum());
			vars << L"&exception=" << exName;
			vars << L"&exlocation=" << exPos;
			vars << FatalErrorHandler::GetCallStack (16);

			vars.Replace (L"::", L".");
			vars.Replace (L":", L".");

			wxString url = Gui->GetHomepageLinkURL (L"err-report", true, vars);
			url.Replace (L"=0x", L"=");
			url.Replace (L"=0X0x", L"=0x");
			url.Replace (L"=0X", L"=0x");

			wxString msg = L"An unhandled exception has occurred and VeraCrypt must be terminated. If this is caused by a bug in VeraCrypt, we would like to fix it. To help us, you can send us an automatically generated error report containing the following items:\n\n- Program version\n- Operating system version\n- Hardware architecture\n- Checksum of VeraCrypt executable\n- Error description\n- Error location\n";
#if wxUSE_STACKWALKER == 1
			msg += L"- VeraCrypt call stack\n";
#endif
			msg += L"\nIf you select 'Yes', the following URL (which contains the entire error report) will be opened in your default Internet browser.\n\n";

#ifdef __WXGTK__
			wxString fUrl = url;
			fUrl.Replace (L"&st", L" &st");
			msg += fUrl;
#else
			msg += url;
#endif

			msg += L"\n\nDo you want to send us the error report?";

			if (Gui->AskYesNo (msg, true))
				wxLaunchDefaultBrowser (url, wxBROWSER_NEW_WINDOW);

		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
		catch (...)
		{
			Gui->ShowError (_("Unknown exception occurred."));
		}

		_exit (1);
	}

	void FatalErrorHandler::Register ()
	{
#ifndef TC_WINDOWS
		 // OnUnhandledException() seems to be called only on Windows
		DefaultTerminateHandler = std::set_terminate (OnTerminate);
#endif

#ifdef TC_UNIX
		struct sigaction action;
		Memory::Zero (&action, sizeof (action));
		action.sa_flags = SA_SIGINFO;
		action.sa_sigaction = OnFatalProgramErrorSignal;

		throw_sys_if (sigaction (SIGILL, &action, nullptr) == -1);
		throw_sys_if (sigaction (SIGFPE, &action, nullptr) == -1);
		throw_sys_if (sigaction (SIGSEGV, &action, nullptr) == -1);
		throw_sys_if (sigaction (SIGBUS, &action, nullptr) == -1);
		throw_sys_if (sigaction (SIGSYS, &action, nullptr) == -1);
#endif
	}
}