Need to run .exe file for 7 seconds and then kill the exe while performing input and output in text files - windows

I want to create a batch file which runs a program for 7 seconds, irrespective of the completion of execution of the other program. I also want that the program should take input and save the output in an external file. This is what I tried:
start program.exe
ping 1.1.1.1 -n 1 -w 7000 > nul
taskkill /im program.exe /f
rem continue here
The above works fine, but when I replace line 1 with:
start program.exe < in.txt > out.txt
then input from file and output in file doesn't work.

cmd doesn't set the STARTF_USESTDHANDLES flag of the CreateProcess STARTUPINFO structure. Instead, it temporarily redirects its own standard handles and relies on inheritance. This approach works even if cmd has to call ShellExecuteEx, which lacks a way to explicitly set the standard handles.
However, redirecting its own standard handles doesn't work when CREATE_NEW_CONSOLE is set in the process creation flags, which is the default for the start command. To avoid this problem, use the /b option to prevent creating a new console.
You may also want to redirect stderr to stdout or a file. This prevents errors from being written to the console. For example:
start /b program.exe <in.txt >out.txt 2>&1
start /b program.exe <in.txt >out.txt 2>err.txt
start /b program.exe <in.txt >out.txt 2>nul
Example using Debugging Tools for Windows
(test) C:\>cdb -Goxi ld cmd
Microsoft (R) Windows Debugger Version 6.12.0002.633 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.
CommandLine: cmd
Symbol search path is: symsrv*symsrv.dll*
C:\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is:
(ed0.1770): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00000000`77848700 cc int 3
0:000> .reload /f
Reloading current modules
.....
0:000> bp CreateProcessW
0:000> g
Run where.exe in a new console.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
(test) C:\>start /w where.exe <nul >nul
Breakpoint 0 hit
kernel32!CreateProcessW:
00000000`775a0660 4883ec68 sub rsp,68h
Note that cmd.exe redirects its StandardOutput before calling CreateProcess:
0:000> ?? ((ntdll!_PEB *)#$peb)->ProcessParameters->StandardOutput
void * 0x00000000`00000060
0:000> !handle 60 3
Handle 60
Type File
Attributes 0
GrantedAccess 0x120196:
ReadControl,Synch
Write/Add,Append/SubDir/CreatePipe,WriteEA,ReadAttr,WriteAttr
HandleCount 2
PointerCount 3
The process creation flags, i.e. dwCreationFlags, the 6th parameter:
0:000> dd (#rsp + 6*8) l1
00000000`00182c58 00080410
is passed as 0x80410, which is a bitwise OR of the following flags:
EXTENDED_STARTUPINFO_PRESENT
CREATE_UNICODE_ENVIRONMENT
CREATE_NEW_CONSOLE
Because a new console is created, where.exe doesn't inherit cmd's standard handles:
0:000> g
Symbol search path is: symsrv*symsrv.dll*
C:\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is:
(1550.1a80): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00000000`77848700 cc int 3
1:001> ?? ((ntdll!_PEB *)#$peb)->ProcessParameters->StandardOutput
void * 0x00000000`00000007
Note: in Windows 8+ a console handle is just a regular file handle, so you'll have to look deeper.
I'm using Windows 7 for this example, so console handles are fake handles tagged by setting the lower 2 bits (e.g. 3, 7, 11 => 0b0011, 0b0111, 0b1011). By 'fake' I mean they're not in the process handle table used for kernel object handles. Thus, for example, you can't use the debugger !handle command to inspect handle 7:
1:001> !handle 7 f
Could not duplicate handle 7, error 87
In Windows 7, console handles are allocated and managed by the console host process, conhost.exe. They're tagged so Windows base functions can make the required LPC call to conhost.exe via NtRequestWaitReplyPort.
The above example demonstrated how creating a new console overrides inheriting cmd's redirected standard handles. Now let's add the /b option to prevent creating a new console.
1:001> g
(test) C:\>start /b /w where.exe <nul >nul
Breakpoint 0 hit
kernel32!CreateProcessW:
00000000`775a0660 4883ec68 sub rsp,68h
dwCreationFlags is 0x80600:
0:000> dd (#rsp + 6*8) l1
00000000`00182c58 00080600
which is a bitwise OR of the following creation flags:
EXTENDED_STARTUPINFO_PRESENT
CREATE_UNICODE_ENVIRONMENT
CREATE_NEW_PROCESS_GROUP
(A side effect of specifying /b is to create the process as the leader of a new process group. If it's a console process, this allows generating a Ctrl+Break event that targets the group.)
In this case, where.exe does inherit the redirected standard handles from cmd.exe:
0:000> g
Symbol search path is: symsrv*symsrv.dll*
C:\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is:
(1508.1534): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00000000`77848700 cc int 3
1:001> ?? ((ntdll!_PEB *)#$peb)->ProcessParameters->StandardOutput
void * 0x00000000`00000064
1:001> !handle 64 3
Handle 64
Type File
Attributes 0
GrantedAccess 0x120196:
ReadControl,Synch
Write/Add,Append/SubDir/CreatePipe,WriteEA,ReadAttr,WriteAttr
HandleCount 3
PointerCount 4
Again, in Windows 7 it's easy to spot a console pseudo handle because it's tagged by setting the low 2 bits of the handle value. For Windows 8+, a quick check is to look at the low nibble (4 bits) of the file's granted access, for which read data access is 1, write data access is 2, and append data access is 4. A file opened for a console buffer has both read and write access, whereas cmd's redirection uses either read (<) or write (>), but not both. The above is the redirected output, and you can see the file is opened with write and append access (2+4), but not read access. That's a quick check, but if you want to be certain you can use a kernel debugger such as kd.exe, or a tool such as Sysinternals Process Explorer or handle.exe. These can show you the NT kernel object path, such as \Device\ConDrv\Input for a Windows 8+ console input handle.

Related

How do I get handles information from a full-dump of a windows process?

I'm trying to debug an issue with what may be handle leak. I have a dump created on a remote windows machine and I would like to see the handles information. I'm using WinDbg. I have seen some articles from the MSDN and from other sources, like https://www.codeproject.com/Articles/6988/Debug-Tutorial-Part-5-Handle-Leaks, but I can't get it to work, so I need some help.
I tried the next
Using !handles or !devhandles - these have failed. I either get no export handles found or a failure to load kdexts. Apparently kernel debugging is not enabled.
I found winxp/kdexts.dll in my path (given from .chain command) but it wouldn't load - .load kdexts yields `DebugExtensionInitializeFailed1 with error code 0x80004005.
Using !handle - with !handle -? I get help for the command but when I try something else, I get "Unable to read handle information". For example,
!handle - I expected a full list of handles
!handle 0 0
!handle 0 0 file
My setup
The remote process is Windows server 2012 (64bit), just as my own machine
I'm using the latest WinDbg from the windows sdk 10
I have a full dump, created by right-clicking task manager
I need some help if possible
Do I need to do kernel-debugging in order to view the list of handles from the dump?
Is it possible at all to do kernel-debugging on a full dump created from task-manager? Or is it required that the dump be taken differently?
How can I know if a given dump file includes the handle information?
How can I use the !handle command properly?
Is there any other alternative, such as using visual studio, another utility, etc.?
I'd appreciate any help
!tamir
your dump was probably a dump taken without handle information
you may use dumpchk.exe that comes with windbg installation to see if Handle Stream exists in the dump
if you have control over dump creation check how to use .dump /ma with windbg
or you may also explore sysinternals procdump.exe
and also make sure you are using the correct bitted debugger for the dump in question
a sample path
D:\>dir /s /b "c:\Program Files (x86)\Windows Kits\10\Debuggers\cdb.exe"
c:\Program Files (x86)\Windows Kits\10\Debuggers\arm\cdb.exe
c:\Program Files (x86)\Windows Kits\10\Debuggers\arm64\cdb.exe
c:\Program Files (x86)\Windows Kits\10\Debuggers\x64\cdb.exe
c:\Program Files (x86)\Windows Kits\10\Debuggers\x86\cdb.exe
here is a sample dump creation with and without handle stream in the dump
:000> .dump /ma d:\madump.dmp
Creating d:\madump.dmp - mini user dump
Dump successfully written
0:000> .dump d:\nomadump.dmp
Creating d:\nomadump.dmp - mini user dump
Dump successfully written
0:000> q
analysing both the dumps with dumpchk and checking for streams present
dumpchk nomadump.dmp > nomachk.txt
dumpchk madump.dmp > machk.txt
D:\>type machk.txt |grep -i number.*stream
NumberOfStreams 17
D:\>type nomachk.txt |grep -i number.*stream
NumberOfStreams 13
diff
D:\>diff -y machk.txt nomachk.txt
Microsoft (R) Windows Debugger Version 10.0.17763.132 AMD64 Microsoft (R) Windows Debugger Version 10.0.17763.132 AMD64
Loading Dump File [D:\madump.dmp] | Loading Dump File [D:\nomadump.dmp]
User Mini Dump File with Full Memory: Only application d | User Mini Dump File: Only registers, stack and portions of me
----- User Mini Dump Analysis ----- User Mini Dump Analysis
MINIDUMP_HEADER: MINIDUMP_HEADER:
Version A793 (A063) Version A793 (A063)
NumberOfStreams 17 | NumberOfStreams 13
Flags 441826 | Flags 40000
0002 MiniDumpWithFullMemory <
0004 MiniDumpWithHandleData <
0020 MiniDumpWithUnloadedModules <
0800 MiniDumpWithFullMemoryInfo <
1000 MiniDumpWithThreadInfo <
40000 MiniDumpWithTokenInformation 40000 MiniDumpWithTokenInformation
400000 MiniDumpWithIptTrace <
if you feel enterprising take a look here for some hints to deciphering a dump without windbg /dbgeng
forgot to post the result of doing !handle on both dumps
D:\>cdb -c "!handle;q" -z nomadump.dmp |awk /Reading/,/quit/"
0:000> cdb: Reading initial command '!handle;q'
ERROR: !handle: extension exception 0x80004002.
"Unable to read handle information"
quit:
D:\>cdb -c "!handle;q" -z madump.dmp |awk /Reading/,/quit/"
0:000> cdb: Reading initial command '!handle;q'
Handle 0000000000000004
Type File
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxSNIPxxxxxxxxx
Handle 0000000000000128
Type Mutant
Handle 000000000000012c
Type
Handle 0000000000000180
Type File
70 Handles
Type Count
None 27
Event 13
File 8
Directory 2
Mutant 1
Semaphore 2
Key 6
IoCompletion 2
TpWorkerFactory 2
ALPC Port 1
WaitCompletionPacket 6
quit:
Check the tool which was used for creating the crash dump. Perhaps it provides an option to include handle data.
Task Manager includes handle data by default
Visual Studio includes handle data by default
In WinDbg, .dump can be used with the /mh switch to include handle data. /ma is a shortcut for /mfFhut, so it also includes handle data.
ProcDump automatically includes handle data.
Windows Error Reporting LocalDumps can be configured with a Registry value called CustomDumpFlags.
If you create the dump programmatically yourself with MiniDumpWriteDump(), use MINIDUMP_TYPE::MiniDumpWithHandleData.

Why Entry Point Address of executable in dumpbin is different from WinDbg?

I'm trying to understand the mechanics of loading an executable file, so I did two different tests with notepad.exe
1) Running dumpbin command:
dumpbin /ALL "C:\Windows\System32\notepad.exe" /OUT:"C:\sample\log4.txt"
I got the following values under OPTIONALHEADER VALUES:
1AC50 entry point (000000014001AC50) WinMainCRTStartup
1000 base of code
140000000 image base (0000000140000000 to 0000000140042FFF)
2) Running WinDbg:
x notepad!*CRT*
I got these:
00b9bf9a notepad!__mainCRTStartup (void)
00b9bf90 notepad!WinMainCRTStartup (<no parameter info>)
00ba04a4 notepad!msvcrt_NULL_THUNK_DATA = <no type information>
00ba050c notepad!_IMPORT_DESCRIPTOR_msvcrt = <no type information>
I don't understand why 14001AC50 and 00b9bf90 are different values. Shouldn't they be the same AddressOfEntryPoint value?
Thanks in advance
There are a couple reasons for the discrepancy.
First, you are running dumpbin on the x64 version of notepad.exe, stored in System32 but you seem to be debugging the x86 notepad.exe stored in SysWoW64. Make sure you've launched the x64 or AMD64 version of WinDbg and that you're attaching to C:\Windows\System32\notepad.exe.
Once that's sorted out things should start making more sense but there's one more thing to keep in mind. The x command in WinDbg is displaying the virtual memory address of the symbol in the running process while dumpbin displays it as an offset from the module base address.
Some quick subtraction from the module base and things should match up.
Here's how it looks on my system:
C:\>dumpbin /ALL "C:\Windows\System32\notepad.exe" | find "entry point"
1AC50 entry point (000000014001AC50) WinMainCRTStartup
0:000> x notepad!WinMainCRTStartup
00007ff6`4fe1ac50 notepad!WinMainCRTStartup (<no parameter info>)
0:000> ? notepad!WinMainCRTStartup - notepad
Evaluate expression: 109648 = 00000000`0001ac50

How to break on the entry point of a program when debug in kernel mode with windbg?

I want to debug a program in kernel mode, and I want to break on the entry point of the program like ollydbg. But I can't break it with bp because the program is not start and the symbol can't be loaded. I have found some way to do it but I think it's not so good.
1.Break on the CreateProcess function in kernel. But I don't know which function exactly should I break and I think there is a long way between CreateProcess and the entry point of the program.
2.Change the entry point of the program with cc. But it needs other tools and I should change the code where the byte changed back. I think it is annoying.
3.With the help of ollydbg. Debugging the program with ollydbg in a virtual machine which is debugged with windbg. I don't think that it is a good idea.
4.Use sxe ld. It can be found on Listing 3.29 in <<Advanced Windows Debugging>>. I have tried it but I found that it only works on the first time. And I don't know what exactly should I do after the break.
5.Break on the entry function with bu. But I don't know what exactly I should do either. For example, how to load the symbol?
6.Use .create. I don't know whether it is properly or not to do what I said.
I think that it is a common use to break on the entry point of a program when debug in kernel mode with windbg , and I think that there must be a good way to do that with the powerful windbg. What's the best way to do it?
By the way, I want to debug a program in kernel mode because I want to get the token vaule of the program. I found that the windbg can identify the token with !token in user mode, but I don't know how to get the value of token in user mode. It seems that I can only get the value of token in the kernel mode, right or wrong?
you can run any exe in the target via ntsd -d to debug it from the kernel mode debugger running in the host
assuming you are running a virtual machine mytarget inside myhost
install windbg in myhost
set symbol path for myhost viz srv*x:\xxxx*http:\xxxxxxxxxxxx
create a kernel connection in the host (choose the best shown below is a serial connnection)
X:\xxxx\windbg.exe -k com:pipe,port=\\.\pipe\debugPipe,resets=0,reconnect
install windbg in mytarget
open a shared folder z:\ pointing to the symbolcache folder in myhost
set symbolpath in mytarget pointing to the shared folder
run ntsd -d calc.exe
kd will break on $exentry of calc.exe with Input Prompt
as long as Input prompt is shown you are using kd like a native usermode debugger
so if you set a bp calc!Winmain and issue g kd will break on calc.exe winmain
to get to kd session use .breakin
messy stuff but will work well once you get accustomed (ie memorizing the docs)
a sample run
kd> g <-------------- kd session running in myhost
CommandLine: calc.exe
Symbol search path is: srv*z:\
*http://msdl.microsoft.com/download/symbols
ntdll!DbgBreakPoint:
7c90120e cc int 3
.sympath
NOTE: The symbol path for this ntsd is relative to where
ntsd.exe is running, not where kd.exe is running.
Symbol search path is: srv*z:\
*http://msdl.microsoft.com/download/symbols
Expanded Symbol search path is: srv*z:\
*http://msdl.microsoft.com/download/symbols
.reload /f calc.exe
lm m calc
start end module name
01000000 0101f000 calc (pdb symbols) z:\calc.pdb\3B7D84101\calc.pdb
0:000> version <--------------------usermode session in kd via ntsd -d
version
Windows XP Version 2600 (Service Pack 3) UP Free x86 compatible
Live user mode: <Local>
command line: 'ntsd -d calc.exe' Debugger Process 0x3F8
? $exentry;? calc!WinmainCrtstartup
Evaluate expression: 16852085 = 01012475
Evaluate expression: 16852085 = 01012475
as to your original request i am not sure what token you are interested to find
if getting the EPROCESS->Token of your exe is the only requirement you dont have to run any kd session
you can get the token of all running process in myhost with a local kernel debugging session (either using kd -kl or by using livekd from sysinternals)
here is a simple script which fetches the sid of all running process employing the above technique
:\>cat sid.txt
!for_each_process "r $t0 =(##c++(((nt!_eprocess *) ##Process )->Token.Object)) &
##(~7); r $t1 = ##c++(((nt!_token *) #$t0 )->UserAndGroups->Sid);!sid #$t1 1; ?
? (char *)((nt!_eprocess *) ##Process )->ImageFileName "
:\>kd -kl -c "$$>a< sid.txt;q"
result
WARNING: Local kernel debugging requires booting with kernel
debugging support (/debug or bcdedit -debug on) to work optimally.
lkd> kd: Reading initial command '$$>a< sid.txt;q'
SID is: S-1-5-18 (Well Known Group: NT AUTHORITY\SYSTEM)
char * 0x8ac729a4
"System"
SID is: S-1-5-18 (Well Known Group: NT AUTHORITY\SYSTEM)
char * 0x8a35729c
"smss.exe"
SID is: S-1-5-20 (Well Known Group: NT AUTHORITY\NETWORK SERVICE)
char * 0x8a3619ac
"svchost.exe"
SID is: S-1-5-19 (Well Known Group: NT AUTHORITY\LOCAL SERVICE)
char * 0x8a36ef14
"svchost.exe"
SID is: S-1-5-21-602162358-1801674531-1417001333-1003 (User: XXXXXX\Admin)
char * 0x8a261b64
"explorer.exe"
Use the method described in the Windbg help file for debugging WinLogon. Substitute your user mode app for WinLogon:
Windbg | Help | Contents | Windows Debugging | Debugging Techniques | Specialized Debugging Techniques | Debugging WinLogon
IFEO will start your user mode app and attach ntsd.exe. From ntsd.exe, you can set a break point on image entry with bu $exentry then g to continue.
At any point that ntsd.exe is broken into your user mode process, you can issue .breakin command to switch to kernel mode debugging.

subinacl get full output

We are using the windows console program subinacl.exe to grant a user the right to stop and start a service. Therfore we use the following command:
subinacl.exe /service %SERVICE_NAME% /grant=%PC_NAME%\%USER_NAME%=PTO
where
%SERVICE_NAME% = name of the service
%PC_NAME% = name of the computer
%USER_NAME% = name of the user that should become the right to start and stop the service
PTO = right to start and stop the service (R would be just reading)
When typing the command into the default windows command line (with administrator rights) on a windows server 2012 the result is:
ELITE_INETRSVSERVER : delete Perm. ACE 4 test-pc\test
ELITE_INETRSVSERVER : new ace for test-pc\test
ELITE_INETRSVSERVER : 2 change(s)
Elapsed Time: 00 00:00:00
Done: 1, Modified 1, Failed 0, Syntax errors 0
Last Done : ELITE_INETRSVSERVER
Now we want to save the text into a file or get it into a programm (via redirect the outputs : Getting output from a shell/dos app into a Delphi app). We need the integer values of Done and Failed found in the result.
The problem is, that we cannot catch the last three lines after the empty lines.
When using console redirect, the first three lines can be found in the file result.txt. But the last three are shown in the console.
subinacl.exe /service %SERVICE_NAME% /grant=%PC_NAME%\%USER_NAME%=PTO > result.txt 1<&2
The same problem we do have, when redirecting the output programmatically.
Of course every command is executed as administrator.
The option /errorlog could help to solve the problem:
subinacl /outputlog=c:\NONERRORS.TXT /errorlog=C:\ERRORLOG.TXT /file C:\TEST.TXT /display
if C:\ERRORLOG.TXT file is empty it means that the command has been executed successfully.

VBS - Error opening connection using ADODB

I'm having problems trying to connect in my oracle database using an ADODB object in VBScript, the code is working on a Win7 machine but not on WinXP, I tried to search for the error code, downloaded the sdk with the help file to look for something but I didn't found nothing useful.
Here is the code sample:
ConnectionString = "DSN=(Oracle in OraClient11g_home1);UID=username ;PWD=password ;DBQ=myDatabase"
Set objCon = CreateObject("ADODB.Connection")
objCon.Open ConnectionString 'the error occurs in this line
I don't know if the connection string must be different for winXP machines... I really don't know how to solve this, can someone help me?
The error trace information:
"Error #-2147024770:
Error reported by: ADODB.Connection
Help File:
Topic ID: 1240640"
-2147024770 = FFFFFFFF8007007E
To Decode 0x8007nnnn Errors
HResults with facility code 7 means the HResult contains a Windows' error code. You have to look up the Windows' error code not the HResult.
To decode 0x8007007e. The 0x means it's a hexadecimal number, the 8 means error, the first 7 means it a windows error, and the rest of the number, 7e, is the actual Windows error.
To look up the error we need it in decimal format. Start Calculator (Start - All Programs - Accessories - Calculator) and choose View menu - Scientific, then View menu - Hex. Enter 7e. Then View menu - Decimal. It will say 126.
Start a Command Prompt (Start - All Programs - Accessories - Command Prompt) and type
net helpmsg 126
and it will say
The specified module could not be found.
or look it up in winerror.h
//
// MessageId: ERROR_MOD_NOT_FOUND
//
// MessageText:
//
// The specified module could not be found.
//
#define ERROR_MOD_NOT_FOUND 126L
To see what is happening start your program in ntsd.
Start a command prompt.
Type
md c:\symbols
set _NT_SYMBOL_PATH=srv*C:\tmp*http://msdl.microsoft.com/download/symbols;c:\symbols
then (changing it to your program from notepad)
ntsd -g -o c:\windows\notepad.exe
so something
ntsd -g -o wscript "c:\folder\script.vbs"
and wait for the error.

Resources