WP7 Shell, Console, Batch files interpreter - Windows Phone 7 Development and Hacking

Hi Friends.
Standard Cmd.exe seems not working on WP7 probably by any restrictions, then we need own solution. There is a simple WP7 console (paied!!!), but this is childer game only, not a real working tool (some connection features from it are so usable).
There is one BIG problem on CE based systems - Shell context absention, especially Current Directory concept miss. Rainer Keuchel's CELib and Console solves it by ENVIRONMENT registry key, common for every console instance. Desktop Windows / POSIX systems concept of many unique shell contexts is very hard implementable here.There is not problem to make new context in registry - this can be unique key, contain all included processes IDs, environment structure and especially current directory path. But, somebody must release this context, when all processes finish. It can not be user applications dependent, any kernel "garbage collector" must be implemented for it. And, how to refer context to launched process? What do you mean about it - is better simple one context shell then nothing, or long work on multicontext solution?
Another problem is popen and pipes absention on WP7 system. I finished very simple solution last weak, based on stdout to file redirecting, which Microsoft forgets in WP7 API from WM6 one. Then we can make simply dedicated applications (dir.exe, set.exe, copy.exe, delete.exe etc.) in \Windows directory, callable by standard ShellExecuteEx, enrolling ouptut do stdout by printf etc. But, is it good solution? Have you got anybody real pipes working on WP7?
Working console appplication with bath files interpreter give us big possibilities for on-device attempts and programming, simple installators/deinstallators building, WP7 Perl, HaRET, Linux, WM, WinRT, WP8 wrappers working etc. It is not problem now to runs anything in kernel mode on WP7. Are you somebody able to cooperate include native coding? We can make real operating system from Microsoft fart bag named WP7.

Martin7Pro said:
Hi Friends.
Standard Cmd.exe seems not working on WP7 probably by any restrictions, then we need own solution. There is a simple WP7 console (paied!!!), but this is childer game only, not a real working tool (some connection features from it are so usable).
There is one BIG problem on CE based systems - Shell context absention, especially Current Directory concept miss. Rainer Keuchel's CELib and Console solves it by ENVIRONMENT registry key, common for every console instance. Desktop Windows / POSIX systems concept of many unique shell contexts is very hard implementable here.There is not problem to make new context in registry - this can be unique key, contain all included processes IDs, environment structure and especially current directory path. But, somebody must release this context, when all processes finish. It can not be user applications dependent, any kernel "garbage collector" must be implemented for it. And, how to refer context to launched process? What do you mean about it - is better simple one context shell then nothing, or long work on multicontext solution?
Another problem is popen and pipes absention on WP7 system. I finished very simple solution last weak, based on stdout to file redirecting, which Microsoft forgets in WP7 API from WM6 one. Then we can make simply dedicated applications (dir.exe, set.exe, copy.exe, delete.exe etc.) in \Windows directory, callable by standard ShellExecuteEx, enrolling ouptut do stdout by printf etc. But, is it good solution? Have you got anybody real pipes working on WP7?
Working console appplication with bath files interpreter give us big possibilities for on-device attempts and programming, simple installators/deinstallators building, WP7 Perl, HaRET, Linux, WM, WinRT, WP8 wrappers working etc. It is not problem now to runs anything in kernel mode on WP7. Are you somebody able to cooperate include native coding? We can make real operating system from Microsoft fart bag named WP7.
Click to expand...
Click to collapse
Pocket CMD from CE7 ARMv7 works fine via telnet. Tested on my Samsung Omnia 7 and Jaxbot's Samsung Focus. You can see it in action in this screenshot: http://windowsphonehacker.com/articles/all_in_a_days_work-03-03-13

Do I have to rename the zip tp xap and install normally?

No. If you don't know how to install it you probably don't need it as it creates a huge security risk on your phone.

Hmm... , interesting. The same exe in other configuratin I tested on my phones in the past with result : "Too much console ones work immediatelly, close any and try again".
Do you know (or is possible to code) telnet WP7 client, functioning on the same IP as server? Especially with hardware keyboard support?

Martin7Pro said:
Hmm... , interesting. The same exe in other configuratin I tested on my phones in the past with result : "Too much console ones work immediatelly, close any and try again".
Do you know (or is possible to code) telnet WP7 client, functioning on the same IP as server? Especially with hardware keyboard support?
Click to expand...
Click to collapse
Silverlight apps can not connect to localhost, it has been blocked.

Simple batch line interpreter
I tried cmd.exe batch and arguments calling, but it seems does not working for me. Then I will try own attempt.
Single batch line interpreter (*.bat files interpreting precursor):
SHLine.cpp
PHP:
// SHLine.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
//#include <atlstr.h>
/*CString*/
#ifdef _DEBUG
#pragma comment (lib, "libcmtd.lib")
#else
#pragma comment (lib, "libcmt.lib")
#endif
/*CString*/
#include <list>
using namespace std;
typedef list<CString> StringList;
#define SEE_MASK_NOASYNC (0x00000100)
CString ErrorString(DWORD err)
{
CString Error;
try
{
LPTSTR s;
if (::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, err, 0, (LPTSTR)&s, 0, NULL) == 0)
{
Error.AppendFormat(TEXT("Error code : %X"), err);
} /* failed */
else
{ /* success */
LPTSTR p = _tcschr(s, _T('\r'));
if(p != NULL)
{ /* lose CRLF */
*p = _T('\0');
} /* lose CRLF */
Error = s;
::LocalFree(s);
} /* success */
return Error;
}
catch (...)
{
Error.AppendFormat(TEXT("Error code : %X"), err);
return Error;
}
}
HRESULT ShellExecuteWait(const wchar_t * file, const wchar_t * args, long lTimeout)
{
TRACE(L"ShellExecuteWait file=%s, args=%s, long lTimeout=%X\n", file, args, lTimeout);
try
{
SHELLEXECUTEINFO lpExecInfo;
memset(&lpExecInfo, 0, sizeof(SHELLEXECUTEINFO));
lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
lpExecInfo.lpFile = file;
lpExecInfo.lpParameters = args;
lpExecInfo.lpDirectory = _T("");
lpExecInfo.lpVerb = _T("open");
lpExecInfo.nShow = SW_MINIMIZE;
lpExecInfo.fMask = 0;
lpExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC;// | SEE_MASK_FLAG_DDEWAIT;//0; lpExecInfo.hwnd = NULL;
lpExecInfo.hInstApp = NULL;//AfxGetInstanceHandle();
if(!ShellExecuteEx(&lpExecInfo))
{
DWORD err = GetLastError();
TRACE(L"ShellExecuteEx Error %d %s\n", err, ErrorString(err));
/// Sleep(100);
return (HRESULT)err;//ERROR_SUCCESS;
}
if (lpExecInfo.hProcess > 0)
{
TRACE(L"ShellExecuteEx WaitForSingleObject hProcess=%X\n", lpExecInfo.hProcess);
DWORD res = ::WaitForSingleObject(lpExecInfo.hProcess, lTimeout/*INFINITE*/);//5000);
TRACE(L"WaitForSingleObject lTimeout=%X, res=%X\n", lTimeout, res);
/// Sleep(100);
if (lTimeout != INFINITE && res != WAIT_OBJECT_0)
{
TerminateProcess(lpExecInfo.hProcess, 0);
TRACE(L"TerminateProcess;\n");
}
CloseHandle(lpExecInfo.hProcess);
}
TRACE(L"return ERROR_SUCCESS;\n");
return ERROR_SUCCESS;
}
catch (...)
{
DWORD err = 0x80070000 | GetLastError();
MessageBox(NULL, ErrorString(err), _T("ShellExecuteWait Error"), MB_OK);
return ERROR_SUCCESS;//(HRESULT)err;
}
}
StringList GetPathList(StringList & slPathList)
{
slPathList.clear();
slPathList.push_front(L"Program Files"); // Only for testing. HKCU\Environment PATH value will splitted instead;
slPathList.push_front(L"My Documents");
return slPathList;
}
CString GetCurrentDirectory(CString & csCurDir)
{
csCurDir = L"Program Files\\SHLine"; // Only for testing. HKCU\Environment CurrentDirectory value will readed instead;
return csCurDir;
}
bool FileExists(const wchar_t * file)
{
WIN32_FIND_DATA FindFileData;
HANDLE hFile = ::FindFirstFile(file, &FindFileData) ;
bool bFound = (hFile && (hFile != INVALID_HANDLE_VALUE));
if(bFound)
{
::FindClose(hFile);
}
return bFound;
}
int _tmain(int argc, _TCHAR* argv[])
{
TRACE(L"_tmain(int argc=%d);\n", argc);
if (argc > 1 && argv[1])
{
CString csRunPath = argv[1];
CString csRunArgs = L"";
if (argc > 2 && argv[2])
{
csRunArgs = argv[2];
for (int i = 3; i <= argc; i++)
{
if (argv[i])
{
csRunArgs = csRunArgs + L" " + argv[i];
}
}
}
CString csCurDir;
GetCurrentDirectory(csCurDir);
HRESULT hRes = ERROR_FILE_NOT_FOUND;
CString csFN = L"\\"+csCurDir+L"\\"+csRunPath/*.GetString()*/;
if (FileExists(csFN))
{
hRes = ShellExecuteWait(csFN, csRunArgs/*.GetString()*/, 60000);
}
if (hRes == ERROR_FILE_NOT_FOUND)
{
csFN = L"\\"+csRunPath;
CString csWin = L"\\Windows\\"+csRunPath;
if (FileExists(csFN) || FileExists(csWin))
{
hRes = ShellExecuteWait(csFN, csRunArgs, 60000); // Full path specified or file is known for CE Shell (included to \\Windows\ directory)
}
if (hRes == ERROR_FILE_NOT_FOUND)
{
StringList slPathList;
GetPathList(slPathList);
DWORD dwPath = 0;
for (StringList::iterator itPath = slPathList.begin(); itPath != slPathList.end(); ++itPath)
{
csFN = L"\\"+*itPath+L"\\"+csRunPath;
if (FileExists(csFN))
{
hRes = ShellExecuteWait(csFN, csRunArgs, 60000);
}
}
}
}
TRACE(L"_tmain returns 0x%X;\n", hRes);
return hRes;
}
TRACE(L"_tmain returns E_INVALIDARG;\n");
return E_INVALIDARG;
}
This interpret will be uploaded to \Windows directory to be used by any appplication. One can be batch files interpreter (call this shell with all lines as paramters), or do any controlling (lines can contain controlling directives as cycles etc.). The .bat extension registering is soluted by CE standard way on unlocked phones.
CD.exe, DIR.exe, ..., etc programs will add standard shell functionality. Output (directories listing etc.) will soluted by stdout file forwarding.
In this way one only shell interpreting application (one current directory only) will allowed immeditelly. Better something then nothing.
EDIT:
I have got batch interpreter working. But, very strange behaviour occures:
1. AygShell does not add exe extension automatically. Then I copied "copy.exe" to "\Windows\copy" etc. It works well. But, it does not work for "start" directive! Start is necessary for Iexplore and other "uncloseable" applications launching to prevent interpreter hanging up. It is interesting too "start.exe" (or "start") everytime renames automatically to "Start" with upcased first letter. Probably "\Windows\Start.html" causes this system behaviour.
2. std::list iterating for multi batch lines interpreting crashes everytime, when lauchched application contains any messagebox. Iterating replacing by numerous cyclus soles it. Unbelievable...
I will publish XAP as soon as. Any filemanager can be used for batch lauching after instllation. I recommend Phone Commander, which is able not only launch, but also edit *.bat files.

Non XAP preliminary beta for testers
1. Copy included files to \Windows directory.
2. Apply registry changes by Batch.reg (can be did automatically from Phone Commander etc.).
3. Try tap to Example.bat from any filemanager (Phone Commander, WP7 Root Tools, wPhoExplorer etc.).
4. Make your own scripts (you can use also automatical shell creating function from Phone Commander menu, rename *.sh file to *.bat and edit it's content by Phone Commander "View" edit function by pencil icon).
"start" and "copy" directives only are implemented still. "copy" is implemented with source and destionation parameters only (copies everytime), switches will added in future versions.
start "filename" [params] = nonblocking shell starting
"filename" [params] (without "start") = blocking shell starting, it waits to application closing (danger for iexplore and any other "uncloseable" applications, use "start" instead). It blocks NonDDE shell directives, DDE (pword.exe, other Office applications, etc.) are nonblocking everytime by principle.
"copy" directive + *.reg files interpreter can be used for simple installator creating for your native applications.
The same principle will used for universal scheduler (for example "switch on wifi every monday morning, switch off ringing and wifi tethering every friday evening" etc.).
"SHLine" part is offered for all console application creators (it interprets one batch line). Use stdout file redirect and ShellExecuteEx(...,L"SHLine.exe",User console input line,...);

jessenic said:
Pocket CMD from CE7 ARMv7 works fine via telnet. Tested on my Samsung Omnia 7 and Jaxbot's Samsung Focus. You can see it in action in this screenshot: http://windowsphonehacker.com/articles/all_in_a_days_work-03-03-13
Click to expand...
Click to collapse
Thanks for a tip. There is working on device Telnet xap screenshot:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Xap release will published, when I solute HaRET and Pocket CMD listing switch.

XAP is released.
Download from HaRET WP7 thread.

Console Big Update - try Ping, IPConfig, NetStat, WLanUtils etc.
New Console7 version can offer to you many usable utilities, as cgacutil, etcha, ipconfig, ipconfig6, ipv6, kbdtest, msmqadm, ndisconfig, net, netlogctl, netstat, ping, rnaapp, route, services, shell, tracert, upnpreg and wlantool. With simply user interface you can write commands (or batch or Mort scripts) with big possibilities as on desktop Windows.
Console7 is not so dangerous as HaRET, but you still keep in mind that it can also destroy your operating system and possibly device ...
1. Install XAP.
2. Enable it by Root Manager.
3. Tap to Upeer screen part, tap to Menu button, slide menu left and select "Install pocketcmd shell etc."
4. Wait to reboot.
5. Wait to automatical Console7 start.
6. Type commands in bottom textbox and send it by Enter key. HELP command is available.
7. Try standard commands. Use help , help cmd commands to see full list.
8. Try additional features. Use help, for example:
ipconfig /?
Also copy, delete, etcha. ipconfig, ipconfig6, ipv6, kbdtest, launchuri, md, messagebox, msmqadm, ndisconfig, net, netlogctl, netstat, ping, reboot, regimport, rnaapp, route, services, shell, start, startback, tracert, upnpreg, wlantool directives are offered, some with help by /?.
9. Try Batch and Mort script making by PhoneCommander editor. Batch files (*.bat) are registered authomatically by Console7 installing. MortScripts installator will available as soon as.
10. When you want to risc device Hard Reset, try also "install haret and kernel driver".
11. Try HaRET/Shell switching by yellow buttons.
Remember: PocketCMD using is relatively safe (when you will not delete any system files or directories), but HaRET may be very danger still! Use both on your own risc.

Related

Open ZIP file in Silverlight

Hi,
I'm working on my first application for Windows Phone. I got a ZIP file which contains a huge amount of XML files and which has to be
updated through the app. So I declared the 'Build Action' of the file to 'Content'. Now I'm stuck opening the file for reading and extracting
a stream for a specific XML file.
I tried File.OpenRead but Visual Studio Express crashes when trying to debug this.
Do I need to use Application.GetResourceStream? If yes, can someone post a working example with a content ZIP file (not resource).
Can anyone help me?
Thank you,
toolsche
Try http://senssoft.com/ZipTest.zip
I've created that example project for Freda's developer.
Hi,
Unfortunately that doesn't help me.
1) U did set the file as "Resource" => it will not be updateable because it's within the assembly. If I'm wrong, please tell me...
2) U used an external library (SharpZipLib) which I hope it wouldn't be necessary.
1) I've used an embedded file (actually, epub == zip) to simplify the solution. It's just an example. U may copy the resource file to IsolatedStorageFile / download it from web/ whatever you want. I can't teach you how to use Silverlight for WP7 - buy some good book...
2) SharpZipLib IS NECESSARY! Other "zippers" looks like not a 100% compatible with WinZip/linux zippers (see Freda corresponding topic). SharpZipLib did the job very well.
Of course it up to you: what you want to use. But I gave you a 100% working and tested solution.
Hi,
I'm not in doubt that your solution is working and I thank you for your suggestion.
Maybe I'm on the wrong path, but what I think I need is a solution for opening
a zip file that is NOT part of the assembly (which I think it is if you declare it as
embedded resource).
My intention is to load one or more zip files from a server which the application
should be able parse/remove/replace if outdated. I tried to find a solution but had
no luck so far. MSDN has an example but I couldn't get it to work because I don't
know where the zip file should be located:
http://msdn.microsoft.com/en-us/library/cc190632(v=VS.95).aspx
Try to use IsolatedStorageFile and WebClient, something like this:
Code:
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
WebClient downloader = new WebClient();
downloader.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("myfile.zip", FileMode.Create, isf))
{
Byte[] buffer = new Byte[e.Result.Length];
e.Result.Read(buffer, 0, buffer.Length);
stream.Write(buffer, 0, buffer.Length);
}
DoSomethingWithZip("myfile.zip");
}
};
downloader.OpenReadAsync(new Uri("http://mysite.com/archive.zip", null));
Thank you for the quick answer. I will try it as soon as possible and post the results.
EDIT: Thanks, it's working as suggested.

ISETool.exe bug

Today I found very annoying and strange bug (or, may be, MS call it "feature" ). Seems like directories on isf can hold 1024 files only...
Try code below:
Code:
Random rnd = new Random();
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
byte[] data = new byte[1024];
isf.CreateDirectory("test");
for (int i=0; i<1025; i++)
{
string fileName = "test\\" + i.ToString("D4") + ".bin";
using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf))
{
rnd.NextBytes(data);
fs.Write(data, 0, data.Length);
}
}
}
After loop completed, resulting directory "test" will be empty! But change i<1024 and you'll get all yours 1024 files...
Tested on emulator and HTC Surround, same results. Can't find any documentation about this limitation... Shame on you, MS!
Update: another strange behavior ('cause of this bug) - if you already have 1024 files and try to add one more, the whole directory content is "magically" disappear But exception isn't thrown...
Interesting, I'll try it as well. This would be lame to have to work around.
Dbeattie said:
Interesting, I'll try it as well.
Click to expand...
Click to collapse
Yes, please, confirm...
I can't test this at the moment but I know I write well over 1000 files to /shared/media so I'm curious to tet this.
sensboston said:
Yes, please, confirm...
Click to expand...
Click to collapse
Hey just tried it out, wrote 2k items to a folder called "Data".
While it didn't show up in the Windows Phone Power tools, the file does exist in the folder itself.
bool success = storage.FileExists(Path.Combine("data", "1999"));
So it's either a problem with the WPConnect api or with the power tools, haven't tried the command line tool.
Yep, fortunately you are right, it's a ISETool.exe (or drivers) bug, not a WP7 ISF.
sensboston said:
Yep, fortunately you are right, it's a ISETool.exe (or drivers) bug, not a WP7 ISF.
Click to expand...
Click to collapse
Could you therefore edit the title of the thread please?
Thanks.

[HACK] Using complete Windows API in Windows Store app (c++)

As we know, MS prohibits using most of standard Win32 API in Windows Store applications. Obviously there are lots of ways to overcome this limit and to call any API you like, if you are not going to publish your app on Windows Store. And here is one of them.
Idea is really simple and rather old (lots of viruses use it): search for kernel32.dll base in memory, then parse its exports for LoadLibraryA and GetProcAddress, call them - and get profit.
Writing here so this post can be indexed by google.
Partial code:
Code:
void DoThings()
{
char *Tmp=(char*)GetTickCount64;
Tmp=(char*)((~0xFFF)&(DWORD_PTR)Tmp);
while(Tmp)
{
__try
{
if(Tmp[0]=='M' && Tmp[1]=='Z')
break;
} __except(EXCEPTION_EXECUTE_HANDLER)
{
}
Tmp-=0x1000;
}
if(Tmp==0)
return;
LoadLibraryA=(t_LLA*)PeGetProcAddressA(Tmp,"LoadLibraryA");
GetProcAddressA=(t_GPA*)PeGetProcAddressA(Tmp,"GetProcAddress");
CreateProcessA=(t_CPA*)PeGetProcAddressA(Tmp,"CreateProcessA");
HMODULE hUser=LoadLibraryA("user32.dll");
MessageBoxA=(t_MBA*)GetProcAddressA(hUser,"MessageBoxA");
MessageBoxA(0,"A native MessageBox!","Test",MB_OK);
STARTUPINFO si;
memset(&si,0,sizeof(si));
si.cb=sizeof(si);
PROCESS_INFORMATION pi;
CreateProcessA("c:\\Windows\\system32\\cmd.exe",0,0,0,FALSE,0,0,0,&si,&pi);
}
Complete project is attached. It contains sources and compiled appx files for side-loading.
Code compiles fine for x86/x64 and ARM, tested on x86/x64. Can someone test it on ARM? Ability to sideload metro apps is required.
The application should output a MessageBox, then execute cmd.exe.
A note: Windows Store application runs in a sandbox and as a limited account, so most of API returns "access denied". You can check this in a launched CMD - it displays "access denied" even on a "dir" command because normally "modern ui" apps don't have even read access to c:\.
To overcome this - add "all application packages" full control to the directories/objects you like (for example to c:\).
Works perfectly on my Windows 8 x64 Tablet :good:... its not ARM based though ...
Can i use this to run a non-store app?
Here is the catch, I have managed to get the installed (not the installation) file from a kind member here on XDA. But when I paste the folder in:
C:\Program Files\WindowsApps\Microsoft.ZuneMusic_1.0.927.0_x64__8wekyb3d8bbwe
The app isnt seen on the metro UI?
Any way to start a scanner of some sorts so that I can see the app in Metro.../?
THanx a ton!
Plz feel free to laugh a little at my noobish question...im stil learning..
Works perfectly on my surface RT!
but type dir in CMD returns "access denied".
There are no code signature checks from the command prompt that you launch.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Code:
#include <iostream>
void main()
{
std::cout << "Hello RT World!\n";
}
Compiled as an exe with info in http://stackoverflow.com/questions/...op-programs-be-built-using-visual-studio-2012
Open properties of your disk c:, go to the security tab and add "ALL APPLICATION PACKAGES" == full control. In this cage "dir" command would work, and your apps would be able to access whole filesystem.
Sorry if it's unrelated, but does RT check signatures for loaded DLLs too? Can one run regedit and change some system CLSID to point to unsigned library, will it be loaded?
Simplestas said:
Sorry if it's unrelated, but does RT check signatures for loaded DLLs too? Can one run regedit and change some system CLSID to point to unsigned library, will it be loaded?
Click to expand...
Click to collapse
Unless the dll is loading with a restricted security policy (such as through a Metro app) it is checked, yes.
Excellent work on the 'App1' technique of starting a cmd prompt from a modern app, and the fact it can run other unsigned cmd line apps.
Note that the cmd prompt still runs in the modern app container and probably has lots of restrictions
And also it only runs when the modern app is running and effectively freezes when the modern app goes into the background and suspends
Don't seem to be able to run win32 gui apps from the cmd prompt it starts -- they start but immediately terminate, presumably because the full win32 stuff cant initialise in a modern app container.
But can tum gui win32 api's, like the create dialog one, from the App1 modern app
Luckily we can also test, investigate and debug this on an intel Windows 8 system (dual monitor is best) when trying to work out what is going on, and then test on ARM after that.
@Simplestas: LoadLibrary is also blocked, I'm afraid. One fo the first things I tried was creating a DLL compatible with the built-in rundll.exe program and using that. It failed to load the third-party library.
@xsoliman3: Don't forget the debugger. You can't run it on the RT device right now, but there are (official) tools for debugging RT apps remotely. That should allow connecting to the child process and seeing what happens as it starts up.
GoodDayToDie said:
@Simplestas: LoadLibrary is also blocked, I'm afraid. One fo the first things I tried was creating a DLL compatible with the built-in rundll.exe program and using that. It failed to load the third-party library.
@xsoliman3: Don't forget the debugger. You can't run it on the RT device right now, but there are (official) tools for debugging RT apps remotely. That should allow connecting to the child process and seeing what happens as it starts up.
Click to expand...
Click to collapse
Great seeing you again!
Anyways, I determined from some work with the VS Remote Debugger that the integrity checks are enforced in ZwCreateUserProcess. But, I bet LoadLibrary has its integrity checks in user-mode, since it normally doesn't access any functions using a call-gate to the kernel on Windows 7, which would mean we can modify it to allow us to load unsigned DLL's.
However, with this vulnerability, I had a different. What about allowing a native application to open, such as Notepad, and before it reaches the entrypoint, remotely injecting a different application to be ran (this would involve some sort of custom LoadLibrary + CreateRemoteThread pair of functions)? With the VS Debugger, you can already attach to any native process in user-mode and modify running code, data, and even the context (e.g. registers and similar data).
That suggestion is possible, and for trivial operations (i.e. replacing some strings in a program, or causing it to take one branch instead of another) people have already done so. Doing a wholesale replacement would be tricky, but should be possible (perhaps aided with WinDBG scripts or similar).
GoodDayToDie said:
Doing a wholesale replacement would be tricky
Click to expand...
Click to collapse
Not so tricky, I've already made a prototype on desktop Win8. Just make an ARM DLL that implements a PE loader using only 2 WinAPI functions - LoadLibrary (used only to get kernel32 handle) and GetProcAddress. Inject that DLL code and data sections via debugger, fixup relocs (you can minimize their amount in your "loader DLL" by not using global variables, placing all code into one file, not using CRT at all, and so on, ARM makes it easy to create position-independent code), and call your injected code via debugger passing it the address of LoadLibrary and GetProcAddress as parameters. Your code than would do what you wish - load and execute an unsigned DLL that you specify.
With this trick you can load EXE files too, as all ARM EXEs contain relocs by default.
But this way is too inconvenient to the end-user, so should be avoided. I really think that MS left enough holes for us to "unlock" unsigned apps on retail WinRT devices.
I'm already thinking on buying an Asus tablet with 3G (instead of waiting for a better device that I wish), so after NY holidays I'll join your game
Ah, that's a much more clever approach than actually trying to load the full program using the debugger itself... if it works. LoadLibrary triggers the same signature check that CreateProcess does (or rather, the system calls that they do will perform that check; if it was user-mode we could bypass it with the debugger). Your method may work, but since the desktop doesn't have the signature check anyhow, prototyping it there doesn't actually mean it will work on RT. Try it out and let us know how it goes, and if it works, posting your source would be awesome!
GoodDayToDie said:
Ah, that's a much more clever approach than actually trying to load the full program using the debugger itself... if it works. LoadLibrary triggers the same signature check that CreateProcess does (or rather, the system calls that they do will perform that check; if it was user-mode we could bypass it with the debugger). Your method may work, but since the desktop doesn't have the signature check anyhow, prototyping it there doesn't actually mean it will work on RT. Try it out and let us know how it goes, and if it works, posting your source would be awesome!
Click to expand...
Click to collapse
He doesn't mean making a prototype and importing from kernel32.dll. He means manually mapping the PE file, then using either CreateRemoteThread or modifying the context of a thread already launched to run it once it's in the memory address of another process. It's basically DLL injection with our own implementation of LoadLibrary. It would work because LoadLibrary doesn't use any system calls except to map memory (and mapping memory doesn't have integrity checks of any sort, and it shouldn't be design -- e.g. VirtualAlloc).
A bigger problem I thought of is automating this. I took a quick peek with Wireshark at my remote debugging session and saw HTTP with what appeared to be a proprietary protocol. In order to automate this from another computer (or any mobile device for that matter), we would need to reverse engineer the protocol. Or, an alternative would be to hook into Visual Studio once the debugging session is launched (maybe just a nice VS plugin would work?).
mamaich said:
Code:
void DoThings()
{
char *Tmp=(char*)GetTickCount64;
Tmp=(char*)((~0xFFF)&(DWORD_PTR)Tmp);
while(Tmp)
{
__try
{
if(Tmp[0]=='M' && Tmp[1]=='Z')
break;
} __except(EXCEPTION_EXECUTE_HANDLER)
{
}
Tmp-=0x1000;
}
if(Tmp==0)
return;
Click to expand...
Click to collapse
I was looking through the provided sample -- wouldn't our own GetModuleHandleA implementation be a better way of doing this? I'm just thinking should the alignment be changed in kernel32.dll it may be better to have something like this:
Code:
522 if (!name)
523 {
524 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
525 }
526 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
527 {
528 void *dummy;
529 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
530 }
Source: http://source.winehq.org/source/dlls/kernel32/module.c#L504
Grabbing the Peb (NtCurrentTeb()->Peb) would involve pulling from the FS register at offset 0x30. Implementing this on ARM could be trickier, as I'm not sure of the inline assembly or availability of intrinsics (not to mention, it would be stored somewhere else than the FS register).
Now, for the PC, it appears __readfsdword is available as an intrinsic, so this *should* work on x86 installations of Windows 8.
mamaich said:
Not so tricky, I've already made a prototype on desktop Win8. Just make an ARM DLL that implements a PE loader using only 2 WinAPI functions - LoadLibrary (used only to get kernel32 handle) and GetProcAddress. Inject that DLL code and data sections via debu
Click to expand...
Click to collapse
I think this approach (of injecting own loader as far as understand) has such problem(even if implemented & automated)
Loaded exe can have own dependant dlls(any complicated-usefull proj has) that it cant load because of signing checks (and even more problems if it uses dynamic loading of own dlls and getprocaddress)
Or do i miss somth in your idea?
Will I be able to read/write to a parallel port using this method? Do the limited store apps have sufficient permissions to do that? Writing to a parallel port requires calling
Code:
hndleLPT = CreateFile("LPT1",(GENERIC_READ | GENERIC_WRITE), 0, 0, OPEN_EXISTING, 0, 0);
. Will this succeed?
Will I be able to successfully load this: http://www.highrez.co.uk/Downloads/InpOut32/default.htm ?
---------- Post added at 03:01 PM ---------- Previous post was at 02:11 PM ----------
This looks like an improved method to get the base address:
http://tedwvc.wordpress.com/2013/07/19/finding-the-kernel32-dll-module-handle-in-a-windows-store-app-using-approved-apis/
You should be able to do that using CreateFile2, which is permitted in Store apps already (no need to use the rest of the Win32 API). As for the permissions, I don't know, but it will probably work.
I mean, assuming your computer *has* an LPT port. I haven't seen one of those in a while...
how about the other way round? can a desktop app have access to the full windows 8 api (including those reserved for win store apps only)?

WP7 FTP+HTTP Client public library - need testers

Hi Friends.
I did some attempts to make working WP7 FTP(+HTTP) library. It may allow to endpoint applications to list, upload and download ANY files (include binaries etc.) from FTP or HTTP servers.
The simpliest way is to use web service. I have got working one, but based on closed code hacked, then it is possible for my internal use only, not for public presentation. Second problem is web services unstability.
Second way is native code, allowed by RootProject or custom ROM. First I tried MFC Internet+FTP classes. But WinInet functions are disabled or not present in WP7 core (or I do not know only, how to allowe them).
Then I have got public multiplatform source FTPClient library, based on native sockets management, and did (very small) changes in it to be usable at unlocked WP7. Library is working now. But, only simple native test application is finished and I have no free time now.
If you somebody want to participate, write here or send me PM. I will send FTP account to site, containing full source code and FTP test subsite too.
It is needed:
1. To repair SIZE command. On some servers library gets code 550 SIZE is not allowed in ASCII mode (library changes mode in download time only).
2. To make better, WM/WP consistent interface.
3. To make managed wrapper (we will do it to w.i.n.c.o's wNativeCom library and as Phone Commander plugin, but WP7DllImport wrapper is needed too).
4. To make automatical tests or to test all functions manually.
5. To refactorize all project by used code opensource licence.
Martin7Pro said:
Second way is native code, allowed by RootProject or custom ROM. First I tried MFC Internet+FTP classes. But WinInet functions are disabled or not present in WP7 core (or I do not know only, how to allowe them).
Click to expand...
Click to collapse
WININET is working and internally used by MS apps.
ultrashot said:
WININET is working and internally used by MS apps.
Click to expand...
Click to collapse
Thanks for info. I thought that it must be used. But, when I use WinInet CE6 API, I have got error "This function is not supported on this system". What I must do to use InternetConnect() etc? Thanks, M.
Martin7Pro said:
Thanks for info. I thinked it must be used. But, when I use WinInet CE6 API, I have got error "This function is not supported on this system". What I must do to use InternetConnect() etc? Thanks, M.
Click to expand...
Click to collapse
I don't know what you use and from where do you get this error - it mustn't happen if you use APIs directly.
ultrashot said:
I don't know what you use and from where do you get this error - it mustn't happen if you use APIs directly
Click to expand...
Click to collapse
Code:
HINTERNET hInternetConnect;
HINTERNET hOpen = InternetOpen (L"FTP",
INTERNET_OPEN_TYPE_PRECONFIG,
NULL, NULL, 0); /// This function works OK.
if ( !hOpen )
{
AfxMessageBox(L"Failed to open WinInet");
}
else
{
hInternetConnect =
InternetConnect(hOpen,
m_URL,
INTERNET_DEFAULT_FTP_PORT,
m_Username,
m_Password,
INTERNET_SERVICE_FTP,
INTERNET_FLAG_PASSIVE,
0); /// This function returns error.
if( hInternetConnect ){
AfxMessageBox(L"Internet Connect succeded");
/*
if(FtpGetFile(hInternetConnect, m_Filename_Remote, m_Filename_Local, 0, 0, FTP_TRANSFER_TYPE_BINARY, 0))
{
}
else{
AfxMessageBox(L"Get File Failed");
return false;
}
*/
InternetCloseHandle(hInternetConnect);
}
else
{
CString csError = ErrorString(GetLastError());
TRACE(csError);
AfxMessageBox(csError);
return false;
}
InternetCloseHandle(hOpen);
}
returns:
This function is not supported on this system. Error code : 78
And another, bigger problem:
When I uncomment FtpGetFile part, application is compiled and deployed OK. But after starting it does nothing, it does not want to start totally. I do not understand, how can the unused portion of the code affect the behavior of the application starts.
Socket library does not do anything similar.
Microsoft!!!
http://support.microsoft.com/kb/2735592
But patch is developed for ARM >=5 only and licensed to PB customers.
Finished - test binaries
Hi friends. There are binaries for testing. Predefined values download nice picture from our Czech glamour atelier to your "Storage card" device directory, but you can try much other servers, directories and accounts. All directory contents may be downloaded to your :Storage card" directory, no selecting is possible in example. I mean there will problems after firewalls etc., post your feedback. WinInet really does not work on WP7 for FTP servers, there is used little changed class from D. J. Bernstein and codeproject. If anybody know, how to export STL templates from dll, help me. Use "Exit" button for appclosing instead WP7 usual "Esc".
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Edit: There is actual version (without licencing conflict probably).
Managed wrapper will be added later (by wNativeCom probably). XAP istallable example for non-developers in deeper future.
Code is totally thread unsafe, after validation I will use http://forum.xda-developers.com/showthread.php?t=2208647 for it.
You can try unfinished Silverlight version:
http://wp7ftp.howto.cz/XDA/FTPClientExample.xap ... will be updated. EDIT: Xap 1.1 version is available from April 5th.
http://wp7ftp.howto.cz/XDA/FtpClientLibrary.dll ... this native library is needed in your device "\Windows\" directory (download and transport it to place). EDIT: If it not works on any device, try to delete \Windows\FtpClientLibrary.dll and install xap 1.1 version only.
Preliminary results:
1. Native FTP library works well.
2. Managed/Native callbacks synchronisation works well. (Thanks to MS idiots I must code all desktop like functionality again). There is a most important part for mechanism studying.
3. Silwerlight for WP7 is the most stupid and bugged Microsoft feature.
Simple app description:
Type Host, User, Pass and Remote (dir) values. You can stay predefined for testing. Tap to "Connect". You can see result in scrollable block on the bottom. If unsuccess, check your internet connection and typed strings, try again. If success, tap to second empty line under "Remote" (thanks to normal multiselectbox WP7 absention). Check wanted file names and tap do bottom cross (is it normal in ListPicker to have two crosses???). Tap to "Download". It is all. You can tap to "Disc.", change remote path or server values and tap to "Connect" again. First empty line under "Remote" contains remote directories list, but I am too busy to finish any logical directory tracing with bugged and unlogical Silverlight Toolkit features.
Known bug: Edit: Solved in 1.1 version. If deadlock occures still (unavailable FTP response), app restart (or phone reboot) helps you. Do you know anybody, if SL TextBox has limited capacity and how to bind string list to ListPicker?
Attention: "Connect" again after successfull previous connect and without disconnect = possible memory leaking!
Note: It is FTP. Must wait for all directives any seconds. If unsuccess, try the same again. This is normal FTP beahiour by mobile connection.
If anybody want, libraries are opensource and you can download them from the same FTP, which is used as predefined example values, or equal http http://wp7ftp.howto.cz/XDA/. You all have full FTP access, do not change anything important, upload relevant patches only! Managed part (Visual Studio 2010 for WP) is usable along by FTPClientUIDebugManagedWrappers.sln solution. I want to add FTP as plugin to Phone Commander only, I mean two-pane UI is the best solution of the FTP client. But, standalone FTP client can be usable too, when somebody Silverlight experienced will repair listControls behaviour there (all n/m callbacks are prepared, UI finishing is necessary only). Download only is finished in native library, upload will repaired in next versions.
Version 1.3
Uploaded FTPClient v 1.3 (the newest version is allways on http://wp7ftp.howto.cz/XDA/FTPClientExample.xap) solves ListPicker issues. Instead Remote Directories ListPicker is used totally wrong, but functioning global strings listbox, I am too busy to solve SL toolkit bugs now.
Known bug: Native library losts connection sometime and does not inform main application about it. You will see empty directories list from non-empty directories in this case. Application (or sometime device) reset helps you.
Known restriction: Server must be typed by name alias, not by IP address. I do not know why still, it will probably repaired in future versions.
Version 1.4
V 1.4:
Repaired file unselect after directory changing.
Showed "./././.." instead ".." as "Up" directory for better tapping.
Response TextBox content is rounded to 1000 characters. Is it a known TextBox bug to show any first characters only?

Intermediate: How to Integrate Location Kit into Hotel booking application

Introduction
This article is based on Multiple HMS services application. I have created Hotel Booking application using HMS Kits. We need mobile app for reservation hotels when we are traveling from one place to another place.
In this article, I am going to implement HMS Location Kit & Shared Preferences.
View attachment 5230279
Flutter setup
Refer this URL to setup Flutter.
Software Requirements
1. Android Studio 3.X
2. JDK 1.8 and later
3. SDK Platform 19 and later
4. Gradle 4.6 and later
Steps to integrate service
1. We need to register as a developer account in AppGallery Connect.
2. Create an app by referring to Creating a Project and Creating an App in the Project
3. Set the data storage location based on current location.
4. Enabling Required Services: Location Kit.
5. Generating a Signing Certificate Fingerprint.
6. Configuring the Signing Certificate Fingerprint.
7. Get your agconnect-services.json file to the app root directory.
Important: While adding app, the package name you enter should be the same as your Flutter project’s package name.
Note: Before you download agconnect-services.json file, make sure the required kits are enabled.
Development Process
Create Application in Android Studio.
1. Create Flutter project.
2. App level gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Add the below permissions in Android Manifest file.
Code:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />
<application ...
</manifest>
3. Refer below URL for cross-platform plugins. Download required plugins.
https://developer.huawei.com/consum...y-V1/flutter-sdk-download-0000001050304074-V1
4. After completing all the steps above, you need to add the required kits’ Flutter plugins as dependencies to pubspec.yaml file. You can find all the plugins in pub.dev with the latest versions.
Code:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^0.5.12+4
bottom_navy_bar: ^5.6.0
cupertino_icons: ^1.0.0
provider: ^4.3.3
huawei_location:
path: ../huawei_location/
flutter:
uses-material-design: true
assets:
- assets/images/
5. After adding them, run flutter pub get command. Now all the plugins are ready to use.
6. Open main.dart file to create UI and business logics.
Location kit
HUAWEI Location Kit assists developers in enabling their apps to get quick and accurate user locations and expand global positioning capabilities using GPS, Wi-Fi, and base station locations.
Fused location: Provides a set of simple and easy-to-use APIs for you to quickly obtain the device location based on the GPS, Wi-Fi, and base station location data.
Activity identification: Identifies user motion status through the acceleration sensor, cellular network information, and magnetometer, helping you adjust your app based on user behaviour.
Geofence: Allows you to set an interested area through an API so that your app can receive a notification when a specified action (such as leaving, entering, or lingering in the area) occurs.
Integration
Permissions
First of all we need permissions to access location and physical data.
Create a PermissionHandler instance,add initState() for initialize.
Code:
final PermissionHandler permissionHandler;
@override
void initState() {
permissionHandler = PermissionHandler(); super.initState();
}
Check Permissions
We need to check device has permission or not using hasLocationPermission() method.
Code:
void hasPermission() async {
try {
final bool status = await permissionHandler.hasLocationPermission();
if(status == true){
showToast("Has permission: $status");
}else{
requestPermission();
}
} on PlatformException catch (e) {
showToast(e.toString());
}
}
If device don’t have permission,then request for Permission to use requestLocationPermission() method.
Code:
void requestPermission() async {
try {
final bool status = await permissionHandler.requestLocationPermission();
showToast("Is permission granted");
} on PlatformException catch (e) {
showToast(e.toString());
}
}
Fused Location
Create FusedLocationPrvoiderClient instance using the init() method and use the instance to call location APIs.
Code:
final FusedLocationProviderClient locationService
@override
void initState() {
locationService = FusedLocationProviderClient(); super.initState();
}
getLastLocation()
Code:
void getLastLocation() async {
try {
Location location = await locationService.getLastLocation();
setState(() {
lastlocation = location.toString();
print("print: " + lastlocation);
});
} catch (e) {
setState(() {
print("error: " + e.toString());
});
}
}
getLastLocationWithAddress()
Create LocationRequest instance and set required parameters.
Code:
final LocationRequest locationRequest;
locationRequest = LocationRequest()
..needAddress = true
..interval = 5000;
void _getLastLocationWithAddress() async {
try {
HWLocation location =
await locationService.getLastLocationWithAddress(locationRequest);
setState(() {
String street = location.street;
String city = location.city;
String countryname = location.countryName;
currentAddress = '$street' + ',' + '$city' + ' , ' + '$countryname';
print("res: $location");
});
showToast(currentAddress);
} on PlatformException catch (e) {
showToast(e.toString());
}
}
Location Update using Call back
Create LocationCallback instance and create callback functions in initstate().
Code:
LocationCallback locationCallback;
@override
void initState() {
locationCallback = LocationCallback(
onLocationResult: _onCallbackResult,
onLocationAvailability: _onCallbackResult,
);
super.initState();
}
void requestLocationUpdatesCallback() async {
if (_callbackId == null) {
try {
final int callbackId = await locationService.requestLocationUpdatesExCb(
locationRequest, locationCallback);
_callbackId = callbackId;
} on PlatformException catch (e) {
showToast(e.toString());
}
} else {
showToast("Already requested location updates.");
}
}
void onCallbackResult(result) {
print(result.toString());
showToast(result.toString());
}
I have created Helper class to store user login information in locally using shared Preferences class.
Code:
class StorageUtil {
static StorageUtil _storageUtil;
static SharedPreferences _preferences;
static Future<StorageUtil> getInstance() async {
if (_storageUtil == null) {
var secureStorage = StorageUtil._();
await secureStorage._init();
_storageUtil = secureStorage;
}
return _storageUtil;
}
StorageUtil._();
Future _init() async {
_preferences = await SharedPreferences.getInstance();
}
// get string
static String getString(String key) {
if (_preferences == null) return null;
String result = _preferences.getString(key) ?? null;
print('result,$result');
return result;
}
// put string
static Future<void> putString(String key, String value) {
if (_preferences == null) return null;
print('result $value');
return _preferences.setString(key, value);
}
}
Result
View attachment 5230281
Tips & Tricks
1. Download latest HMS Flutter plugin.
2. To work with mock location we need to add permissions in Manifest.XML.
3. Whenever you updated plugins, click on pug get.
Conclusion
We implemented simple hotel booking application using Location kit in this article. We have learned how to get Lastlocation, getLocationWithAddress and how to use callback method, in flutter how to store data into Shared Preferences in applications.
Thank you for reading and if you have enjoyed this article, I would suggest you to implement this and provide your experience.
Reference
Location Kit URL
Shared Preferences URL
Read full article
@XDARoni
Spoiler: I guess I'm missing the question part?
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}

Categories

Resources