Currently I am developing an C# console application using .NET 4.5 to set some configuration values of the access point. This access point is in my local network. Further I am using SnmpSharpNet library to make SNMP requests. To make the SNMP requests I used SNMP version 2.
The problem is that I can't do SET request to the access point and it always responds with "no-access" (error code 6). But I can do GET request without a problem. I checked the MIB file as well and the variable which I am going to change also has read-write access.
This is the code I wrote.
private static LogFile log;
private static SnmpV2Packet response;
private static UdpTarget target;
static void Main(string[] args)
{
try
{
log = new LogFile(args[0]);
target = new UdpTarget((IPAddress)new IpAddress("<host address>"));
Pdu pdu = new Pdu();
pdu.Type = PduType.Set;
pdu.VbList.Add(new Oid("1.3.6.1.4.1.2356.11.2.88.2.0"), new Integer32(1111));
AgentParameters aparam = new AgentParameters(SnmpVersion.Ver2, new OctetString("public"));
response = (SnmpV2Packet)target.Request(pdu, aparam);
}
catch (Exception ex)
{
log.LogError("Request failed with the exception " + ex, "Main");
target.Close();
return;
}
if (response == null)
{
log.LogError("Error in SNMP request", "Main");
}
else
{
//If an incorrect response
if (response.Pdu.ErrorStatus != 0)
{
log.LogError("SNMP agent returned error status " + response.Pdu.ErrorStatus, "Main");
}
//If a successful response
else
{
log.LogInfo("Value of the " + response.Pdu[0].Oid.ToString() + "changed to " + response.Pdu[0].Value.ToString(), "Main");
}
}
target.Close();
log.CloseLogFile();
}
This is the part related to the variable in the MIB file
-- {SCALAR} 1.3.6.1.4.1.2356.11.2.88.2
lcsSetupWirelessEpaperPort OBJECT-TYPE
SYNTAX Integer32 (0..65535)
MAX-ACCESS read-write
STATUS current
DESCRIPTION
"-- empty --"
::= { lcsSetupWirelessEpaper 2 }
I tired same using Net-SNMP on the command line also. but the result was same.
Can someone please tell me what would be the issue and what I is the point I am missing here.
Thank you.
A "no-access" (SNMP error code 6) could also indicate that SNMP community you are using ( I'm guessing it's "public" ) does not have write access. A monitoring system, for instance, should be able to read (GET) certain values, but not write (SET) them. From a security point-of-view, it is desirable to use a SNMP community that only has read access in this case.
Check the SNMP community configuration of your AP, to make sure it has write access. I would suggest adding a new community with write access, rather than changing access for "public".
Related
I'm using the official Plaid Java API to make a demo application. I've got the back end working in Sandbox, with their /sandbox/public_token/create generated public keys.
Now, I'm trying to modify the front-end from Plaid's quickstart project to talk with my back end, so I can start using the development tier to work with my IRL bank account.
I'm implementing the basic first step - generating a link_token. However, when the front end calls my controller, I get the following error:
ErrorResponse{displayMessage='null', errorCode='INVALID_FIELD', errorMessage='client_id must be a properly formatted, non-empty string', errorType='INVALID_REQUEST', requestId=''}
This is my current iteration on trying to generate a link_token:
public LinkTokenResponse generateLinkToken() throws IOException {
List<String> plaidProducts = new ArrayList<>();
plaidProducts.add("transactions");
List<String> countryCodes = new ArrayList<>();
countryCodes.add("US");
countryCodes.add("CA");
Response<LinkTokenCreateResponse> response =
plaidService.getClient().service().linkTokenCreate(new LinkTokenCreateRequest(
new LinkTokenCreateRequest.User("test_user_ID"),
"test client",
plaidProducts,
countryCodes,
"en"
).withRedirectUri("")).execute();
try {
ErrorResponse errorResponse = plaidService.getClient().parseError(response);
System.out.println(errorResponse.toString());
} catch (Exception e) {
// deal with it. you didn't even receive a well-formed JSON error response.
}
return new LinkTokenResponse(response.body().getLinkToken());
}
I modeled this after how it seems to work in the Plaid Quickstart's example. I do not see client ID being set explicitly anywhere in there, or anywhere else in Plaid's Java API. I'm at a bit of a loss.
I'm not super familiar with the Java Plaid library specifically, but when using the Plaid client libraries, the client ID is generally set when initializing the client instance. From there, it is automatically included in any calls you make from that client.
You can see the client ID being set in the Java Quickstart here:
https://github.com/plaid/quickstart/blob/master/java/src/main/java/com/plaid/quickstart/QuickstartApplication.java#L67
PlaidClient.Builder builder = PlaidClient.newBuilder()
.clientIdAndSecret(configuration.getPlaidClientID(), configuration.getPlaidSecret());
switch (configuration.getPlaidEnv()) {
case "sandbox":
builder = builder.sandboxBaseUrl();
break;
case "development":
builder = builder.developmentBaseUrl();
break;
case "production":
builder = builder.productionBaseUrl();
break;
default:
throw new IllegalArgumentException("unknown environment: " + configuration.getPlaidEnv());
}
PlaidClient plaidClient = builder.build();
Today I just received this email from Google:
Your app(s) listed at the end of this email have an unsafe
implementation of the HostnameVerifier interface, which accepts all
hostnames when establishing an HTTPS connection to a remote host with
the setDefaultHostnameVerifier API, thereby making your app vulnerable
to man-in-the-middle attacks. An attacker could read transmitted data
(such as login credentials), and even change the data transmitted on
the HTTPS connection.
Sadly, I searched all my code and found no use of HostnameVerifier, nor setDefaultHostnameVerifier or even any HTTPS connections!
I'm using Google's compatibility libraries in its latest version: 25.0.1, and in some of my apps the Google Ads 9.8.0. Will upgrade Ads to 10.0.1, as I can only assume the culprit is in there?!
Did anyone received this alert and if so how did you solve it?
Same here - Insecure Hostname Verifier Detected in APK
Your app is using an unsafe implementation of HostnameVerifier. Please
see this Google Help Center article for details, including the
deadline for fixing the vulnerability. Im not using HostnameVerifier
and not calling setDefaultHostnameVerifier. Moreover - Im using OKHTTP
lib for http-requests. I hope that defining TrustManager will solve
this issue.
Since I'm not subclassing HostnameVerifier or calling setDefaultHostnameVerifier() I assume it relies to some 3rd party lib. Since I can't detect such lib I think I will try to add a class with following code
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(final String hostname, final SSLSession session) {
if (check if SSL is really valid)
return true;
else
return false;
}
});
to my project and will see if it fixes the issue.
So I did it and additionally to every webView I've added overridden method
#Override
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
// the main thing is to show dialog informing user
// that SSL cert is invalid and prompt him to continue without
// protection: handler.proceed();
// or cancel: handler.cancel();
String message;
switch(error.getPrimaryError()) {
case SslError.SSL_DATE_INVALID:
message = ResHelper.getString(R.string.ssl_cert_error_date_invalid);
break;
case SslError.SSL_EXPIRED:
message = ResHelper.getString(R.string.ssl_cert_error_expired);
break;
case SslError.SSL_IDMISMATCH:
message = ResHelper.getString(R.string.ssl_cert_error_idmismatch);
break;
case SslError.SSL_INVALID:
message = ResHelper.getString(R.string.ssl_cert_error_invalid);
break;
case SslError.SSL_NOTYETVALID:
message = ResHelper.getString(R.string.ssl_cert_error_not_yet_valid);
break;
case SslError.SSL_UNTRUSTED:
message = ResHelper.getString(R.string.ssl_cert_error_untrusted);
break;
default:
message = ResHelper.getString(R.string.ssl_cert_error_cert_invalid);
}
mSSLConnectionDialog = new MaterialDialog.Builder(getParentActivity())
.title(R.string.ssl_cert_error_title)
.content(message)
.positiveText(R.string.continue_button)
.negativeText(R.string.cancel_button)
.titleColorRes(R.color.black)
.positiveColorRes(R.color.main_red)
.contentColorRes(R.color.comment_grey)
.backgroundColorRes(R.color.sides_menu_gray)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
mSSLConnectionDialog.dismiss();
handler.proceed();
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
handler.cancel();
}
})
.build();
mSSLConnectionDialog.show();
}
to the
mWebView.setWebViewClient(new WebViewClient() {
... // other corresponding overridden methods
}
And finally Google says:
SECURITY SCAN COMPLETE
No known vulnerabilities were detected for APK 158.
However I'm not sure what code made it, HostNameVerifier or onReceivedSslError() of mWebView.setWebViewClient.
As per the mail received from Google, there can be two possibilities for this issue:
Primarily you have to check your package name is not using any keywords restricted by Google. For example "com.companyname.android", .android is not allowed. Secondary is to check for HostNameVerifier
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(final String hostname, final SSLSession session) {
if (/* check if SSL is really valid */)
return true;
else
return false;
}
});
I am trying to make a XBAP application communicating with a webservice with login.
But I want the user to skip the login step if they already logged in the last seven days.
I got it to work using html/aspx.
But it fails continuously with XBAP.
While debugging, the application is given full trust.
This is the code I have so far to write the cookie:
protected static void WriteToCookie(
string pName,
Dictionary<string, string> pData,
int pExiresInDays)
{
// Set the cookie value.
string data = "";
foreach (string key in pData.Keys)
{
data += String.Format("{0}={1};", key, pData[key]);
}
string expires = "expires=" + DateTime.Now.AddDays(pExiresInDays).ToUniversalTime().ToString("r");
data += expires;
try
{
Application.SetCookie(new Uri(pName), data);
}
catch (Exception ex)
{
}
}
And this is what I have to read the cookie:
protected static Dictionary<string, string> ReadFromCookie(
string pName)
{
Dictionary<string, string> data = new Dictionary<string, string>();
try
{
string myCookie = Application.GetCookie(new Uri(pName));
// Returns the cookie information.
if (String.IsNullOrEmpty(myCookie) == false)
{
string[] splitted = myCookie.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
string[] sub;
foreach(string split in splitted)
{
sub = split.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
if (sub[0] == "expires")
{
continue;
}
data.Add(sub[0], sub[1]);
}
}
}
catch(Exception ex)
{
}
return data;
}
The pName is set with:
string uri = "http://MyWebSiteName.com";
When the user authenticate the first time, I call the WriteToCookie function and set it with 7 days to expire.
It looks like everything is fine as I get no exception of error messages. (I have a break point in the catch)
After that, I close the session and start it again.
The first thing I do is a ReadFromCookie.
Then I get an exception with the following message: No more data is available
So my application is sending the user automatically back to the login screen.
I also tried to do a ReadFromCookie right after the WriteToCookie in the same session, and I get the same error.
Application.SetCookie(new Uri("http://MyWebSiteName.com/WpfBrowserApplication1.xbap"), "Hellllo");
string myCookie2 = Application.GetCookie(new Uri("http://MyWebSiteName.com/WpfBrowserApplication1.xbap"));
It seems to me that the cookie is not even written in the first place.
So I am guessing I am doing something wrong.
Maybe the uri I am using is wrong. Is there a specific format needed for it?
Just like you need a very specific format for the expire date.
I have been searching quite a lot of internet for a good sample/tutorial about using cookies with XBAP, and I could not find anything really well documented or tested.
A lot of people say that it works, but no real sample to try.
A lot of people also handle the authentication in html, then go to the XBAP after successfully reading/writing the cookies.
I would prefer a full XBAP solution if possible.
To answer some questions before they are asked, here are the project settings:
Debug:
Command line arguments: -debug -debugSecurityZoneURL http://MyWebSiteName.com "C:\Work\MyWebSiteName\MyWebSiteNameXBAP\bin\Debug\MyWebSiteNameXBAP.xbap"
Security:
Enable ClickOnce security settings (Checked)
This is a full trust application (selected)
I also created a certificate, and added it the 3 stores like explained in "publisher cannot be verified" message displayed
So I do not have the warning popup anymore. I just wanted to make sure that it was not a permission issue.
Finally found the answer to this problem.
Thanks for this CodeProject I was finally able to write/read cookies from the XBAP code.
As I had guessed, the URI needs to be very specific and you cannot pass everything you want in it.
What did the trick was using: BrowserInteropHelper.Source
In the end the read/write code looks like:
Application.SetCookie(BrowserInteropHelper.Source, data);
string myCookie = Application.GetCookie(BrowserInteropHelper.Source);
It looks like you cannot use ';' to separate your own data.
If you do so, you will only get the first entry in your data.
Use a different separator (ex: ':') and then you can get everything back
The data look like this:
n=something:k=somethingElse;expires=Tue, 12 May 2015 14:18:56 GMT ;
The only thing I do not get back from Application.GetCookie is the expire date.
Not sure if it is normal or not. Maybe it is flushed out automatically for some reason. If someone knows why, I would appreciate a comment to enlighten me.
At least now I can read/write data to the cookie in XBAP. Yeah!
I have created a C sharp Wpf ClickOnce application which uses xml rpc for communincation. A lot of my users get there proxy settings in different ways. Some use a pac file, other from IE or dhcp etc. I want to automate this whole process of getting the proxy details in any kind of environment. I have tried a LOT of different code snippets but want to hear if something like this already exists.
I see the Xml Rpc documentation has a setProxy method but I'm not sure how to specify the username or passsword if one is used. This whole process is still a little bit confusing for me.
I have also tried many different pieces of code including the WebProxy Class and using DefaultCredentials,DefaultProxy,GetSystemWebProxy etc.
At the moment I'm going to try a dllimport using winhttp to get the proxy settings. I am not sure if one can do this in a Clickonce Deployment. Is the dllimport the same as p/invoke ?
As you can see I would appreciate some advice on how to go about getting ANY type of proxy setting.
Appreciate any feedback.
ClickOnce installation/update doesn't really support proxy authentication. It will use the information in IE, and sometimes the machine.config file. The definitive thread with all known information about this is here.
I haven't had have problems with proxy authentication from the standpoint of installing applications. When using our application, which called backend WCF services, we let the user provide his proxy authentication information, and we applied the settings programmatically when making the service calls. This has nothing to do with ClickOnce.
This worked for me :
public static IExample ProxyAndCredentials { get; set; }
public static string ProxyUrl { get; set; }
public static void SetupProxyAndCredentials() {
//Insert your website here where XmlRpc calls should go
var url = new Uri("http://www.example.com/");
try
{
ProxyUrl = WebRequest.DefaultWebProxy.GetProxy(url).ToString();
Log.Debug(url + " is using proxy " + ProxyUrl);
if (ProxyUrl == url.ToString() || ProxyUrl == url + "/"){
// A proxy is not in use here
ProxyUrl = "";
Log.Debug("No proxy is used for " + url);
}
else if (!String.IsNullOrEmpty(ProxyUrl)){
// A proxy is in use
ProxyAndCredentials.Proxy = new WebProxy(ProxyUrl);
Log.Debug("A proxy is used for " + url);
}
//Set credentials, in my experience it is better to always set these
ProxyAndCredentials.Credentials = CredentialCache.DefaultNetworkCredentials;
ProxyAndCredentials.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
}
catch (Exception p)
{
//Handle Exception
}
}
I need to send hundreds of newsletters, but would like to check first if email exists on server. It's called SMTP validation, at least I think so, based on my research on Internet.
There's several libraries that can do that, and also a page with open-source code in ASP Classic (http://www.coveryourasp.com/ValidateEmail.asp#Result3), but I have hard time reading ASP Classic, and it seems that it uses some third-party library...
Is there some code for SMTP validation in C#, and/or general explanation of how it works?
Be aware that most MTAs (Mail Transfer Agent) will have the VRFY command turned off for spam protection reasons, they'll probably even block you if you try several RCPT TO in a row (see http://www.spamresource.com/2007/01/whatever-happened-to-vrfy.html). So even if you find a library to do that verification, it won't be worth a lot. Ishmaeel is right, the only way to really find out, is sending an email and see if it bounces or not.
#Hrvoje: Yes, I'm suggesting you monitor rejected emails. BUT: not all the bounced mails should automatically end up on your "does not exist"-list, you also have to differentiate between temporary (e.g. mailbox full) and permanent errors.
SMTP is a text based protocol carried over TCP/IP.
Your validation program needs to open a TCP/IP connection to the server's port 25 (SMTP), write in a few lines and read the answer. Validation is done (but not always) on the "RCTP TO" line and on the "VFRY" line.
The SMTP RFC describes how this works (see Green#Beta.ARPA below, S are lines sent by the client, R are lines received from the server):
Example of the SMTP Procedure
This SMTP example shows mail sent by Smith at host Alpha.ARPA,
to Jones, Green, and Brown at host Beta.ARPA. Here we assume
that host Alpha contacts host Beta directly.
S: MAIL FROM:
R: 250 OK
S: RCPT TO:
R: 250 OK
S: RCPT TO:
R: 550 No such user here
While it's true that many domains will return false positives because of abuse, there are still some great components out there that will perform several levels of validation beyond just the SMTP validation. For example, it's worth it to check first to see if at least the domain exists. I'm in the process of compiling my own list of resources related to this question which you can track here:
http://delicious.com/dworthley/email.validation (broken link)
For those who might want to add to this list, I'll also include what I currently have here:
aspNetMX
.NET Email Validation Wizard Class Library
MONOProg Email Validator.Net
For a bulletproof form and a great user experience, it's helpful to validate as many aspects of the email address as possible. I can see from the aspNetMX validator that they check:
the syntax
the email against a list of bad email addresses
the domain against a list of bad domains
a list of mailbox domains
whether or not the domain exists
whether there are MX records for the domain
and finally through SMTP whether or not a mailbox exists
It's this last step that can be circumvented by administrators by returning true to basically all account verification requests, but in most cases if the user has intentionally entered a bad address it's already been caught. And if it was user error in the domain part of the address, that will be caught too.
Of course, a best practice for using this kind of a service for a registration screen or form would be to combine this kind of validation with a verification process to ensure that the email address is valid. The great thing about using an email validator in front of a verification process is that it will make for a better overall user experience.
You can try the below code, it works fine for me :
public class EmailTest {
private static int hear(BufferedReader in) throws IOException {
String line = null;
int res = 0;
while ((line = in.readLine()) != null) {
String pfx = line.substring(0, 3);
try {
res = Integer.parseInt(pfx);
} catch (Exception ex) {
res = -1;
}
if (line.charAt(3) != '-')
break;
}
return res;
}
private static void say(BufferedWriter wr, String text) throws IOException {
wr.write(text + "\r\n");
wr.flush();
return;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
private static ArrayList getMX(String hostName) throws NamingException {
// Perform a DNS lookup for MX records in the domain
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
Attribute attr = attrs.get("MX");
// if we don't have an MX record, try the machine itself
if ((attr == null) || (attr.size() == 0)) {
attrs = ictx.getAttributes(hostName, new String[] { "A" });
attr = attrs.get("A");
if (attr == null)
throw new NamingException("No match for name '" + hostName + "'");
}
/*
Huzzah! we have machines to try. Return them as an array list
NOTE: We SHOULD take the preference into account to be absolutely
correct. This is left as an exercise for anyone who cares.
*/
ArrayList res = new ArrayList();
NamingEnumeration en = attr.getAll();
while (en.hasMore()) {
String mailhost;
String x = (String) en.next();
String f[] = x.split(" ");
// THE fix *************
if (f.length == 1)
mailhost = f[0];
else if (f[1].endsWith("."))
mailhost = f[1].substring(0, (f[1].length() - 1));
else
mailhost = f[1];
// THE fix *************
res.add(mailhost);
}
return res;
}
#SuppressWarnings("rawtypes")
public static boolean isAddressValid(String address) {
// Find the separator for the domain name
int pos = address.indexOf('#');
// If the address does not contain an '#', it's not valid
if (pos == -1)
return false;
// Isolate the domain/machine name and get a list of mail exchangers
String domain = address.substring(++pos);
ArrayList mxList = null;
try {
mxList = getMX(domain);
} catch (NamingException ex) {
return false;
}
/*
Just because we can send mail to the domain, doesn't mean that the
address is valid, but if we can't, it's a sure sign that it isn't
*/
if (mxList.size() == 0)
return false;
/*
Now, do the SMTP validation, try each mail exchanger until we get
a positive acceptance. It *MAY* be possible for one MX to allow
a message [store and forwarder for example] and another [like
the actual mail server] to reject it. This is why we REALLY ought
to take the preference into account.
*/
for (int mx = 0; mx < mxList.size(); mx++) {
boolean valid = false;
try {
int res;
//
Socket skt = new Socket((String) mxList.get(mx), 25);
BufferedReader rdr = new BufferedReader(new InputStreamReader(skt.getInputStream()));
BufferedWriter wtr = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
res = hear(rdr);
if (res != 220)
throw new Exception("Invalid header");
say(wtr, "EHLO rgagnon.com");
res = hear(rdr);
if (res != 250)
throw new Exception("Not ESMTP");
// validate the sender address
say(wtr, "MAIL FROM: <tim#orbaker.com>");
res = hear(rdr);
if (res != 250)
throw new Exception("Sender rejected");
say(wtr, "RCPT TO: <" + address + ">");
res = hear(rdr);
// be polite
say(wtr, "RSET");
hear(rdr);
say(wtr, "QUIT");
hear(rdr);
if (res != 250)
throw new Exception("Address is not valid!");
valid = true;
rdr.close();
wtr.close();
skt.close();
} catch (Exception ex) {
// Do nothing but try next host
ex.printStackTrace();
} finally {
if (valid)
return true;
}
}
return false;
}
public static void main(String args[]) {
String testData[] = { "rahul.saraswat#techblue.com", "rahul.saraswat#techblue.co.uk", "srswt.rahul12345#gmail.com",
"srswt.rahul#gmail.com" };
System.out.println(testData.length);
for (int ctr = 0; ctr < testData.length; ctr++) {
System.out.println(testData[ctr] + " is valid? " + isAddressValid(testData[ctr]));
}
return;
}
}
Thanks & Regards
Rahul Saraswat
The Real(TM) e-mail validation is trying to send something to the address, and seeing if it is rejected/bounced. So, you'll just have to send them away, and remove the addresses that fail from your mailing list.
Don't take this the wrong way, but sending newsletters to more than a handful of people these days is a fairly serious matter. Yes, you need to be monitoring bounces (rejected emails) which can occur synchronously during the SMTP send (typically if the SMTP server you are connected to is authoritative), or asynchronously as a system-generated email message that occurs some amount of time after the SMTP send succeeded.
Also keep the CAN-SPAM Act in mind and abide by the law when sending these emails; you've got to provide an unsub link as well as a physical street address (to both identify you and t0 allow users to send unsub requests via snail-mail if they so choose).
Failure to do these things could get your IP null-routed at best and sued at worst.
You may need this Email Validator component for .NET
Here is the code example:
// Create a new instance of the EmailValidator class.
EmailValidator em = new EmailValidator();
em.MessageLogging += em_MessageLogging;
em.EmailValidated += em_EmailValidationCompleted;
try
{
string[] list = new string[3] { "test1#testdomain.com", "test2#testdomain.com", "test3#testdomain.com" };
em.ValidateEmails(list);
}
catch (EmailValidatorException exc2)
{
Console.WriteLine("EmailValidatorException: " + exc2.Message);
}