ColdFusion API using new http() and setMethod("POST") throwing 500 error - http

I have two ColdFusion sites in different servers.
I need to send a structure of an Agent (person) to be inserted in the other database server.
in the source server I wrote this code:
public Struct function addAgentToRemote(struct oAgent) {
local.stResult = {};
try {
myHttp = new http();
myHttp.setMethod("POST");
myHttp.setCharset("utf-8");
myHttp.setUrl(application.APIURL & "_com/API/agentAPI.cfc?method=addAgent");
myHttp.addParam(name="api_token", type="url", value=application.APIToken);
myHttp.addParam(name="agent", type="url", value=serializeJSON(arguments.oAgent));
local.stResult.data = myHttp.send().getPrefix();
} catch (Any excpt) {
local.stResult.success = false;
local.stResult.error = excpt;
}
return local.stResult;
}
In the destination server I wrote this code:
Remote String function addAgent(Required String api_token, Required String agent) {
local.stResult = newResult();
if (arguments.api_token NEQ application.APIToken) {
local.stResult.success = false;
local.stResult.error = "Wrong API Token...";
} else {
try {
agentDAO = new cfc.API.daos.agentDAO().init();
local.stResult = agentDAO.insertNewAgent(deserializeJSON(arguments.agent));
} catch (Any excpt) {
local.stResult.success = false;
local.stResult.error = excpt;
}
}
return serializeJSON(local.stResult);
}
I'm getting 500 error.
What is wrong ? My source or destination codes ?
Thanks.

Related

vulnerability from security team in forget password controller in asp .net

I have a controller form application and the security team they said there is a vulnerability you can put any user_id fom postman inside the controller like this
ForgotPassword/user_id
how I can remove this vulnerability check the code below:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult ForgotPassword(string emailId)
{
var helper = new Helper.Helper();
List<SqlParameter> args = new List<SqlParameter>();
args.Add(new SqlParameter("#Pin_email_id", emailId));
var req_resp = new Dictionary<string, object>();
try
{
using (DataSet dataset = helper.ExecuteSqlQuery("Web_Forgot_Password", args))
{
if (dataset != null && dataset.Tables.Count > 0 && dataset.Tables[0].Rows.Count > 0)
{
if (dataset.Tables[0].Rows[0]["Status"].ToString() == "Success")
{
req_resp["status"] = true;
req_resp["message"] = dataset.Tables[0].Rows[0]["Description"].ToString();
req_resp["code"] = dataset.Tables[0].Rows[0]["Code"].ToString();
string password = dataset.Tables[0].Rows[0]["user_password"].ToString();
SendForgotMail(emailId, dataset.Tables[0].Rows[0]["user_name"].ToString(), helper.Decrypt(password), dataset.Tables[0].Rows[0]["employee"].ToString());
return Json(req_resp);
}
else
{
req_resp["status"] = false;
req_resp["message"] = dataset.Tables[0].Rows[0]["Description"].ToString();
req_resp["code"] = dataset.Tables[0].Rows[0]["Code"].ToString();
return Json(req_resp);
}
}
else
{
req_resp["status"] = false;
req_resp["message"] = "Request Failed";
req_resp["code"] = "1005";
return Json(req_resp);
}
}
}
catch
{
var response = new
{
status = false,
message = "Request failed",
code = "1005"
};
return Json(response);
}
}
Well normally you store only password hashes in your database, which are not decryptable. Watching helper.Decrypt(password) in your code and sending the original password as a plain text in email is something painful. Normally I would just send a password reset link which can be used only once.
I checked the SqlParemater docs, it is added as a String value the way you use it, so it is not SQL injectable. Without the exact SQL I cannot tell much. I think they meant that it is SQL injectable, but then they should send evidence at least.

DotRas 1.3 dial created Vpn entry error from application but not from Windows

I'm using dotras to create a vpn connection. When I try to connect to the vpn using the dotras dial async method it doesn't work:
"Error 718: The connection was terminated because the remote computer did not respond in a timely manner".
So I tried connecting to the vpn connection i've just created via the windows interface and it works just fine. Strangely enough, I then tried to connect again via the dotras method and it worked!
So, if I try to connect first via dotras I can't, but if I connect first via windows, disconnect, and then connect again via dotras it works.
I'm using Windows 10 pro and Windows 2012 server and the version of DotRas is 1.3
Here is my code:
RasPhoneBook _allUsersPhoneBook;
public RasPhoneBook allUsersPhoneBook
{
get
{
_allUsersPhoneBook = new RasPhoneBook();
_allUsersPhoneBook.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));
return _allUsersPhoneBook;
}
set
{
_allUsersPhoneBook = value;
}
}
private RasDialer _dialer;
public RasDialer dialer
{
get
{
if (_dialer== null)
{
_dialer = new RasDialer();
_dialer.Error += new EventHandler<ErrorEventArgs>(Dialer_Error);
_dialer.StateChanged += new EventHandler<StateChangedEventArgs>(Dialer_StateChanged);
_dialer.EntryName = connectionName;
_dialer.PhoneBookPath = allUsersPhoneBook.Path;
}
return _dialer;
}
set
{
_dialer = value;
}
}
//Here I create the connection entry or if already exists update its properties
public void CreateOrUpdate()
{
using (dialer)
{
using (var allUsersPhoneBookLocal = new RasPhoneBook())
{
allUsersPhoneBookLocal.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers));
if (allUsersPhoneBook.Entries.Contains(connectionName))
{
allUsersPhoneBookLocal.Entries[connectionName].PhoneNumber = serverAddress;
allUsersPhoneBookLocal.Entries[connectionName].VpnStrategy = RasVpnStrategy;
allUsersPhoneBookLocal.Entries[connectionName].Device = RasDevice;
allUsersPhoneBookLocal.Entries[connectionName].Options.RemoteDefaultGateway = false;
allUsersPhoneBookLocal.Entries[connectionName].Options.IPv6RemoteDefaultGateway = false;
allUsersPhoneBookLocal.Entries[connectionName].Options.CacheCredentials = true;
allUsersPhoneBookLocal.Entries[connectionName].UpdateCredentials(new System.Net.NetworkCredential(userName, passWord));
allUsersPhoneBookLocal.Entries[connectionName].Update();
}
else
{
RasEntry entry = RasEntry.CreateVpnEntry(connectionName, serverAddress, RasVpnStrategy.IkeV2Only,
RasDevice);
entry.EncryptionType = RasEncryptionType.Optional;
entry.Options.IPv6RemoteDefaultGateway = false;
entry.Options.RemoteDefaultGateway = false;
entry.Options.CacheCredentials = true;
/*
dialer.EntryName = connectionName;
dialer.Credentials = new System.Net.NetworkCredential(userName, ConvertToSecureString(passWord));
dialer.PhoneBookPath = allUserPhoneBookPath;
*/
allUsersPhoneBook.Entries.Add(entry);
entry.UpdateCredentials(new System.Net.NetworkCredential(userName, ConvertToSecureString(passWord)));
// 26 means eap-mschapv2 username/password
entry.UpdateCredentials(new System.Net.NetworkCredential(userName, ConvertToSecureString(passWord)));
// entry.Options.RequireEap = true;
entry.CustomAuthKey = 26;
entry.Update();
entry.VpnStrategy = RasVpnStrategy;
entry.Update();
}
}
}
}
//here I dial the connection
public RasHandle Dial()
{
RasHandle handle = null;
try
{
using (allUsersPhoneBook)
{
if (allUsersPhoneBook.Entries.Contains(connectionName))
{
handle = dialer.DialAsync();
}
}
return handle;
}
catch (Exception)
{
throw;
}
}

WebAPI call hangs when return a large amount of data

I have a web api call that I recently added to my app. I returns a complete list of all countries, states and cities in the app (currently 486 rows) I perform this call when all of the reference data for my application loads (I have a base loading page and call the function in my startup class to load all the data there). The challenge is that the call to get all my countries.... hangs and eventually I get "The operation was canceled" error. If I modify my stored procedure that selects the data from the database on the server to only return say 20 rows, it runs fine. Any suggestions?
Below is the code from the startup class:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace GBarScene
{
class StartUpClass
{
public event GeneralDataLoad BaseDataLoadComplete;
public async Task<GBSStartUpEventArgs> ProcessStartup()
{
GBSStartUpEventArgs lobj_EventArgs;
lobj_EventArgs = new GBSStartUpEventArgs();
App.InStartUpDataLoad = true;
try
{
if (!App.IsGeolocationEnabled)
{
lobj_EventArgs.ErrorOccurred = true;
lobj_EventArgs.ShowRetry = true;
lobj_EventArgs.ShowWebSite = false;
lobj_EventArgs.ErrorMessage = resourcestrings.GetValue("NoLocationServicesMessage");
}
else if (!App.InternetIsAvailable)
{
lobj_EventArgs.ErrorOccurred = true;
lobj_EventArgs.ErrorMessage = resourcestrings.GetValue("NoInternetConnectionFound");
lobj_EventArgs.ShowRetry = true;
lobj_EventArgs.ShowWebSite = false;
}
else
{
Debug.WriteLine("Process StartUp");
await Task.Delay(500);
//Reset values
ViewModelObjects.DayOfWeek.DataLoadProcessed = false;
ViewModelObjects.Languages.DataLoadProcessed = false;
if (await ViewModelObjects.DayOfWeek.LoadData() == false)
// //try it once more
await ViewModelObjects.DayOfWeek.LoadData();
Debug.WriteLine("GBar After DayofWeek Load");
await ViewModelObjects.Languages.LoadData();
Debug.WriteLine("GBar After Languages Load");
if ((ge_AppMode)ViewModelObjects.AppSettings.AppMode == ge_AppMode.CitySelected)
{
//We need to reload the NearbyCities and set the selected one
await ViewModelObjects.NearbyCities.LoadData();
}
Debug.WriteLine("Before load of coutries");
await ViewModelObjects.CountryStateCity.LoadData();
Debug.WriteLine("After load of coutries");
Debug.WriteLine("Count: " + ViewModelObjects.CountryStateCity.CountryItems_ForList.Count.ToString());
ViewModelObjects.NumberOfResults.LoadData();
ViewModelObjects.Perspectives.LoadData();
ViewModelObjects.SearchRadiuses.LoadData();
ViewModelObjects.UseMetric.LoadData();
while (!ViewModelObjects.DayOfWeek.DataLoadProcessed && !ViewModelObjects.Languages.DataLoadProcessed && !App.IsGeolocationEnabled)
{
await Task.Delay(100);
}
if (App.BaseDataLoadError)
{
lobj_EventArgs.ErrorOccurred = true;
lobj_EventArgs.ShowRetry = true;
lobj_EventArgs.ShowWebSite = true;
lobj_EventArgs.ErrorMessage = resourcestrings.GetValue("ErrorLoadingReferenceData");
}
}
Debug.WriteLine("StartUp Process Ended");
BaseDataLoadComplete(this, lobj_EventArgs);
}
catch (Exception ex)
{
App.ProcessException(ex);
}
App.InStartUpDataLoad = false;
return lobj_EventArgs;
}
}
}
This is the helper class that makes all the WebAPI calls:
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace GBarScene
{
public class WebAPICaller: IDisposable
{
HttpClient iobj_HTTPClient = null;
public void Dispose()
{
if (iobj_HTTPClient != null)
iobj_HTTPClient.Dispose();
}
public async Task<string> HTTPGetWebServiceAsync(string ps_URI)
{
string ls_Response = "";
string ls_JSONData = "";
string ls_Prefix = "";
try
{
iobj_HTTPClient = await GetClient();
switch (Device.RuntimePlatform)
{
case Device.Android:
ls_Prefix = App.APIStandardPrefix;
break;
//case Device.Android:
// ls_Prefix = App.APISecurePrefix;
// break;
//case Device.Windows:
//case Device.WinPhone:
// ls_Prefix = App.APISecurePrefix;
// break;
default:
ls_Prefix = App.APISecurePrefix;
break;
}
Debug.WriteLine("before api call");
iobj_HTTPClient.BaseAddress = new Uri(ls_Prefix);
ls_JSONData = await iobj_HTTPClient.GetStringAsync(ps_URI);
Debug.WriteLine("after api call");
ls_Response = System.Net.WebUtility.HtmlDecode(ls_JSONData);
}
catch (Exception ex)
{
Debug.WriteLine("api call error");
App.ProcessException(ex);
}
return ls_Response;
}
public async Task<bool> HTTPPostWebService(string ps_URI, object pobj_BodyObject)
{
HttpResponseMessage lobj_HTTPResponse = null;
bool lb_Response = false;
HttpContent lobj_Content = null;
try
{
if (iobj_HTTPClient != null)
iobj_HTTPClient = await GetClient();
iobj_HTTPClient.BaseAddress = new Uri(App.APISecurePrefix);
lobj_Content = new StringContent(JsonConvert.SerializeObject(pobj_BodyObject == null ? "" : pobj_BodyObject));
lobj_Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
lobj_HTTPResponse = await iobj_HTTPClient.PostAsync(ps_URI, lobj_Content);
if (!lobj_HTTPResponse.IsSuccessStatusCode)
{
Exception lobj_Exception = new Exception(lobj_HTTPResponse.ToString());
lobj_Exception.Source = "HTTPGetWebService for: " + ps_URI;
App.ProcessException(lobj_Exception);
}
else
{
lb_Response = true;
}
}
catch (Exception ex)
{
App.ProcessException(ex);
}
finally
{
if (lobj_HTTPResponse != null)
{
lobj_HTTPResponse.Dispose();
}
//Debug.WriteLine("WebAPICaller-CallWebService-1: Done");
}
return lb_Response;
}
private async Task<HttpClient> GetClient()
{
HttpClient lobj_HTTPClient = null;
if (lobj_HTTPClient == null)
{
lobj_HTTPClient = new HttpClient();
lobj_HTTPClient.DefaultRequestHeaders.Add("Accept", "application/json");
lobj_HTTPClient.MaxResponseContentBufferSize = 2147483647;
lobj_HTTPClient.Timeout = new TimeSpan(0,0,0,0,60000);
}
return lobj_HTTPClient;
}
}
}
Sorry I forget to include the method in the CountryStateCity view model that calls the webapi helper class.
public async Task<bool> LoadData()
{
string ls_Response = "";
string ls_WorkURI = "";
WebAPICaller lobj_WebAPICaller = null;
bool lb_DataLoaded = false;
try
{
IsDataLoaded = false;
//Debug.WriteLine("City Data Load");
lobj_WebAPICaller = new WebAPICaller();
ls_WorkURI = ic_CoutryStateCityAPIUrl.Replace("{Language}", "EN");
ls_Response = await lobj_WebAPICaller.HTTPGetWebServiceAsync(ls_WorkURI);
if (ls_Response.Trim().Length == 0)
{
AddErrorEntry();
}
else
{
CountryItems_ForList = new ObservableCollection<GBSCountry_ForList>();
StateItems_ForList = new ObservableCollection<GBSState_ForList>();
CityItems_ForList = new ObservableCollection<GBSCity_ForList>();
iobj_CountryStateCity = JsonConvert.DeserializeObject<ObservableCollection<GBSCountryStateCity>>(ls_Response);
//Now load the display lists
CountryItems_ForList = new ObservableCollection<GBSCountry_ForList>(
(from lobj_Country in iobj_CountryStateCity
select new GBSCountry_ForList()
{
ID = lobj_Country.Country_Code,
Value = lobj_Country.Country_Name_Text
}).Distinct().ToList());
CountryItems_ForList.Insert(0, new GBSCountry_ForList
{
ID = "XX",
Value = "Base Value"
});
lb_DataLoaded = true;
}
}
catch (Exception ex)
{
AddErrorEntry();
App.ProcessException(ex);
}
finally
{
IsDataLoaded = true;
if (lobj_WebAPICaller != null)
lobj_WebAPICaller.Dispose();
}
return lb_DataLoaded;
}
So after much time, I believe I figured out what the problem is. The problem started to manifest itself again with smaller amounts of data and I could not figure out why. The problem appeared. The issue appears to be the IP address I was using. (I was using the IP address of the actual laptop I was hosting both the App and WebAPIs on.) It appears you have to use one of the other network adaptors for the emulator to have this work reliably.
Here are the steps I used to resolved this:
I launched my Windows 10 mobile emulator.
Click on the >> (Tools) icon in the tool bar of the emulator.
Click on the Network tab of the Additional Tools window.
Look in the list for the network adaptor labeled Desktop Adaptor #1 and copy the IP address.
Edit the Applicationhost.config file in the folder of the WebAPI project.
Find the entry in the file for site name="XXXXX" where XXXXX is the name of the Visual Studio project you are hosting your WebAPIs in.
Within the section of the entry for your WebAPI project, add a binding for the IP address you copied from in step 4. It should look something like this:
<binding protocol="http" bindingInformation="*:56952:169.254.69.220" />
Where 56952 is the port my IIS Express is hosting the WebAPIs on and 169.254.69.220 is the IP address I copied from step 4. After adding this, I was able to connect to locally hosted WebAPIs in IIS Express.
Hope this helps.

Directory levels Quotas on remote shared folder

I have 2 servers in AD (2008R2)
On one of them I have shared folder (c:\Shared\dirForUserAAA ==> \DC1\dir1)
On other one I have c# program that must manage folder quota on \DC1\dir1
Is it possible and how it can be done?
I try to use this piece of code, but it works only on local paths :(
public static void SetQuotaToFolder(string UNCPathForQuota, int quotaLimitBytes)
{
if (!Directory.Exists(UNCPathForQuota))
{
Directory.CreateDirectory(UNCPathForQuota);
}
// Create our interface
IFsrmQuotaManager FSRMQuotaManager = new FsrmQuotaManagerClass();
IFsrmQuota Quota = null;
try
{
// First we need to see if there is already a quota on the directory.
Quota = FSRMQuotaManager.GetQuota(UNCPathForQuota);
// If there is quota then we just set it to our new size
Quota.QuotaLimit = quotaLimitBytes;
}
catch (COMException e)
{
unchecked
{
if (e.ErrorCode == (int)0x80045301)
{
// There is no quota on this directory so we need to create it.
Quota = FSRMQuotaManager.CreateQuota(UNCPathForQuota);
// And then set our desired quota
Quota.QuotaLimit = quotaLimitBytes;
}
else
{
// some other COM exception occured so we return the error
Console.WriteLine(e);
return;
}
}
}
catch (Exception e)
{
// Generic error handling would go here
Console.WriteLine(e);
return;
}
// and finally we commit our changes.
Quota.Commit();
}
}
Old Question, but if someone needs a hint:
Open a RemotePowershell on the server where your folders are saved. Then use the Cmdlets from here
Some code snippets:
Open Runspace:
public static Runspace CreateAndOpen(string domain, string username, string password, string computername)
{
string userName = username + "#" + domain;
var securePassword = password.ToSecureString();
PSCredential credential = new PSCredential(username, securePassword);
var connectionInfo = new WSManConnectionInfo(false, computername, 5985, "/wsman", shellUri, credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
connectionInfo.OpenTimeout = 2 * 60 * 1000; // 2 minutes
Runspace powershellRunspace = RunspaceFactory.CreateRunspace(connectionInfo);
powershellRunspace.Open();
return powershellRunspace;
}
Set a quota on a path
public void SetQuotaTemplateOnPath(Runspace runspace, string path, string template)
{
using (var pipe = runspace.CreatePipeline())
{
var newFsrmQuotaCommand = new Command("New-FsrmQuota");
newFsrmQuotaCommand.Parameters.Add("Path", path);
newFsrmQuotaCommand.Parameters.Add("Template", template);
newFsrmQuotaCommand.Parameters.Add("Confirm", false);
pipe.Commands.Add(newFsrmQuotaCommand);
var results = pipe.Invoke();
if (pipe.Error.Count > 0)
{
//Handle error
}
}
}

GetMessageCount() returns 0 (zero)

public class _Variable
{
public bool MailStat;
public Pop3Client pop3;
public int lastmailCount;
public int currentmailCount;
public Message msg;
public MessagePart msgPart;
public Timer _timer;
}
public List<int> _MailReader()
{
_Variable _var = new _Variable();
try
{
//HttpContext.Current.Session["Pop3Client"]
if (HttpContext.Current.Session["Pop3Client"] == null)
{
_var.pop3 = new Pop3Client();
_var.pop3.Connect("pop.gmail.com", 995, true);
_var.MailStat = _var.pop3.Connected;
_var.pop3.Authenticate("nithin.testing1#gmail.com", "xxxxxxx");
HttpContext.Current.Session["Pop3Client"] = _var.pop3;
}
else
{
_var.pop3 = (Pop3Client)HttpContext.Current.Session["Pop3Client"];
}
if (_var.MailStat)
{
//HttpContext.Current.Application["lastmailCount"] = _var.pop3.GetMessageCount();
_var.currentmailCount = _var.pop3.GetMessageCount();
_var.lastmailCount = _global.lastmailCount;
if (_var.lastmailCount < _var.currentmailCount)
{
_global.lastmailCount = _var.currentmailCount;
int _diff = _var.currentmailCount - _var.lastmailCount;
for (int _loop = _var.currentmailCount; _diff > 0; _diff--)
{
_var.msg = _var.pop3.GetMessage(_loop-(_diff-1));
_var.msgPart = _var.msg.MessagePart.MessageParts[0];
string bodyPart = _var.msgPart.BodyEncoding.GetString(_var.msgPart.Body).ToString().Trim();
int _result;
if (int.TryParse(bodyPart, out _result))
{
_global._vbill.Add(Int32.Parse(bodyPart));
_global._vDate.Add(_var.msg.Headers.DateSent.ToString());
}
}
}
}
_var.pop3.Dispose();
return _global._vbill;
}
catch (Exception ex)
{
return _global._vbill;
}
}
I am using the OpenPop.dll and In the following code pop.getMessageCount is returning zero even there are mails in my account.
_Variable method contains all the variables I used in the code and in _MailReader. I am just reading all my mails from my application and returning into a list but this is the problem count is zero always.
It's a feature of gmail pop3 server. By default, you can receive only unread messages. That means, if you or somebody else already has downloaded certain message once, it will not be possible to receive it by pop3 protocol anymore.
To avoid it, you have to configure your gmail account. Check "Enable POP for all mail (event mail that's already been downloaded)" in "Forwarding and POP/IMAP" section of gmail settings.
Screenshot: http://i.stack.imgur.com/UE7ip.png

Resources