Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED)) in INetFwServices using NET_FW_SERVICE_REMOTE_DESKTOP type - interop

I am trying to iterate within INetFwServices elements in Windows 10. However when I access to item Service Name: "Remote Desktop" Type: NET_FW_SERVICE_REMOTE_DESKTOP the application throws an exception Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED)).
The firewall.LocalPolicy.CurrentProfile.Services collection returns 3 items:
1. File and Printer Sharing
2. Network Discovery
3. Remote Desktop
When I read the third item "Remote Desktop" to get its GloballyOpenPorts occurred the error.
In Windows 7 this type NET_FW_SERVICE_REMOTE_DESKTOP works correctly but in Windows 10 fails. How can I read the GloballyOpenPorts of Service Name: "Remote Desktop" in Windows 10?
progID = Type.GetTypeFromProgID("HNetCfg.FwMgr");
firewall = Activator.CreateInstance(progID) as INetFwMgr;
ports = firewall.LocalPolicy.CurrentProfile.GloballyOpenPorts;
Debug.WriteLine("Count Services: " + firewall.LocalPolicy.CurrentProfile.Services.Count);
foreach (INetFwService service in firewall.LocalPolicy.CurrentProfile.Services)
{
Debug.WriteLine("Service: " + service.Name);
var port = service.GloballyOpenPorts;
}
StackTrace: at NetFwTypeLib.INetFwService.get_GloballyOpenPorts()
at FirewallCustomTest.Firewall.isPortFound(Int32 portNumber) in c:\Users\Smartmatic\Documents\Visual Studio 2012\Projects\FirewallCustomTest\FirewallCustomTest\Firewall.cs:line 178

Related

How to use backup semantics (seBackup privilege) over the network?

I am trying to enumerate a directory on a remote file server.
I want to use backup-semantics in order to not require administrator credentials.
On the test server, I have created a share:
Share permissions: everyone full control
NTFS permissions: only SYSTEM (I removed all others)
I am currently using this code:
static void accessWithBackupSemantics() {
NetResource netResource = new NetResource() {
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplayType.Share,
Usage = ResourceUsage.Connectable,
RemoteName = #"\\target-srv\TargetShare"
};
// open "net use" connection
int netResult = Native.WNetAddConnection2(netResource,
#"***password***",
#"DOMAIN\backup_op_user",
0);
if (netResult == 0 || netResult == 1219) {
// enable privileges
// (this is taken from AplhaFS)
using (new PrivilegeEnabler(Privilege.Backup)) {
try {
// try open remote directory
SafeFileHandle fsHandle = Native.CreateFile(
#"\\target-srv\TargetShare",
EFileAccess.GenericRead,
EFileShare.Read | EFileShare.Write,
IntPtr.Zero,
ECreationDisposition.OpenExisting,
EFileAttributes.BackupSemantics,
IntPtr.Zero);
Console.WriteLine("Handle is valid: " + !fsHandle.IsInvalid);
}
catch (Exception ex) {}
finally {
Native.WNetCancelConnection2(netResource.RemoteName, 0, true);
}
}
}
}
PrivilegeEnabler class is taken from AlphaFS
Native win32 structures and flags are taken from pinvoke.net/kernel32.createfile
This works if I specify "DOMAIN\Administrator" in the username, but does not work (the error is 5 - access denied) if I try to use a domain account that is a member of the local "Backup Operators" on target-srv server.
I have also examined the security event log on target-srv, for every connection created with WNetAddConnection2 a "Special Logon" event is written. The details of this event include the list of privileges that the logon account was given.
In both cases (when I connect with administrator or with backup_op_user) - seBackupPrivilege is indeed listed.
I tried to give extra privileges to the "Backup Operators" so the list has all the privileges that the Administrator has - but it made no change.
Questions:
What is the right way to use Backup-Semantics over the network?
How come it works with Administrator and not with a member of "Backup Operators" - are there additional implicit permissions for the Admin?
I have seen many examples of local use of Backup-Semantics, but not one that can be used over the network - please don't reply with links to examples of local usage.

Trying to make a search bar to a data grid view and getting a SQLException

I'm trying to create a form with a data grid view, a combo box with columns, and a text box search bar. I've found lots of YouTube videos on line (https://www.youtube.com/watch?v=KaQs1K63Q-o&list=PL4Io1EUy0d2zUOyEiVt-GwI6WzqdEgVbZ&index=15) and I keep getting an exception error. I've tried to look on the manuals, stack overflow forums, videos, and other sources for days and still coming up dry. I am very new to C# and programming SQL to C# so I think its something simple that I'm just not seeing. When I look closer in the exception detail it says that there is an error being returned by SQL Server. I've tried hitting it at all angles but nothing gets fixed.
SqlConnection con = new SqlConnection("Data Source = LAPTOP - 2H9706D7\\THIBEAUX; Initial Catalog = MetroTest; Integrated Security = True");
This is the connection but this part is "2H97067\THIBEAUX; I put an extra "\" to get rid of the escape sequence error.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (comboBox1.Text == "ID")
{
SqlDataAdapter sda = new SqlDataAdapter("Select * from [Program Tools] where ID like '%" + textBox1.Text + "%'", con);
DataTable data = new DataTable();
sda.Fill(data);//right here the exception is being thrown
ToolDataGrid.DataSource = data;
}
}
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
can anyone help me out with this?
And yes I know I shouldn't have put spaces between my Tables names I'm working on renaming them later.

InitiateShutdown fails with RPC_S_SERVER_UNAVAILABLE error for a remote computer

I'm trying to implement rebooting of a remote computer with InitiateShutdown API using the following code, but it fails with RPC_S_SERVER_UNAVAILABLE or 1722 error code:
//Process is running as administrator
//Select a remote machine to reboot:
//INFO: Tried it with and w/o two opening slashes.
LPCTSTR pServerName = L"192.168.42.105";
//Or use 127.0.0.1 if you don't have access to another machine on your network.
//This will attempt to reboot your local machine.
//In that case make sure to call shutdown /a /m \\127.0.0.1 to cancel it.
if(AdjustPrivilege(NULL, L"SeShutdownPrivilege", TRUE) &&
AdjustPrivilege(pServerName, L"SeRemoteShutdownPrivilege", TRUE))
{
int nErrorCode = ::InitiateShutdown(pServerName, NULL, 30,
SHUTDOWN_INSTALL_UPDATES | SHUTDOWN_RESTART, 0);
//Receive nErrorCode == 1722, or RPC_S_SERVER_UNAVAILABLE
}
BOOL AdjustPrivilege(LPCTSTR pStrMachine, LPCTSTR pPrivilegeName, BOOL bEnable)
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
BOOL bRes = FALSE;
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
return FALSE;
if(LookupPrivilegeValue(pStrMachine, pPrivilegeName, &tkp.Privileges[0].Luid))
{
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : SE_PRIVILEGE_REMOVED;
bRes = AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
int nOSError = GetLastError();
if(bRes)
{
if(nOSError != ERROR_SUCCESS)
bRes = FALSE;
}
}
CloseHandle(hToken);
return bRes;
}
So to prepare for this code to run I do the following on this computer, which is Windows 7 Pro (as I would do for the Microsoft's shutdown tool):
Run the following "as administrator" to allow SMB access to the logged in user D1 on the 192.168.42.105 computer (per this answer):
NET USE \\192.168.42.105\IPC$ 1234 /USER:D1
Run the process with my code above "as administrator".
And then do the following on remote computer, or 192.168.42.105, that has Windows 7 Pro (per answer here with most upvotes):
Control Panel, Network and Sharing Center, Change Advanced Sharing settings
"Private" enable "Turn on File and Printer sharing"
Set the following key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
LocalAccountTokenFilterPolicy=dword:1
RUN secpol.msc, then go to Local Security Policy, Security Settings, Local Policies, User Rights Assignment. Add "Everyone" to "Force shutdown from a remote system". (Just remember to remove it after you're done testing!)
Note that the following shutdown command seems to work just fine to reboot the remote computer:
shutdown /r /m \\192.168.42.105 /t 30
What am I missing with my code?
EDIT:
OK. I will admit that I was merely interested in why InitiateShutdown doesn't seem to "want" to work with a remote server connection, while InitiateSystemShutdownEx or InitiateSystemShutdown had no issues at all. (Unfortunately the latter two did not have the dwShutdownFlags parameter, which I needed to pass the SHUTDOWN_INSTALL_UPDATES flag to, which caused my persistence...)
At this point I had no other way of finding out than dusting out a copy of WinDbg... I'm still trying to dig into it, but so far this is what I found...
(A) It turns out that InitiateSystemShutdownEx internally uses a totally different RPC call. W/o too many details, it initiates RPC binding with RpcStringBindingComposeW using the following parameters:
ObjUuid = NULL
ProtSeq = ncacn_np
NetworkAddr = \\192.168.42.105
EndPoint = \\PIPE\\InitShutdown
Options = NULL
or the following binding string:
ncacn_np:\\\\192.168.42.105[\\PIPE\\InitShutdown]
(B) While InitiateShutdown on the other hand uses the following binding parameters:
ObjUuid = 765294ba-60bc-48b8-92e9-89fd77769d91
ProtSeq = ncacn_ip_tcp
NetworkAddr = 192.168.42.105
EndPoint = NULL
Options = NULL
which it later translates into the following binding string:
ncacn_np:\\\\192.168.42.105[\\PIPE\\lsarpc]
that it uses to obtain the RPC handle that it passes to WsdrInitiateShutdown (that seems to have its own specification):
So as you see, the InitiateShutdown call is technically treated as Unknown RPC service (for the UUID {765294ba-60bc-48b8-92e9-89fd77769d91}), which later causes a whole bunch of credential checks between the server and the client:
which, honestly, I'm not sure I want to step into with a low-level debugger :)
At this stage I will say that I am not very well versed on "Local Security Authority" interface (or the \PIPE\lsarpc named pipe configuration.) So if anyone knows what configuration is missing on the server side to allow this RPC call to go through, I would appreciate if you could post your take on it?

Open a windows phone 7 application In Emulator using Command Line

Is there a way to open a Windows Phone 7 Application in emulator using command line?
I know that there already exists a question related to this here, but I want a simple way to start a wp7 application (having the xap file) from command line without modify the code of the application.
I know that this is possible for XNA applications (info here) but I do not know if this is possible for apps made under Silverlight framework?!
Later edit - problem RESOLVED
Looking deeply, the Justin blog seemed to be very ok for this problem I've had.
Anyway I had to make some small changes:
changed the line:
Platform WP7SDK = dsmgrObj.GetPlatforms().Single(p => p.Name == "New Windows Mobile 7 SDK");
into line:
Platform WP7SDK = dsmgrObj.GetPlatforms().Single(p => p.Name == "Windows Phone 7");
I used a foreach for retrieving the platform names:
// iterate over all platforms and write their names
foreach (Platform p in dsmgrObj.GetPlatforms().ToList<Platform>())
{
Console.WriteLine("Platform: " + p.Name);
}
and the line:
WP7Device = WP7SDK.GetDevices().Single(d => d.Name == "Windows Phone 7 Emulator");
into line:
WP7Device = WP7SDK.GetDevices().Single(d => d.Name == "Windows Phone Emulator");
Used again a foreach :
// iterate over all devces and write their names
foreach (Device d in WP7SDK.GetDevices().ToList<Device>())
{
Console.WriteLine("Device: " + d.Name);
}
As mentioned you should follow Justin Angel's blog post. The end result is a very simple command line application which you run to, amongst other things, install your XAP file to the emulator/phone and start this application.
There is one thing I would modify though. Justin's app uninstalls the previous version of your application before installing the new one. This removes all files in isolated storage, including the IsolatedStorageSettings resource. I made the following changes to update the the phone application if it already exists.
// ... code to get command line parameters, device instance etc ...
if (WP7Device.IsApplicationInstalled(appID)) {
Console.WriteLine("Found {0} XAP on Windows Phone 7 Emulator/Device...", appName);
app = WP7Device.GetApplication(appID);
app.TerminateRunningInstances();
app.UpdateApplication("NormalApp",
appLocation + #"\ApplicationIcon.png",
appLocation + #"\Bin\" + configuration + #"\" + appName + #".xap");
Console.WriteLine("{0} XAP Updated from Windows Phone 7 Emulator/Device...", appName);
} else {
// Install XAP
Console.WriteLine("Installing {0} XAP to Windows Phone 7 Emulator/Device...", appName);
app = WP7Device.InstallApplication(appID,
appID,
"NormalApp",
appLocation + #"\ApplicationIcon.png",
appLocation + #"\Bin\" + configuration + #"\" + appName + #".xap");
Console.WriteLine("{0} XAP installed to Windows Phone 7 Emulator...", appName);
}
// Launch Application
Console.WriteLine("Launching {0} on Windows Phone 7 Emulator...", appName);
app.Launch();
Console.WriteLine("Launched {0} on Windows Phone 7 Emulator...", appName);
Cheers,
Alasdair

Recycling IIS application pool using PowerShell: "Exception calling Recycle"

It looks like a recent windows update has broken some functionality I was using to recycle IIS6 application pools, as this has been working for months up to today.
Exception calling "Recycle" : "Win32: The object identifier does not representException calling "Recycle" : "Win32: The object identifier does not represent a valid object.
the function I was using to recycle the application pools was:
function recycle-pool($strServerName)
{
$objWMI = [WmiSearcher] "Select * From IIsApplicationPool"
$objWMI.Scope.Path = "\\" + $strServerName + "\root\microsoftiisv2"
$objWMI.Scope.Options.Authentication = 6
$pools = $objWMI.Get()
foreach ($pool in $pools)
{
$pool.recycle()
if (!$?)
{
Write-Host $pool.name " - ERROR"
}
else
{
Write-Host $pool.name " - Recycled"
}
}
Any idea on what the problem is and how I should approach this?
The original question was for IIS6, but I ran into something similar using the WebAdministration Module's Restart-WebAppPool on Windows 2012. So I dropped back to calling AppCMD, and that worked fine:
& $env:windir\system32\inetsrv\appcmd recycle apppool "YOURAPPPOOLNAMEHERE"
Sometimes, you don't have to over-engineer the solution. Hope that helps others some day.
One of the application pools was stopped, which was causing the error. The other application pools were recycling fine. The code above is ok to use for anyone else.
You can try to recycle with ADSI:
$server = "IIsServerName"
$iis = [adsi]"IIS://$server/W3SVC/AppPools"
$iis.psbase.children | foreach {
$pool = [adsi]($_.psbase.path)
$pool.psbase.invoke("recycle")
}

Resources