I got a “XPath Injection” issue from Fortify scan for below code,
string username = string.Empty;
string password = string.Empty;
string officePrefix = "";
if (!String.IsNullOrEmpty(securityNode.Prefix))
{
officePrefix = securityNode.Prefix + ":";
ns.AddNamespace(securityNode.Prefix, securityNode.Namespace);
}
var regexPattern =
ConfigurationManager.AppSettings["xxx"];
var regexItem = new Regex(regexPattern, RegexOptions.None);
if(regexItem.IsMatch(officePrefix ))
{
//wsse:UsernameToken
XmlNode usernameTokenNode = securityNode.SelectSingleNode(officePrefix +
"UsernameTkn", ns);
username = usernameTokenNode.SelectSingleNode(officePrefix + "name", ns).InnerText;
password = usernameTokenNode.SelectSingleNode(officePrefix + "Pwd", ns).InnerText;
above code i am getting issue from ( XmlNode usernameTokenNode = securityNode.SelectSingleNode(officePrefix +
"UsernameToken", ns);) this line of code. So, I tried to use regex and as you can see in the code. Even though the xpath injection issue still persists. Can any one kindly give a solution for the xpath injection issue.
You don't need to re-use the namespace alias from the actual XML. you can use your own. The only thing is that the actual namespace must be the same
string username = string.Empty;
string password = string.Empty;
const string officePrefix = "myPrefix";
bool hasPrefix = !string.IsNullOrEmpty(securityNode.Namespace);
if (hasPrefix)
{
ns.AddNamespace(officePrefix, securityNode.Namespace);
}
XmlNode usernameTokenNode = securityNode.SelectSingleNode(hasPrefix ? officePrefix + ":UsernameTkn" : "UsernameTkn", ns);
username = usernameTokenNode.SelectSingleNode(hasPrefix ? officePrefix + ":name" : "name", ns).InnerText;
password = usernameTokenNode.SelectSingleNode(hasPrefix ? officePrefix + ":Pwd" : "Pwd", ns).InnerText;
I note that XName and XNode are newer and much easier to use, they are in the System.Xml.Linq library.
Related
I need to check whether a word is present in a JSON file or not. So if I'm searching for "root", then even though the word "byroots" contain root, it should give me false.
Here's my code
using (StreamReader r = new StreamReader("filename.json"))
{
string json1 = r.ReadToEnd();
if (json1.Contains("root"))
{
filename = path + #"" + branch + "-" + testsuite.Title + ".json";
}
}
I've also tried this condition:-
if (json1.IndexOf(testsuite.Title, StringComparison.OrdinalIgnoreCase) >= 0)
But I'm getting the same results.
Here's the json data
{
"LV": {
"build_number": "20180517.1",
"blah_blah": "blah",
"name": "byroots",
}
}
You should use Regex
var pattern = #"*root*";
Regex rgx = new Regex(pattern);
using (StreamReader r = new StreamReader("filename.json"))
{
string json1 = r.ReadToEnd();
if (rgx.IsMatch(json1))
{
filename = path + #"" + branch + "-" + testsuite.Title + ".json";
}
}
I am trying to construct a string which I want to use it to update a JSON.
The code is below
public string ConstructCylicLoop(string fieldName, int LoopCount, string BadDataLabel,string ImmediateParent)
{
string start = "";
string fullbody = "";
string end = "";
string body = "";
for (int i = 0; i < LoopCount; i++)
{
LoopTestData = (new ExcelUtilities().getAPITestData(ApplicationConfiguration.LoopSheetName));
body = "";
foreach (Dictionary<string, string> loopData in LoopTestData)
{
string ParentNode = "";
string Key = "";
string Data = "";
loopData.TryGetValue("ParentNode", out ParentNode);
loopData.TryGetValue("Key", out Key);
loopData.TryGetValue("Data", out Data);
if(ImmediateParent.Equals(ParentNode)) //&& Key.Equals(fieldName)
{
body = body + '"' + Key + '"' + ":" + '"' + Data + '"'+',';
}
}
body = body.Remove(body.Length - 1);
body = "{" + body + "},";
fullbody = fullbody + body;
}
fullbody = fullbody.Remove(fullbody.Length - 1);
return start + fullbody + end;
}
The issue with this code is it always returns a text like this
"{\"my_address_type\":\"primarypropertyaddress\",\"my_address-street\":\"52 Street\",\"my_address-suburb\":\"vinvent\",\"my_address-postcode\":\"2121\"}"
When I update this string to an JSON node, the server is not able to parse it and the issue is with the back slash. Is there a way to remove the back slash. so I get something like this..
"{"my_address_type":"primarypropertyaddress","my_address-street":"52 Street","my_address-suburb":"vinvent","my_address-postcode":"2121"}"
I tried all possibilities but not able to clear/remove the backslash. Any code snippet on removing the backslashes. Thanks in advance.
Im searching multiple text files and there are some lines missing which I'm trying to replace it with "NO DATA"
var GetNotes = new Regex(#"(?<=[A-Z0-9/jfc]</B>)([\s\Sa-z]*?[\s\S])(?=<tr><td>|<tr class=disabled>|</table><h4 class|[£])").Matches(set);
foreach (var Notes in GetNotes)
{
String NotesAtLine1 = File.ReadLines(FractionTwoData).ElementAtOrDefault(NotesPositionLine);
string NotesToString = Notes.ToString();
string replacement = Regex.Replace(NotesToString, #"\t|\n|\r", "");
File.AppendAllText(NotesData, NotesAtLine1 + replacement + Environment.NewLine);
NotesPositionLine++;
if (DebugChechBox.Checked == true)
{
Console.WriteLine("Notes are " + replacement);
NotesBox.Text = replacement;
}
}
if it finds my regex it works fine, but how do I get it to do something if it doesn't exist?
I create a list, add 2 columns and insert 2 items via c# Webservice. In SharePoint I cannot see the 2 columns, only Title. When I edit the items, I see the other columns. In SharePoint I can change the view to see the 2 columns. But how to change the view with Webservice?
I try this:
private void SetView(string listName, string viewName, String[] arr)
{
AllViews.Views viewService = new AllViews.Views();
viewService.Credentials = System.Net.CredentialCache.DefaultCredentials;
//from msdn
//string strQuery1 = "<Where><Gt><FieldRef Name=\"Title\" />" +
// "<Value Type=\"Title\"></Value>" + "</Gt></Where>" +
// "<OrderBy><FieldRef Name=\"Title\" /></OrderBy>";
string strQuery = "<Query><Where><IsNotNull><FieldRef Name=\"Title\" />" +
"</IsNotNull></Where></Query>";
string strRowLimit = "150";
string strViewFields = "";
int count = arr.Length;
for (int i = 0; i < count; i++)
{
strViewFields += "<FieldRef Name=\'" + arr[i] + "\'/>";
}
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
System.Xml.XmlNode ndRowLimit = xmlDoc.CreateNode(XmlNodeType.Element, "RowLimit", "");
System.Xml.XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
ndQuery.InnerXml = strQuery;
ndRowLimit.InnerXml = strRowLimit;
ndViewFields.InnerXml = strViewFields;
XmlNode retNode = viewService.AddView(listName, viewName, ndViewFields, ndQuery, ndRowLimit, "HTML", false)
}
All without error, but columns hidden in the list. Maybe the query is wrong. Or the way that I use. Any tipps for me? Searching results are all about the SharePoint.dll, but I need a way with Webservice.
Solution
Change strQuery to:
string strQuery = "<Where><IsNotNull><FieldRef Name=\"Title\" />" +
"</IsNotNull></Where>";
// is in Node ndQuery, dont need it again. Maybe a dirty trick to hide new Columns
Set the new View as default with UpdateView. Be sure to use the GUID from the view.
For viewProperties only the prop that you want to change
string strProp = "DefaultView =\"TRUE\"";
All works fine. Have a nice weekend.
I am having an issue when attempting to create a new user in active directory. I followed the steps provided in this link for using PrincipalContext (with the exception that I am only doing one user at a time when they are hired and entered into the system and not multiple so no loop is required). I am also using a UserPrincipal Extender.
Here is the code that I have:
protected void CreateUserPE()
{
try
{
PrincipalContext userCtx = new PrincipalContext(ContextType.Domain, DomainFQDN, DomainFull);
string UserName = txtFirstName.Text.ToLower() + " " + txtLastName.Text.ToLower();
string password = "superSecretPassword";
UserPrincipalsEx newUser = new UserPrincipalsEx(userCtx, UserName, password, true);
newUser.SamAccountName = txtFirstName.Text.ToLower() + "." + txtLastName.Text.ToLower();
newUser.UserPrincipalName = txtFirstName.Text.ToLower() + "." + txtLastName.Text.ToLower() + "#rasm.com";
newUser.EmployeeId = txtEmpID.Text;
newUser.LastName = txtLastName.Text;
newUser.GivenName = txtFirstName.Text;
newUser.DisplayName = txtFirstName.Text + " " + txtLastName.Text;
newUser.Name = txtFirstName.Text + " " + txtLastName.Text;
newUser.SetPassword(password);
newUser.HomePostalAddress = txtAddress.Text + ", " + txtCity.Text + ", " + txtState.Text + ", " + txtZip.Text;
newUser.CountryName = txtCountry.Text;
newUser.HomePhone = txtHomePhone.Text;
newUser.MobilePhone = txtMobilePhone.Text;
newUser.DateOfBirth = txtDOB.Text;
newUser.EmergencyContact = txtEmergencyCnt.Text;
newUser.EmergencyPhone = txtContactPhone.Text;
newUser.Relationship = ddlRelationship1.SelectedItem.ToString();
newUser.EmergencyContact2 = txtEmergencyCnt2.Text;
newUser.EmergencyPhone2 = txtContactPhone2.Text;
newUser.Relationship2 = ddlRelationship2.SelectedItem.ToString();
newUser.EyeColor = ddlEyeColor.SelectedItem.ToString();
newUser.HairColor = ddlHairColor.SelectedItem.ToString();
newUser.Height = txtHeight.Text;
newUser.Weight = txtWeight.Text;
newUser.Gender = ddlGender.SelectedItem.ToString();
newUser.PersonalEmail = txtPersonalEmail.Text;
newUser.PassportExpires = txtPassportExp.Text;
newUser.HomeBase = ddlHomeStation.SelectedItem.ToString();
newUser.WorkLocation = txtWorkLocation.Text;
newUser.PID = txtPID.Text;
newUser.Team = txtTeam.Text;
newUser.Manager = "CN=" + txtSupervisor.Text + "," + DomainFull;
newUser.Title = ddlJobTitle.SelectedItem.ToString();
newUser.JobCode = txtJobCode.Text;
newUser.PLC = txtPLC.Text;
newUser.BPLC = txtBPLC.Text;
newUser.Specialty = txtSpecialty.Text;
newUser.Position = txtPosition.Text;
newUser.DateOfHire = txtDOH.Text;
newUser.DateOnContract = txtDOC.Text;
newUser.TaskOrder = ddlTaskOrder.SelectedItem.ToString();
newUser.Classification = ddlClass.SelectedIndex.ToString();
newUser.Section = txtSection.Text;
newUser.GatePass = txtGatePass.Text;
newUser.GatePassExpires = txtGatePassExp.Text;
newUser.WorkPhone = txtWorkPhone.Text;
newUser.CompanyEmail = txtCompEmail.Text;
newUser.aKOEmail = txtMilEmail.Text;
newUser.aKOSponsor = txtMilEmailSp.Text;
newUser.CACSponsor = txtCacSponsor.Text;
newUser.CACSponsorEmail = txtCacSponsorEmail.Text;
newUser.CacCardExpires = txtCacExpires.Text;
newUser.Enabled = true;
newUser.ExpirePasswordNow();
newUser.Save();
newUser.Dispose();
}
catch
{
}
}
The program goes all the way to newUser.Save() and then throws the following error in the catch statement:
System.DirectoryServices.AccountManagement.PrincipalOperationException was caught
HResult=-2146233087
Message=The attribute syntax specified to the directory service is invalid.
Source=System.DirectoryServices.AccountManagement
ErrorCode=-2147016693
StackTrace:
at System.DirectoryServices.AccountManagement.ADStoreCtx.Insert(Principal p)
at System.DirectoryServices.AccountManagement.Principal.Save()
at Personnel_Employee.CreateUserPE() in c:\inetpub\wwwroot\TestingFolder\Personnel\Add\Employee.aspx.cs:line 263
InnerException: System.DirectoryServices.DirectoryServicesCOMException
HResult=-2147016693
Message=The attribute syntax specified to the directory service is invalid.
Source=System.DirectoryServices
ErrorCode=-2147016693
ExtendedError=87
ExtendedErrorMessage=00000057: LdapErr: DSID-0C090D11, comment: Error in attribute conversion operation, data 0, v23f0
StackTrace:
at System.DirectoryServices.DirectoryEntry.CommitChanges()
at System.DirectoryServices.AccountManagement.SDSUtils.ApplyChangesToDirectory(Principal p, StoreCtx storeCtx, GroupMembershipUpdater updateGroupMembership, NetCred credentials, AuthenticationTypes authTypes)
InnerException:
Where am I going wrong.
You can not update an attribute with null or empty. I personaly dislike solutions with dummy values. If you are using the context principle just simply check for null or empty and dont update if its the case like:
if (!string.IsNullOrEmpty(txtbox.Text)){ newUser.attributeName = txtbox.Text}
If you are using an directory entry instead of an usercontext you can do something like this:
string adPath = "LDAP://server.domain.com/CN=John,CN=Users,dc=domain,dc=com";
DirectoryEntry userEntry = new DirectoryEntry(adPath);
if (txtBox.text == "")
{
userEntry.Properties["proppertyName"].Clear();
}
else if (!string.IsNullOrEmpty(txtBox.text))
{
userEntry.Properties[attribute.Key].Value = txtBox.text;
}
// dont do a thing when txtBox.Text is empty
It looks like more code but its much easier to make a foreachloop for it if you have a list with all attribute like:
private void UpdateEntryAttributes(DirectoryEntry entry, Dictionary<string, string> attributes)
{
foreach (KeyValuePair<string, string> attribute in attributes)
{
entry.Properties[attribute.Key].Value = attribute.Value;
if (attribute.Value == "")
{
entry.Properties[attribute.Key].Clear();
}
else if (!string.IsNullOrEmpty(attribute.Value))
{
entry.Properties[attribute.Key].Value = attribute.Value;
}
}
This can happen when attempting to write either a null or empty string to an AD field that prohibits it. An easy way to check whether this is the problem is to temporarily replace all such values with a dummy string (length > 0) and then run the code again. If that works, you can attempt a fix by changing the offending value--with AD, sometimes if null doesn't work, then an empty string will work, or vice versa.