How to set l2tp preshared key? - c

I need to create RASENTRY for L2TP with pre-shared key set. So far, I can see that entry has somewhat correct flags, but no key is set, unfortunately.
Here is code:
int common_ras_manager_create_entry(const char* server_address, const char* username, const char* password, MY_VPN_CONNECTION_TYPE connection_type, const char* preshared_key)
{
DWORD EntryInfoSize = 0;
DWORD DeviceInfoSize = 0;
DWORD Ret;
LPRASENTRY lpRasEntry;
LPBYTE lpDeviceInfo;
// Get buffer sizing information for a default phonebook entry
if ((Ret = RasGetEntryProperties(NULL, "", NULL, &EntryInfoSize, lpDeviceInfo, &DeviceInfoSize)) != 0)
{
if (Ret != ERROR_BUFFER_TOO_SMALL)
{
printf("RasGetEntryProperties sizing failed with error %d\n", Ret);
return Ret;
}
}
lpRasEntry = (LPRASENTRY) GlobalAlloc(GPTR, EntryInfoSize);
if (DeviceInfoSize == 0)
lpDeviceInfo = NULL;
else
lpDeviceInfo = (LPBYTE) GlobalAlloc(GPTR, DeviceInfoSize);
// Get default phonebook entry
lpRasEntry->dwSize = sizeof(RASENTRY);
if ((Ret = RasGetEntryProperties(NULL, "", lpRasEntry, &EntryInfoSize, lpDeviceInfo, &DeviceInfoSize)) != 0)
{
printf("RasGetEntryProperties failed with error %d\n", Ret);
return Ret;
}
// Validate new phonebook name "Testentry"
if ((Ret = RasValidateEntryName(NULL, APP_NAME)) != ERROR_SUCCESS)
{
printf("RasValidateEntryName failed with error %d\n", Ret);
if (Ret != ERROR_ALREADY_EXISTS)
return Ret;
}
LPRASDEVINFO ras_devices;
DWORD cb =sizeof(RASDEVINFO);
DWORD cbDevices = 0;
ras_devices = (LPRASDEVINFO)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cb);
if (NULL == ras_devices)
{
printf("HeapAlloc failed.\n");
return ERROR_OUTOFMEMORY;
}
ras_devices->dwSize = sizeof(RASDEVINFO);
if ((Ret = RasEnumDevices(ras_devices, &cb, &cbDevices)) != ERROR_SUCCESS)
{
printf("RasEnumDevices failed with error %d\n", Ret);
switch(Ret)
{
case ERROR_BUFFER_TOO_SMALL:
printf("buffer too small");
HeapFree(GetProcessHeap(), 0, (LPVOID)ras_devices);
ras_devices = (LPRASDEVINFO)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cb);
if (NULL == ras_devices)
{
printf("HeapAlloc failed.\n");
return ERROR_OUTOFMEMORY;
}
ras_devices->dwSize = sizeof(RASDEVINFO);
Ret = RasEnumDevices(ras_devices, &cb, &cbDevices);
if (ERROR_SUCCESS == Ret)
{
//fSuccess = TRUE;
}
else
{
printf("RasEnumDevices failed again: Error = %d\n", Ret);
return Ret;
//goto done;
}
break;
case ERROR_NOT_ENOUGH_MEMORY:
printf("ERROR_NOT_ENOUGH_MEMORY");
return Ret;
break;
case ERROR_INVALID_PARAMETER:
printf("ERROR_INVALID_PARAMETER");
return Ret;
break;
case ERROR_INVALID_USER_BUFFER:
printf("ERROR_INVALID_USER_BUFFER");
return Ret;
break;
}
}
DWORD dwVpnStrategy = 0;
char device_name_mask[5];
strcpy(device_name_mask, "");
gboolean preshared_key_valid = 0;
switch(connection_type)
{
case PPTP:
strcpy(device_name_mask, "PPTP");
dwVpnStrategy = VS_PptpOnly;
break;
case L2TP:
if (preshared_key == 0 || strlen(preshared_key) == 0)
{
printf("CRITICAL: preshared key not set.");
return 1;
}
else
{
preshared_key_valid = TRUE;
}
strcpy(device_name_mask, "L2TP");
dwVpnStrategy = VS_L2tpOnly;
break;
}
int i =0;
for (i = 0; i < cbDevices; i++)
{
RASDEVINFO r = ras_devices[i];
if (strstr(r.szDeviceName, device_name_mask))
{
break;
}
}
//lpRasEntry->dwfOptions |= RASEO_SpecificIpAddr;
//lpRasEntry->szLocalPhoneNumber = RASDT_Vpn;
lpRasEntry->dwfNetProtocols |= RASNP_Ip;
lpRasEntry->dwFramingProtocol = RASFP_Ppp;
lstrcpy(lpRasEntry->szDeviceType, RASDT_Vpn);
lstrcpy(lpRasEntry->szDeviceName, ras_devices[i].szDeviceName);
lstrcpy(lpRasEntry->szLocalPhoneNumber, server_address);
lpRasEntry->dwVpnStrategy = dwVpnStrategy; // VS_PptpOnly; VS_SstpOnly
if (preshared_key_valid)
{
L2TP_CONFIG_DATA* data = GlobalAlloc(GPTR, sizeof(L2TP_CONFIG_DATA));
lpRasEntry->dwfOptions2 |= RASEO2_UsePreSharedKey;
data->dwOffsetKey = 16;
memcpy((PBYTE)data + data->dwOffsetKey, preshared_key, strlen(preshared_key));
data->dwAuthType =L2TP_IPSEC_AUTH_PRESHAREDKEY;
RasSetCustomAuthData(NULL, APP_NAME, data, sizeof(L2TP_CONFIG_DATA));
}
if ((Ret = RasSetEntryProperties(NULL, APP_NAME, lpRasEntry, EntryInfoSize, lpDeviceInfo, DeviceInfoSize)) != 0)
{
printf("RasSetEntryProperties failed with error %d\n", Ret);
return Ret;
}
//if ((Ret = RasSetCredentials(NULL, lpRasEntry.))
}
I cant find where is buffer to fill for pre-shared key.

Following code works fine.
// l2tp
if (preshared_key_valid)
{
RASCREDENTIALS ras_cre_psk = {0};
ras_cre_psk.dwSize = sizeof(ras_cre_psk);
ras_cre_psk.dwMask = 0x00000010; //RASCM_PreSharedKey;
wcscpy(ras_cre_psk.szPassword, preshared_key);
if ((Ret = RasSetCredentials(NULL, APP_NAME, &ras_cre_psk, FALSE)))
{
printf("RasSetCredentials failed with error %d\n", Ret);
return Ret;
}
}

Related

Defragmenting File Programatically On Windows

I am attempting to follow this tutorial: Defragmenting Files.
I call DeviceIoControl() with FSCTL_GET_VOLUME_BITMAP on a handle to the C: volume, and I get a proper response.
I then open a handle to another file (I tried files from 10KB to a few MB) successfully, then I call DeviceIoControl() with FSCTL_GET_RETRIEVAL_POINTERS, and it succeeds with no last error or failed result, but the RETRIEVAL_POINTERS_BUFFER is not filled.
I also tried calling it on the C: volume handle, but it keeps returning ERROR_HANDLE_EOF even after trying to set the OVERLAPPED offset to 0, and setting the file pointer with SetFilePointer() to 0 relative to the beginning of the file.
BOOL dic(HANDLE dev, DWORD code, LPVOID in, DWORD ins, LPVOID out, LPDWORD outs)
{
HANDLE h = GetProcessHeap();
DWORD s = 1000;
DWORD r = 0;
out = HeapAlloc(h,HEAP_ZERO_MEMORY,s);
while (!DeviceIoControl(dev, code, in, ins, out, s, &r, 0))
{
if (ERROR_INSUFFICIENT_BUFFER == GetLastError() || ERROR_MORE_DATA == GetLastError())
{
s *= 10;
LPVOID t = HeapReAlloc(h, HEAP_ZERO_MEMORY, out, s);
if(!t){
HeapFree(h, 0, out);
return 0;
}
out = t;
}
else
{
HeapFree(h, 0, out);
printf("dic unk: %d\n", GetLastError());
return 0;
}
}
*outs = s;
return 1;
}
BOOL getvolptr(HANDLE volh, PRETRIEVAL_POINTERS_BUFFER rpb, LPDWORD rpbs)
{
STARTING_VCN_INPUT_BUFFER vcn = { 0 };
return dic(volh, FSCTL_GET_RETRIEVAL_POINTERS, &vcn, sizeof(vcn), rpb, rpbs);
}
RETRIEVAL_POINTERS_BUFFER rpb = { 0 };
DWORD rpbs = 0;
ULONGLONG cluster_cnt=0;
HANDLE fi = openfile("C:\\Windows\\System32\\Kernel32.dll");
if (INVALID_HANDLE_VALUE == fi)
{
printf("failed to open file! (%d)\n", GetLastError());
getchar();
}
r = getvolptr(fi, &rpb, &rpbs);
if (!r)
{
printf("failed to get vol ptrs! (%d)\n", GetLastError());
getchar();
}
for (int i = 0; i < rpb.ExtentCount; ++i)
{
cluster_cnt = (ULONGLONG)(rpb.Extents[i].NextVcn.QuadPart) - (ULONGLONG)(rpb.StartingVcn.QuadPart);
printf("%d) size: %llu clusters (0x%016X)\n", i, cluster_cnt, rpb.Extents[i].Lcn.QuadPart);
}
You are not checking the first HeapAlloc() for failure. And HeapFree() can wipe the last error code from DeviceIoControl() before you print it.
But more importantly, you are not passing the out data back to the caller correctly, so you are leaking the allocated memory, and the caller ends up with garbage for output.
Since the caller is passing in their own RETRIEVAL_POINTERS_BUFFER to receive the data, you need to copy the contents of the allocate memory into that buffer, eg:
BOOL dic(HANDLE dev, DWORD code, LPVOID in, DWORD ins, LPVOID out, LPDWORD outs)
{
if (!in || !out || !outs)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
*outs = 0;
HANDLE h = GetProcessHeap();
DWORD s = 1000;
LPVOID buf = HeapAlloc(h, HEAP_ZERO_MEMORY, s);
if (!buf)
return FALSE;
DWORD r = 0;
while (!DeviceIoControl(dev, code, in, ins, buf, s, &r, 0))
{
if (ERROR_INSUFFICIENT_BUFFER == GetLastError() || ERROR_MORE_DATA == GetLastError())
{
s *= 10;
LPVOID t = HeapReAlloc(h, HEAP_ZERO_MEMORY, buf, s);
if (!t)
{
HeapFree(h, 0, buf);
return FALSE;
}
buf = t;
}
else
{
printf("dic unk: %u\n", GetLastError());
HeapFree(h, 0, buf);
return FALSE;
}
}
if (s > *outs)
{
HeapFree(h, 0, buf);
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
CopyMemory(out, buf, s);
*outs = s;
HeapFree(h, 0, buf);
return TRUE;
}
BOOL getvolptr(HANDLE volh, PRETRIEVAL_POINTERS_BUFFER rpb, LPDWORD rpbs)
{
STARTING_VCN_INPUT_BUFFER vcn = { 0 };
return dic(volh, FSCTL_GET_RETRIEVAL_POINTERS, &vcn, sizeof(vcn), rpb, rpbs);
}
HANDLE fi = openfile("C:\\Windows\\System32\\Kernel32.dll");
if (INVALID_HANDLE_VALUE == fi)
{
printf("failed to open file! (%u)\n", GetLastError());
getchar();
}
else
{
RETRIEVAL_POINTERS_BUFFER rpb = { 0 };
DWORD rpbs = sizeof(rpb);
if (!getvolptr(fi, &rpb, &rpbs))
{
printf("failed to get vol ptrs! (%u)\n", GetLastError());
getchar();
}
else
{
ULONGLONG cluster_cnt = 0;
for (int i = 0; i < rpb.ExtentCount; ++i)
{
cluster_cnt = (ULONGLONG)(rpb.Extents[i].NextVcn.QuadPart) - (ULONGLONG)(rpb.StartingVcn.QuadPart);
printf("%d) size: %llu clusters (0x%016X)\n", i, cluster_cnt, rpb.Extents[i].Lcn.QuadPart);
}
}
closefile(fi);
}
Alternatively, you can return the pointer to the allocated memory to the caller, and the caller will have to free the memory when done using it, eg:
BOOL dic(HANDLE dev, DWORD code, LPVOID in, DWORD ins, LPVOID* out, LPDWORD outs)
{
if (!in || !out || !outs)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
*out = NULL;
*outs = 0;
HANDLE h = GetProcessHeap();
DWORD s = 1000;
LPVOID buf = HeapAlloc(h, HEAP_ZERO_MEMORY, s);
if (!buf)
return FALSE;
DWORD r = 0;
while (!DeviceIoControl(dev, code, in, ins, buf, s, &r, 0))
{
if (ERROR_INSUFFICIENT_BUFFER == GetLastError() || ERROR_MORE_DATA == GetLastError())
{
s *= 10;
LPVOID t = HeapReAlloc(h, HEAP_ZERO_MEMORY, buf, s);
if (!t)
{
HeapFree(h, 0, buf);
return FALSE;
}
buf = t;
}
else
{
printf("dic unk: %u\n", GetLastError());
HeapFree(h, 0, buf);
return FALSE;
}
}
*out = buf;
*outs = s;
return TRUE;
}
BOOL getvolptr(HANDLE volh, PRETRIEVAL_POINTERS_BUFFER* rpb, LPDWORD rpbs)
{
STARTING_VCN_INPUT_BUFFER vcn = { 0 };
return dic(volh, FSCTL_GET_RETRIEVAL_POINTERS, &vcn, sizeof(vcn), (void**)rpb, rpbs);
}
HANDLE fi = openfile("C:\\Windows\\System32\\Kernel32.dll");
if (INVALID_HANDLE_VALUE == fi)
{
printf("failed to open file! (%u)\n", GetLastError());
getchar();
}
else
{
PRETRIEVAL_POINTERS_BUFFER rpb = NULL;
DWORD rpbs = 0;
if (!getvolptr(fi, &rpb, &rpbs))
{
printf("failed to get vol ptrs! (%u)\n", GetLastError());
getchar();
}
else
{
ULONGLONG cluster_cnt = 0;
for (int i = 0; i < rpb->ExtentCount; ++i)
{
cluster_cnt = (ULONGLONG)(rpb->Extents[i].NextVcn.QuadPart) - (ULONGLONG)(rpb->StartingVcn.QuadPart);
printf("%d) size: %llu clusters (0x%016X)\n", i, cluster_cnt, rpb->Extents[i].Lcn.QuadPart);
}
HeapFree(GetProcessHeap(), 0, rpb);
}
closefile(fi);
}

Driver Blue Screen of Death System Service Exception

I'm Trying to test this Sagaan AntiCheat but i got bluescreen i use OSRLoader to load the driver and its load perfectly but when i open the .exe it's give me Blue Screen of Death https://prnt.sc/m9zl6o
the Source code of the FullProject https://github.com/SagaanTheEpic/Sagaan-AntiCheat-V2.0 I cant see where is the error can someone help me analyze this project that im trying to build. i want to recode it to add more features and make it better more.
#include <ntdef.h>
#include <ntifs.h>
#include <ntddk.h>
#include <ntdddisk.h>
#include <scsi.h>
#include <ntddscsi.h>
#include <mountdev.h>
#include <mountmgr.h>
#include <stdio.h>
#include <ntifs.h>
#include <ntddk.h>
#include <windef.h>
#include <wdf.h>
#include <ntdef.h>
#include "BlackBone\VadRoutines.h"
#include "BlackBone\Routines.h"
#include "DriverIO.h"
#include "Formula.h"
DRIVER_INITIALIZE DriverEntry;
#pragma alloc_text(INIT, DriverEntry)
#define PROCESS_QUERY_LIMITED_INFORMATION 0x1000
#define SYSTEM_PROCESS_ID (HANDLE)4
PVOID ObHandle = NULL;
ULONG ProtectedProcess = 0;
ULONG UsermodeAntiCheat = 0;
ULONG ProtectionThreads[7];
VOID CreateThreadNotifyRoutine(
IN HANDLE ProcessId,
IN HANDLE ThreadId,
IN BOOLEAN Create
);
// Terminating a process of your choice using the PID, usefull if the cheat is also using a driver to strip it's handles and therefore you can forcefully close it using the driver
NTSTATUS TerminateProcess(ULONG targetPid)
{
if (targetPid == ProtectedProcess)
{
ProtectedProcess = 0;
}
if (targetPid == UsermodeAntiCheat)
{
UsermodeAntiCheat = 0;
}
NTSTATUS NtRet = ((NTSTATUS)0x00000000L);
PEPROCESS PeProc = { 0 };
NtRet = PsLookupProcessByProcessId(targetPid, &PeProc);
if (NtRet != ((NTSTATUS)0x00000000L))
{
return NtRet;
}
HANDLE ProcessHandle;
NtRet = ObOpenObjectByPointer(PeProc, NULL, NULL, 25, *PsProcessType, KernelMode, &ProcessHandle);
if (NtRet != ((NTSTATUS)0x00000000L))
{
return NtRet;
}
ZwTerminateProcess(ProcessHandle, 0);
ZwClose(ProcessHandle);
return NtRet;
}
NTSTATUS DriverDispatchRoutine(PDEVICE_OBJECT pDeviceObject, PIRP pIrp)
{
PVOID buffer;
NTSTATUS NtStatus = STATUS_SUCCESS;
PIO_STACK_LOCATION pIo;
pIo = IoGetCurrentIrpStackLocation(pIrp);
pIrp->IoStatus.Information = 0;
switch (pIo->MajorFunction)
{
case IRP_MJ_CREATE:
NtStatus = STATUS_SUCCESS;
break;
case IRP_MJ_READ:
NtStatus = STATUS_SUCCESS;
break;
case IRP_MJ_WRITE:
break;
case IRP_MJ_CLOSE:
NtStatus = STATUS_SUCCESS;
break;
default:
NtStatus = STATUS_INVALID_DEVICE_REQUEST;
break;
}
pIrp->IoStatus.Status = STATUS_SUCCESS;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
return NtStatus;
}
// This will be called, if the driver is unloaded or just returns something
VOID DriverUnload(PDRIVER_OBJECT pDriverObject)
{
DbgPrintEx(0, 0, "UNLOADED \n");
UNICODE_STRING SACSymbolName;
RtlInitUnicodeString(&SACSymbolName, L"\\DosDevices\\SACDriver"); // Giving the driver a symbol
if (ObHandle)
{
ObUnRegisterCallbacks(ObHandle);
ObHandle = NULL;
}
PsRemoveCreateThreadNotifyRoutine(CreateThreadNotifyRoutine);
IoDeleteSymbolicLink(&SACSymbolName);
IoDeleteDevice(pDriverObject->DeviceObject);
}
NTSTATUS Create(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
NTSTATUS Close(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return STATUS_SUCCESS;
}
extern NTSTATUS PsLookupProcessByProcessId(
HANDLE ProcessId,
PEPROCESS *Process
);
typedef struct _OB_REG_CONTEXT {
USHORT Version;
UNICODE_STRING Altitude;
USHORT ulIndex;
OB_OPERATION_REGISTRATION *OperationRegistration;
} REG_CONTEXT, *PREG_CONTEXT;
OB_PREOP_CALLBACK_STATUS ThreadPreCallback(PVOID RegistrationContext, POB_PRE_OPERATION_INFORMATION OperationInformation)
{
UNREFERENCED_PARAMETER(RegistrationContext);
if (OperationInformation->KernelHandle)
return OB_PREOP_SUCCESS;
if ((ULONG)PsGetCurrentProcessId() == UsermodeAntiCheat)
{
return OB_PREOP_SUCCESS;
}
if ((ULONG)PsGetCurrentProcessId() == ProtectedProcess)
{
return OB_PREOP_SUCCESS;
}
if (PsGetThreadProcessId(OperationInformation->Object) == UsermodeAntiCheat)
{
if (OperationInformation->Operation == OB_OPERATION_HANDLE_CREATE)
OperationInformation->Parameters->CreateHandleInformation.DesiredAccess = (SYNCHRONIZE | THREAD_QUERY_LIMITED_INFORMATION);
else
OperationInformation->Parameters->DuplicateHandleInformation.DesiredAccess = (SYNCHRONIZE | THREAD_QUERY_LIMITED_INFORMATION);
}
else if (PsGetThreadProcessId(OperationInformation->Object) == ProtectedProcess)
{
if (OperationInformation->Operation == OB_OPERATION_HANDLE_CREATE)
OperationInformation->Parameters->CreateHandleInformation.DesiredAccess = (SYNCHRONIZE | THREAD_QUERY_LIMITED_INFORMATION);
else
OperationInformation->Parameters->DuplicateHandleInformation.DesiredAccess = (SYNCHRONIZE | THREAD_QUERY_LIMITED_INFORMATION);
}
return OB_PREOP_SUCCESS;
}
OB_PREOP_CALLBACK_STATUS ProcessPreCallback(PVOID RegistrationContext, POB_PRE_OPERATION_INFORMATION OperationInformation)
{
UNREFERENCED_PARAMETER(RegistrationContext);
if (UsermodeAntiCheat == 0)
return OB_PREOP_SUCCESS;
if (ProtectedProcess == 0)
return OB_PREOP_SUCCESS;
PEPROCESS ProtectedProcessPEPROCESS;
PEPROCESS ProtectedUserModeACPEPROCESS;
PEPROCESS OpenedProcess = (PEPROCESS)OperationInformation->Object,
CurrentProcess = PsGetCurrentProcess();
ULONG ulProcessId = PsGetProcessId(OpenedProcess);
PsLookupProcessByProcessId(ProtectedProcess, &ProtectedProcessPEPROCESS);
PsLookupProcessByProcessId(ProtectedProcess, &ProtectedUserModeACPEPROCESS);
if (OperationInformation->KernelHandle)
return OB_PREOP_SUCCESS;
if (ProtectedProcess != 0)
{
if (PsGetProcessId((PEPROCESS)OperationInformation->Object) == ProtectedProcess)
{
if (OperationInformation->Operation == OB_OPERATION_HANDLE_CREATE) // striping handle
{
OperationInformation->Parameters->CreateHandleInformation.DesiredAccess = (SYNCHRONIZE);
}
else
{
OperationInformation->Parameters->DuplicateHandleInformation.DesiredAccess = (SYNCHRONIZE);
}
return OB_PREOP_SUCCESS;
}
}
if (UsermodeAntiCheat != 0)
{
if (PsGetProcessId((PEPROCESS)OperationInformation->Object) == UsermodeAntiCheat)
{
if (OperationInformation->Operation == OB_OPERATION_HANDLE_CREATE) // striping handle
{
OperationInformation->Parameters->CreateHandleInformation.DesiredAccess = (SYNCHRONIZE);
}
else
{
OperationInformation->Parameters->DuplicateHandleInformation.DesiredAccess = (SYNCHRONIZE);
}
return OB_PREOP_SUCCESS;
}
}
return OB_PREOP_SUCCESS;
}
VOID CreateThreadNotifyRoutine(
IN HANDLE ProcessId,
IN HANDLE ThreadId,
IN BOOLEAN Create
)
{
if (!Create)
{
if (UsermodeAntiCheat == ProcessId)
{
for (int x = 0; x > 8; x++)
{
if ((ULONG)ThreadId == ProtectionThreads[x])
{
TerminateProcess(ProtectedProcess);
TerminateProcess(UsermodeAntiCheat);
}
}
}
if (ProtectedProcess == ProcessId)
{
}
}
}
VOID EnableCallBack()
{
NTSTATUS NtHandleCallback = STATUS_UNSUCCESSFUL;
NTSTATUS NtThreadCallback = STATUS_UNSUCCESSFUL;
OB_OPERATION_REGISTRATION OBOperationRegistration[2];
OB_CALLBACK_REGISTRATION OBOCallbackRegistration;
REG_CONTEXT regContext;
UNICODE_STRING usAltitude;
memset(&OBOperationRegistration, 0, sizeof(OB_OPERATION_REGISTRATION));
memset(&OBOCallbackRegistration, 0, sizeof(OB_CALLBACK_REGISTRATION));
memset(&regContext, 0, sizeof(REG_CONTEXT));
regContext.ulIndex = 1;
regContext.Version = 120;
RtlInitUnicodeString(&usAltitude, L"1000");
if ((USHORT)ObGetFilterVersion() == OB_FLT_REGISTRATION_VERSION)
{
//OBOperationRegistration.ObjectType = PsProcessType; // Use To Strip Handle Permissions For Threads PsThreadType
//OBOperationRegistration.Operations = OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE;
//OBOperationRegistration.PostOperation = PostCallBack; // Giving the function which happens after creating
//OBOperationRegistration.PreOperation = PreCallback; // Giving the function which happens before creating
OBOperationRegistration[1].ObjectType = PsProcessType;
OBOperationRegistration[1].Operations = OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE;
OBOperationRegistration[1].PreOperation = ProcessPreCallback;
OBOperationRegistration[1].PostOperation = NULL;
OBOperationRegistration[0].ObjectType = PsThreadType;
OBOperationRegistration[0].Operations = OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE;
OBOperationRegistration[0].PreOperation = ThreadPreCallback;
OBOperationRegistration[0].PostOperation = NULL;
OBOCallbackRegistration.Version = OB_FLT_REGISTRATION_VERSION;
OBOCallbackRegistration.OperationRegistrationCount = 2;
OBOCallbackRegistration.RegistrationContext = NULL;
OBOCallbackRegistration.OperationRegistration = &OBOperationRegistration;
NtHandleCallback = ObRegisterCallbacks(&OBOCallbackRegistration, &ObHandle); // Register The CallBack
PsSetCreateThreadNotifyRoutine(CreateThreadNotifyRoutine);
if (!NT_SUCCESS(NtHandleCallback))
{
if (ObHandle)
{
ObUnRegisterCallbacks(ObHandle);
ObHandle = NULL;
}
DbgPrintEx(0, 0, "Error: ObRegisterCallbacks Has Failed\n");
}
else
{
}
}
}
static ULONG KsecRandomSeed = 0x62b409a1;
NTSTATUS
NTAPI
KsecGenRandom(
PVOID Buffer,
SIZE_T Length)
{
LARGE_INTEGER TickCount;
ULONG i, RandomValue;
PULONG P;
/* Try to generate a more random seed */
KeQueryTickCount(&TickCount);
KsecRandomSeed ^= _rotl(TickCount.LowPart, (KsecRandomSeed % 23));
P = Buffer;
for (i = 0; i < Length / sizeof(ULONG); i++)
{
P[i] = RtlRandomEx(&KsecRandomSeed);
}
Length &= (sizeof(ULONG) - 1);
if (Length > 0)
{
RandomValue = RtlRandomEx(&KsecRandomSeed);
RtlCopyMemory(&P[i], &RandomValue, Length);
}
return STATUS_SUCCESS;
}
ULONG FOR1 = 100, FOR2 = 200, FOR3 = 300, FOR4 = 400, FOR5 = 500;
ULONG Encryption_Forward1 = 1, Encryption_Forward2 = 1, Encryption_Forward3 = 1, Encryption_Forward4 = 1, Encryption_Forward5 = 1;
BOOL Request_1 = FALSE;
BOOLEAN ProtectedGameRecieved = FALSE;
BOOLEAN UsermodeAntiCheatRecieved = FALSE;
NTSTATUS IoControl(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
NTSTATUS Status;
ULONG BytesIO = 0;
PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp);
// Code received from user space
ULONG ControlCode = stack->Parameters.DeviceIoControl.IoControlCode;
if (ControlCode == IO_SEND_CURRENTPROCESS && UsermodeAntiCheat < 1)
{
PKERNEL_READ_REQUEST ReadInput = (PKERNEL_READ_REQUEST)Irp->AssociatedIrp.SystemBuffer;
UsermodeAntiCheat = ReadInput->UsermodeProgram;
Status = STATUS_SUCCESS;
BytesIO = sizeof(KERNEL_READ_REQUEST);
}
if ((ULONG)UsermodeAntiCheat == (ULONG)PsGetProcessId(PsGetCurrentProcess()))
{
if (ControlCode == IO_SEND_PROCESSID && ProtectedGameRecieved == FALSE)
{
PKERNEL_READ_REQUEST ReadInput = (PKERNEL_READ_REQUEST)Irp->AssociatedIrp.SystemBuffer;
ProtectedProcess = ReadInput->GameProcess;
if (ProtectedProcess > 0)
{
ProtectedGameRecieved = TRUE;
}
Status = STATUS_SUCCESS;
BytesIO = sizeof(KERNEL_READ_REQUEST);
}
else if (ControlCode == IO_PROTECTIONT_THREADS)
{
PKERNEL_THREAD_REQUEST ReadInput = (PKERNEL_THREAD_REQUEST)Irp->AssociatedIrp.SystemBuffer;
ProtectionThreads[0] = ReadInput->ThreadID;
ProtectionThreads[1] = ReadInput->ThreadID2;
ProtectionThreads[2] = ReadInput->ThreadID3;
ProtectionThreads[3] = ReadInput->ThreadID4;
ProtectionThreads[4] = ReadInput->ThreadID5;
ProtectionThreads[5] = ReadInput->ThreadID6;
ProtectionThreads[6] = ReadInput->ThreadID7;
ProtectionThreads[7] = ReadInput->ThreadID8;
Status = STATUS_SUCCESS;
BytesIO = sizeof(KERNEL_THREAD_REQUEST);
}
else if (ControlCode == IO_TerminateProcess)
{
PKERNEL_READ_REQUEST ReadInput = (PKERNEL_READ_REQUEST)Irp->AssociatedIrp.SystemBuffer;
TerminateProcess(ReadInput->UsermodeProgram);
Status = STATUS_SUCCESS;
BytesIO = sizeof(KERNEL_READ_REQUEST);
}
else if (ControlCode == HEARTBEATMAINSTART_FORWARD)
{
PKERNEL_HEARTBEAT_REQUEST ReadInput = (PKERNEL_HEARTBEAT_REQUEST)Irp->AssociatedIrp.SystemBuffer;
Encryption_Forward1 = ReadInput->Encrypt1;
Encryption_Forward2 = ReadInput->Encrypt2;
Encryption_Forward3 = ReadInput->Encrypt3;
Encryption_Forward4 = ReadInput->Encrypt4;
Encryption_Forward5 = ReadInput->Encrypt5;
Status = STATUS_SUCCESS;
BytesIO = sizeof(KERNEL_HEARTBEAT_REQUEST);
}
else if (ControlCode == HEARTBEATMAINSTART_RETURN)
{
PKERNEL_HEARTBEAT_REQUEST ReadInput = (PKERNEL_HEARTBEAT_REQUEST)Irp->AssociatedIrp.SystemBuffer;
ReadInput->Encrypt1 = Formula1(Encryption_Forward1);
ReadInput->Encrypt2 = Formula2(Encryption_Forward2);
ReadInput->Encrypt3 = Formula3(Encryption_Forward3);
ReadInput->Encrypt4 = Formula4(Encryption_Forward4);
ReadInput->Encrypt5 = Formula5(Encryption_Forward5);
//DbgPrintEx(0, 0, "HEARTBEATMAINSTART_RETURN Called: Formula1(Encryption_Forward1) %d", Formula1(Encryption_Forward1));
Status = STATUS_SUCCESS;
BytesIO = sizeof(KERNEL_HEARTBEAT_REQUEST);
}
else if (ControlCode == HEARTBEATCREATEPROCESS_RETURN)
{
PKERNEL_HEARTBEAT_REQUEST ReadInput = (PKERNEL_HEARTBEAT_REQUEST)Irp->AssociatedIrp.SystemBuffer;
KsecGenRandom(FOR1, sizeof(FOR1));
KsecGenRandom(FOR2, sizeof(FOR2));
KsecGenRandom(FOR3, sizeof(FOR3));
KsecGenRandom(FOR4, sizeof(FOR4));
KsecGenRandom(FOR5, sizeof(FOR5));
ReadInput->Encrypt1 = FOR1;
ReadInput->Encrypt2 = FOR2;
ReadInput->Encrypt3 = FOR3;
ReadInput->Encrypt4 = FOR4;
ReadInput->Encrypt5 = FOR5;
Status = STATUS_SUCCESS;
BytesIO = sizeof(KERNEL_HEARTBEAT_REQUEST);
}
else if (ControlCode == IO_VADPROTECTION)
{
PHIDE_VAD ReadInput = (PHIDE_VAD)Irp->AssociatedIrp.SystemBuffer;
if (ReadInput->pid == ProtectedProcess || ReadInput == UsermodeAntiCheat)
{
// Enable it if you like. I dont need it so eh
//BBHideVAD(ReadInput);
}
Status = STATUS_SUCCESS;
BytesIO = sizeof(HIDE_VAD);
}
else if (ControlCode == HEARTBEATCREATEPROCESS_FORWARD)
{
PKERNEL_HEARTBEAT_REQUEST ReadInput = (PKERNEL_HEARTBEAT_REQUEST)Irp->AssociatedIrp.SystemBuffer;
if (ReadInput->Encrypt1 == Formula1(FOR1))
{
if (ReadInput->Encrypt2 == Formula2(FOR2))
{
if (ReadInput->Encrypt3 == Formula3(FOR3))
{
if (ReadInput->Encrypt4 == Formula4(FOR4))
{
if (ReadInput->Encrypt5 == Formula5(FOR5))
{
//DbgPrintEx(0, 0, "Process Id ( IOCONTROL )%s\n", (ULONG)PsGetProcessId(IoGetCurrentProcess()));
Status = STATUS_SUCCESS;
// GOOD
}
else
{
if (ProtectedProcess)
{
TerminateProcess(ProtectedProcess);
}
TerminateProcess(UsermodeAntiCheat);
Status = STATUS_INVALID_PARAMETER;
//BAD
// ERROR
// TERMINATE GAME OR PROTECTION
// BLUE SCREEN OF DEATH OR WHATEVER YOU LIKE
DbgPrintEx(0, 0, "Error: ReadInput->Encrypt5 == Formula5(FOR5) Encrypt: %s Formula: %s \n", ReadInput->Encrypt5, Formula5(FOR5));
}
}
else
{
if (ProtectedProcess)
{
TerminateProcess(ProtectedProcess);
}
TerminateProcess(UsermodeAntiCheat);
Status = STATUS_INVALID_PARAMETER;
//BAD
// ERROR
// TERMINATE GAME OR PROTECTION
// BLUE SCREEN OF DEATH OR WHATEVER YOU LIKE
DbgPrintEx(0, 0, "Error: ReadInput->Encrypt4 == Formula4(FOR4) Encrypt: %s Formula: %s \n", ReadInput->Encrypt4, Formula4(FOR4));
}
}
else
{
if (ProtectedProcess)
{
TerminateProcess(ProtectedProcess);
}
TerminateProcess(UsermodeAntiCheat);
Status = STATUS_INVALID_PARAMETER;
//BAD
// ERROR
// TERMINATE GAME OR PROTECTION
// BLUE SCREEN OF DEATH OR WHATEVER YOU LIKE
DbgPrintEx(0, 0, "Error: ReadInput->Encrypt3 == Formula3(FOR3) Encrypt: %s Formula: %s \n", ReadInput->Encrypt3, Formula3(FOR3));
}
}
else
{
if (ProtectedProcess)
{
TerminateProcess(ProtectedProcess);
}
TerminateProcess(UsermodeAntiCheat);
Status = STATUS_INVALID_PARAMETER;
//BAD
// ERROR
// TERMINATE GAME OR PROTECTION
// BLUE SCREEN OF DEATH OR WHATEVER YOU LIKE
DbgPrintEx(0, 0, "Error: ReadInput->Encrypt2 == Formula2(FOR2) Encrypt: %s Formula: %s \n", ReadInput->Encrypt2, Formula2(FOR2));
}
}
else
{
if (ProtectedProcess)
{
TerminateProcess(ProtectedProcess);
}
TerminateProcess(UsermodeAntiCheat);
Status = STATUS_INVALID_PARAMETER;
//BAD
// ERROR
// TERMINATE GAME OR PROTECTION
// BLUE SCREEN OF DEATH OR WHATEVER YOU LIKE
DbgPrintEx(0, 0, "Error: ReadInput->Encrypt1 == Formula1(FOR1) Encrypt: %s Formula: %s \n", ReadInput->Encrypt1, Formula1(FOR1));
}
BytesIO = sizeof(KERNEL_HEARTBEAT_REQUEST);
}
}
else if ((ULONG)ProtectedProcess == (ULONG)PsGetProcessId(PsGetCurrentProcess()))
{
if (ControlCode == IO_RETURNANTICHEATUSERMODE_PROCESSID_GMAE)
{
PKERNEL_READ_REQUEST ReadInput = (PKERNEL_READ_REQUEST)Irp->AssociatedIrp.SystemBuffer;
ReadInput->UsermodeProgram = UsermodeAntiCheat;
Status = STATUS_SUCCESS;
BytesIO = sizeof(KERNEL_READ_REQUEST);
}
}
// Complete the request
Irp->IoStatus.Status = Status;
Irp->IoStatus.Information = BytesIO;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return Status;
}
// Driver's Main function. This will be called and looped through till returned, or unloaded.
NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pUniStr)
{
DbgPrintEx(0, 0, "LOADED \n");
UNICODE_STRING SACDriverName, SACSymbolName;
NTSTATUS NtRet = STATUS_SUCCESS;
PDEVICE_OBJECT pDeviceObj;
RtlInitUnicodeString(&SACDriverName, L"\\Device\\SACDriver"); // Giving the driver a name
RtlInitUnicodeString(&SACSymbolName, L"\\DosDevices\\SACDriver"); // Giving the driver a symbol
UNICODE_STRING deviceNameUnicodeString, deviceSymLinkUnicodeString;
NTSTATUS NtRet2 = IoCreateDevice(pDriverObject, 0, &SACDriverName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &pDeviceObj);
IoCreateSymbolicLink(&SACSymbolName, &SACDriverName);
pDriverObject->MajorFunction[IRP_MJ_CREATE] = Create;
pDriverObject->MajorFunction[IRP_MJ_CLOSE] = Close;
pDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = IoControl;
pDeviceObj->Flags |= DO_DIRECT_IO;
pDeviceObj->Flags &= (~DO_DEVICE_INITIALIZING);
pDriverObject->DriverUnload = DriverUnload;
EnableCallBack();
return NtRet;
}
Im not sure why i got bluescreen of death because of this rand() function.
#include "DLLInjectorDector.h"
#include "AbortFailureDetects.h"
#include "DriverLoader\\driver.h"
#include "DriverIO.h"
#include "openssl\\md5.h"
#include "DriverIORequests.h"
#include "Formulas.h"
#include "Anti Debug.h"
#include "DLLInjectionDetector\Utils.h"
#include "Utlis.h"
#include "NamePipe.h"
#include "DigitalSignatureChecker.h"
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <Softpub.h>
#include <wincrypt.h>
#include <wintrust.h>
#include <sys/types.h>
#include <signal.h>
#include <vector>
// Link with the Wintrust.lib file.
#pragma comment (lib, "wintrust")
// Varibles
HANDLE hDriver; // Driver
ULONG NamePipe1, NamePipe2, NamePipe3, NamePipe4, NamePipe5;
ULONG FOR1, FOR2, FOR3, FOR4, FOR5;
ULONG CHECK1, CHECK2, CHECK3, CHECK4, CHECK5;
ULONG CHECK_CREATEPROCESS1, CHECK_CREATEPROCESS2, CHECK_CREATEPROCESS3, CHECK_CREATEPROCESS4, CHECK_CREATEPROCESS5;
int GameProcessID = 0;
// Functions
bool CheckTestMode();
int randNum(int min, int max);
DWORD TidHeartBeat = 0;
DWORD TidGameValidChech = 0;
DWORD TidAntiDebug = 0;
DWORD tidDriverScanner = 0;
DWORD TidCommonCheatScanner = 0;
DWORD TidOverlayScanner = 0;
DWORD TidAntiKill = 0;
DWORD TidMainThread = 0;
BOOL HeartBeatThreadAntiKill = FALSE;
HANDLE hHeartBeatThread = NULL;
DWORD WINAPI HeartBeatThread()
{
AntiDebug::HideThread(GetCurrentThread());
while (1)
{
srand(time(0));
FOR1 = randNum(2, 63);
FOR2 = randNum(3, 34);
FOR3 = randNum(8, 45);
FOR4 = randNum(5, 67);
FOR5 = randNum(2, 12);
if (DriverRequest::HEARTBEATMAINSTART_FORWARD_Function(FOR1, FOR2, FOR3, FOR4, FOR5))
{
KERNEL_HEARTBEAT_REQUEST RETURNED_HEARTBEAT_CREATEPROCESS = DriverRequest::HEARTBEATMAINSTART_RETURN_Function();
if (RETURNED_HEARTBEAT_CREATEPROCESS.Encrypt1 == HeartbeatFormula::Formula1(FOR1))
{
if (RETURNED_HEARTBEAT_CREATEPROCESS.Encrypt2 == HeartbeatFormula::Formula2(FOR2))
{
if (RETURNED_HEARTBEAT_CREATEPROCESS.Encrypt3 == HeartbeatFormula::Formula3(FOR3))
{
if (RETURNED_HEARTBEAT_CREATEPROCESS.Encrypt4 == HeartbeatFormula::Formula4(FOR4))
{
if (RETURNED_HEARTBEAT_CREATEPROCESS.Encrypt5 == HeartbeatFormula::Formula5(FOR5))
{
KERNEL_HEARTBEAT_REQUEST RETURNED_HEARTBEAT_CREATEPROCESS_CREATEPROCESS = DriverRequest::HEARTBEATCREATEPROCESS_RETURN_Function();
CHECK_CREATEPROCESS1 = HeartbeatFormula::Formula1(RETURNED_HEARTBEAT_CREATEPROCESS_CREATEPROCESS.Encrypt1);
CHECK_CREATEPROCESS2 = HeartbeatFormula::Formula2(RETURNED_HEARTBEAT_CREATEPROCESS_CREATEPROCESS.Encrypt2);
CHECK_CREATEPROCESS3 = HeartbeatFormula::Formula3(RETURNED_HEARTBEAT_CREATEPROCESS_CREATEPROCESS.Encrypt3);
CHECK_CREATEPROCESS4 = HeartbeatFormula::Formula4(RETURNED_HEARTBEAT_CREATEPROCESS_CREATEPROCESS.Encrypt4);
CHECK_CREATEPROCESS5 = HeartbeatFormula::Formula5(RETURNED_HEARTBEAT_CREATEPROCESS_CREATEPROCESS.Encrypt5);
if (DriverRequest::HEARTBEATCREATEPROCESS_FORWARD_Function(CHECK_CREATEPROCESS1, CHECK_CREATEPROCESS2, CHECK_CREATEPROCESS3, CHECK_CREATEPROCESS4, CHECK_CREATEPROCESS5))
{
if ( CUtils::IsSuspendedThread(TidMainThread))
{
ErrorHandler::ErrorMessage("63452 ( Thread Mismatched )", 6);
}
HeartBeatThreadAntiKill = TRUE;
Sleep(400);
}
else
{
ErrorHandler::ErrorMessage("601 ( HeartBeat System Failed )", 5);
Sleep(3000);
exit(1);
}
}
else
{
ErrorHandler::ErrorMessage("602 ( HeartBeat System Failed )", 5);
Sleep(3000);
exit(1);
}
}
else
{
ErrorHandler::ErrorMessage("603 ( HeartBeat System Failed )", 5);
Sleep(3000);
exit(1);
}
}
else
{
ErrorHandler::ErrorMessage("604 ( HeartBeat System Failed )", 5);
Sleep(3000);
exit(1);
}
}
else
{
ErrorHandler::ErrorMessage("605 ( HeartBeat System Failed )", 5);
Sleep(3000);
exit(1);
}
}
else
{
ErrorHandler::ErrorMessage("606 ( HeartBeat System Failed )", 5);
Sleep(3000);
exit(1);
}
}
else
{
ErrorHandler::ErrorMessage("607 ( HeartBeat System Failed )", 5);
Sleep(3000);
exit(1);
}
}
return 0;
}
BOOL GameCheckerAntiKill = FALSE;
HANDLE hGameChecker = NULL;
DWORD WINAPI GameValidCheckThread()
{
AntiDebug::HideThread(GetCurrentThread());
while (1)
{
if (GameProcessID == 0)
{
Sleep(200);
}
else
{
if (!ErrorHandler::isProcessRunning(GameProcessID))
{
ErrorHandler::ErrorMessage("901 ( Game Stopped Running )", 3);
}
}
if (CUtils::IsSuspendedThread(TidAntiDebug)
|| CUtils::IsSuspendedThread(TidAntiKill))
{
ErrorHandler::ErrorMessage("32156 ( Thread Mismatched )", 6);
}
GameCheckerAntiKill = TRUE;
}
}
BOOL AntiDebugAntiKill = FALSE;
HANDLE hAntiDebug = NULL;
DWORD WINAPI AntiDebugThread()
{
AntiDebug::HideThread(GetCurrentThread());
while (1)
{
if (AntiDebug::CheckRemoteDebuggerPresentAPI())
{
ErrorHandler::ErrorMessage("701", 6);
}
Sleep(200);
if (AntiDebug::IsDebuggerPresentAPI())
{
ErrorHandler::ErrorMessage("702", 6);
}
Sleep(200);
if (AntiDebug::HardwareBreakpoints())
{
ErrorHandler::ErrorMessage("703", 6);
}
Sleep(200);
if (AntiDebug::MemoryBreakpoints_PageGuard())
{
ErrorHandler::ErrorMessage("704", 6);
}
Sleep(200);
if (AntiDebug::UnhandledExcepFilterTest())
{
ErrorHandler::ErrorMessage("706", 6);
}
Sleep(200);
if (AntiDebug::SharedUserData_KernelDebugger())
{
ErrorHandler::ErrorMessage("707", 6);
}
Sleep(200);
if (CUtils::IsSuspendedThread(TidAntiDebug)
|| CUtils::IsSuspendedThread(TidAntiKill))
{
ErrorHandler::ErrorMessage("34524 ( Thread Mismatched )", 6);
}
AntiDebugAntiKill = TRUE;
}
}
BOOL DriversScanAntiKill = FALSE;
HANDLE hDriversScan = NULL;
DWORD WINAPI DriversScanThread()
{
AntiDebug::HideThread(GetCurrentThread());
while (1)
{
LPVOID drivers[1024];
DWORD cbNeeded;
int cDrivers, i;
if (EnumDeviceDrivers(drivers, sizeof(drivers), &cbNeeded) && cbNeeded < sizeof(drivers))
{
/*
TCHAR szDriver[1024];
cDrivers = cbNeeded / sizeof(drivers[0]);
for (i = 0; i < cDrivers; i++)
{
if (GetDeviceDriverBaseName(drivers[i], szDriver, sizeof(szDriver) / sizeof(szDriver[0])))
{
TCHAR szName[MAX_PATH] = { 0 };
GetDeviceDriverFileName(drivers[i], szName, MAX_PATH);
//_tprintf(TEXT("%d: %s\n"), i + 1, szName);
Sleep(10);
}
}*/
Sleep(100);
}
else
{
ErrorHandler::ErrorMessage("9753 ( Please Restart Your PC )", 5);
}
if (CUtils::IsSuspendedThread(TidAntiDebug)
|| CUtils::IsSuspendedThread(TidAntiKill))
{
ErrorHandler::ErrorMessage("565435 ( Thread Mismatched )", 6);
}
DriversScanAntiKill = TRUE;
}
}
BOOL CommonCheatsScannerAntiKill = FALSE;
HANDLE hCommonCheatsScanner = NULL;
DWORD WINAPI CommonCheatsScannerThread()
{
AntiDebug::HideThread(GetCurrentThread());
while (1)
{
const char DebuggingDrivers[9][20] = {
"\\\\.\\EXTREM", "\\\\.\\ICEEXT",
"\\\\.\\NDBGMSG.VXD", "\\\\.\\RING0",
"\\\\.\\SIWVID", "\\\\.\\SYSER",
"\\\\.\\TRW", "\\\\.\\SYSERBOOT",
"\0"
};
for (int i = 0; DebuggingDrivers[i][0] != '\0'; i++) {
HANDLE h = CreateFileA(DebuggingDrivers[i], 0, 0, 0, OPEN_EXISTING, 0, 0);
if (h != INVALID_HANDLE_VALUE)
{
CloseHandle(h);
ErrorHandler::ErrorMessage("2001 ( Debugging Drivers Found )", 6);
}
CloseHandle(h);
Sleep(200);
}
const char CheatingDrivers[5][20] = {
"\\\\.\\kernelhop", "\\\\.\\BlackBone",
"\\\\.\\VBoxDrv", "\\\\.\\Htsysm72FB",
"\0"
};
for (int i = 0; CheatingDrivers[i][0] != '\0'; i++) {
HANDLE hCheats = CreateFileA(CheatingDrivers[i], 0, 0, 0, OPEN_EXISTING, 0, 0);
if (hCheats != INVALID_HANDLE_VALUE)
{
CloseHandle(hCheats);
ErrorHandler::ErrorMessage("3001 ( Cheating Drivers Found )", 2);
}
CloseHandle(hCheats);
Sleep(200);
}
if (CUtils::IsSuspendedThread(TidAntiDebug)
|| CUtils::IsSuspendedThread(TidAntiKill))
{
ErrorHandler::ErrorMessage("34536 ( Thread Mismatched )", 6);
}
CommonCheatsScannerAntiKill = TRUE;
Sleep(200);
}
}
BOOL OverlayScannerAntiKill = FALSE;
HANDLE hOverlayScanner = NULL;
DWORD WINAPI OverlayScannerThread()
{
// https://www.unknowncheats.me/forum/anti-cheat-bypass/263403-window-hijacking-dont-overlay-betray.html
AntiDebug::HideThread(GetCurrentThread());
while (1)
{
OverlayFinderParams params;
params.style = WS_VISIBLE;
params.styleEx = WS_EX_LAYERED | WS_EX_TRANSPARENT;
params.percentMainScreen = 90.0f;
params.satisfyAllCriteria = true;
std::vector<HWND> hwnds = Utlis::OverlayFinder(params);
for (int i(0); i < hwnds.size(); ++i) {
DWORD ProcessIDForOverlay = 0;
DWORD tid = GetWindowThreadProcessId(hwnds[i], &ProcessIDForOverlay);
if (ErrorHandler::isProcessRunning(ProcessIDForOverlay))
{
DriverRequest::TerminatePrcoess(ProcessIDForOverlay);
Sleep(200);
}
Sleep(200);
}
OverlayScannerAntiKill = TRUE;
Sleep(200);
}
}
BOOL AntiKillBool = FALSE;
HANDLE hAntiKill = NULL;
DWORD WINAPI AntiKillThread()
{
AntiDebug::HideThread(GetCurrentThread());
while (1)
{
if (CUtils::IsSuspendedThread(TidHeartBeat)
|| CUtils::IsSuspendedThread(tidDriverScanner)
|| CUtils::IsSuspendedThread(TidCommonCheatScanner)
|| CUtils::IsSuspendedThread(TidOverlayScanner)
|| CUtils::IsSuspendedThread(TidGameValidChech)
|| CUtils::IsSuspendedThread(TidMainThread)
|| CUtils::IsSuspendedThread(TidAntiDebug))
{
ErrorHandler::ErrorMessage("34536 ( Thread Mismatched )", 6);
}
else
{
Sleep(200);
}
}
}
bool IsSystemCodeIntegrityEnabled()
{
//https://stackoverflow.com/questions/40084077/can-i-have-any-way-to-detect-the-driver-signing-policy-status/50944791
typedef NTSTATUS(__stdcall* td_NtQuerySystemInformation)(
ULONG SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength
);
struct SYSTEM_CODEINTEGRITY_INFORMATION {
ULONG Length;
ULONG CodeIntegrityOptions;
};
static td_NtQuerySystemInformation NtQuerySystemInformation = (td_NtQuerySystemInformation)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtQuerySystemInformation");
SYSTEM_CODEINTEGRITY_INFORMATION Integrity = { sizeof(SYSTEM_CODEINTEGRITY_INFORMATION), 0 };
NTSTATUS status = NtQuerySystemInformation(103, &Integrity, sizeof(Integrity), NULL);
return (status && (Integrity.CodeIntegrityOptions & 1));
}
void OnExit()
{
if (GameProcessID != 0)
{
if (ErrorHandler::isProcessRunning(GameProcessID))
{
DriverRequest::TerminatePrcoess(GameProcessID);
}
}
ErrorHandler::UnloadDriver();
}
int main()
{
using namespace std;
//FreeConsole();
InitializeDLLCheck();
InitializeThreadCheck();
TidMainThread = GetCurrentThreadId();
if (IsSystemCodeIntegrityEnabled())
{
ErrorHandler::ErrorMessage("0392 Test Mode Is Enabled. Please Disable It", 6);
}
if (Utlis::IsRunAsAdministrator)
{
HANDLE CheckHandle = CreateFileA("\\\\.\\SACDriver", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (CheckHandle != INVALID_HANDLE_VALUE)
{
ErrorHandler::UnloadDriver();
CloseHandle(CheckHandle);
}
ErrorHandler::LoadDriver();
Sleep(100);
hDriver = CreateFileA("\\\\.\\SACDriver", GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
//printf("File Size: %d \n", WhiteListedDLLs::GetFileSize("SAC-V2-DLL.dll"));
if (hDriver)
{
if (DriverRequest::SendCurrentProcessID())
{
hAntiDebug = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)AntiDebugThread, NULL, 0, &TidAntiDebug);
srand(time(0));
FOR1 = randNum(1, 35);
FOR2 = randNum(1, 23);
FOR3 = randNum(1, 23);
FOR4 = randNum(1, 23);
FOR5 = randNum(1, 34);
if (DriverRequest::HEARTBEATMAINSTART_FORWARD_Function(FOR1, FOR2, FOR3, FOR4, FOR5))
{
KERNEL_HEARTBEAT_REQUEST RETURNED_HEARTBEAT = DriverRequest::HEARTBEATMAINSTART_RETURN_Function();
ULONG TEST1 = HeartbeatFormula::Formula1(FOR1);
ULONG TEST2 = RETURNED_HEARTBEAT.Encrypt1;
if (RETURNED_HEARTBEAT.Encrypt1 == HeartbeatFormula::Formula1(FOR1))
{
if (RETURNED_HEARTBEAT.Encrypt2 == HeartbeatFormula::Formula2(FOR2))
{
if (RETURNED_HEARTBEAT.Encrypt3 == HeartbeatFormula::Formula3(FOR3))
{
if (RETURNED_HEARTBEAT.Encrypt4 == HeartbeatFormula::Formula4(FOR4))
{
if (RETURNED_HEARTBEAT.Encrypt5 == HeartbeatFormula::Formula5(FOR5))
{
KERNEL_HEARTBEAT_REQUEST RETURNED_HEARTBEAT_CREATEPROCESS = DriverRequest::HEARTBEATCREATEPROCESS_RETURN_Function();
CHECK_CREATEPROCESS1 = HeartbeatFormula::Formula1(RETURNED_HEARTBEAT_CREATEPROCESS.Encrypt1);
CHECK_CREATEPROCESS2 = HeartbeatFormula::Formula2(RETURNED_HEARTBEAT_CREATEPROCESS.Encrypt2);
CHECK_CREATEPROCESS3 = HeartbeatFormula::Formula3(RETURNED_HEARTBEAT_CREATEPROCESS.Encrypt3);
CHECK_CREATEPROCESS4 = HeartbeatFormula::Formula4(RETURNED_HEARTBEAT_CREATEPROCESS.Encrypt4);
CHECK_CREATEPROCESS5 = HeartbeatFormula::Formula5(RETURNED_HEARTBEAT_CREATEPROCESS.Encrypt5);
if (DriverRequest::HEARTBEATCREATEPROCESS_FORWARD_Function(CHECK_CREATEPROCESS1, CHECK_CREATEPROCESS2, CHECK_CREATEPROCESS3, CHECK_CREATEPROCESS4, CHECK_CREATEPROCESS5))
{
hHeartBeatThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)HeartBeatThread, NULL, 0, &TidHeartBeat);
hDriversScan = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)DriversScanThread, NULL, 0, &tidDriverScanner);
hCommonCheatsScanner = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CommonCheatsScannerThread, NULL, 0, &TidCommonCheatScanner);
hOverlayScanner = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)OverlayScannerThread, NULL, 0, &TidOverlayScanner);
STARTUPINFO StartupInfo = { sizeof(StartupInfo) };
PROCESS_INFORMATION ProcessInfo;
if (CreateProcess("D:\\SteamLibrary\\steamapps\\common\\Kingdom New Lands\\Kingdom.exe", NULL, NULL, NULL, TRUE, 0, NULL, NULL, &StartupInfo, &ProcessInfo))
{
BlockInput(TRUE);
Utlis::Injection(L"SAC-V2-DLL.dll", ProcessInfo.dwProcessId);
GameProcessID = ProcessInfo.dwProcessId;
if (DriverRequest::SendProcessIDs(GameProcessID))
{
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
BlockInput(FALSE);
hGameChecker = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)GameValidCheckThread, NULL, 0, &TidGameValidChech);
hAntiKill = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)AntiKillThread, NULL, 0, &TidAntiKill);
KERNEL_THREAD_REQUEST Threads;
Threads.ThreadID = TidAntiDebug;
Threads.ThreadID2 = TidHeartBeat;
Threads.ThreadID3 = tidDriverScanner;
Threads.ThreadID4 = TidCommonCheatScanner;
Threads.ThreadID5 = TidOverlayScanner;
Threads.ThreadID6 = TidGameValidChech;
Threads.ThreadID7 = TidAntiKill;
Threads.ThreadID8 = TidMainThread;
if (DriverRequest::SendProtectedThreadID(Threads))
{
while (1)
{
atexit(OnExit);
Sleep(4000);
if (CUtils::IsSuspendedThread(TidHeartBeat)
|| CUtils::IsSuspendedThread(tidDriverScanner)
|| CUtils::IsSuspendedThread(TidGameValidChech)
|| CUtils::IsSuspendedThread(TidCommonCheatScanner)
|| CUtils::IsSuspendedThread(TidOverlayScanner)
|| CUtils::IsSuspendedThread(TidAntiDebug)
|| CUtils::IsSuspendedThread(TidAntiKill))
{
ErrorHandler::ErrorMessage("32947 ( Thread Mismatched )", 6);
}
if (IsSystemCodeIntegrityEnabled())
{
ErrorHandler::ErrorMessage("0392 Test Mode Is Enabled. Please Disable It", 6);
}
if (OverlayScannerAntiKill && CommonCheatsScannerAntiKill && DriversScanAntiKill && AntiDebugAntiKill && HeartBeatThreadAntiKill)
{
OverlayScannerAntiKill = FALSE;
CommonCheatsScannerAntiKill = FALSE;
DriversScanAntiKill = FALSE;
AntiDebugAntiKill = FALSE;
HeartBeatThreadAntiKill = FALSE;
}
else
{
ErrorHandler::ErrorMessage("9452 ( Thread Mismatched )", 5);
}
}
}
else
{
BlockInput(FALSE);
ErrorHandler::ErrorMessage("43524 ( Thread Mismatched )", 5);
}
}
else
{
ErrorHandler::ErrorMessage("202 ( Driver Not Found )", 1);
}
}
else
{
ErrorHandler::ErrorMessage("945 ( Failed To Start Game )", 1);
}
}
else
{
ErrorHandler::ErrorMessage("207 ( Driver Not Found )", 1);
}
}
else
{
ErrorHandler::ErrorMessage("206 ( Driver Not Found )", 1);
}
}
else
{
ErrorHandler::ErrorMessage("205 ( Driver Not Found )", 1);
}
}
else
{
ErrorHandler::ErrorMessage("204 ( Driver Not Found )", 1);
}
}
else
{
ErrorHandler::ErrorMessage("203 ( Driver Not Found )", 1);
}
}
else
{
ErrorHandler::ErrorMessage("249 ( Driver Not Found )", 1);
}
}
else
{
ErrorHandler::ErrorMessage("201 ( Driver Not Found )", 1);
}
}
else
{
ErrorHandler::ErrorMessage("301 ( Driver Not Found )", 1);
}
}
else
{
ErrorHandler::ErrorMessage("67 ( Driver Not Found )", 1);
}
}
else
{
ErrorHandler::ErrorMessage("1001 ( Run As Admin )", 1);
}
return 0;
}
int randNum(int min, int max)
{
return rand() % max + min;
}

"bad packet length" error after updating to OpenSSL 0.9.8.zf

I was using OpenSSL version 0.9.8h in an Android project. I update it to the 0.9.8.zf version but now it doesn't work.
The two functions that highlight the problem are initialize_client_ctx and initialize_client_ctx. When I call SSL_connect I get an SSL_ERROR_SSL error value. By checking details I retrieve a "bad packet length" error (error:14092073:SSL routines:SSL3_GET_SERVER_HELLO:bad packet length).
The point in the code is indicated in a comment. The code works well with the previous version. I attach also a Wireshark capture file. Any ideas?
SSL_CTX *initialize_client_ctx(const char *keyfile, const char *certfile,
const char *password, int transport)
{
SSL_METHOD *meth = NULL;
X509 *cert = NULL;
SSL_CTX *ctx;
if (transport == IPPROTO_UDP) {
meth = DTLSv1_client_method();
} else if (transport == IPPROTO_TCP) {
meth = TLSv1_client_method();
} else {
return NULL;
}
ctx = SSL_CTX_new(meth);
if (ctx == NULL) {
//print ... Couldn't create SSL_CTX
return NULL;
}
if (password[0] != '\0') {
SSL_CTX_set_default_passwd_cb_userdata(ctx, (void *) password);
SSL_CTX_set_default_passwd_cb(ctx, password_cb);
}
if (tls_client_local_cn_name[0] != '\0') {
cert = _tls_set_certificate(ctx, tls_client_local_cn_name);
}
if (cert==NULL && certfile[0] != '\0') {
//print several warnings....
}
if (cert!=NULL)
{
X509_free(cert);
cert = NULL;
}
/* Load the CAs we trust */
{
char *caFile = 0, *caFolder = 0;
int fd = open(eXosip_tls_ctx_params.root_ca_cert, O_RDONLY);
if (fd >= 0) {
struct stat fileStat;
if (fstat(fd, &fileStat) < 0) {
} else {
if (S_ISDIR(fileStat.st_mode)) {
caFolder = eXosip_tls_ctx_params.root_ca_cert;
} else {
caFile = eXosip_tls_ctx_params.root_ca_cert;
}
}
close(fd);
}
{
int verify_mode = SSL_VERIFY_PEER;
SSL_CTX_set_verify(ctx, verify_mode, &verify_cb);
SSL_CTX_set_verify_depth(ctx, ex_verify_depth + 1);
}
}
SSL_CTX_set_options(ctx, SSL_OP_ALL | SSL_OP_NO_SSLv2 |
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
SSL_OP_CIPHER_SERVER_PREFERENCE);
if(!SSL_CTX_set_cipher_list(ctx,"ALL")) {
//print ... set_cipher_list: cannot set anonymous DH cipher
SSL_CTX_free(ctx);
return NULL;
}
return ctx;
}
static int _tls_tl_ssl_connect_socket(struct socket_tab *sockinfo)
{
X509 *cert;
BIO *sbio;
int res;
if (sockinfo->ssl_ctx == NULL) {
sockinfo->ssl_ctx =
initialize_client_ctx(eXosip_tls_ctx_params.client.priv_key,
eXosip_tls_ctx_params.client.cert,
eXosip_tls_ctx_params.client.priv_key_pw,
IPPROTO_TCP);
sockinfo->ssl_conn = SSL_new(sockinfo->ssl_ctx);
if (sockinfo->ssl_conn == NULL) {
return -1;
}
sbio = BIO_new_socket(sockinfo->socket, BIO_NOCLOSE);
if (sbio == NULL) {
return -1;
}
SSL_set_bio(sockinfo->ssl_conn, sbio, sbio);
}
do {
struct timeval tv;
int fd;
fd_set readfds;
res = SSL_connect(sockinfo->ssl_conn);
res = SSL_get_error(sockinfo->ssl_conn, res);
if (res == SSL_ERROR_NONE) {
//printf... SSL_connect succeeded
break;
}
if (res != SSL_ERROR_WANT_READ && res != SSL_ERROR_WANT_WRITE) {
//<-- here there is a problem res == SSL_ERROR_SSL
//print ERR_reason_error_string(ERR_get_error()));
//print ERR_error_string(ERR_get_error(), NULL));
return -1;
}
tv.tv_sec = SOCKET_TIMEOUT / 1000;
tv.tv_usec = (SOCKET_TIMEOUT % 1000) * 1000;
//retry the connection
fd = SSL_get_fd(sockinfo->ssl_conn);
FD_ZERO(&readfds);
FD_SET(fd, &readfds);
res = select(fd + 1, &readfds, NULL, NULL, &tv);
if (res < 0) {
//print error
return -1;
} else if (res > 0) {
//print...connetrion done!
} else {
//socket timeout, no data to read
return 1;
}
} while (!SSL_is_init_finished(sockinfo->ssl_conn));
if (SSL_is_init_finished(sockinfo->ssl_conn)) {
//print.. SSL_is_init_finished done
} else {
//print.. failed
}
cert = SSL_get_peer_certificate(sockinfo->ssl_conn);
if (cert != 0) {
int cert_err;
tls_dump_cert_info("tls_connect: remote certificate: ", cert);
cert_err = SSL_get_verify_result(sockinfo->ssl_conn);
if (cert_err != X509_V_OK) {
//print... Failed to verify remote certificate
tls_dump_verification_failure(cert_err);
if (eXosip_tls_ctx_params.server.cert[0] != '\0') {
X509_free(cert);
return -1;
} else if (cert_err != X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
&& cert_err != X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN
&& cert_err != X509_V_ERR_CRL_HAS_EXPIRED
&& cert_err != X509_V_ERR_CERT_HAS_EXPIRED
&& cert_err != X509_V_ERR_CERT_REVOKED
&& cert_err != X509_V_ERR_CERT_UNTRUSTED
&& cert_err != X509_V_ERR_CERT_REJECTED) {
X509_free(cert);
return -1;
}
}
X509_free(cert);
} else {
//print .. No certificate received
/* X509_free is not necessary because no cert-object was created -> cert == NULL */
if (eXosip_tls_ctx_params.server.cert[0] == '\0') {
#ifdef ENABLE_ADH
/* how can we guess a user want ADH... specific APIs.. */
sockinfo->ssl_state = 3;
return 0;
#endif
}
return -1;
}
sockinfo->ssl_state = 3;
return 0;
}
SOLVED Thanks to Eric Tsui that helps me to figure out the problem. The 'hello' that I receive from the server in the handshake has zero length. To solve this I modified the file openssl/ssl/s3_clnt.c in the following way (toggling off the length control):
diff -ur ./s3_clnt.c ./original/s3_clnt.c
--- submodules/externals/openssl/ssl/s3_clnt.c 2015-06-29 14:59:56.723462992 +0200
+++ ../../opensslOrig/s3_clnt.c 2015-06-29 15:00:22.487464221 +0200
## -868,12 +868,14 ##
}
#endif
+#ifndef OPENSSL_NO_TLSEXT
if (p != (d + n)) {
/* wrong packet length */
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_BAD_PACKET_LENGTH);
goto f_err;
}
+#endif
return (1);
f_err:

Not able to decode mp4 file using latest ffmpeg library : av_decode_video2

I am writing a wrapper code around latest ffmpeg library. I am supplying MP4 files from local system. My problem is that I am unable to get any decoded frames when I use av_decode_video2(). The return value comes out to be negative. I have used av_read_frame() which returns 0. I googled about the problem I am facing but no where could I find the correct explanation. Please give me insight here. Pasting the pseudo code here.
av_init_packet(avpkt);
picture=av_frame_alloc();
pFrameRGB=av_frame_alloc();
codec = avcodec_find_decoder(CODEC_ID_H264);
c= avcodec_alloc_context3(codec)
avcodec_open2(decoderLibraryData->c, decoderLibraryData->codec, NULL)
FormatContext = avformat_alloc_context();
char *pUrl ="./1.MP4";
iRet = avformat_open_input(atContext, pUrl, pFmt, NULL);
if(FormatContext == NULL)
{
printf("could not assign any memory !!!!!!!!! \n");
}
avformat_find_stream_info(FormatContext, NULL);
while(av_read_frame(FormatContext,avpkt) >= 0)
{
len = avcodec_decode_video2(c, picture, &got_picture,avpkt);
printf("CODEC MANAGER len %d Frame decompressed %d \n",len,got_picture);
if (len <= 0)
{
return ERROR;
}
}
}
if(lastHeight != 0 && lastWidth != 0)
{
if(lastWidth != c->width || lastHeight != c->height )
{
av_free(buffer);
buffer = NULL;
lastWidth = c->width;
lastHeight = c->height;
}
}
else
{
lastWidth = c->width;
lastHeight = c->height;
}
decodeFlag = 1;
if(!buffer)
{
int numBytes;
v_mutex_lock(globalCodecLock);
switch(inPixFormat)
{
case RGB:
// Determine required buffer size and allocate buffer
numBytes=avpicture_get_size(PIX_FMT_RGB24, c->width, c->height);
buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));
avpicture_fill((AVPicture *)pFrameRGB,buffer,PIX_FMT_RGB24,c->width, c->height);
if(cntxt)
sws_freeContext(cntxt);
cntxt = sws_getContext(c->width, c->height, c->pix_fmt,
c->width, c->height, PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);
break;
}
v_mutex_unlock(globalCodecLock);
if(cntxt == NULL)
{
printf("sws_getContext error\n");
return ERROR;
}
}
{
sws_scale(cntxt, picture->data, picture->linesize, 0, c->height, pFrameRGB->data, pFrameRGB->linesize);
if(rgbBuff)
{
if(c->width <= *width && c->height <= *height)
{
saveFrame(pFrameRGB, c->width, c->height, rgbBuff,inPixFormat);
*width = c->width;
*height = c->height;
rs = SUCCESS;
break;
}
else
{
rs = VA_LOWBUFFERSIZE;
}
}
else
{
rs = VA_LOWBUFFERSIZE;
}
}
if(width)
{
*width = c->width;
}
if(height)
{
*height = c->height;
}
if(rs == VA_LOWBUFFERSIZE)
{
break;
}
I am getting the return value of av_read_frame as 0 but av_decode_video2 returns value in negative. I am not able to get any clue here.
Make sure you have called
av_register_all();
or
avcodec_register_all();
at the beginning of your app.
Also it seems the problem is from calling avformat_find_stream_info. Test with the following code:
AVPacket avpkt;
av_init_packet(&avpkt);
AVFrame* picture = av_frame_alloc();
AVFrame* pFrameRGB = av_frame_alloc();
AVFormatContext* c2 = avformat_alloc_context();
char *pUrl = "C:/Sample Videos/20-06-34.MP4";
int video_stream_index = 0;
AVInputFormat* pFmt;
int iRet = avformat_open_input(&c2, pUrl, pFmt, NULL);
AVStream* stream = c2->streams[video_stream_index];
AVCodec* codec = avcodec_find_decoder(stream->codec->codec_id);
avcodec_open2(stream->codec, codec, NULL);
if (c2 == NULL)
{
printf("could not assign any memory !!!!!!!!! \n");
}
while (av_read_frame(c2, &avpkt) >= 0)
{
int got_picture;
int len = avcodec_decode_video2(stream->codec, picture, &got_picture, &avpkt);
printf("CODEC MANAGER len %d Frame decompressed %d \n", len, got_picture);
if (len <= 0)
{
return ERROR;
}
}

Cropping Square Video using FFmpeg

Updated
So I am trying to decode a mp4 file, crop the video into a square, and then re encode it back out to another mp4 file. This is my current code but there are a few issues with it.
One is that the video doesn't keep its rotation after the video has been re encoded
Second is that the frames get outputted in a very fast video file that is not the same length as the original
Third is that there is no sound
Lastly and most importantly is do I need AVFilter to do the frame cropping or can it just be done per frame as a resize of the frame and then encoded back out.
const char *inputPath = "test.mp4";
const char *outPath = "cropped.mp4";
const char *outFileType = "mp4";
static AVFrame *oframe = NULL;
static AVFilterGraph *filterGraph = NULL;
static AVFilterContext *crop_ctx = NULL;
static AVFilterContext *buffersink_ctx = NULL;
static AVFilterContext *buffer_ctx = NULL;
int err;
int crop_video(int width, int height) {
av_register_all();
avcodec_register_all();
avfilter_register_all();
AVFormatContext *inCtx = NULL;
// open input file
err = avformat_open_input(&inCtx, inputPath, NULL, NULL);
if (err < 0) {
printf("error at open input in\n");
return err;
}
// get input file stream info
err = avformat_find_stream_info(inCtx, NULL);
if (err < 0) {
printf("error at find stream info\n");
return err;
}
// get info about video
av_dump_format(inCtx, 0, inputPath, 0);
// find video input stream
int vs = -1;
int s;
for (s = 0; s < inCtx->nb_streams; ++s) {
if (inCtx->streams[s] && inCtx->streams[s]->codec && inCtx->streams[s]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
vs = s;
break;
}
}
// check if video stream is valid
if (vs == -1) {
printf("error at open video stream\n");
return -1;
}
// set output format
AVOutputFormat * outFmt = av_guess_format(outFileType, NULL, NULL);
if (!outFmt) {
printf("error at output format\n");
return -1;
}
// get an output context to write to
AVFormatContext *outCtx = NULL;
err = avformat_alloc_output_context2(&outCtx, outFmt, NULL, NULL);
if (err < 0 || !outCtx) {
printf("error at output context\n");
return err;
}
// input and output stream
AVStream *outStrm = avformat_new_stream(outCtx, NULL);
AVStream *inStrm = inCtx->streams[vs];
// add a new codec for the output stream
AVCodec *codec = NULL;
avcodec_get_context_defaults3(outStrm->codec, codec);
outStrm->codec->thread_count = 1;
outStrm->codec->coder_type = AVMEDIA_TYPE_VIDEO;
if(outCtx->oformat->flags & AVFMT_GLOBALHEADER) {
outStrm->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
}
outStrm->codec->sample_aspect_ratio = outStrm->sample_aspect_ratio = inStrm->sample_aspect_ratio;
err = avio_open(&outCtx->pb, outPath, AVIO_FLAG_WRITE);
if (err < 0) {
printf("error at opening outpath\n");
return err;
}
outStrm->disposition = inStrm->disposition;
outStrm->codec->bits_per_raw_sample = inStrm->codec->bits_per_raw_sample;
outStrm->codec->chroma_sample_location = inStrm->codec->chroma_sample_location;
outStrm->codec->codec_id = inStrm->codec->codec_id;
outStrm->codec->codec_type = inStrm->codec->codec_type;
if (!outStrm->codec->codec_tag) {
if (! outCtx->oformat->codec_tag
|| av_codec_get_id (outCtx->oformat->codec_tag, inStrm->codec->codec_tag) == outStrm->codec->codec_id
|| av_codec_get_tag(outCtx->oformat->codec_tag, inStrm->codec->codec_id) <= 0) {
outStrm->codec->codec_tag = inStrm->codec->codec_tag;
}
}
outStrm->codec->bit_rate = inStrm->codec->bit_rate;
outStrm->codec->rc_max_rate = inStrm->codec->rc_max_rate;
outStrm->codec->rc_buffer_size = inStrm->codec->rc_buffer_size;
const size_t extra_size_alloc = (inStrm->codec->extradata_size > 0) ?
(inStrm->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE) :
0;
if (extra_size_alloc) {
outStrm->codec->extradata = (uint8_t*)av_mallocz(extra_size_alloc);
memcpy( outStrm->codec->extradata, inStrm->codec->extradata, inStrm->codec->extradata_size);
}
outStrm->codec->extradata_size = inStrm->codec->extradata_size;
AVRational input_time_base = inStrm->time_base;
AVRational frameRate = {25, 1};
if (inStrm->r_frame_rate.num && inStrm->r_frame_rate.den
&& (1.0 * inStrm->r_frame_rate.num / inStrm->r_frame_rate.den < 1000.0)) {
frameRate.num = inStrm->r_frame_rate.num;
frameRate.den = inStrm->r_frame_rate.den;
}
outStrm->r_frame_rate = frameRate;
outStrm->codec->time_base = inStrm->codec->time_base;
outStrm->codec->pix_fmt = inStrm->codec->pix_fmt;
outStrm->codec->width = width;
outStrm->codec->height = height;
outStrm->codec->has_b_frames = inStrm->codec->has_b_frames;
if (!outStrm->codec->sample_aspect_ratio.num) {
AVRational r0 = {0, 1};
outStrm->codec->sample_aspect_ratio =
outStrm->sample_aspect_ratio =
inStrm->sample_aspect_ratio.num ? inStrm->sample_aspect_ratio :
inStrm->codec->sample_aspect_ratio.num ?
inStrm->codec->sample_aspect_ratio : r0;
}
avformat_write_header(outCtx, NULL);
filterGraph = avfilter_graph_alloc();
if (!filterGraph) {
printf("could not open filter graph");
return -1;
}
AVFilter *crop = avfilter_get_by_name("crop");
AVFilter *buffer = avfilter_get_by_name("buffer");
AVFilter *buffersink = avfilter_get_by_name("buffersink");
char args[512];
snprintf(args, sizeof(args), "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
width, height, inStrm->codec->pix_fmt,
inStrm->codec->time_base.num, inStrm->codec->time_base.den,
inStrm->codec->sample_aspect_ratio.num, inStrm->codec->sample_aspect_ratio.den);
err = avfilter_graph_create_filter(&buffer_ctx, buffer, NULL, args, NULL, filterGraph);
if (err < 0) {
printf("error initializing buffer filter\n");
return err;
}
err = avfilter_graph_create_filter(&buffersink_ctx, buffersink, NULL, NULL, NULL, filterGraph);
if (err < 0) {
printf("unable to create buffersink filter\n");
return err;
}
snprintf(args, sizeof(args), "%d:%d", width, height);
err = avfilter_graph_create_filter(&crop_ctx, crop, NULL, args, NULL, filterGraph);
if (err < 0) {
printf("error initializing crop filter\n");
return err;
}
err = avfilter_link(buffer_ctx, 0, crop_ctx, 0);
if (err < 0) {
printf("error linking filters\n");
return err;
}
err = avfilter_link(crop_ctx, 0, buffersink_ctx, 0);
if (err < 0) {
printf("error linking filters\n");
return err;
}
err = avfilter_graph_config(filterGraph, NULL);
if (err < 0) {
printf("error configuring the filter graph\n");
return err;
}
printf("filtergraph configured\n");
for (;;) {
AVPacket packet = {0};
av_init_packet(&packet);
err = AVERROR(EAGAIN);
while (AVERROR(EAGAIN) == err)
err = av_read_frame(inCtx, &packet);
if (err < 0) {
if (AVERROR_EOF != err && AVERROR(EIO) != err) {
printf("eof error\n");
return 1;
} else {
break;
}
}
if (packet.stream_index == vs) {
//
// AVPacket pkt_temp_;
// memset(&pkt_temp_, 0, sizeof(pkt_temp_));
// AVPacket *pkt_temp = &pkt_temp_;
//
// *pkt_temp = packet;
//
// int error, got_frame;
// int new_packet = 1;
//
// error = avcodec_decode_video2(inStrm->codec, frame, &got_frame, pkt_temp);
// if(error < 0) {
// LOGE("error %d", error);
// }
//
// // if (error >= 0) {
//
// // push the video data from decoded frame into the filtergraph
// int err = av_buffersrc_write_frame(buffer_ctx, frame);
// if (err < 0) {
// LOGE("error writing frame to buffersrc");
// return -1;
// }
// // pull filtered video from the filtergraph
// for (;;) {
// int err = av_buffersink_get_frame(buffersink_ctx, oframe);
// if (err == AVERROR_EOF || err == AVERROR(EAGAIN))
// break;
// if (err < 0) {
// LOGE("error reading buffer from buffersink");
// return -1;
// }
// }
//
// LOGI("output frame");
err = av_interleaved_write_frame(outCtx, &packet);
if (err < 0) {
printf("error at write frame");
return -1;
}
//}
}
av_free_packet(&packet);
}
av_write_trailer(outCtx);
if (!(outCtx->oformat->flags & AVFMT_NOFILE) && outCtx->pb)
avio_close(outCtx->pb);
avformat_free_context(outCtx);
avformat_close_input(&inCtx);
return 0;
}
It looks like you are looking for vf_crop.
The CropContext contains a x, y, w, and h, which should be what you need to crop a video to a specific width and height.

Resources