Directory.CreateDirectory failed on Remote Server - asp.net

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.

Related

Authentication Issue when accesing Reporting Service

Well, I already tried a lot of stuff to solve this issue, but none did.
I developed a Reporting Service (2005) and deployed it.
This report will be used by everyone who access a website (it's a internet site, so, won't be accessed by intranet) developed on the framework 3.5 (but I think the framework's version is not the source of the problem).
When the user clicks on the button to download the .pdf which the Reporting automatically generates (the end-user never sees the html version of the Report), it asks for windows credentials.
If the user enters a valid credential (and this credential must be a valid credential on the server which the Reporting Service is deployed), the .pdf is obviously downloaded.
But this can't happen. The end-user must download the .pdf directly, without asking for credentials. Afterall, he doesn't even have the credentials.
Response.Redirect("http://MyServer/ReportServer/Pages/ReportViewer.aspx?%2fReportLuiza%2fReportContract&rs:Format=PDF&NMB_CONTRACT=" + txtNmbContractReport.Text);
The code snippet above, shows the first version of my code when the user clicks the button. This one propmts for the Windows credentials.
I already tried to change on IIS the Authentication of the virtual directory ReportServer, but the only one which works is the Windows Credentials. The other ones doesn't even let me open the virtual directory of the Report or the Report Manager's virtual directory.
When I tried to change it to Anonymous Authentication he couldn't access the DataBase. Then I choose the option to Credentials stored securely on the report server. Still doesn't work.
The physical directory of my ReportServer virtual directory points to the reporting server folder on the Hard Disk (C:\Program Files\Microsoft SQL Server\MSSQL.5\Reporting Services\ReportServer). I moved the same folder to my wwwroot directory.
Didn't work. The virtual directory didn't even open. Then I read this could be a problem because I had the same name on two folders (one in C: and other in wwwroot). So I changed the name of the one in wwwroot. Same issue of the DataBase connection couldn't be done.
I returned the physical path to C:
Below, is the second version of my button's event code:
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://MyServer/ReportServer/ReportExecution2005.asmx";
// Render arguments
byte[] result = null;
string reportPath = "/ReportLuiza/ReportContract";
string format = "PDF";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "NMB_CONTRACT";
parameters[0].Value = txtNmbContractReport.Text;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, null);
rs.SetExecutionParameters(parameters, "pt-br");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (SoapException se)
{
ShowMessage(se.Detail.OuterXml);
}
// Write the contents of the report to an pdf file.
try
{
using (FileStream stream = new FileStream(#"c:\report.pdf", FileMode.Create, FileAccess.ReadWrite))
{
stream.Write(result, 0, result.Length);
stream.Close();
}
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
For this code, I had to add a WebReference to the .asmx file mentioned in it.
When I'm debugging (on Visual Studio 2010), the code above works fine, doesn't asking for credentials (unfortunately, it doesn't prompt the option to open, save or cancel de file download. But this is another problem, no need to worry with it now) and save the file on C:.
When published, the code doesn't work. An erros says: The permission granted to user 'IIS APPPOOL\ASP.NET v4.0' are insuficient for performing this operation. So I added to the Reporting Service's users this user. When I tried again, the error is: Login failed for user IISAPPPOOL\ASP.NET v4.0. Cannot create a connection to data source 'MyDataSourceName'.
Both Report and WebSite are deployed/published on the same server with a IIS 7.5 version.
Summarizing: I need a solution where there is no credential prompt, and the user can choose where it wants to save the .pdf file.
Any help will be appreciated.
If you need more information to help me, just ask.
Thanks in advance.
One solution would be to create a new App Pool with an account that has the rights to access your restricted resources and then assign your web application to it.

Starting new process from ASP.NET fails

I'm trying to start a new process from my WCF Service. For that purpose I use
var process = Process.Start(
new ProcessStartInfo { WorkingDirectory = config.WorkingDirectory,
FileName = config.WorkingDirectory,
Arguments = string.Format("{0} {1}", mpcName, jobId),
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Hidden });
The WebApp is using a separate AppDomain whose Identity is set to a user account having administrator rights on the server.
Process.Start throws an exception telling
Server execution failed, at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
I also tested setting user and password in ProcessStartInfo. Specifying the password was quite tricky (SecureString) and then I received
The stub received bad data, at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
so I skipped this way.
Do you know what is the reason for my problem and how I can fix it.
I forgot: I'm using Windows Server 2008 R2, IIS 7
I got it!
It's very strange but the only change needed was to invoke
Process.Start(exeFullPath, args);
Obviously the combination of ProcessStartInfo props is important.
This q/a helped me fix this issue in one of my projects, but different cause --
was trying to start process as a Domain user from an integration test being run by nCrunch. Turns out MY problem was a really long argument string.
(same argument string works with no user/password)
Environment is Windows 8, 64 bit.
Anyway, just gonna have to pass the arg data a different way.

Novell eDirectory with .NET DirectoryServices

In our company, we have a project which should use Novell eDirectory with .net applications.
I have tried Novell Api (http://www.novell.com/coolsolutions/feature/11204.html) to connect between .NET applications. It is working fine.
But, as per requirement, we specifically need .net API to connect not with Novell Api, which is not working. Connection and binding with .NET Api DirectoryServices not working.
Our Novell eDirectory is installed with following credentials:
IP address: 10.0.x.xx(witsxxx.companyname.com)
Tree : SXXXX
New Tree Context: WIxxxK01-NDS.OU=STATE.O=ORG
ADMIN Context is: ou=STATE,o=ORG
admin : admin
password: admin
I used Novell Api and used following code
String ldapHost ="10.0.x.xx";
String loginDN = "cn=admin,cn=WIxxxK01-NDS,OU=STATE,o=ORG";
String password = string.Empty;
String searchBase = "o=ORG";
String searchFilter = "(objectclass=*)";
Novell.Directory.Ldap.LdapConnection lc = new Novell.Directory.Ldap.LdapConnection();
try
{
// connect to the server
lc.Connect(ldapHost, LdapPort);
// bind to the server
lc.Bind(LdapVersion, loginDN, password);
}
This is binding correctly and searching can be done.
Now my issue is with when I trying to use .NET APi and to use System.DirectoryServices
or System.DirectoryServices.Protocols, it is not connecting or binding.
I can't even test the following DirectoryEntry.Exists method. It is going to exception.
string myADSPath = "LDAP://10.0.x.xx:636/OU=STATE,O=ORG";
// Determine whether the given path is correct for the DirectoryEntry.
if (DirectoryEntry.Exists(myADSPath))
{
Console.WriteLine("The path {0} is valid",myADSPath);
}
else
{
Console.WriteLine("The path {0} is invalid",myADSPath);
}
It is saying Server is not operational or Local error occurred etc. I don't know what is happening with directory path.
I tried
DirectoryEntry de = new DirectoryEntry("LDAP://10.0.x.xx:636/O=ORG,DC=witsxxx,DC=companyname,DC=com", "cn=admin,cn=WIxxxK01-NDS,o=ORG", "admin");
DirectorySearcher ds = new DirectorySearcher(de, "&(objectClass=user)");
var test = ds.FindAll();
All are going to exceptions.
Could you please help me to solve this? How should be the userDN for DirectoryEntry?
I used System.DirectoryServices.Protocols.LdapConnection too with LdapDirectoryIdentifier and System.Net.NetworkCredential but no result. Only same exceptions.
I appreciate your valuable time and help.
Thanks,
Binu
To diagnose your LDAP connection error, get access to the eDirectory server from the admins, and use iMonitor (serverIP:8028/nds and select Dstrace), in Dstrace clear all tabs and enable LDAP tracing, then do your bind see what happens on the LDAP side to see if there is a more descriptive error there. Or if you even get far enough to bind and make a connection.

How to use SharpSVN in ASP.NET?

Trying to use use SharpSVN in an ASP.NET app. So far, it's been nothing but trouble. First, I kept getting permission errors on "lock" files (that don't exist), even though NETWORK SERVICE has full permissions on the directories. Finally in frustration I just granted Everyone full control. Now I get a new error:
OPTIONS of 'https://server/svn/repo': authorization failed: Could not authenticate to server: rejected Basic challenge (https://server)
This happens whether I have the DefaultCredentials set below or not:
using (SvnClient client = new SvnClient())
{
//client.Authentication.DefaultCredentials = new System.Net.NetworkCredential("user", "password");
client.LoadConfiguration(#"C:\users\myuser\AppData\Roaming\Subversion");
SvnUpdateResult result;
client.Update(workingdir, out result);
}
Any clues? I wish there was SOME documentation with this library, as it seems so useful.
The user you need to grant permission is most likely the ASPNET user, as that's the user the ASP.NET code runs as by default.
ASPNET user is a local account, preferably youd'd want to run this code in an Impersonate block, using a network account set up for this specific reason

Access Denied errors accessing IIS WMI provider from ASP

I have a Windows 2003 server running IIS 6 and have some scripts that do automated setup and creation of websites. They are not working on a new server I cam commissioning (they already work happily on 3 other W2K3 servers). The problem appear to boil down to WMI security on the IIS provider. The ASP code below represents the problem (although it is not the original code that causes the problem - this is a simplified demonstration of the problem).
Set wmiProvider = GetObject("winmgmts:\\.\root\MicrosoftIISv2")
If wmiProvider is Nothing Then
Response.Write "Failed to get WMI provider MicrosoftIISv2<br>"
End If
Response.Write "Querying for IISWebService...<br>"
Set colItems = wmiProvider.ExecQuery("Select * From IISWebServer",,0)
Response.Write "Error: " & Hex(Err.Number) & " (" & Err.Description & ")<br>"
If I run this in my browser, I get an access denied error reported after the ExecQuery call. I have set WMI access for the IUSR_ user from the Root branch all the way down. In fact, I can query for IP address information using the CIMV2 provider quite happily. If I put the IUSR user in the machine admins group it all works, but I don't really want to do that.
This must be a DCOM/WMI security problem, but I can't work out what else there is. Can anyone shed any light?
After reading G. Stoynev's comment asking if any events were logged in the Windows Logs, I checked the event logs on the server to which I'm attempting to access IIS remotely via WMI, and lo and behold I found an event with the following text:
Access to the root\WebAdministration namespace was denied because the namespace is marked with RequiresEncryption but the script or application attempted to connect to this namespace with an authentication level below Pkt_Privacy. Change the authentication level to Pkt_Privacy and run the script or application again.
See the code in this answer to the related SO question c# - "Access is denied" Exception with WMI.
Here's some example C# code that I added that seemed to resolve this issue for me:
ConnectionOptions options = new ConnectionOptions();
options.Authentication = AuthenticationLevel.PacketPrivacy;
ManagementScope managementScope = new ManagementScope(#"\\remote-server\root\WebAdministration", options);
// ...
If this is something that you intend to run as a tool for yourself or your admin (as opposed to the unwashed anonymous masses), here is a way I have used in the past (YMMV):
Set up a new directory in your website (e.g. /SiteCreate) and place your WMI scripts there
Configure a Windows user that has appropriate rights (probably admin in this case but you should use whatever is pertinent to your app)
Turn off the anonymous access to the directory you created in step 1 and then set the security to allow access only to the user you created in step 2 (turn on the authentication for that directory)
Now, when you navigate to that directory in your browser, you should get a login prompt. When you enter the username/password you created in step 2 your script will have the appropriate rights to perform your WMI requests.
Not a DCOM issue, more so a WMI security and encryption issue. Try changing the GetObject moniker to include impersonation and pktPrivacy, eg:
Set wmiProvider = GetObject("winmgmts:{impersonationLevel=impersonate;authenticationLevel=pktPrivacy}!\root\MicrosoftIISv2")
Refer to the follow MS article for more info:
http://msdn.microsoft.com/en-us/library/aa393618(v=vs.85).aspx

Resources