HighTechTalks DotNet Forums  

Problem establishing SSL connection in code-behind

ASP.net Security microsoft.public.dotnet.framework.aspnet.security


Discuss Problem establishing SSL connection in code-behind in the ASP.net Security forum.



Reply
 
Thread Tools Search this Thread Display Modes
  #1  
Old   
gnewsgroup
 
Posts: n/a

Default Problem establishing SSL connection in code-behind - 01-02-2008 , 03:50 PM






In my web application, I need to establish an SSL connection to a
remote web site and authenticate a user using Integrated Windows
Authentication.

The remote website only allows this authentication method, and it has
only one web page: index.html, which simply says: hola, amigo.

Please note that I can check out that remote website in IE through
HTTPS connection without a problem.

I put together the following code after I did some google search. I
know it scares people away at the sight of a lengthy pasted code. But
the idea is really simple: Simply accept all certificates. That's why
ServerCertificateValidationCallback in my code always return true.

I thought that this logic is correct, but when I debug it, the VS2005
shows that the Exception message (ex.Message) says:

The remote server returned an error: (401) Unauthorized

The really simple and easy-to-read code is as follows. Please share a
little wisdom of yours. Thanks.

using System;
using System.Data;
using System.Data.SqlClient;
using System.DirectoryServices;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Do nothing.
}

protected void btnLogin_Click(object s, EventArgs e)
{
string userName = txtUserName.Text.Trim().ToLower();
string password = txtPassword.Text.Trim().ToLower();
string domain = "mydomain.com";
NetworkCredential userCredential = new
NetworkCredential(userName, password, domain);
string myUri = "https://somehost:8443/index.html"
bool isAuthenticated = GetSecureSocketStream(myUri,
userCredential);

if (isAuthenticated)
{
lblMessage.Text = "You are authenticated.";
return;
}
else
{
lblMessage.Text = "Authentication failed. Please try
again.";
return;
}
}

protected bool GetSecureSocketStream(string uri,
NetworkCredential userCredential)
{
ServicePointManager.ServerCertificateValidationCal lback +=
delegate
(object s, X509Certificate cert, X509Chain chain,
System.Net.Security.SslPolicyErrors errors)
{ return true; };


HttpWebRequest myRequest = null;
HttpWebResponse myResponse = null;
Stream answer = null;
StreamReader streamReader = null;
bool isAuthenticated = false;
string remoteMessage = "";

try
{
myRequest = (HttpWebRequest)WebRequest.Create(uri);
myRequest.Method = "GET";
string postData = "";
myRequest.ContentLength = postData.Length;
myRequest.Credentials = userCredential;
myResponse = (HttpWebResponse)myRequest.GetResponse();
answer = myResponse.GetResponseStream();
streamReader = new StreamReader(answer);
remoteMessage = streamReader.ReadToEnd();

if (remoteMessage.ToLower().Contains("hola, amigo."))
{
isAuthenticated = true;
}
}
catch(Exception ex)
{
Trace.Write(ex.Message);
isAuthenticated = false;
}

return isAuthenticated;
}
}

Reply With Quote
  #2  
Old   
Joe Kaplan
 
Posts: n/a

Default Re: Problem establishing SSL connection in code-behind - 01-02-2008 , 04:37 PM






The 401 indicates that your creds are not being accepted. You would get a
different error if there was an SSL problem.

I'd suggest enabling auditing of logon events (success and failure) on the
remote web server and see if you can find out why the authentication is
failing.

Joe K.

--
Joe Kaplan-MS MVP Directory Services Programming
Co-author of "The .NET Developer's Guide to Directory Services Programming"
http://www.directoryprogramming.net
--
"gnewsgroup" <gnewsgroup (AT) gmail (DOT) com> wrote

Quote:
In my web application, I need to establish an SSL connection to a
remote web site and authenticate a user using Integrated Windows
Authentication.

The remote website only allows this authentication method, and it has
only one web page: index.html, which simply says: hola, amigo.

Please note that I can check out that remote website in IE through
HTTPS connection without a problem.

I put together the following code after I did some google search. I
know it scares people away at the sight of a lengthy pasted code. But
the idea is really simple: Simply accept all certificates. That's why
ServerCertificateValidationCallback in my code always return true.

I thought that this logic is correct, but when I debug it, the VS2005
shows that the Exception message (ex.Message) says:

The remote server returned an error: (401) Unauthorized

The really simple and easy-to-read code is as follows. Please share a
little wisdom of yours. Thanks.

using System;
using System.Data;
using System.Data.SqlClient;
using System.DirectoryServices;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Do nothing.
}

protected void btnLogin_Click(object s, EventArgs e)
{
string userName = txtUserName.Text.Trim().ToLower();
string password = txtPassword.Text.Trim().ToLower();
string domain = "mydomain.com";
NetworkCredential userCredential = new
NetworkCredential(userName, password, domain);
string myUri = "https://somehost:8443/index.html"
bool isAuthenticated = GetSecureSocketStream(myUri,
userCredential);

if (isAuthenticated)
{
lblMessage.Text = "You are authenticated.";
return;
}
else
{
lblMessage.Text = "Authentication failed. Please try
again.";
return;
}
}

protected bool GetSecureSocketStream(string uri,
NetworkCredential userCredential)
{
ServicePointManager.ServerCertificateValidationCal lback +=
delegate
(object s, X509Certificate cert, X509Chain chain,
System.Net.Security.SslPolicyErrors errors)
{ return true; };


HttpWebRequest myRequest = null;
HttpWebResponse myResponse = null;
Stream answer = null;
StreamReader streamReader = null;
bool isAuthenticated = false;
string remoteMessage = "";

try
{
myRequest = (HttpWebRequest)WebRequest.Create(uri);
myRequest.Method = "GET";
string postData = "";
myRequest.ContentLength = postData.Length;
myRequest.Credentials = userCredential;
myResponse = (HttpWebResponse)myRequest.GetResponse();
answer = myResponse.GetResponseStream();
streamReader = new StreamReader(answer);
remoteMessage = streamReader.ReadToEnd();

if (remoteMessage.ToLower().Contains("hola, amigo."))
{
isAuthenticated = true;
}
}
catch(Exception ex)
{
Trace.Write(ex.Message);
isAuthenticated = false;
}

return isAuthenticated;
}
}



Reply With Quote
  #3  
Old   
gnewsgroup
 
Posts: n/a

Default Re: Problem establishing SSL connection in code-behind - 01-02-2008 , 04:48 PM



On Jan 2, 5:37 pm, "Joe Kaplan"
<joseph.e.kap... (AT) removethis (DOT) accenture.com> wrote:
Quote:
The 401 indicates that your creds are not being accepted. You would get a
different error if there was an SSL problem.

I'd suggest enabling auditing of logon events (success and failure) on the
remote web server and see if you can find out why the authentication is
failing.

Joe K.

--
Joe Kaplan-MS MVP Directory Services Programming
Co-author of "The .NET Developer's Guide to Directory Services Programming"http://www.directoryprogramming.net
Thank you very much. So you suggest that the SSL connection wasn't
established at all, right? Let me try to figure out how to enable
auditing logon events and see what is going on.


Reply With Quote
  #4  
Old   
gnewsgroup
 
Posts: n/a

Default Re: Problem establishing SSL connection in code-behind - 01-02-2008 , 05:34 PM



On Jan 2, 5:37 pm, "Joe Kaplan"
<joseph.e.kap... (AT) removethis (DOT) accenture.com> wrote:
Quote:
The 401 indicates that your creds are not being accepted. You would get a
different error if there was an SSL problem.

I'd suggest enabling auditing of logon events (success and failure) on the
remote web server and see if you can find out why the authentication is
failing.

Joe K.

--
Joe Kaplan-MS MVP Directory Services Programming
Co-author of "The .NET Developer's Guide to Directory Services Programming"http://www.directoryprogramming.net
I enabled logon event auditing and did find something interesting.
Look:

Event Type: Error
Event Source: Userenv
Event Category: None
Event ID: 1058
Date: 1/2/2008
Time: 6:17:48 PM
User: MYCOMPANY.COM\myusername
Computer: Mercury01
Description:
Windows cannot access the file gpt.ini for GPO cn={4D440ED8-E77F-447C-
A091-739F3F676AB0},cn=policies,cn=system,DC=mycompany,D C=com. The file
must be present at the location <\\mycompany.com\SysVol\mycompany.com
\Policies\{4D440ED8-E77F-447C-A091-739F3F676AB0}\gpt.ini>. (The system
detected a possible attempt to compromise security. Please ensure that
you can contact the server that authenticated you. ). Group Policy
processing aborted. For more information, see Help and Support Center
at http://go.microsoft.com/fwlink/events.asp.

It looks like that the system is trying to access the so-called
gpt.ini file. I just checked the remote computer, it does not even
have a folder called \\mycompany.com\SysVol\.

So, somehow, I have to create that path and that gpt.ini file in order
for this to work?



Reply With Quote
  #5  
Old   
Joe Kaplan
 
Posts: n/a

Default Re: Problem establishing SSL connection in code-behind - 01-02-2008 , 10:15 PM



Regarding your first question, SSL is negotiated before any HTTP traffic is
sent, so SSL must have already been successful. That's what I meant by
saying that it was not the problem.

This error you are getting in the event log doesn't look right though. I
would not expect to see a group policy processing error for a network login.
That seems like something that should happen on an interactive logon. I
could be wrong though as I'm not a GPO guy. However, I'd also expect to see
that same error when you log on using IWA with those same credentials using
the browser.

There is a tool that is often helpful for troubleshooting HTTP
authentication issues called wfetch.exe from the IIS 6 resource kit that I
would probably try to use to simulate the GET request that your .NET code is
making to see if I get the same error.

Joe K.

--
Joe Kaplan-MS MVP Directory Services Programming
Co-author of "The .NET Developer's Guide to Directory Services Programming"
http://www.directoryprogramming.net
--
"gnewsgroup" <gnewsgroup (AT) gmail (DOT) com> wrote

Quote:
On Jan 2, 5:37 pm, "Joe Kaplan"
joseph.e.kap... (AT) removethis (DOT) accenture.com> wrote:
The 401 indicates that your creds are not being accepted. You would get
a
different error if there was an SSL problem.

I'd suggest enabling auditing of logon events (success and failure) on
the
remote web server and see if you can find out why the authentication is
failing.

Joe K.

--
Joe Kaplan-MS MVP Directory Services Programming
Co-author of "The .NET Developer's Guide to Directory Services
Programming"http://www.directoryprogramming.net

I enabled logon event auditing and did find something interesting.
Look:

Event Type: Error
Event Source: Userenv
Event Category: None
Event ID: 1058
Date: 1/2/2008
Time: 6:17:48 PM
User: MYCOMPANY.COM\myusername
Computer: Mercury01
Description:
Windows cannot access the file gpt.ini for GPO cn={4D440ED8-E77F-447C-
A091-739F3F676AB0},cn=policies,cn=system,DC=mycompany,D C=com. The file
must be present at the location <\\mycompany.com\SysVol\mycompany.com
\Policies\{4D440ED8-E77F-447C-A091-739F3F676AB0}\gpt.ini>. (The system
detected a possible attempt to compromise security. Please ensure that
you can contact the server that authenticated you. ). Group Policy
processing aborted. For more information, see Help and Support Center
at http://go.microsoft.com/fwlink/events.asp.

It looks like that the system is trying to access the so-called
gpt.ini file. I just checked the remote computer, it does not even
have a folder called \\mycompany.com\SysVol\.

So, somehow, I have to create that path and that gpt.ini file in order
for this to work?




Reply With Quote
  #6  
Old   
gnewsgroup
 
Posts: n/a

Default Re: Problem establishing SSL connection in code-behind - 01-03-2008 , 01:28 PM



On Jan 2, 11:15 pm, "Joe Kaplan"
<joseph.e.kap... (AT) removethis (DOT) accenture.com> wrote:
Quote:
Regarding your first question, SSL is negotiated before any HTTP traffic is
sent, so SSL must have already been successful. That's what I meant by
saying that it was not the problem.

This error you are getting in the event log doesn't look right though. I
would not expect to see a group policy processing error for a network login.
That seems like something that should happen on an interactive logon. I
could be wrong though as I'm not a GPO guy. However, I'd also expect to see
that same error when you log on using IWA with those same credentials using
the browser.

There is a tool that is often helpful for troubleshooting HTTP
authentication issues called wfetch.exe from the IIS 6 resource kit that I
would probably try to use to simulate the GET request that your .NET code is
making to see if I get the same error.

Joe K.

--
Yes, you are right. I mulled it over last night, and also thought
that that error message should be irrelevant. I am still working on
this problem. I'll post the solution here if I find one.


Reply With Quote
  #7  
Old   
gnewsgroup
 
Posts: n/a

Default Re: Problem establishing SSL connection in code-behind - 01-03-2008 , 02:40 PM



On Jan 2, 11:15 pm, "Joe Kaplan"
<joseph.e.kap... (AT) removethis (DOT) accenture.com> wrote:
Quote:
Regarding your first question, SSL is negotiated before any HTTP traffic is
sent, so SSL must have already been successful. That's what I meant by
saying that it was not the problem.

This error you are getting in the event log doesn't look right though. I
would not expect to see a group policy processing error for a network login.
That seems like something that should happen on an interactive logon. I
could be wrong though as I'm not a GPO guy. However, I'd also expect to see
that same error when you log on using IWA with those same credentials using
the browser.

There is a tool that is often helpful for troubleshooting HTTP
authentication issues called wfetch.exe from the IIS 6 resource kit that I
would probably try to use to simulate the GET request that your .NET code is
making to see if I get the same error.

Joe K.

OK, I did test it with wfetch. I am confused by the wfetch log.
Click here http://gnewsgroup.googlepages.com/home to view the log.

Especially confusing is that at once place, the log says that I am not
authorized to view that requested page. At another place, it displays
that page nicely right in front of me. What does it mean?

Now when I debug my web application (see my first post in this
thread), the Exception Message (ex.Message) says:

"The operation has timed out"

I thought that maybe port 4443 (the SSL port I use) is blocked by the
firewall, but the target host has the Windows Firewall turned off.

I am at my wit's end.



Reply With Quote
  #8  
Old   
Joe Kaplan
 
Posts: n/a

Default Re: Problem establishing SSL connection in code-behind - 01-03-2008 , 04:32 PM



What you are seeing is a standard NTLM request/response pattern. Normally
with NTLM, the browser does a GET and the server responds with 401 and a
WWW-Authenticate header with a challenge. The browser then does the GET
again with a responding Authorization request header and the server responds
with 200 if the browser's response is accepted. Kerberos auth looks a
little different because it can preauthenticate.

Based on what I see here, it looks like NTLM worked ok from wfetch. You
might try with Negotiate auth selected to allow the possibility of Kerberos
and not just NTLM. Kerberos will only work if there is a valid SPN
registered in AD for that hostname though (and the DC can be contacted by
the client to get a Kerb ticket).

As to why your code is getting a timeout now, I don't know. The fact that
it used to get something different and is now timing out doesn't make a lot
of sense.

Joe K.

--
Joe Kaplan-MS MVP Directory Services Programming
Co-author of "The .NET Developer's Guide to Directory Services Programming"
http://www.directoryprogramming.net
--
"gnewsgroup" <gnewsgroup (AT) gmail (DOT) com> wrote

Quote:
On Jan 2, 11:15 pm, "Joe Kaplan"
joseph.e.kap... (AT) removethis (DOT) accenture.com> wrote:
Regarding your first question, SSL is negotiated before any HTTP traffic
is
sent, so SSL must have already been successful. That's what I meant by
saying that it was not the problem.

This error you are getting in the event log doesn't look right though. I
would not expect to see a group policy processing error for a network
login.
That seems like something that should happen on an interactive logon. I
could be wrong though as I'm not a GPO guy. However, I'd also expect to
see
that same error when you log on using IWA with those same credentials
using
the browser.

There is a tool that is often helpful for troubleshooting HTTP
authentication issues called wfetch.exe from the IIS 6 resource kit that
I
would probably try to use to simulate the GET request that your .NET code
is
making to see if I get the same error.

Joe K.


OK, I did test it with wfetch. I am confused by the wfetch log.
Click here http://gnewsgroup.googlepages.com/home to view the log.

Especially confusing is that at once place, the log says that I am not
authorized to view that requested page. At another place, it displays
that page nicely right in front of me. What does it mean?

Now when I debug my web application (see my first post in this
thread), the Exception Message (ex.Message) says:

"The operation has timed out"

I thought that maybe port 4443 (the SSL port I use) is blocked by the
firewall, but the target host has the Windows Firewall turned off.

I am at my wit's end.




Reply With Quote
  #9  
Old   
gnewsgroup
 
Posts: n/a

Default Re: Problem establishing SSL connection in code-behind - 01-03-2008 , 05:01 PM



On Jan 3, 5:32 pm, "Joe Kaplan"
<joseph.e.kap... (AT) removethis (DOT) accenture.com> wrote:
Quote:
What you are seeing is a standard NTLM request/response pattern. Normally
with NTLM, the browser does a GET and the server responds with 401 and a
WWW-Authenticate header with a challenge. The browser then does the GET
again with a responding Authorization request header and the server responds
with 200 if the browser's response is accepted. Kerberos auth looks a
little different because it can preauthenticate.

Based on what I see here, it looks like NTLM worked ok from wfetch. You
might try with Negotiate auth selected to allow the possibility of Kerberos
and not just NTLM. Kerberos will only work if there is a valid SPN
registered in AD for that hostname though (and the DC can be contacted by
the client to get a Kerb ticket).

As to why your code is getting a timeout now, I don't know. The fact that
it used to get something different and is now timing out doesn't make a lot
of sense.

Joe K.

--
Joe Kaplan-MS MVP Directory Services Programming
Co-author of "The .NET Developer's Guide to Directory Services Programming"http://www.directoryprogramming.net
OK, thank you. Are you suggesting that NTLM is different from
Integrated Windows Authentication? (The remote web site uses
Integrated Windows Authentication). I thought they are the same, NTLM
is only an old terminology.

I did try using Negotiate, and the result is different: It gives an
401 unauthorized message, and the hola, amigo webpage is not shown.


Reply With Quote
  #10  
Old   
Joe Kaplan
 
Posts: n/a

Default Re: Problem establishing SSL connection in code-behind - 01-03-2008 , 06:45 PM



Integrated Windows Authentication is the term in IIS used to mean Windows
Negotiate authentication over HTTP (usually). Negotiate authentication is a
protocol in Windows as of Win2K that "negotiates" between Kerberos
(preferred) and NTLM (down level compatibility). It is possible to
configure IIS to only advertise for NTLM, but the default is for it to
request Negotiate when IWA is selected.

You can see exactly what your server is requesting if you do the GET in
Wfetch with anonymous auth selected and then look at the content of the
WWW-Authenticate header returned in the 401 response from the server. If it
says "Negotiate" with some other Base64 gibberish, then you know it is using
the default.

Wfetch allows you to be more granular with which protocol will actually be
used, which is helpful for some troubleshooting.

It is possible that there is a problem with Kerberos auth and not NTLM,
which might cause you to see a 401 when Negotiate is attempted instead of
NTLM. Normally, there will be an error from Kerberos in the event log from
the web server and should also be a logon failure audit in the security
event log. Wfetch will sometimes return an error code as well that can be
helpful.

A common reason why you might get a Kerberos error is if the app pool
identity in IIS is running under an account other than Network Service or
System but you are using the default machine name for the host name in your
URI and the SPN in AD is still associated with the machine account. That
will usually result in a KERB_APP_ERR_MODIFIED error. If that is the
problem, there are a number of ways to fix it.

Joe K.

--
Joe Kaplan-MS MVP Directory Services Programming
Co-author of "The .NET Developer's Guide to Directory Services Programming"
http://www.directoryprogramming.net
--
Quote:
OK, thank you. Are you suggesting that NTLM is different from
Integrated Windows Authentication? (The remote web site uses
Integrated Windows Authentication). I thought they are the same, NTLM
is only an old terminology.

I did try using Negotiate, and the result is different: It gives an
401 unauthorized message, and the hola, amigo webpage is not shown.



Reply With Quote
Reply




Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.