ASP.NET Bind and Query LDAP - asp.net

So I have been driving myself crazy trying to figure out why I can't get my LDAP search to work.
private String getDNFromLDAP(String strUID)
{
String strDN = "";
//Create an LDAP Entry Object
DirectoryEntry entry = new DirectoryEntry("LDAP://something.blah.com/cn=people,dc=blah,dc=com");
entry.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;
entry.Username = "cn=myaccount,cn=special,dc=blah,dc=com";
entry.Password = "supersecret";
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.SearchScope = SearchScope.Subtree;
mySearcher.Filter = "(uid=" + strUID + ")";
SearchResult result = mySearcher.FindOne();
int nIndex = result.Path.LastIndexOf("/");
strDN = result.Path.Substring((nIndex + 1)).ToString().TrimEnd();
//Clean up objects
entry.Close();
entry.Dispose();
mySearcher.Dispose();
//returns the DN
return strDN;
}
I know the object I am searching for exist (confirmed with ldapsearch), but my result keeps coming back empty. I suspect there is an issue with the base dn, but I don't know how to confirm what what DirectorySearch is using as the base dn. Any help at all would be appreciated.

You set the root using the searchroot property. The root is set to entry you pass on the constructor, so this might be why you can't find your entry.

Related

SqlQuerySpec parameterized query returns no results

I'm not sure whether it is an emulator issue or not but i have a really simple query
var collectionUri = UriFactory.CreateDocumentCollectionUri(Constants.CosmosDbName, CollectionName);
var spec = new SqlQuerySpec()
{
QueryText = "SELECT * FROM Users u WHERE u.firstName = #firstname",
Parameters = new SqlParameterCollection
{
new SqlParameter{
Name = "#firstname",
Value = value
}
}
};
var query = client.CreateDocumentQuery<User>(collectionUri, spec);
var users = await query.ToListAsync();
the parametrized query returns no results i.e. 0 users
while the same plain query below retuns 1 user that matches the WHERE condition:
spec.Parameters.Clear();
spec.QueryText = $"SELECT * FROM Users u WHERE u.firstName = '{value}'";
query = client.CreateDocumentQuery<User>(collectionUri, spec);
users = await query.ToListAsync(); // returns 1 user
do I need somehow explicitly enable parameterized queries
or am I doing something wrong above with a parameterized query?
According to the Syntax, your query should be like this,
SqlQuerySpec sqlQuerySpec = new SqlQuerySpec
{
QueryText = #"SELECT *
FROM Users u
WHERE u.u.firstName = #firstname",
Parameters = new SqlParameterCollection
{
new SqlParameter("#firstname", value)
}
};
The issue is a kind of var pitfall
the SqlParameter value was taken from an Azure function HttpRequest request:
var value = req.Query["firstname"];
which is
Microsoft.Extensions.Primitives.StringValues value = req.Query["firstname"];
When SqlParameter is created with value of StringValues type it makes slightly different query:
SELECT * FROM Users u WHERE u.firstName = ['Dima']
the brackets ['Dima'] here are excess
the correct query must be without brackets
SELECT * FROM Users u WHERE u.firstName = 'Dima'
so to fix the parameterized query the parameter value should be a string
new SqlParameter("#firstname",value.ToString())

Npgsql passing an array of parameters

I am new in using Npgsql and I tried to make an helper in my asp.net project so that I can call it conveniently in my controllers method.
npgsqlqueryhelper
public DataSet ExecuteQueryWithParams(string commandText, params NpgsqlParameter[] parameters)
{
using (var connection = npgsqlcon.GetnpgsqlConnection())
using (NpgsqlCommand command = new NpgsqlCommand(commandText, connection))
{
DataSet ds = new DataSet();
command.Parameters.AddRange(parameters);
command.CommandTimeout = 5000;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
da.Fill(ds);
connection.Close();
return ds;
}
}
My Controller Method
List<rollingPAR> rollingparlist = new List<rollingPAR>();
npgsqlhelper = new npgsqlQueryHelper();
NpgsqlParameter[] parameterList = {
new NpgsqlParameter("#lid", r.lid),
new NpgsqlParameter("#posting_date", r.date_end)
};
var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status()", parameterList).Tables[0];
rollingparlist = table.AsEnumerable().Select(row => new rollingPAR
{
get_payment_status = row.Field<int>("get_payment_status")
}).ToList();
As I tried to run my program, I always encountered an error saying that function ln.get_payment_status() does not exist but when I tried to supply the parameters directly on the query
(e.g var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status(1231,'06-18-2019')", parameterList).Tables[0];)
It gives me the data that I need. I don't know what is my mistake and I'm stuck here since yesterday. Can anyone help me with this? TIA
The parameter place holders are not automatically included in the function call. Try adding them:
var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status(#lid,#posting_date)", parameterList).Tables[0];
With the help of Sir #JGH, it turns out that my query is missing the parameter placeholders but after I edit it, I encountered an error regarding the datatype between the asp.net datetime and postgresql date so I added this code to remove the error.
parameterList[1].NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Date;
So here is now the new code:
List<rollingPAR> rollingparlist = new List<rollingPAR>();
npgsqlhelper = new npgsqlQueryHelper();
NpgsqlParameter[] parameterList = {
new NpgsqlParameter("#lid", r.lid),
new NpgsqlParameter("#posting_date", r.date_end)
};
parameterList[1].NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Date;
var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status(#lid,#posting_date)", parameterList).Tables[0];
rollingparlist = table.AsEnumerable().Select(row => new rollingPAR
{
get_payment_status = row.Field<int?>("get_payment_status")
}).ToList();
Thank you sir #JGH

Allowing the attacker to access unathorized records finding

I have a scan finding and hope someone can provide any ideas as to best ways to resolve the issue. First I will show the scan Finding then my code and finally what the scanner's recommended solution is.
Finding
Without proper access control, the method GetAttributeKey() in Provider.cs can execute a SQL statement on line 163 that contains an attacker-controlled primary key, thereby allowing the attacker to access unauthorized records.
Rather than relying on the presentation layer to restrict values submitted by the user, access control should be handled by the application and database layers. Under no circumstances should a user be allowed to retrieve or modify a row in the database without the appropriate permissions. Every query that accesses the database should enforce this policy, which can often be accomplished by simply including the current authenticated username as part of the query.
My Code:
Offending line:
myParam.SqlParam.Value = attribute;
Method:
public string GetAttributeKey(string attribute)
{
string qry = "SELECT ws_attribute_key FROM webservice_attributes WHERE ws_attribute = #attribute";
QueryContainer Instance = new QueryContainer(qry);
MyParam myParam = new MyParam();
myParam.SqlParam = new SqlParameter("#attribute", Instance.AddParameterType(_DbTypes._string));
myParam.SqlParam.Value = attribute;
Instance.parameterList.Add(myParam);
object key = ExecuteScaler(Instance);
return Convert.ToString(key);
}
Scanner's Recommend fix:
string user = ctx.getAuthenticatedUserName();
int16 id = System.Convert.ToInt16(invoiceID.Text);
SqlCommand query = new SqlCommand(
"SELECT * FROM invoices WHERE id = #id AND user = #user", conn);
query.Parameters.AddWithValue("#id", id);
query.Parameters.AddWithValue("#user", user);
SqlDataReader objReader = query.ExecuteReader();
I think the problem is dealing with the code calling the GetAttributeKey. The method is called only if the user has no access to to the Attribute. I think I need some type of checking. Here is the calling code:
if (result.Rows.Count > 0)
{
// get the attribute
DataRow[] rows = result.Select("ws_attribute = '" + attribute + "'");
if (rows.Length > 0)
{
// check time range
string hr = DateTime.Now.Hour.ToString();
DataRow[] valid = result.Select("ws_attribute = '" + attribute + "' AND start_time <= " + hr + " AND end_time >= " + hr);
if (valid.Length > 0)
{
ws_user_attribute_key = Convert.ToInt32(valid[0]["ws_user_attribute_key"].ToString());
ret = true;
// generate salt
TextEncryptor te = new TextEncryptor();
salt = te.CreateSalt(8);
// save to the log, return false if failed to log
if (!LogTransfer(ipAddress, accessDate, fileName, ws_user_attribute_key, salt, out logKey))
return false;
}
else
{
ret = false;
LogInvalidAccess(username, rows[0]["ws_attribute_key"].ToString(), ipAddress, accessDate, WSInvalidAccessReason.OutsideValidTimeRange);
}
}
else
{
// if user has no access to attribute
ret = false;
LogInvalidAccess(username, GetAttributeKey(attribute), ipAddress, accessDate, WSInvalidAccessReason.AttributeNotAccessible);
}
}
else
{
ret = false;
LogInvalidAccess(username, GetAttributeKey(attribute), ipAddress, accessDate, WSInvalidAccessReason.InvalidAccount);
}

Updated Google Analytic API and older version

Before Google Analytic Update there api this code works.
string userName = GAEmailAddress.ToString();//Its From Database
string passWord = GAPassword.ToString();//Its From Database
const string dataFeedUrl = "https://www.google.com/analytics/feeds/data";
AccountQuery query = new AccountQuery();
AnalyticsService service = new AnalyticsService("AnalyticsApp");
if (!string.IsNullOrEmpty(userName))
{
service.setUserCredentials(userName, passWord);
}
string str = "";
try
{
AccountFeed accountFeed = service.Query(query);
foreach (AccountEntry entry in accountFeed.Entries)
{
str = entry.ProfileId.Value;
}
DataQuery query1 = new DataQuery(dataFeedUrl);
// Bounce Rate Calculations
query1.Ids = str;
query1.Metrics = "ga:visits,ga:bounces";//visitors
query1.Sort = "ga:visits";
query1.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");
query1.StartIndex = 1;
//Others code and other data for bound
I search in SO and and Find this link.
gapi account data url goes to 404
I replace this link :
const string dataFeedUrl = "https://www.google.com/analytics/feeds/data";
with:
https://www.googleapis.com/analytics/v2.4/management/accounts?start-index=1&max-results=100&key=API_KEY
But I still I gett error:
Execution of request failed: https://www.google.com/analytics/feeds/accounts/default
I still search and find this link:
https://developers.google.com/analytics/devguides/reporting/core/v2/#register
As link says I replace :
https://www.googleapis.com/analytics/v2.4/data
But still I got error ? What I am missing here? Thanks.

ASIN List on Products API?

Morning,
I am trying to pass a list of Amazon ASIN's so i can process them using the MWS API.
List<string> prodASINs = dc.aboProducts.Select(a => a.asin).ToList();
var count = prodASINs.Count();
//Loop through passing 10 at a time to AWS
for (var i = 0; i < count; i++)
{
var prodASINToSend = prodASINs.Skip(i * 10).Take(10).ToList();
//Send to AWS
MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig();
config.ServiceURL = productsURL;
MarketplaceWebServiceProducts.MarketplaceWebServiceProductsClient service = new MarketplaceWebServiceProductsClient(appname, version, accesskeyID, secretkey, config);
GetLowestOfferListingsForASINRequest request = new GetLowestOfferListingsForASINRequest();
request.SellerId = merchantID;
request.MarketplaceId = marketids[0];
request.ItemCondition = condition;
request.ASINList.ASIN = prodASINToSend;
However the request.ASINList.ASIN = prodASINToSend; is saying "Object reference not set to an instance of an object." However it is passing over the required List<string> prodASINToSend
Could anyone shed some light on this for em please?
The error means you forgot to declare a new instance of a class before trying to use the class object.
In your case the ASINList will need to be declared as a new instance of the ASINList class.

Resources