How to get the name of a console in Windows? - windows

Is possible to get the name of a console in Windows? Just like is done by the C function ttyname in Unix systems

You can use the WinAPI GetConsoleTitle function to retrieve it.
You might find links to all of the console functions useful.
You didn't specify a language, so here's the one in C++ from MSDN
#include <windows.h>
#include <tchar.h>
#include <conio.h>
#include <strsafe.h>
int main( void )
{
TCHAR szOldTitle[MAX_PATH];
TCHAR szNewTitle[MAX_PATH];
// Save current console title.
if( GetConsoleTitle(szOldTitle, MAX_PATH) )
{
// Build new console title string.
StringCchPrintf(szNewTitle, MAX_PATH, TEXT("TEST: %s"), szOldTitle);
// Set console title to new title
if( !SetConsoleTitle(szNewTitle) )
{
_tprintf(TEXT("SetConsoleTitle failed (%d)\n"), GetLastError());
return 1;
}
else
{
_tprintf(TEXT("SetConsoleTitle succeeded.\n"));
}
}
return 0;
}

Related

How can I decrypt a string using CryptUnprotectData

I have been trying to decrypt some encrypted data (AES key encrypting chrome cookies) via the c++ CryptUnprotectData function for a short while now, but I cant seem to get it working. Currently the function will fail and return an error code of 13 (meaning "The parameter is incorrect."). Here is my code so far:
#include <iostream>
#include <Windows.h>
#include <wincrypt.h>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
std::string GetLastErrorAsString()
{
DWORD errorMessageID = ::GetLastError();
if(errorMessageID == 0) {
return std::string();
}
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
LocalFree(messageBuffer);
return message;
}
int main()
{
string data = "(data I want to decode)";
cout << data;
DATA_BLOB DataBytes;
DataBytes.pbData = (BYTE*)data.data();
DataBytes.cbData = (DWORD)data.size()+1;
DATA_BLOB output;
output.pbData = NULL;
output.cbData = (DWORD)data.size();
CryptUnprotectData(&DataBytes, NULL, NULL, NULL, NULL, 0, &output);
cout << GetLastErrorAsString() << endl;
cout << output.pbData;
LocalFree(output.pbData);
return 0;
}
If anyone can provide any help, that would be greatly appreciated.
I have tried different variations of the data types the parameters are stored in, although it still returns this error.
I modified your code, which is as follows. It only implements simple decryption.
And the data is not encrypted, so CryptUnprotectData() does not return the correct value.
#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
#pragma comment (lib, "Crypt32.lib")
int main()
{
// Decrypt data from DATA_BLOB DataOut to DATA_BLOB DataVerify.
//--------------------------------------------------------------------
// Declare and initialize variables.
string data = ("data I want to decode \n");
cout << data;
LPWSTR pDescrOut = NULL;
DATA_BLOB DataBytes;
BYTE* pbDataOutput = (BYTE*)data.data();
DWORD cbDataOutput = strlen((char*)pbDataOutput) + 1;
DataBytes.pbData = pbDataOutput;
DataBytes.cbData = cbDataOutput;
//DATA_BLOB DataVerify;
//--------------------------------------------------------------------
// The buffer DataOut would be created using the CryptProtectData
// function. If may have been read in from a file.
//--------------------------------------------------------------------
// Begin unprotect phase.
BOOL res = CryptUnprotectData(
&DataBytes,
&pDescrOut,
NULL, // Optional entropy
NULL, // Reserved
NULL, // Here, the optional
// prompt structure is not
// used.
0,
&DataBytes);
if (res==1)
{
printf("The decrypted data is: %s\n", DataBytes.pbData);
printf("The description of the data was: %s\n", pDescrOut);
}
else
{
printf("Decryption error!");
}
// LocalFree(DataVerify.pbData);
LocalFree(pDescrOut);
//LocalFree(DataBytes.pbData);
}
It is recommended to refer to Microsoft's official documentation when you add additional code.

NT Security API: SECURITY_DESCRIPTOR.Control, when can I see SE_OWNER_DEFAULTED?

From Windows NT security API, SE_OWNER_DEFAULTED is a flag bit from SECURITY_DESCRIPTOR_CONTROL.
MSDN states it quite briefly:
(SE_OWNER_DEFAULTED) Indicates that the SID of the owner of the security descriptor was provided by a default mechanism. This flag can be used by a resource manager to identify objects whose owner was set by a default mechanism.
I'm curious that when I can see this flag set.
I write NtfsOwner.cpp to display owner SID of an NTFS file/directory's security descriptor, and use GetSecurityDescriptorOwner to query that SE_OWNER_DEFAULTED flag, but have no chance seeing it even once.
Could somebody give me some clue. Could it be possible that SE_OWNER_DEFAULTED exhibits on other type of NT objects(not on a file/directory)?
#include <Windows.h>
#include <AclAPI.h>
#include <sddl.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <locale.h>
template<typename T1, typename T2>
bool IsSameBool(T1 a, T2 b)
{
if(a && b)
return true;
else if(!a && !b)
return true;
else
return false;
}
void myDisplayNtfsOwner(const TCHAR *szfn)
{
DWORD succ = 0;
HANDLE hFile = CreateFile(szfn,
READ_CONTROL, // dwDesiredAccess=GENERIC_READ etc
FILE_SHARE_READ|FILE_SHARE_WRITE, // shareMode
NULL, // SecuAttr, no need bcz we are opening existing file
OPEN_EXISTING, // dwCreationDisposition
FILE_FLAG_BACKUP_SEMANTICS, // this is required for open a directory
NULL);
if(hFile==INVALID_HANDLE_VALUE)
{
_tprintf(_T("Warning: CreateFile() failed!(WinErr=%d) But I will go on calling GetSecurityInfo(0xFFFFffff, ...)\n"),
GetLastError());
}
SECURITY_DESCRIPTOR *pSD = nullptr;
DWORD winerr = GetSecurityInfo(hFile, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION,
NULL, NULL, NULL, NULL,
(PSECURITY_DESCRIPTOR*)&pSD);
assert(winerr==0);
SID* psidOwner = nullptr;
BOOL isOwnerDefaulted = 0;
succ = GetSecurityDescriptorOwner(pSD, (PSID*)&psidOwner, &isOwnerDefaulted);
assert(succ);
PTSTR strOwner = nullptr;
succ = ConvertSidToStringSid(psidOwner, &strOwner);
assert(succ);
_tprintf(_T("Owner SID is: %s\n"), strOwner);
_tprintf(_T("Is owner SID defaulted? %s\n"), isOwnerDefaulted?_T("yes"):_T("no"));
assert(IsSameBool(pSD->Control & SE_OWNER_DEFAULTED, isOwnerDefaulted));
LocalFree(strOwner);
LocalFree(pSD);
CloseHandle(hFile);
}
int _tmain(int argc, TCHAR* argv[])
{
setlocale(LC_ALL, "");
if(argc==1)
{
const TCHAR *s = _T("D:\\test\\foo.txt");
_tprintf(_T("Missing parameters.\n"));
_tprintf(_T("Example:\n"));
_tprintf(_T(" NtfsOwner1 %s\n"), s);
exit(1);
}
const TCHAR *szfn = argv[1];
myDisplayNtfsOwner(szfn);
return 0;
}

How to detect screen lock (Qt5, C++, Windows, OSX)

In my Qt5 C++ client, I'm wanting to detect when a user running Windows or OSX has locked the screen, then simultaneously lock my client application.
I have yet to come across a Qt5 class that provides this function, so I'm wondering if I'll need to write an OS-specific library. Does anyone have any experience doing something like this?
Thanks!
On windows you can use below code:
mywidget.cpp
#include "mywidget.h"
#include <Windows.h>
#include <WtsApi32.h>
#include <QDebug>
MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
WTSRegisterSessionNotification((HWND)this->winId(), NOTIFY_FOR_THIS_SESSION);
}
MyWidget::~MyWidget()
{
WTSUnRegisterSessionNotification((HWND)this->winId());
}
bool MyWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
if (eventType != "windows_generic_MSG") return false;
MSG *msg = static_cast<MSG*>(message);
switch (msg->message) {
case WM_WTSSESSION_CHANGE:
qDebug() << "session change: " << msg->wParam;
}
return false;
}
project.pro
...
LIBS += -lwtsapi32
...
reference1
reference2

Why isn't my Event Trace for Windows working?

I'm trying to figure out how to use Event Tracing for Windows... but I'm failing.
Why does this code give me the error code ERROR_WMI_INSTANCE_NOT_FOUND?
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <Wmistr.h>
#include <Evntrace.h>
#include <evntcons.h>
ULONG NTAPI EtpEtwBufferCallback(IN PEVENT_TRACE_LOGFILE Buffer) { return TRUE; }
VOID NTAPI EtpEtwEventCallback(IN PEVENT_TRACE EventTrace) { }
int _tmain()
{
LPCTSTR loggerName = KERNEL_LOGGER_NAME;
EVENT_TRACE_LOGFILE logFile = {0};
logFile.LoggerName = const_cast<LPTSTR>(loggerName);
logFile.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME;
logFile.BufferCallback = EtpEtwBufferCallback;
logFile.EventCallback = EtpEtwEventCallback;
TRACEHANDLE hTrace = OpenTrace(&logFile);
ULONG result = ProcessTrace(&hTrace, 1, NULL, NULL);
// result is ERROR_WMI_INSTANCE_NOT_FOUND
_tprintf(_T("%u\n"), result);
}
From the ProcessTrace docs, ERROR_WMI_INSTANCE_NOT_FOUND means "the session from which you are trying to consume events in real time is not running or does not have the real-time trace mode enabled".
You can start the NT Kernel Logger using tracelog from the Windows Driver Kit, though I don't have the WDK to hand so I haven't tried it.
This article explains how to start the NT Kernel Logger yourself.

Qt - get all opened windows title

how can i check whether a specific window is open or not. I only got part of the window's name. i thinking of using EnumWindows() in QT console app but i get a few errors stating "main.obj:-1: error: unresolved external symbol imp__GetWindowTextW#12 referenced in function "int __stdcall EnumWindowsProc(struct HWND *,long)" (?EnumWindowsProc##YGHPAUHWND__##J#Z)"
Below is my sample code
BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam) {
char buff[255];
if (IsWindowVisible(hWnd)) {
GetWindowText(hWnd, (LPWSTR) buff, 254);
}
return TRUE;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
EnumWindows(EnumWindowsProc, 0);
return 0;
}
That's a linker error rather than a compile error.
You have correctly included windows.h but you also need to add the import libraries to your linker options. All three Win32 functions in your sample code require you to link user32.lib.
EnumWindowsProc is not from Qt, it's a windows API function, you need to include windows.h
I did not use Qt, and the code can pass complie, but the output seems NOT right. Anyway, here's my code
#include <conio.h>
#include <iostream>
#include <windows.h>
using namespace std;
char buff[255];
BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam)
{
if (IsWindowVisible(hWnd))
{
GetWindowText(hWnd, (LPWSTR) buff, 254);
}
return TRUE;
}
int main()
{
EnumWindows(EnumWindowsProc, 0);
for(int i = 0; i != 254; ++i)
cout << buff[i];
getch();
return 0;
}
You can use:
Application.OpenForms["FormName"]
To check if the form is open or not.

Resources