Reverse DNS lookup to https over vpn not resolving - asp.net

I'm performing a reverse DNS lookup to determine whether the user is on an appropriate domain in order to tailor the experience to their specific requirements and the code below is working correctly, except under the following specific instance.
when connecting to the site over a VPN and via https:// (vpn and http:// work as intended) The following error is thrown: "Error: The requested name is valid, but no data of the requested type was found."
Upon closer investigation the system is returning an odd computer name (eg: 3EDs45F46FG) and not the expected reverse lookup (eg: ws234.domainName.com)
Public Shared Function GetDomain() As String
Dim RQST As System.Web.HttpRequest
RQST = HttpContext.Current.Request
Return ReverseLookup(RQST.UserHostName)'UserHostName as ip address
End Function
Public Shared Function ReverseLookup(ip As String) As String
Dim netDns As System.Net.Dns
Try
Dim host As New IPHostEntry
host = netDns.GetHostEntry(ip)
Return host.HostName & "<BR><BR>ip: " & ip
Catch ex As System.Net.Sockets.SocketException
Return "Error: " & ex.Message & "<BR><BR>" & "ip: " & ip
End Try
End Function

Related

Your request is prohibited because the request is on loopback from external IP

Getting this error when trying to save entity in local dynamodb ,i am running my application also locally .My all request are routed through a proxy which i can't disable due to organisation policy .Is there any way to avoid this error ?
#RequestMapping(value = "/dynamoPost", method = {RequestMethod.POST}, consumes = {"application/json"}, produces = {"application/json"})
#ResponseBody
public TxnClass testPost(#RequestBody TxnClass input) {
TxnClass response = txnInfoRepository.save(input);
System.out.println("saved successfully");
return response;
}
error :-
om.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: (byte[])"Request on loopback from external IP
Request on loopback from external IP
Description: Your request is prohibited because the request is on loopback from external IP.

smtp connection works in telnet but not in ASP -- same server, same credentials

I'm trying to send email from an ASP.NET using my SendGrid account. It works on my dev machine, but not in production, even though the credentials are the same. Likewise, in production I can connect to the SMTP server via telnet (using base64 encoded credentials), but the ASP site can't connect--I get error "Unauthenticated senders not allowed."
I've tried a mix of port numbers (25, 587, 465 -- my site is SSL). Using port 465 times out. 25 and 587 return respond immediately--but with the login error. This is really baffling because, like I say, it's the same credentials on dev machine and production.
I looked very briefly at Microsoft Network Monitor 3.4, but could not make heads or tails of it. I was hoping it would tell me the blow-by-blow commands being sent since I suspect the web site is doing something a little different from how telnet connects, but I don't know what.
Note I also asked my web host if outgoing traffic on these ports were blocked on production firewall, but they aren't.
Here's the actual code--like I say works fine on localhost, but SMTP connection fails in production
[AllowAnonymous]
[HttpPost]
public ActionResult ResetPasswordSend(string email)
{
List<string> userList = new List<string>();
try
{
string[] invalidChars = new string[] { ";", "," };
foreach (var invalidChar in invalidChars) if (email.Contains(invalidChar)) throw new Exception("Email contains invalid character.");
int count = 0;
// since emails are not unique, I must launch resets for all of them
var users = _db.HsProfile.Query("[Email]=#0", SqlDb.Params(email));
foreach (var profile in users)
{
count++;
userList.Add(profile.UserName);
var token = WebSecurity.GeneratePasswordResetToken(profile.UserName, 15);
WebMail.Send(profile.Email, "HumaneSolution.com Password Reset for user " + profile.UserName,
"You received this email because you or someone with your email address requested a password reset on HumaneSolution.com. " +
"If you didn't do this, then you don't need to take any action, and nothing will happen.\n\n" +
"To proceed with the password reset, click the link below within 15 minutes:\n\n" +
Url.BaseUrl("Account/EnterNewPassword/" + token) + "\n\n" +
"Sent to: " + email + " at " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "\n" +
"User name: " + profile.UserName);
}
if (count == 0) throw new Exception("Email " + email + " is not registered at HumaneSolution.com.");
}
catch (Exception exc)
{
ViewBag.Error = exc.Message;
}
return View(userList);
}
Based on suggestion from SendGrid, I re-wrote the email code so it does not use WebMail.Send but rather the SmtpClient and MailMessage objects explicitly. SendGrid says there might be some kind of timing problem in how ASP.NET loads credentials from the config file automatically. Here's exactly what they said:
Are you by chance storing your SendGrid credentials in a configuration file, separate from the code that connects to our SMTP server? The reason I ask is because I have seen rails and C# configurations like this receive the unauthenticated error due to the credentials not being passed at the correct time. Usually this is solved by moving the credentials directly in with the code instead of a separate configuration file. Give that a try and see if you notice a difference.<<
I didn't follow their advice completely -- i.e. I'm still using config file, but I'm loading the config values in subclasses of SmtpClient and MailMessage so I avoid hardcoding creds in my app. Anyway, it worked, all is well again.

Get LAN client machine name in servlet based web application

I have spring MVC application, that runs in LAN. In there client machines IP addresses are changing time to time. Therefore I want to get client machines names(Their machine name is fixed ),because I want to get client machine's details without creating log in.
Is that possible to get client machine's name?? if it's possible how??
Or is there any other way to get that user details
Edit:
codes I have tried so far
In HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String hostname = request.getRemoteUser(); //this gives null
String hostname = request.getRemoteHost(); //This gives host machine name
}
Edit: reply to #Eugeny Loy
In web.xml
<init-param>
<param-name>jcifs.smb.client.username</param-name>
<param-value>username</param-value>
</init-param>
In serverlet class
String username = config.getInitParameter("username");//This gives client IP address
I found the way to get client machine's name.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
Logger.getLogger(this.getClass()).warning("Inside Confirm Servlet");
response.setContentType("text/html");
String hostname = request.getRemoteHost(); // hostname
System.out.println("hostname"+hostname);
String computerName = null;
String remoteAddress = request.getRemoteAddr();
System.out.println("remoteAddress: " + remoteAddress);
try {
InetAddress inetAddress = InetAddress.getByName(remoteAddress);
System.out.println("inetAddress: " + inetAddress);
computerName = inetAddress.getHostName();
System.out.println("computerName: " + computerName);
if (computerName.equalsIgnoreCase("localhost")) {
computerName = java.net.InetAddress.getLocalHost().getCanonicalHostName();
}
} catch (UnknownHostException e) {
}
System.out.println("computerName: " + computerName);
}
Is that possible to get client machine's name??
You're probably referring to NetBIOS name here. If that's the case - you should use some library that implements NetBIOS/SMB/CIFS in java to do this.
if it's possible how??
Have a look on JCIFS. I won't give you the exact code snippet but this is the direction you should move to solve this.
Or is there any other way to get that user details
As far as I understand your problem, what you need is a way to identify host and you cannot rely on IP address for that.
If that's the case one of the other options would be using MAC address, but you'll probably wont be able to do this with pure java since this is more low-level protocol java normally deals with, so it will probably be less portable. This tutorial might help.
UPDATE
I come across NetBIOS/SMB/CIFS stack but I haven't worked with it in Java and JCIFS. That's why I won't give you specific code piece that will solve your issue but rather direction where you should look.
Check out NbtAddress class docs. Seems to be what you are looking for. Also check out the examples to get the idea how it can be used.

Email using System.Net.Mail through Google Apps Timing out

I have a ASP.NET 4.0 web application, which the HR team uses to send out surveys to employees. Since we use a Google Apps, I am trying to send these survey emails through the Google Apps Account.
I have used the following settings to send out emails.
Host - smtp.gmail.com
Port - 587
EnableSsl=true
along with my username and password.
This is the code for sending out emails.
using (SmtpClient smtp = new SmtpClient())
{
smtp.Timeout = 0;
smtp.Send(message);
}
The settings are in the web.config and are read from there.
Now my issue..
The hr team selects multiple users to send the survey to. They could just select 1 or maybe up to 100 at a time to send out surveys. Since each survey link has to be different, I iterate the list of users and email them.
Now after the application send out a maximum of 12 emails, it stops sending out any more. The next email it tries to send it throws an error.
Message = The operation has timed out.
Status Code =GeneralFailure
Stack Trace = at System.Net.Mail.SmtpClient.Send(MailMessage message)
at ABC.Business.Mail.SendMail(MailMessage message, String& errorMessage)
Then onwards if I retry again it throws an error
Message = Failure sending mail.
Status Code =GeneralFailure
Stack Trace = at System.Net.Mail.SmtpClient.Send(MailMessage message)
at ABC.Business.Mail.SendMail(MailMessage message, String& errorMessage)
If its come to this state, the only way out is to retart IIS. If I restart IIS, it starts working fine again for the next 12 odd.
What could be the issue? Please help.
You shouldn't set the Timeout to zero.
Its default is 100,000mS (100 seconds), try to leave it at that at least.
System.Net.Mail only supports "Explicit SSL".
Explicit SSL
System.Net.Mail only supports "Explicit SSL". Explicit SSL starts as unencrypted on port 25, then issues a STARTDLS and switches to an Encrypted connection. See RFC 2228.
Explicit SLL would go something like: Connect on 25 -> StartTLS (starts to encrypt) -> authenticate -> send data
If the SMTP server expects SSL/TLS connection right from the start then this will not work.
Implicit SSL
There is no way to use Implicit SSL (SMTPS) with System.Net.Mail. Implicit SSL would have the entire connection is wrapped in an SSL layer. A specific port would be used (port 465 is common). There is no formal RFC covering Implicit SSL.
Implicit SLL would go something like: Start SSL (start encryption) -> Connect -> Authenticate -> send data
This is not considered a bug, it’s a feature request. There are two types of SSL authentication for SMTP, and we only support one (by design) – Explicit SSL.
Demo Code:
*
protected void Btn_SendMail_Click(object sender, EventArgs e)
{
try
{
var fromAddress = "xyz#gmail.com";
var toAddress = "abc#gmail.com";
const string fromPassword = "xxxxxxxx";
string subject = "Sending Demonstration";
string body = "From: " + txtFrom.Text + "\n";
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
}
smtp.Send(fromAddress, toAddress, subject, body);
Response.Write("<script language=javascript> alert('send')</script>");
}
catch (Exception ex)
{
txtBody.Text = ex.Message;
}
}
*
This Code Is Working Without Any Error!!!!
Chris, TimeOut makes ASP.NET application to wait for the request to perform before it shutting down automatically. So, If you give timeOut as zero, ASP.NET will not wait for the request to perform and it will throw error as operation has timed out.
TimeOut should be atleast 180 seconds.
Thanks.

HTTP Connection Parameters

I am using the HTTP Connection in the following way:
HttpConnection _httpConnection = null;
try {
_httpConnection = (HttpConnection)Connector.open(_url);
} catch(Exception e) { }
byte [] postDataBytes = _postData.getBytes();
_httpConnection.setRequestMethod(HttpConnection.POST);
_httpConnection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
_httpConnection.setRequestProperty("Content-Language", "en-US");
_httpConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
_httpConnection.setRequestProperty("Connection", "close");
_httpConnection.setRequestProperty("Content-Length", Integer.toString(_postData.getBytes().length));
os = _httpConnection.openOutputStream();
os.write(postDataBytes);
os.flush();
This HTTP Connection requires parameters to successfully open. For example on a WIFI network, it requires the ";deviceside=true;interface=wifi" to be added to the URL.
The problem is for the EDGE connection. Each country requires different parameters to be added. For example in lebanon it requires ";deviceside=false" but in KSA if i add this parameter the connection will not open. In USA it needs different types of parametes. The question is how to establish an HTTP connection for all the countries with the same parameters. So that the application will successfully have an internet connection no matter where it is downloaded.
Welcome to the confusing world of network transports on BlackBerry! You will want to start with the article Connecting your BlackBerry - http and socket connections to the world.
Here is a simple example for "just give me a connection" (note, you will need to add appropriate error handling; also, myURL in the code below should have no connection descriptor info appended to it):
ConnectionFactory factory = new ConnectionFactory();
ConnectionDescriptor descriptor = factory.getConnection(myURL);
if (descriptor != null) {
_httpConnection = (HttpConnection) descriptor.getConnection();
...
}
Try using to use the method reffered in this link melick-rajee.blogspot.com and use it like
_url = "http://www.example.com";
_httpConnection = (HttpConnection)Connector.open(_url + getConnectionString());
You will have to sign the application to use this else the application will show exception.
To sign your application just go here Code Signing Keys
To use the connectionFactory, seems you need to set BisBOptions.
Try this:
connFact = new ConnectionFactory();
connFact.setTransportTypeOptions(TransportInfo.TRANSPORT_BIS_B,
new BisBOptions("mds-public"));

Resources