Access is denied 0x80070005 in ASP.net using SQL Server SMO - asp.net

I am trying to create a simple web form which will give me a service restart button onscreen.
Upon clicking the button, I am creating an SMO object to talk to a SQL Server database and trying to stop and start the MSSQLSERVER service. All goes well until the Stop() method is called, at which point an exception is thrown stating:
Access is denied. (Exception from HRESULT: 0x80070005
(E_ACCESSDENIED))
The code under the button is as follows:
// connect the to server
ManagedComputer computer =
new ManagedComputer("172.16.150.52",#"Administrator","secret");
// return if there is a problem
if (computer.Services["MSSQLSERVER"] == null)
{
PageErrorMessage = "Bad or missing service \"MSSQLSERVER\"";
return;
}
// get the SQL Server Service
Service sqlServer = computer.Services["MSSQLSERVER"];
// is the server running?
if (sqlServer.ServiceState == ServiceState.Running)
sqlServer.Stop();
// wait for it to stop completely
int timeout = 0;
while (sqlServer.ServiceState != ServiceState.Stopped || timeout <= 60)
{
Thread.Sleep(1000);
sqlServer.Refresh();
timeout++;
}
if (timeout > 60)
{
PageErrorMessage = "Stop operation has timed out after 60secs";
return;
}
// start it again!
sqlServer.Start();
The IP address, username & password are 100% correct. Does anyone know why this would throw an AccessDenied exception?

It sounds like you're missing the UAC. Often, to do system-wide tasks such as rebooting, shutting down (and probably also starting/stopping services), you have to get the elevated priviliges, which includes obtaining a token, etc.
Take a look at this article - http://www.codeproject.com/KB/vista-security/UAC__The_Definitive_Guide.aspx - it has helped me on a few occasions.
But http://www.codeproject.com/KB/vista-security/ElevatedPrivilegesDemand.aspx might also be helpful.
I have only ever done this client side myself - I don't know how it works when running on a server. For that, you might want to take a look at: http://blogs.msdn.com/b/lightswitch/archive/2011/04/07/how-to-elevate-permissions-in-server-code-ravi-eda.aspx
And if it's not code, but configuration, take a look at this: http://www.lansweeper.com/kb/WMI-Access-is-denied.aspx

Related

CMIS connection issue

cannot tell if this issue is the same as some others posted. ours simply throws a msg, but it appears CMIS connection related - our application uses CMIS/Alfresco. i am not very familiar, but we have a server related to it. not sure if a power outage is related to the fact that we this error[pwr outage yesterday, then mysteriously this error was later noticed]. we normally post information on the web page that is populated by our sql data[a table field populates a textarea/text editor] - instead we get the error above: "CMIS connection issue". that verbiage comes from a file that instantiates connection with CMIS, here is the related code:
//Check cmis service connect or not
try{
$client = new CMISService($repo_url, $repo_username, $repo_password);
}catch (Exception $ec) {
echo "CMIS connection issue";
echo "<br >\n" ;
echo $ec->getMessage() ;
die;
}
the CMISService parms have not changed, and they appear to be proper values. i even tried "admin", and "root" as "repo_username" in addition to the defined username.
Ideas on what we can check?

"Token has expired or is not yet valid" for token from FirebaseUser.getToken(true)

We experience problems with authentication when on Android:
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
Task<GetTokenResult> tokenTask = firebaseUser.getToken(true)
.addOnCompleteListener(TaskExecutors.MAIN_THREAD, null);
try {
token = Tasks.await(tokenTask).getToken();
} catch (Throwable e) { }
and on Java server:
Task<FirebaseToken> authTask = FirebaseAuth.getInstance().verifyIdToken(principal.getClientToken());
try {
Tasks.await(authTask);
} catch(ExecutionException | InterruptedException e ) { }
if (authTask.isSuccessful()) {
firebaseToken = authTask.getResult();
} else {
log.error(authTask.getException().getMessage());
}
The problem is that we got in log (that corresponds to above logging statement):
Token has expired or is not yet valid
We also dump device number and resulted token and can use it successfully afterwards with requests on server so Java server validate this token...
What is meaning of is not yet valid? Do we need to wait some time before token become valid?
Because of firebaseUser.getToken(true) on Android we can't authenticate mobile client.
We change this to firebaseUser.getToken(false). This call return same token between calls for a long period of time and after some delay (near 40 sec) from first attempt token is validated by server. So after several attempts mobile application is able to authenticate.
The time necessary to wait for token to become valid within a minute and this can be issue with time mismatching on Google servers...
On Android we work with:
compile 'com.google.firebase:firebase-core:9.2.0'
compile 'com.google.firebase:firebase-messaging:9.2.0'
compile 'com.google.firebase:firebase-auth:9.2.0'
on server we work with:
compile 'com.google.firebase:firebase-server-sdk:3.0.1'
After debugging issue further we found that local authentication server depends on hardware time.
Our hosting virtual server late on 7 min from current time.
Fixing VM hardware time settings is resolved our problem.
It is not wise for Google to depend on malformed local server time. At least on broken VM time is consistent, they most probably compare time with other parties so we resulted in error.

Cannot open window service error with admin permission set in "app.manifest"

I'm trying to start an installed Windows Service inside my ASP .NET MVC application. Even with <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
in my app.manifest file, I keep running into cannot open window service <Service Name> on computer '.'
HomeController.cs
ServiceController sc = new ServiceController();
sc.ServiceName = "TestWindowsService";
//I can see Service status correctly stored in sc.Status
Debug.WriteLine(sc.ServiceName+ " service status is {0}",
sc.Status.ToString());
if (sc.Status == ServiceControllerStatus.Stopped)
{
// Start the service if the current status is stopped.
Debug.WriteLine("Starting the " + sc.ServiceName +" service...");
try
{
// Start the service, and wait until its status is "Running".
sc.Start(); //Error here
}
catch (InvalidOperationException)
{
Debug.WriteLine("Could not start the " +sc.ServiceName +" service.");
throw;
}
}
If you host ASP.NET Website on IIS, then it's privileges are determined by the application pools identity, it's running on. I've never heard of app.manifest for websites. May be i'm wrong, but try to run website in an Application Pool with enough permissions to start a WindowsService, or Debug as different user, if you're using a test webserver.

Directory.CreateDirectory failed on Remote Server

I am working on a small project, in asp.net mvc3, that would copy the deployment files from a local drive to a share drive on a window server 2008 R2 server. I am connected using WMI, and the connection is successful. However, I tried to create a folder, and I receive the message "Logon failure: unknown user name or bad password." Here is a sample code:
bool isConnected = false;
options.Username = user.Name.Trim();
options.Password = user.password.Trim();
mScope = new ManagementScope("\\\\xxx.xxx.xxx.xxx\\root\\cimv2", options);
mScope.Connect();
if (mScope.IsConnected == true)
{
//I've gotten to this point. Then, the code below throw the exception
Directory.CreateDirectory(#"\\\\xxx.xxx.xxx.xxx\Tester\shareFile.txt");
isConnected = true;
}
I'd like to know what am I doing? Is that the right way of doing it?
it is the correct way however it will be the current user you are trying to access that gets passed to the remote computer to create the directory. The management scope at this point has nothing to do with Directory.CreateDirectory. These are 2 different "worlds". you do give the creds to ManagementScope but this has no affect on Directory.CreateDirectory. you could use impersonation to do what you are wanting to:
How do you do Impersonation in .NET?
it is unclear though if you are doing this in ASP.NET/MVC or a different platform. your tags indicate ASP.NET MVC but not your main question.
remember, if you are using ASP.NET/MVC, the credentials of the app pool are being used to perform such actions.

Active directory - exception has been thrown by the target of an invocation

I have a web application in a separate server than Active Directory and I want to change a user password. The code is the next:
string newPassword = Membership.GeneratePassword(int.Parse(WebConfigurationManager.AppSettings["passLenght"]),
int.Parse(WebConfigurationManager.AppSettings["passNonAlpha"]));
DirectoryEntry de = new DirectoryEntry(WebConfigurationManager.ConnectionStrings["ADConnString"].ConnectionString,
WebConfigurationManager.AppSettings["ADAdmin"], WebConfigurationManager.AppSettings["ADAdminPass"]);
DirectorySearcher deSearch = new DirectorySearcher(de);
deSearch.Filter = "(&(objectClass=user) (userPrincipalName=" + name + "))";
SearchResultCollection results = deSearch.FindAll();
if (results.Count == 1)
{
foreach (SearchResult OneSearchResult in results)
{
DirectoryEntry AlterUser = OneSearchResult.GetDirectoryEntry();
AlterUser.AuthenticationType = AuthenticationTypes.Secure;
AlterUser.Invoke("SetPassword", newPassword);
AlterUser.CommitChanges();
AlterUser.Close();
}
}
When I run this in my development environment (where Active Directory and the web application are on the same server) it is working. But when I try to run it in the production environment I am having the next error:
Exception has been thrown by the target of an invocation
What am I missing?
Thanks.
EDIT:
I could go deep in the exception error and I get this:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Permissions are the issue. The account under which your ASP.NET code is running doesn't have the permission to set the account password.
Either:
Run the AppPool under a user that has the required permissions, or
Use impersonation to elevate the permissions for the SetPassword call
The reason it is working in your dev environment/failing in production is likely due to a combination of:
You are running the app under the Visual Studio development web server that runs under your user account, which has the necessary permissions. Running it under "real" IIS will run it under a less privileged account.
In the live environment there's another machine hop from the web server to the AD server, and the credentials don't get passed along. The web server needs to have network credentials (either as part of the AppPool identity, or a call to LogonUser) in order to authenticate to AD.
The code looks correct. This could be happening because the password your sending though Active Directory does not meet the minimum requirements. Trying using a more complex password such as "M2k3ThisWork!"
If you want to change the password of AD then you use this
AlterUser.Invoke("ChangePassword", OldPassword, newPassword);

Resources