NtRequestPort - parameter incorrect - windows

I'm try to communicate with \Windows\SbApiPort port .
The problem is that I get an error from NtRequestPort (0xc000000d - status invalid parameter).
The parameters of PORT_MESSAGE are not documented so I don't know where is my problem...
I tried to change the length, CallbackId, but the same problem...
Thanks for the help !
Here is the code:
HANDLE hSection=0;
LARGE_INTEGER SecSize;
SecSize.LowPart=0x10000;
SecSize.HighPart=0x0;
if(NtCreateSection(&hSection, SECTION_ALL_ACCESS, NULL, &SecSize, PAGE_READWRITE,SEC_COMMIT ,NULL))
{
printf("couldn't create a section");
}
HANDLE hPort;
PORT_VIEW sectionInfo;
REMOTE_PORT_VIEW mapInfo;
byte ConnectDataBuffer[0x100];
DWORD Size = sizeof(ConnectDataBuffer);
UNICODE_STRING uStr;
WCHAR * uString=L"\\Windows\\SbApiPort";
DWORD maxSize;
SECURITY_QUALITY_OF_SERVICE qos;
for (int i=0 ; i < 0x100 ; i++)
{
ConnectDataBuffer[i]=0xcc;
}
memset(&sectionInfo, 0, sizeof(sectionInfo));
memset(&mapInfo, 0, sizeof(mapInfo));
memset(&mapInfo, 0, sizeof(mapInfo));
memset(&qos, 0, sizeof(qos));
qos.Length = sizeof(SECURITY_QUALITY_OF_SERVICE);
qos.ImpersonationLevel = SecurityImpersonation;
qos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
qos.EffectiveOnly = TRUE;
sectionInfo.Length = sizeof(LPC_SECTION_OWNER_MEMORY);
sectionInfo.SectionHandle = hSection;
sectionInfo.SectionOffset = 0;
sectionInfo.ViewSize = 0x10000;
sectionInfo.ViewBase = NULL;
sectionInfo.ViewRemoteBase = NULL;
mapInfo.Length = sizeof(LPC_SECTION_MEMORY);
mapInfo.ViewSize = 0;
mapInfo.ViewBase = NULL;
uStr.Length = wcslen(uString)*2;
uStr.MaximumLength = wcslen(uString)*2+2;
uStr.Buffer =uString;
NTSTATUS res = NtConnectPort(&hPort,&uStr,&qos,&sectionInfo,&mapInfo,&maxSize,(DWORD*)&ConnectDataBuffer,&Size);
if (res)
{
printf("Could not connect to LPC port.\n -%x", res);
return 1;
}
PORT_MESSAGE PortMessage;
ZeroMemory(&PortMessage,sizeof(PORT_MESSAGE));
PortMessage.u1.Length = 0x20;
PortMessage.u2.s2.DataInfoOffset = 15;
PortMessage.u2.ZeroInit = 0x20;
PortMessage.MessageId = LPC_REQUEST;
PortMessage.ClientViewSize = 0x20;
PortMessage.ClientId.UniqueProcess = GetCurrentProcess();
PortMessage.ClientId.UniqueThread = GetCurrentThread();
PortMessage.CallbackId = 0;
res = NtRequestPort(hPort, &PortMessage);
if (res)
{
printf("Could not request LPC port.\n -%x", res);
return 1;
}
printf("End\n", res);

Related

CreateFileA Visit a windows file system driver returned INVALID_HANDLE_VALUE

I writed a file system demo most likely fast fat ,but when I use CreateFileA to call my dirver ,it gives an INVALID_HANDLE_VALUE result . I have checked the driver `s IRP dispatches and found no DbgPrint setting in the function entries triggered .
This is the user mode code:
public IntPtr LoadDriver(string lpFileName)
{
int error = 0;
string openName = string.Format("\\\\.\\{0}", EXE_DRIVER_NAME);
IntPtr hSCManager = WinAPI.OpenSCManager(null, null,
WinAPI.SC_MANAGER_CREATE_SERVICE);
if (IntPtr.Zero != hSCManager)
{
//创建服务
IntPtr hService = WinAPI.CreateService(hSCManager, EXE_DRIVER_NAME,
DISPLAY_NAME, WinAPI.SERVICE_START,
WinAPI.SERVICE_KERNEL_DRIVER, WinAPI.SERVICE_DEMAND_START,
WinAPI.SERVICE_ERROR_IGNORE, lpFileName, null, IntPtr.Zero, null, null, null);
if (WinAPI.ERROR_SERVICE_EXISTS == WinAPI.GetLastError())
{
hService = WinAPI.OpenService(hSCManager, EXE_DRIVER_NAME, WinAPI.SERVICE_START);
}
error = WinAPI.GetLastError();
if(error!=0)
{
dumpErrorCode("OpenService失败 ", error);
}
int startflag = WinAPI.StartService(hService, 0, 0);
if (startflag == 0)
{
error = WinAPI.GetLastError();
if (error != WinAPI.ERROR_SERVICE_ALREADY_RUNNING) //已经启动
{
dumpErrorCode("StartService失败", error);
}
else
{
MessageBox.Show("服务已经启动");
}
}
// WinAPI.CloseServiceHandle(hService);
// WinAPI.CloseServiceHandle(hSCManager);
MessageBox.Show(openName);
try
{
hDriver = WinAPI.CreateFileA(openName, WinAPI.GENERIC_READ , 0, IntPtr.Zero, WinAPI.OPEN_EXISTING, null, IntPtr.Zero);
if (hDriver == (IntPtr)(-1))
{
dumpErrorCode("获取文件句柄失败 ", error);
}
else
{
MessageBox.Show("成功创建驱动");
//his.OpenDriverEvent();
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
return hDriver;
}
This is the driver`s entry point code:
NTSTATUS
DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
{
NTSTATUS Status;
UNICODE_STRING UnicodeString;
FS_FILTER_CALLBACKS FilterCallbacks;
UNREFERENCED_PARAMETER( RegistryPath );
DbgPrint("\nThis is HRFS Driver Entry\n");
RtlInitUnicodeString(&UnicodeString, L"\\fastFatDemo");
gSFilterDriverObject = DriverObject;
Status = IoCreateDevice( DriverObject,
0,
&UnicodeString,
FILE_DEVICE_DISK_FILE_SYSTEM,
0,
FALSE,
&HrfsDiskFileSystemDeviceObject );
if (!NT_SUCCESS( Status )) {
return Status;
}
DbgPrint("HRFS device HRFS created\n ");
DriverObject->DriverUnload = FatUnload;
DriverObject->MajorFunction[IRP_MJ_CREATE] = (PDRIVER_DISPATCH)FatFsdCreate;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = (PDRIVER_DISPATCH)HrfsFsdClose;
DriverObject->MajorFunction[IRP_MJ_READ] = (PDRIVER_DISPATCH)FatFsdRead;
DriverObject->MajorFunction[IRP_MJ_WRITE] = (PDRIVER_DISPATCH)FatFsdWrite;
DriverObject->MajorFunction[IRP_MJ_QUERY_INFORMATION] = (PDRIVER_DISPATCH)FatFsdQueryInformation;
DriverObject->MajorFunction[IRP_MJ_SET_INFORMATION] = (PDRIVER_DISPATCH)FatFsdSetInformation;
DriverObject->MajorFunction[IRP_MJ_QUERY_EA] = (PDRIVER_DISPATCH)FatFsdQueryEa;
DriverObject->MajorFunction[IRP_MJ_SET_EA] = (PDRIVER_DISPATCH)FatFsdSetEa;
DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS] = (PDRIVER_DISPATCH)FatFsdFlushBuffers;
DriverObject->MajorFunction[IRP_MJ_QUERY_VOLUME_INFORMATION] = (PDRIVER_DISPATCH)FatFsdQueryVolumeInformation;
DriverObject->MajorFunction[IRP_MJ_SET_VOLUME_INFORMATION] = (PDRIVER_DISPATCH)FatFsdSetVolumeInformation;
DriverObject->MajorFunction[IRP_MJ_CLEANUP] = (PDRIVER_DISPATCH)FatFsdCleanup;
DriverObject->MajorFunction[IRP_MJ_DIRECTORY_CONTROL] = (PDRIVER_DISPATCH)FatFsdDirectoryControl;
DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] = (PDRIVER_DISPATCH)FatFsdFileSystemControl;
DriverObject->MajorFunction[IRP_MJ_LOCK_CONTROL] = (PDRIVER_DISPATCH)FatFsdLockControl;
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = (PDRIVER_DISPATCH)FatFsdDeviceControl;
DriverObject->MajorFunction[IRP_MJ_SHUTDOWN] = (PDRIVER_DISPATCH)FatFsdShutdown;
DriverObject->MajorFunction[IRP_MJ_PNP] = (PDRIVER_DISPATCH)FatFsdPnp;
DbgPrint("HRFS device HRFS MajorFunction created\n ");
DriverObject->FastIoDispatch = NULL;
DbgPrint("HRFS device HRFS FatFastIoDispatch created\n ");
RtlZeroMemory(&FatFastIoDispatch, sizeof(FatFastIoDispatch));
FatFastIoDispatch.SizeOfFastIoDispatch = sizeof(FAST_IO_DISPATCH);
FatFastIoDispatch.FastIoCheckIfPossible = FALSE; // CheckForFastIo
FatFastIoDispatch.FastIoRead = FALSE; // Read
FatFastIoDispatch.FastIoWrite = FALSE; // Write
FatFastIoDispatch.FastIoQueryBasicInfo = FALSE; // QueryBasicInfo
FatFastIoDispatch.FastIoQueryStandardInfo = FALSE; // QueryStandardInfo
FatFastIoDispatch.FastIoLock = FALSE; // Lock
FatFastIoDispatch.FastIoUnlockSingle = FALSE; // UnlockSingle
FatFastIoDispatch.FastIoUnlockAll = FALSE; // UnlockAll
FatFastIoDispatch.FastIoUnlockAllByKey = FALSE; // UnlockAllByKey
FatFastIoDispatch.FastIoQueryNetworkOpenInfo = FALSE;
FatFastIoDispatch.AcquireForCcFlush = FALSE;
FatFastIoDispatch.ReleaseForCcFlush = FALSE;
FatFastIoDispatch.MdlRead = FALSE;
FatFastIoDispatch.MdlReadComplete = FALSE;
FatFastIoDispatch.PrepareMdlWrite = FALSE;
FatFastIoDispatch.MdlWriteComplete = FALSE;
//FatFastIoDispatch.SizeOfFastIoDispatch = sizeof(FAST_IO_DISPATCH);
//FatFastIoDispatch.FastIoCheckIfPossible = FatFastIoCheckIfPossible; // CheckForFastIo
//FatFastIoDispatch.FastIoRead = FsRtlCopyRead; // Read
//FatFastIoDispatch.FastIoWrite = FsRtlCopyWrite; // Write
//FatFastIoDispatch.FastIoQueryBasicInfo = FatFastQueryBasicInfo; // QueryBasicInfo
//FatFastIoDispatch.FastIoQueryStandardInfo = FatFastQueryStdInfo; // QueryStandardInfo
//FatFastIoDispatch.FastIoLock = FatFastLock; // Lock
//FatFastIoDispatch.FastIoUnlockSingle = FatFastUnlockSingle; // UnlockSingle
//FatFastIoDispatch.FastIoUnlockAll = FatFastUnlockAll; // UnlockAll
//FatFastIoDispatch.FastIoUnlockAllByKey = FatFastUnlockAllByKey; // UnlockAllByKey
//FatFastIoDispatch.FastIoQueryNetworkOpenInfo = FatFastQueryNetworkOpenInfo;
//FatFastIoDispatch.AcquireForCcFlush = HrfsAcquireForCcFlush;
//FatFastIoDispatch.ReleaseForCcFlush = HrfsReleaseForCcFlush;
//FatFastIoDispatch.MdlRead = FsRtlMdlReadDev;
//FatFastIoDispatch.MdlReadComplete = FsRtlMdlReadCompleteDev;
//FatFastIoDispatch.PrepareMdlWrite = FsRtlPrepareMdlWriteDev;
//FatFastIoDispatch.MdlWriteComplete = FsRtlMdlWriteCompleteDev;
/* FsFilter通知回调例程在下层文件系统执行某些操作之前或之后调用。
如果需要获取更多有关于FsFilter回调例程相关信息,可参见FsRtlRegisterFileSystemFilterCallbacks例程
为了注册FsFilter的通知回调例程必须分配并初始化FS_FILTER_CALLBACKS结构体,然后向该结构体中促出FsFilter回调例程,
并将存储有Callbacks parameter到FsRtlRegisterFileSystemFilterCallbacks中。*/
RtlZeroMemory( &FilterCallbacks,
sizeof(FS_FILTER_CALLBACKS) );
FilterCallbacks.SizeOfFsFilterCallbacks = sizeof(FS_FILTER_CALLBACKS);
FilterCallbacks.PreAcquireForSectionSynchronization = HrfsFilterCallbackAcquireForCreateSection;
Status = FsRtlRegisterFileSystemFilterCallbacks( DriverObject,
&FilterCallbacks );
if (!NT_SUCCESS( Status )) {
IoDeleteDevice( HrfsDiskFileSystemDeviceObject );
return Status;
}
DbgPrint("HRFS device HRFS FilterCallbacks registed\n ");
RtlZeroMemory( &HrfsData, sizeof(FAT_DATA));
HrfsData.NodeTypeCode = HRFS_NTC_DATA_HEADER;
HrfsData.NodeByteSize = sizeof(FAT_DATA);
InitializeListHead(&HrfsData.VcbQueue);
pDriverObject = DriverObject;
HrfsData.DiskFileSystemDeviceObject = HrfsDiskFileSystemDeviceObject;
//
// This list head keeps track of closes yet to be done.
//
InitializeListHead( &HrfsData.AsyncCloseList );
InitializeListHead( &HrfsData.DelayedCloseList );
HrfsData.FatCloseItem = IoAllocateWorkItem( HrfsDiskFileSystemDeviceObject);
if (HrfsData.FatCloseItem == NULL) {
IoDeleteDevice (HrfsDiskFileSystemDeviceObject);
return STATUS_INSUFFICIENT_RESOURCES;
}
DbgPrint("HRFS device HRFS workitem created\n ");
//
// Allocate the zero page
//
HrfsData.ZeroPage = ExAllocatePoolWithTag( NonPagedPoolNx, PAGE_SIZE, 'ZtaF' );
if (HrfsData.ZeroPage == NULL) {
IoDeleteDevice (HrfsDiskFileSystemDeviceObject);
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlZeroMemory( HrfsData.ZeroPage, PAGE_SIZE );
//
// Now initialize our general purpose spinlock (gag) and figure out how
// deep and wide we want our delayed lists (along with fooling ourselves
// about the lookaside depths).
//
KeInitializeSpinLock( &HrfsData.GeneralSpinLock );
HrfsData.CacheManagerCallbacks.AcquireForLazyWrite = &HrfsAcquireFcbForLazyWrite;
HrfsData.CacheManagerCallbacks.ReleaseFromLazyWrite = &HrfsReleaseFcbFromLazyWrite;
HrfsData.CacheManagerCallbacks.AcquireForReadAhead = &HrfsAcquireFcbForReadAhead;
HrfsData.CacheManagerCallbacks.ReleaseFromReadAhead = &HrfsReleaseFcbFromReadAhead;
HrfsData.CacheManagerNoOpCallbacks.AcquireForLazyWrite = &HrfsNoOpAcquire;
HrfsData.CacheManagerNoOpCallbacks.ReleaseFromLazyWrite = &HrfsNoOpRelease;
HrfsData.CacheManagerNoOpCallbacks.AcquireForReadAhead = &HrfsNoOpAcquire;
HrfsData.CacheManagerNoOpCallbacks.ReleaseFromReadAhead = &HrfsNoOpRelease;
//
// Set up global pointer to our process.
//
HrfsData.OurProcess = PsGetCurrentProcess();
DbgPrint("HRFS device HRFS our process getted\n ");
//
// Setup the number of processors we support for statistics as the current number
// running.
//
#if (NTDDI_VERSION >= NTDDI_VISTA)
HrfsData.NumberProcessors = KeQueryActiveProcessorCount( NULL );
#else
HrfsData.NumberProcessors = KeNumberProcessors;
#endif
DbgPrint("HrfsData.NumberProcessors :%d", HrfsData.NumberProcessors);
ExInitializeResourceLite( &HrfsData.Resource );
IoRegisterFileSystem(HrfsDiskFileSystemDeviceObject);
ObReferenceObject (HrfsDiskFileSystemDeviceObject);
DbgPrint("Device HRFS HrfsDiskFileSystemDeviceObject registed\n ");
return( STATUS_SUCCESS );
}

rgb32 data resource mapping. using directx memcpy

I have been trying to solve the problem for a month with googling.
But Now I have to ask for help here.
I want to render using ffmpeg decoded frame.
and using frame(it converted to RGB32 format), I try to render frame with DX2D texture.
ZeroMemory(&TextureDesc, sizeof(TextureDesc));
TextureDesc.Height = pFrame->height;
TextureDesc.Width = pFrame->width;
TextureDesc.MipLevels = 1;
TextureDesc.ArraySize = 1;
TextureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; //size 16
TextureDesc.SampleDesc.Count = 1;
TextureDesc.SampleDesc.Quality = 0;
TextureDesc.Usage = D3D11_USAGE_DYNAMIC;
TextureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
TextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
TextureDesc.MiscFlags = 0;
result = m_device->CreateTexture2D(&TextureDesc, NULL, &m_2DTex);
if (FAILED(result)) return false;
ShaderResourceViewDesc.Format = TextureDesc.Format;
ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
ShaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
ShaderResourceViewDesc.Texture2D.MipLevels = 1;
D3D11_MAPPED_SUBRESOURCE S_mappedResource_tt = { 0, };
ZeroMemory(&S_mappedResource_tt, sizeof(D3D11_MAPPED_SUBRESOURCE));
result = m_deviceContext->Map(m_2DTex, 0, D3D11_MAP_WRITE_DISCARD, 0, &S_mappedResource_tt);
if (FAILED(result)) return false;
BYTE* mappedData = reinterpret_cast<BYTE *>(S_mappedResource_tt.pData);
for (auto i = 0; i < pFrame->height; ++i) {
memcpy(mappedData, pFrame->data, pFrame->linesize[0]);
mappedData += S_mappedResource_tt.RowPitch;
pFrame->data[0] += pFrame->linesize[0];
}
m_deviceContext->Unmap(m_2DTex, 0);
result = m_device->CreateShaderResourceView(m_2DTex, &ShaderResourceViewDesc, &m_ShaderResourceView);
if (FAILED(result)) return false;
m_deviceContext->PSSetShaderResources(0, 1, &m_ShaderResourceView);
but it shows me just black screen(nothing render).
I guess it's wrong memcpy size.
The biggest problem is that I don't know what is the problem.
Question 1 :
It has any problem creating 2D texture for mapping?
Question 2 :
What size of the memcpy parameters should I enter (related to formatting)?
I based on the link below.
[1]https://www.gamedev.net/forums/topic/667097-copy-2d-array-into-texture2d/
[2]https://www.gamedev.net/forums/topic/645514-directx-11-maping-id3d11texture2d/
[3]https://www.gamedev.net/forums/topic/606100-solved-dx11-updating-texture-data/
Thank U for watching, Please reply.
Nobody reply. I solved my issue.
I have modified some code and I'm not sure if it solves the problem. The problem with the black screen Reason is my matrix.
D3D11_TEXTURE2D_DESC TextureDesc;
D3D11_RENDER_TARGET_VIEW_DESC RenderTargetViewDesc;
D3D11_SHADER_RESOURCE_VIEW_DESC ShaderResourceViewDesc;
ZeroMemory(&TextureDesc, sizeof(TextureDesc));
TextureDesc.Height = pFrame->height;
TextureDesc.Width = pFrame->width;
TextureDesc.MipLevels = 1;
TextureDesc.ArraySize = 1;
TextureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;/*DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;*/ //size 32bit
TextureDesc.SampleDesc.Count = 1;
TextureDesc.SampleDesc.Quality = 0;
TextureDesc.Usage = D3D11_USAGE_DYNAMIC;
TextureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
TextureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
TextureDesc.MiscFlags = 0;
DWORD* pInitImage = new DWORD[pFrame->width*pFrame->height];
memset(pInitImage, 0, sizeof(DWORD)*pFrame->width*pFrame->height);
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = pInitImage;
InitData.SysMemPitch = pFrame->width*sizeof(DWORD);
InitData.SysMemSlicePitch = 0;
result = m_device->CreateTexture2D(&TextureDesc, &InitData, &m_2DTex);
if (FAILED(result)) return false;
ShaderResourceViewDesc.Format = TextureDesc.Format;
ShaderResourceViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
ShaderResourceViewDesc.Texture2D.MostDetailedMip = 0;
ShaderResourceViewDesc.Texture2D.MipLevels = 1;
result = m_device->CreateShaderResourceView(m_2DTex, &ShaderResourceViewDesc, &m_ShaderResourceView);
if (FAILED(result)) return false;
D3D11_MAPPED_SUBRESOURCE S_mappedResource_tt;
ZeroMemory(&S_mappedResource_tt, sizeof(S_mappedResource_tt));
DWORD Stride = pFrame->linesize[0];
result = m_deviceContext->Map(m_2DTex, 0, D3D11_MAP_WRITE_DISCARD, 0, &S_mappedResource_tt);
if (FAILED(result)) return false;
BYTE * pFrameData = pFrame->data[0]; // now we have a pointer that points to begin of the destination buffer
BYTE* mappedData = (BYTE *)S_mappedResource_tt.pData;// +S_mappedResource_tt.RowPitch;
for (auto i = 0; i < pFrame->height; i++) {
memcpy(mappedData, pFrameData, Stride);
mappedData += S_mappedResource_tt.RowPitch;
pFrameData += Stride;
}
m_deviceContext->Unmap(m_2DTex, 0);
It works vell. I hope that it will be helpful to those who are doing the same thing with me.

Send Concatinated SMS message using EasySMPP API (How to Add UDH Info)

i am using c# API called EasySMPP, it is pretty great in sending single SMS, it is also good in send large SMS, but the recipient get the messages separately, which is not meaningful, what i am looking is how to modify the PDU so that i can append the UDH info.
How can i achieve adding a UHD info, here is the SubmitSM method from the API,
public int SubmitSM
(
byte sourceAddressTon,
byte sourceAddressNpi,
string sourceAddress,
byte destinationAddressTon,
byte destinationAddressNpi,
destinationAddress,
byte esmClass,
byte protocolId,
byte priorityFlag,
DateTime sheduleDeliveryTime,
DateTime validityPeriod,
byte registeredDelivery,
byte replaceIfPresentFlag,
byte dataCoding,
byte smDefaultMsgId,
byte[] message)
{
try
{
byte[] _destination_addr;
byte[] _source_addr;
byte[] _SUBMIT_SM_PDU;
byte[] _shedule_delivery_time;
byte[] _validity_period;
int _sequence_number;
int pos;
byte _sm_length;
_SUBMIT_SM_PDU = new byte[KernelParameters.MaxPduSize];
////////////////////////////////////////////////////////////////////////////////////////////////
/// Start filling PDU
Tools.CopyIntToArray(0x00000004, _SUBMIT_SM_PDU, 4);
_sequence_number = smscArray.currentSMSC.SequenceNumber;
Tools.CopyIntToArray(_sequence_number, _SUBMIT_SM_PDU, 12);
pos = 16;
_SUBMIT_SM_PDU[pos] = 0x00; //service_type
pos += 1;
_SUBMIT_SM_PDU[pos] = sourceAddressTon;
pos += 1;
_SUBMIT_SM_PDU[pos] = sourceAddressNpi;
pos += 1;
_source_addr = Tools.ConvertStringToByteArray(Tools.GetString(sourceAddress, 20, ""));
Array.Copy(_source_addr, 0, _SUBMIT_SM_PDU, pos, _source_addr.Length);
pos += _source_addr.Length;
_SUBMIT_SM_PDU[pos] = 0x00;
pos += 1;
_SUBMIT_SM_PDU[pos] = destinationAddressTon;
pos += 1;
_SUBMIT_SM_PDU[pos] = destinationAddressNpi;
pos += 1;
_destination_addr = Tools.ConvertStringToByteArray(Tools.GetString(destinationAddress, 20, ""));
Array.Copy(_destination_addr, 0, _SUBMIT_SM_PDU, pos, _destination_addr.Length);
pos += _destination_addr.Length;
_SUBMIT_SM_PDU[pos] = 0x00;
pos += 1;
_SUBMIT_SM_PDU[pos] = esmClass;
pos += 1;
_SUBMIT_SM_PDU[pos] = protocolId;
pos += 1;
_SUBMIT_SM_PDU[pos] = priorityFlag;
pos += 1;
_shedule_delivery_time = Tools.ConvertStringToByteArray(Tools.GetDateString(sheduleDeliveryTime));
Array.Copy(_shedule_delivery_time, 0, _SUBMIT_SM_PDU, pos, _shedule_delivery_time.Length);
pos += _shedule_delivery_time.Length;
_SUBMIT_SM_PDU[pos] = 0x00;
pos += 1;
_validity_period = Tools.ConvertStringToByteArray(Tools.GetDateString(validityPeriod));
Array.Copy(_validity_period, 0, _SUBMIT_SM_PDU, pos, _validity_period.Length);
pos += _validity_period.Length;
_SUBMIT_SM_PDU[pos] = 0x00;
pos += 1;
_SUBMIT_SM_PDU[pos] = registeredDelivery;
pos += 1;
_SUBMIT_SM_PDU[pos] = replaceIfPresentFlag;
pos += 1;
_SUBMIT_SM_PDU[pos] = dataCoding;
pos += 1;
_SUBMIT_SM_PDU[pos] = smDefaultMsgId;
pos += 1;
_sm_length = message.Length > 254 ? (byte)254 : (byte)message.Length;
_SUBMIT_SM_PDU[pos] = _sm_length;
pos += 1;
Array.Copy(message, 0, _SUBMIT_SM_PDU, pos, _sm_length);
pos += _sm_length;
Tools.CopyIntToArray(pos, _SUBMIT_SM_PDU, 0);
Send(_SUBMIT_SM_PDU, pos);
undeliveredMessages++;
return _sequence_number;
}
catch (Exception ex)
{
logMessage(LogLevels.LogExceptions, "SubmitSM | " + ex.ToString());
}
return -1;
}
Thanks a lot!!!!
As I can see, EasySMPP has option to split long text.
public int SendSms(String from, String to, bool splitLongText, String text, byte askDeliveryReceipt, byte esmClass, byte dataCoding)
Otherwise, smpp protocol has ability to do manually also.
Either in SAR parameters:
SAR_MSG_REF_NUM - reference, unique to all sms parts
SAR_SEGMENT_SEQNUM - sequence number (1,2,3...)
SAR_TOTAL_SEGMENTS - number of all sequences
or you can encapsulate in the beggining of the message
with UDHI set to 64
or you can set message in MESSAGE_PAYLOAD TLV and SMSC will do it for you.
Hope it helps
Here is the method where UDH is added.
public int SendSms(String from, String to,
bool splitLongText, String text,
byte askDeliveryReceipt,
byte esmClass, byte dataCoding)
{
int messageId = -1;
byte sourceAddressTon;
byte sourceAddressNpi;
string sourceAddress;
byte destinationAddressTon;
byte destinationAddressNpi;
string destinationAddress;
byte registeredDelivery;
byte maxLength;
sourceAddress = Tools.GetString(from, 20, "");
sourceAddressTon = getAddrTon(sourceAddress);
sourceAddressNpi = getAddrNpi(sourceAddress);
destinationAddress = Tools.GetString(to, 20, "");
destinationAddressTon = getAddrTon(destinationAddress);
destinationAddressNpi = getAddrNpi(destinationAddress);
registeredDelivery = askDeliveryReceipt;
if (dataCoding == 8)
{
// text = Tools.Endian2UTF(text);
maxLength = 70;
}
else
maxLength = 160;
if ((text.Length <= maxLength) || (splitLongText))
{
byte protocolId;
byte priorityFlag;
DateTime sheduleDeliveryTime;
DateTime validityPeriod;
byte replaceIfPresentFlag;
byte smDefaultMsgId;
// byte[] message = new byte[146];
byte[] udh = new byte[6];
string smsText = text;
byte[] message;
protocolId = 0;
priorityFlag = PriorityFlags.VeryUrgent;
sheduleDeliveryTime = DateTime.MinValue;
validityPeriod = DateTime.MinValue;
replaceIfPresentFlag =
ReplaceIfPresentFlags.DoNotReplace;
smDefaultMsgId = 0;
if (dataCoding == 8)
{
message = new byte[70];
}
else
{
message = new byte[146];
}
string[] lists = dataCoding == 8 ?
split_message_unicode(text) :
split_message_asci(text);
int count = 1;
foreach (string s in lists)
{
Array.Clear(message, 0, message.Length);
// while (smsText.Length > 0)
// {
int pos = 0;
// byte desc = Convert.ToByte('c');
byte headerLen = Convert.ToByte(05);
byte concat = Convert.ToByte(00);
byte refNo = Convert.ToByte(03);
byte sequenceNo = Convert.ToByte(03);
byte NoOfMessages = Convert.ToByte(lists.Length);
byte partNo = Convert.ToByte(count);
count++;
udh[pos] = headerLen;
pos++;
udh[pos] = concat;
pos++;
udh[pos] = refNo;
pos++;
udh[pos] = sequenceNo;
pos++;
udh[pos] = NoOfMessages;
pos++;
udh[pos] = partNo;
pos++;
Array.Copy(udh, 0, message, 0, pos);
if (dataCoding == 8)
{
int len = Tools.GetEthiopic(s).Length;
Array.Copy(Tools.GetEthiopic(s), 0, message,
pos, len);
//message =
Tools.GetEthiopic(smsText.Substring(0, smsText.Length >
maxLength ? maxLength : smsText.Length));
//message =
Encoding.UTF8.GetBytes(smsText.Substring(0, smsText.Length >
maxLength ? maxLength : smsText.Length));
}
else{
// message = Encoding.ASCII.GetBytes(s);
Array.Copy(Encoding.ASCII.GetBytes(s), 0,
message, pos, Encoding.ASCII.GetBytes(s).Length);
}
smsText = smsText.Remove(0, smsText.Length >
maxLength ? maxLength : smsText.Length);
messageId = SubmitSM(sourceAddressTon,
sourceAddressNpi, sourceAddress,
destinationAddressTon,
destinationAddressNpi, destinationAddress,
esmClass, protocolId,
priorityFlag,
sheduleDeliveryTime,
validityPeriod, registeredDelivery, replaceIfPresentFlag,
dataCoding, smDefaultMsgId,
message);
// }
}
}
else
{
byte[] data;
if (dataCoding == 8)
data = Tools.GetEthiopic(text);
//data = Encoding.UTF8.GetBytes(text);
else
data = Encoding.ASCII.GetBytes(text);
messageId = DataSM(sourceAddressTon, sourceAddressNpi,
sourceAddress,
destinationAddressTon,
destinationAddressNpi, destinationAddress,
esmClass, registeredDelivery,
dataCoding, data);
}
return messageId;
}
pass ems_class as 0x40, what you need to to is just to split your message in to parts, here is splitting method,
private string[] split_message_asci(string message)
{
int message_len = message.Length;
decimal val=(message.Length / 140m);
decimal parts = Math.Ceiling(val);
string[] strs = new string[(int)parts];
string str = string.Empty;
int interval=140;
int i =0;
int Count= 0;
while (i < message_len)
{
if (Count < (int)parts-1)
{
str = message.Substring(i, interval);
strs[Count] = str;
i += interval ;
}
else
{
str = message.Substring(i, message_len-i);
strs[Count] = str;
i += interval + 1;
}
Count++;
}
return strs;
}

Structure of the certificate pointed to by NCRYPT_KEY_HANDLE

I've written a credential provider and a key storage provider to logon to windows via certificate. As the documentation in this points is quite vague I used different samples from Microsoft to get things working.
I think I'm nearly there, but the logon behaves unpredictably. Sometimes I get through to the kerberos server (which complains about the certificate), sometimes the process fails with 0x80090029 without any information and sometimes windows crashes. As these crashes all have to do with access violations or null pointers and happen to occur in various places (kerberos.dll, Windows.UI.Logon.dll, ...) I think it has something to do with my key structure that i point the given NCRYT_KEY_HANDLE to in my OpenKey-implementation.
The KeyStorageProviderSample in the CNG-Kit has an example, but relies on a RSA-key stored in %AppData%. I don't have the private key available as it is stored in secure hardware, I just have the public part (i.e. the public certificate), that I read from another device and import via the following code:
SECURITY_STATUS WINAPI KeyHandler::ReadPemCert(__inout KSP_KEY *keyHandle)
{
LOG_FUNCTION;
CERT_CONTEXT certContext = {};
DWORD readLength = 0;
LOG("Fetch certificate");
const int maxSizeInBytes = 4096;
char pemCertificateAsBytes[maxSizeInBytes];
BluetoothClient bluetoothClient = BluetoothClient();
bluetoothClient.getCertificate((PBYTE)pemCertificateAsBytes, readLength);
DWORD certAsDerLen = readLength;
BYTE* certAsDer = new BYTE[certAsDerLen];
LOG("convert PEM to DER");
if (!CryptStringToBinaryA(pemCertificateAsBytes, 0, CRYPT_STRING_BASE64, certAsDer, &certAsDerLen, NULL, NULL))
{
LOG_LAST_ERROR("CryptStringToBinary failed. Err:");
}
LOG_BYTES_AS_HEX("DER-Zertifikat", certAsDer, certAsDerLen);
PCCERT_CONTEXT pcCertContext = CertCreateCertificateContext(X509_ASN_ENCODING, certAsDer, certAsDerLen);
certContext->pCertInfo = pcCertContext->pCertInfo;
certContext->cbCertEncoded = pcCertContext->cbCertEncoded;
certContext->pbCertEncoded = pcCertContext->pbCertEncoded;
certContext->dwCertEncodingType = pcCertContext->dwCertEncodingType;
CERT_INFO *certInfo;
certInfo = certContext.pCertInfo;
CERT_PUBLIC_KEY_INFO pubKeyInfo = certInfo->SubjectPublicKeyInfo;
LOG("Aquire cryptocontext");
HCRYPTPROV hProv = 0;
if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
{
{
LOG_LAST_ERROR("CryptAcquireContext failed. Err:");
return -1;
}
}
LOG("Importing public key");
NCRYPT_KEY_HANDLE publicKeyHandle = NULL;
if (!CryptImportPublicKeyInfo(hProv, X509_ASN_ENCODING, &pubKeyInfo, &publicKeyHandle))
{
LOG_LAST_ERROR("CryptImportPublicKeyInfo failed. Err:");
return -1;
}
keyHandle->fFinished = TRUE;
keyHandle->hPublicKey = (BCRYPT_KEY_HANDLE)publicKeyHandle;
keyHandle->pszKeyBlobType = BCRYPT_RSAPUBLIC_BLOB;
LocalFree(certInfo);
return ERROR_SUCCESS;
}
The key structure is initialized this way:
SECURITY_STATUS
WINAPI
KeyHandler::CreateNewKeyObject(
__in_opt LPCWSTR pszKeyName,
__deref_out KSP_KEY **ppKey)
{
LOG_FUNCTION;
KSP_KEY *pKey = NULL;
DWORD cbKeyName = 0;
SECURITY_STATUS Status = NTE_INTERNAL_ERROR;
NTSTATUS ntStatus = STATUS_INTERNAL_ERROR;
pKey = (KSP_KEY *)HeapAlloc(GetProcessHeap(), 0, sizeof(KSP_KEY));
if (pKey == NULL)
{
return NTE_NO_MEMORY;
}
pKey->cbLength = sizeof(KSP_KEY);
pKey->dwMagic = KSP_KEY_MAGIC;
pKey->dwAlgID = KSP_RSA_ALGID;
pKey->pszKeyFilePath = NULL;
pKey->pszKeyBlobType = NULL;
pKey->dwKeyBitLength = 0;
pKey->fFinished = FALSE;
//Copy the keyname into the key struct.
if (pszKeyName != NULL)
{
cbKeyName = (DWORD)(wcslen(pszKeyName) + 1) * sizeof(WCHAR);
pKey->pszKeyName = (LPWSTR)HeapAlloc(
GetProcessHeap(),
0,
cbKeyName + sizeof(WCHAR));
if (pKey->pszKeyName == NULL)
{
return NTE_NO_MEMORY;
}
CopyMemory(pKey->pszKeyName, pszKeyName, cbKeyName);
pKey->pszKeyName[cbKeyName / sizeof(WCHAR)] = L'\0';
}
else
{
pKey->pszKeyName = NULL;
}
if (globalRSAProviderHandle == NULL)
{
ntStatus = BCryptOpenAlgorithmProvider(
&globalRSAProviderHandle,
BCRYPT_RSA_ALGORITHM,
NULL,
0);
if (!NT_SUCCESS(ntStatus))
{
return NormalizeNteStatus(ntStatus);
}
}
pKey->hProvider = globalRSAProviderHandle;
pKey->pbKeyFile = NULL;
pKey->cbKeyFile = 0;
pKey->pbPrivateKey = NULL;
pKey->cbPrivateKey = 0;
pKey->hPublicKey = NULL;
pKey->hPrivateKey = NULL;
pKey->dwExportPolicy = NCRYPT_ALLOW_EXPORT_FLAG | NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;
pKey->dwKeyUsagePolicy = NCRYPT_ALLOW_DECRYPT_FLAG | NCRYPT_ALLOW_SIGNING_FLAG;
pKey->pbSecurityDescr = NULL;
pKey->cbSecurityDescr = 0;
InitializeListHead(&pKey->PropertyList);
*ppKey = pKey;
pKey = NULL;
return ERROR_SUCCESS;
}
Somewhere in there must be the mistake leading to the various memory errors. But as I'm quite new to windows programming and c/c++ I just can't spot the point and can't find any documentation about the datastructure that windows expects for the NCRYTP_KEY_HANDLE.
Does anybody know more about this structure?
NCRYPT_KEY_HANDLE is just a pointer to a structure that you defined.
Windows itself doesn't care about this structure and expect that your provider knows how to work with it.
In KeyHandler::ReadPemCert you mixed legacy CryptoAPI and CNG API. Since you are implementing KSP you should use only CNG API (CryptImportPublicKeyInfoEx2).
DWORD error = NTE_FAIL;
BCRYPT_KEY_HANDLE hKey = NULL;
...
PCCERT_CONTEXT pcCertContext = CertCreateCertificateContext(X509_ASN_ENCODING, certAsDer, certAsDerLen);
if(!pcCertContext)
{
goto Exit;
}
if (!CryptImportPublicKeyInfoEx2(X509_ASN_ENCODING, &pcCertContext->pCertInfo->SubjectPublicKeyInfo, 0, nullptr, &hKey))
{
goto Exit;
}
/* Also you can export key and print out the result to make sure everything works
DWORD temp = 0;
status = BCryptExportKey(hKey, 0, BCRYPT_RSAPUBLIC_BLOB, nullptr, 0, &temp, 0);
if (status != ERROR_SUCCESS)
{
goto Exit;
}
std::vector<BYTE> key(temp);
status = BCryptExportKey(hKey, 0, BCRYPT_RSAPUBLIC_BLOB, key.data(), key.size(), &temp, 0);
if (status != ERROR_SUCCESS)
{
goto Exit;
}
for (auto const& i : key)
{
std::cout << std::hex << (int)i;
}
}
*/
keyHandle->fFinished = TRUE;
keyHandle->hPublicKey = hKey;
keyHandle->pszKeyBlobType = BCRYPT_RSAPUBLIC_BLOB;
erro = ERROR_SUCCESS;
Exit:
if(pcCertContext)
{
CertFreeCertificateContext(pcCertContext);
}
return error;

Hooking NtQueryDirectoryFile can't hide files

I want to hide files (in my program). I decided to use NtQueryDirectoryFile. But the files are not hidden, the code does not work. I don't use a driver, I use user mode. Can anybody help me please?
The code snippet:
typedef NTSTATUS (WINAPI * NTQUERYDIRECTORYFILE) (IN HANDLE FileHandle,IN HANDLE Event OPTIONAL,IN PIO_APC_ROUTINE ApcRoutine OPTIONAL,IN PVOID ApcContext OPTIONAL,OUT PIO_STATUS_BLOCK IoStatusBlock,OUT PVOID FileInformation,IN ULONG FileInformationLength,IN MYFILE_INFORMATION_CLASS FileInformationClass,IN BOOLEAN ReturnSingleEntry,IN PUNICODE_STRING FileName OPTIONAL,IN BOOLEAN RestartScan);
NTQUERYDIRECTORYFILE OriginalNtQueryDirectoryFile;
#define STATUS_NO_SUCH_FILE 0xC000000F
NTSTATUS
HookedNtQueryDirectoryFile(
IN HANDLE FileHandle,
IN HANDLE Event OPTIONAL,
IN PIO_APC_ROUTINE ApcRoutine OPTIONAL,
IN PVOID ApcContext OPTIONAL,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FileInformation,
IN ULONG FileInformationLength,
IN MYFILE_INFORMATION_CLASS FileInformationClass,
IN BOOLEAN ReturnSingleEntry,
IN PUNICODE_STRING FileName OPTIONAL,
IN BOOLEAN RestartScan)
{
NTSTATUS status = OriginalNtQueryDirectoryFile(FileHandle,Event,ApcRoutine,ApcContext,IoStatusBlock,FileInformation,FileInformationLength,FileInformationClass,ReturnSingleEntry,FileName,RestartScan);
vector<wstring> listDataForHidding;
listDataForHidding.push_back(L"afile.txt");
listDataForHidding.push_back(L"bfile.txt");
listDataForHidding.push_back(L"cfile.txt");
listDataForHidding.push_back(L"dfile.txt");
if (NT_SUCCESS(status))
{
PMYFILE_DIRECTORY_INFORMATION FileDirectoryInfo, LastFileDirectoryInfo;
PMYFILE_FULL_DIR_INFORMATION LastFileFullDirectoryInfo, FileFullDirectoryInfo;
PMYFILE_BOTH_DIR_INFORMATION LastFileBothDirectoryInfo, FileBothDirectoryInfo;
PMYFILE_NAMES_INFORMATION LastFileNamesInfo, FileNamesInfo;
ULONG Offset = 0;
BOOL bNeedHide = FALSE;
switch (FileInformationClass)
{
case FileDirectoryInformation :
FileDirectoryInfo = NULL;
do
{
//FileDirectoryInfo = (PVOID)((ULONG)FileInformation + Offset);
FileDirectoryInfo = (PMYFILE_DIRECTORY_INFORMATION)((ULONG)FileInformation + Offset);
LastFileDirectoryInfo = FileDirectoryInfo;
wstring wstrCurrFileName = FileDirectoryInfo->FileName;
bNeedHide = FALSE;
for(size_t index = 0; index < listDataForHidding.size(); index ++)
{
if(wstrCurrFileName.find(listDataForHidding[index]) != wstring::npos)
{
bNeedHide = TRUE;
break;
}
}
//if (FileDirectoryInfo->FileName[0] == 0x5F00)
if(bNeedHide == TRUE)
{
if (!FileDirectoryInfo->NextEntryOffset)
{
if (LastFileDirectoryInfo) LastFileDirectoryInfo->NextEntryOffset = 0;
else status = STATUS_NO_SUCH_FILE;
return status;
} else
if (LastFileDirectoryInfo) LastFileDirectoryInfo->NextEntryOffset += FileDirectoryInfo->NextEntryOffset;
}
Offset += FileDirectoryInfo->NextEntryOffset;
} while (FileDirectoryInfo->NextEntryOffset);
break;
case FileFullDirectoryInformation :
FileFullDirectoryInfo = NULL;
do
{
LastFileFullDirectoryInfo = FileFullDirectoryInfo;
//FileFullDirectoryInfo = (PVOID)((ULONG)FileInformation + Offset);
FileFullDirectoryInfo = (PMYFILE_FULL_DIR_INFORMATION)((ULONG)FileInformation + Offset);
wstring wstrCurrFileName = FileDirectoryInfo->FileName;
bNeedHide = FALSE;
for(size_t index = 0; index < listDataForHidding.size(); index ++)
{
if(wstrCurrFileName.find(listDataForHidding[index]) != wstring::npos)
{
bNeedHide = TRUE;
break;
}
}
//if (FileFullDirectoryInfo->FileName[0] == 0x5F00)
if(bNeedHide == TRUE)
{
if (!FileFullDirectoryInfo->NextEntryOffset)
{
if (LastFileFullDirectoryInfo) LastFileFullDirectoryInfo->NextEntryOffset = 0;
else status = STATUS_NO_SUCH_FILE;
return status;
} else
if (LastFileFullDirectoryInfo) LastFileFullDirectoryInfo->NextEntryOffset += FileFullDirectoryInfo->NextEntryOffset;
}
Offset += FileFullDirectoryInfo->NextEntryOffset;
} while (FileFullDirectoryInfo->NextEntryOffset);
break;
case FileBothDirectoryInformation :
FileBothDirectoryInfo = NULL;
do
{
LastFileBothDirectoryInfo = FileBothDirectoryInfo;
//FileBothDirectoryInfo = (PVOID)((ULONG)FileInformation + Offset);
FileBothDirectoryInfo = (PMYFILE_BOTH_DIR_INFORMATION)((ULONG)FileInformation + Offset);
wstring wstrCurrFileName = FileDirectoryInfo->FileName;
bNeedHide = FALSE;
for(size_t index = 0; index < listDataForHidding.size(); index ++)
{
if(FileBothDirectoryInfo->FileNameLength > 1 && wstrCurrFileName.find(listDataForHidding[index]) != wstring::npos)
{
bNeedHide = TRUE;
break;
}
}
//if (FileBothDirectoryInfo->FileNameLength > 1 && FileBothDirectoryInfo->FileName[0] == 0x5F00)
if(bNeedHide == TRUE)
{
if (!FileBothDirectoryInfo->NextEntryOffset)
{
if (LastFileBothDirectoryInfo) LastFileBothDirectoryInfo->NextEntryOffset = 0;
else status = STATUS_NO_SUCH_FILE;
return status;
} else
if (LastFileBothDirectoryInfo) LastFileBothDirectoryInfo->NextEntryOffset += FileBothDirectoryInfo->NextEntryOffset;
}
Offset += FileBothDirectoryInfo->NextEntryOffset;
} while (FileBothDirectoryInfo->NextEntryOffset);
break;
case FileNamesInformation :
FileNamesInfo = NULL;
do
{
LastFileNamesInfo = FileNamesInfo;
//FileNamesInfo = (PVOID)((ULONG)FileInformation + Offset);
FileNamesInfo = (PMYFILE_NAMES_INFORMATION)((ULONG)FileInformation + Offset);
wstring wstrCurrFileName = FileDirectoryInfo->FileName;
bNeedHide = FALSE;
for(size_t index = 0; index < listDataForHidding.size(); index ++)
{
if(wstrCurrFileName.find(listDataForHidding[index]) != wstring::npos)
{
bNeedHide = TRUE;
break;
}
}
//if (FileNamesInfo->FileName[0] == 0x5F00)
if(bNeedHide == TRUE)
{
if (!FileNamesInfo->NextEntryOffset)
{
if(LastFileNamesInfo) LastFileNamesInfo->NextEntryOffset = 0;
else status = STATUS_NO_SUCH_FILE;
return status;
} else
if (LastFileNamesInfo) LastFileNamesInfo->NextEntryOffset += FileNamesInfo->NextEntryOffset;
}
Offset += FileNamesInfo->NextEntryOffset;
} while (FileNamesInfo->NextEntryOffset);
break;
}
}
return status;
}

Resources