/// <summary> /// call a webconnector /// </summary> public List <object> CallWebConnector( string AModuleName, string methodname, SortedList <string, object> parameters, string expectedReturnType) { NameValueCollection Parameters = ConvertParameters(parameters); string result; try { result = THTTPUtils.PostRequest(ServerURL + "/server" + AModuleName + ".asmx/" + methodname.Replace(".", "_"), Parameters); } catch (Exception e) { if (e.Message == THTTPUtils.SESSION_ALREADY_CLOSED) { TLogging.Log("session has already been closed!"); } throw; } if (expectedReturnType == "void") { // did we get a positive response at all? yes, otherwise we would have gotten an exception return(null); } if ((result == null) || (result.Length == 0)) { throw new Exception("invalid response from the server"); } result = TrimResult(result); List <object> resultObjects = new List <object>(); if (expectedReturnType == "list") { string[] resultlist = result.Split(new char[] { ',' }); foreach (string o in resultlist) { string[] typeAndVal = o.Split(new char[] { ':' }); resultObjects.Add(THttpBinarySerializer.DeserializeObject(typeAndVal[0], typeAndVal[1])); } } else { resultObjects.Add(THttpBinarySerializer.DeserializeObject(result, expectedReturnType)); } return(resultObjects); }
public static bool ValidateIBAN(string AIban, out string ABic, out string ABankName, out TVerificationResultCollection AVerificationResult) { AVerificationResult = new TVerificationResultCollection(); ABic = String.Empty; ABankName = String.Empty; if ((AIban == null) || (AIban.Trim() == String.Empty)) { AVerificationResult.Add(new TVerificationResult("error", "The IBAN is invalid", "", "MaintainPartners.ErrInvalidIBAN", TResultSeverity.Resv_Critical)); return(false); } string IBANCheckURL = TAppSettingsManager.GetValue("IBANCheck.Url", "https://kontocheck.solidcharity.com/?iban="); string url = IBANCheckURL + AIban.Replace(" ", ""); string result = THTTPUtils.ReadWebsite(url); XmlDocument doc = new XmlDocument(); try { doc.LoadXml(result); XmlNode IbanCheck = TXMLParser.GetChild(doc.DocumentElement, "iban"); if (IbanCheck.InnerText == "0") { AVerificationResult.Add(new TVerificationResult("error", "The IBAN is invalid", "", "MaintainPartners.ErrInvalidIBAN", TResultSeverity.Resv_Critical)); return(false); } XmlNode BankName = TXMLParser.GetChild(doc.DocumentElement, "bankname"); XmlNode City = TXMLParser.GetChild(doc.DocumentElement, "city"); ABankName = BankName.InnerText + ", " + City.InnerText; XmlNode BIC = TXMLParser.GetChild(doc.DocumentElement, "bic"); ABic = BIC.InnerText; } catch (Exception) { TLogging.Log("Error validating IBAN: " + AIban.Replace(" ", "")); AVerificationResult.Add(new TVerificationResult("error", "The IBAN is invalid", "", "MaintainPartners.ErrInvalidIBAN", TResultSeverity.Resv_Critical)); return(false); } return(true); }
/// <summary> /// create a UIConnector on the server /// </summary> public static string CreateUIConnector( string AModuleName, string classname, SortedList <string, object> parameters) { NameValueCollection Parameters = ConvertParameters(parameters); string result = THTTPUtils.PostRequest(ServerURL + "/server" + AModuleName + ".asmx/Create_" + classname, Parameters); result = TrimResult(result); TLogging.LogAtLevel(4, String.Format("CreateUIConnector called for Module '{0}' and Class '{1}'", AModuleName, classname)); return(THttpBinarySerializer.DeserializeObject(result, "System.String").ToString()); }
/// connect to the server public static eLoginEnum Connect(string AConfigName, bool AThrowExceptionOnLoginFailure = true) { TUnhandledThreadExceptionHandler UnhandledThreadExceptionHandler; // Set up Handlers for 'UnhandledException' // Note: BOTH handlers are needed for a WinForms Application!!! AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionHandling.UnhandledExceptionHandler); UnhandledThreadExceptionHandler = new TUnhandledThreadExceptionHandler(); Application.ThreadException += new ThreadExceptionEventHandler(UnhandledThreadExceptionHandler.OnThreadException); new TAppSettingsManager(AConfigName); CommonNUnitFunctions.InitRootPath(); Catalog.Init(); TClientTasksQueue.ClientTasksInstanceType = typeof(TClientTaskInstance); TConnectionManagementBase.GConnectionManagement = new TConnectionManagement(); new TClientSettings(); TClientInfo.InitializeUnit(); TCacheableTablesManager.InitializeUnit(); // Set up Data Validation Delegates TSharedValidationHelper.SharedGetDataDelegate = @TServerLookup.TMCommon.GetData; TSharedPartnerValidationHelper.VerifyPartnerDelegate = @TServerLookup.TMPartner.VerifyPartner; TSharedPartnerValidationHelper.PartnerIsLinkedToCCDelegate = @TServerLookup.TMPartner.PartnerIsLinkedToCC; TSharedPartnerValidationHelper.PartnerOfTypeCCIsLinkedDelegate = @TServerLookup.TMPartner.PartnerOfTypeCCIsLinked; TSharedPartnerValidationHelper.PartnerHasCurrentGiftDestinationDelegate = @TServerLookup.TMPartner.PartnerHasCurrentGiftDestination; TSharedFinanceValidationHelper.GetValidPostingDateRangeDelegate = @TServerLookup.TMFinance.GetCurrentPostingRangeDates; TSharedFinanceValidationHelper.GetValidPeriodDatesDelegate = @TServerLookup.TMFinance.GetCurrentPeriodDates; // Ensure we throw away the previous client session cookies! THTTPUtils.ResetSession(); eLoginEnum Result = Connect(TAppSettingsManager.GetValue("AutoLogin"), TAppSettingsManager.GetValue("AutoLoginPasswd"), TAppSettingsManager.GetInt64("SiteKey")); if ((Result != eLoginEnum.eLoginSucceeded) && AThrowExceptionOnLoginFailure) { throw new Exception("login failed"); } return(Result); }
/// <summary> /// constructor /// </summary> /// <param name="properties"></param> public EncryptionClientSinkProvider(IDictionary properties) { // do not use property, but create local symmetric key, and send to the server, encrypted with the public key of the server try { XmlDocument doc = new XmlDocument(); // get the public key from the server, from a secure site. if the SSL certificate is self signed or not valid, this will fail. // publicKeyXml will contain: <RSAKeyValue><Modulus>w7/g+...+sU=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue> if (properties["HttpsPublicKeyXml"] != null) { string publicKeyXml = THTTPUtils.ReadWebsite((string)properties["HttpsPublicKeyXml"]); doc.LoadXml(publicKeyXml); } else { string publicKeyXml = (string)properties["FilePublicKeyXml"]; doc.Load(publicKeyXml); } try { FPublicKeyServer = new RSAParameters(); FPublicKeyServer.Modulus = Convert.FromBase64String(TXMLParser.GetChild(doc.FirstChild, "Modulus").InnerText); FPublicKeyServer.Exponent = Convert.FromBase64String(TXMLParser.GetChild(doc.FirstChild, "Exponent").InnerText); } catch { throw new Exception("Invalid public key XML file, cannot find Modulus or Exponent"); } } catch (Exception) { TLogging.Log("Cannot get the public key of the OpenPetra server"); throw; } }
/// <summary> /// initialise the server for each Web Request /// </summary> private static bool Init() { string ConfigFileName = string.Empty; // make sure the correct config file is used string Instance = HttpContext.Current.Request.Url.ToString().Replace("http://", "").Replace("https://", ""); Instance = Instance.Substring(0, Instance.IndexOf(".")).Replace("op_", "op").Replace("op", "op_"); // for demo etc if (!Instance.StartsWith("op_")) { Instance = "op_" + Instance; } ConfigFileName = "/home/" + Instance + "/etc/PetraServerConsole.config"; if (File.Exists(ConfigFileName)) { // we are in a multi tenant hosting scenario } else if (Environment.CommandLine.Contains("/appconfigfile=")) { // this happens when we use fastcgi-mono-server4 ConfigFileName = Environment.CommandLine.Substring( Environment.CommandLine.IndexOf("/appconfigfile=") + "/appconfigfile=".Length); if (ConfigFileName.IndexOf(" ") != -1) { ConfigFileName = ConfigFileName.Substring(0, ConfigFileName.IndexOf(" ")); } } else { // this is the normal behaviour when running with local http server ConfigFileName = AppDomain.CurrentDomain.BaseDirectory + Path.DirectorySeparatorChar + "web.config"; } TTypedDataTable.ResetStaticVariables(); TPdfPrinter.ResetStaticVariables(); THTTPUtils.ResetStaticVariables(); TSharedDataCache.TMPartner.ResetStaticVariables(); TServerManagerBase.ResetStaticVariables(); TClientManager.ResetStaticVariables(); TSession.InitThread("TOpenPetraOrgSessionManager.Init", ConfigFileName); if (HttpContext.Current != null) { HttpContext.Current.Server.ScriptTimeout = Convert.ToInt32( TimeSpan.FromMinutes(TAppSettingsManager.GetInt32("WebRequestTimeOutInMinutes", 15)). TotalSeconds); } // if the Login Method is called: reset cookie, ignore any old session if ((HttpContext.Current != null) && (HttpContext.Current.Request.PathInfo == "/Login")) { TSession.CloseSession(); TSession.InitThread("TOpenPetraOrgSessionManager.Init Reset", ConfigFileName); } Catalog.Init(); ErrorCodeInventory.Init(); ErrorCodeInventory.BuildErrorCodeInventory(typeof(Ict.Petra.Shared.PetraErrorCodes)); ErrorCodeInventory.BuildErrorCodeInventory(typeof(Ict.Common.Verification.TStringChecks)); TServerManager.TheServerManager = new TServerManager(); // initialise the cached tables and the delegates TSetupDelegates.Init(); TLogging.LogAtLevel(4, "Server has been initialised"); return(true); }
public static bool PerformUserAuthentication(String AUserID, String APassword, string AClientComputerName, string AClientIPAddress, out Boolean ASystemEnabled, TDBTransaction ATransaction) { SUserRow UserDR; DateTime LoginDateTime; TPetraPrincipal PetraPrincipal = null; string UserAuthenticationMethod = TAppSettingsManager.GetValue("UserAuthenticationMethod", "OpenPetraDBSUser", false); IUserAuthentication AuthenticationAssembly; string AuthAssemblyErrorMessage; Int32 AProcessID = -1; ASystemEnabled = true; CheckDatabaseVersion(ATransaction.DataBaseObj); string EmailAddress = AUserID; try { UserDR = LoadUser(AUserID, out PetraPrincipal, ATransaction); } catch (EUserNotExistantException) { // pass ATransaction UserInfo.SetUserInfo(new TPetraPrincipal("SYSADMIN")); // Logging TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_FOR_NONEXISTING_USER, String.Format(Catalog.GetString( "User with User ID '{0}' attempted to log in, but there is no user account for this user! "), AUserID) + String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress), out AProcessID, ATransaction); // Only now throw the Exception! throw; } // pass ATransaction UserInfo.SetUserInfo(PetraPrincipal); if (AUserID == "SELFSERVICE") { APassword = String.Empty; } else if ((AUserID == "SYSADMIN") && TSession.HasVariable("ServerAdminToken")) { // Login via server admin console authenticated by file token APassword = String.Empty; } // // (1) Check user-supplied password // else if (UserAuthenticationMethod == "OpenPetraDBSUser") { if (!TPasswordHelper.EqualsAntiTimingAttack( Convert.FromBase64String( CreateHashOfPassword(APassword, UserDR.PasswordSalt, UserDR.PwdSchemeVersion)), Convert.FromBase64String(UserDR.PasswordHash))) { // The password that the user supplied is wrong!!! --> Save failed user login attempt! // If the number of permitted failed logins in a row gets exceeded then also lock the user account! SaveFailedLogin(AUserID, UserDR, AClientComputerName, AClientIPAddress, ATransaction); if (UserDR.AccountLocked && (Convert.ToBoolean(UserDR[SUserTable.GetAccountLockedDBName(), DataRowVersion.Original]) != UserDR.AccountLocked)) { // User Account just got locked! throw new EUserAccountGotLockedException(StrInvalidUserIDPassword); } else { throw new EPasswordWrongException(StrInvalidUserIDPassword); } } } else { AuthenticationAssembly = LoadAuthAssembly(UserAuthenticationMethod); if (!AuthenticationAssembly.AuthenticateUser(EmailAddress, APassword, out AuthAssemblyErrorMessage)) { // The password that the user supplied is wrong!!! --> Save failed user login attempt! // If the number of permitted failed logins in a row gets exceeded then also lock the user account! SaveFailedLogin(AUserID, UserDR, AClientComputerName, AClientIPAddress, ATransaction); if (UserDR.AccountLocked && (Convert.ToBoolean(UserDR[SUserTable.GetAccountLockedDBName(), DataRowVersion.Original]) != UserDR.AccountLocked)) { // User Account just got locked! throw new EUserAccountGotLockedException(StrInvalidUserIDPassword); } else { throw new EPasswordWrongException(AuthAssemblyErrorMessage); } } } // // (2) Check if the User Account is Locked or if the user is 'Retired'. If either is true then deny the login!!! // // IMPORTANT: We perform these checks only AFTER the check for the correctness of the password so that every // log-in attempt that gets rejected on grounds of a wrong password takes the same amount of time (to help prevent // an attack vector called 'timing attack') if (UserDR.AccountLocked || UserDR.Retired) { if ((AUserID == "SYSADMIN") && TSession.HasVariable("ServerAdminToken")) { // this is ok. we need to be able to activate the sysadmin account on SetInitialSysadminEmail } else if (UserDR.AccountLocked) { // Logging TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_FOR_LOCKED_USER, Catalog.GetString("User attempted to log in, but the user account was locked! ") + String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress), out AProcessID, ATransaction); // Only now throw the Exception! throw new EUserAccountLockedException(StrInvalidUserIDPassword); } else { // Logging TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_FOR_RETIRED_USER, Catalog.GetString("User attempted to log in, but the user is retired! ") + String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress), out AProcessID, ATransaction); // Only now throw the Exception! throw new EUserRetiredException(StrInvalidUserIDPassword); } } // // (3) Check SystemLoginStatus (whether the general use of the OpenPetra application is enabled/disabled) in the // SystemStatus table (this table always holds only a single record) // SSystemStatusTable SystemStatusDT; SystemStatusDT = SSystemStatusAccess.LoadAll(ATransaction); if (SystemStatusDT[0].SystemLoginStatus) { ASystemEnabled = true; } else { ASystemEnabled = false; // TODO: Check for Security Group membership might need reviewal when security model of OpenPetra might get reviewed... if (PetraPrincipal.IsInGroup("SYSADMIN")) { PetraPrincipal.LoginMessage = String.Format(StrSystemDisabled1, SystemStatusDT[0].SystemDisabledReason) + Environment.NewLine + Environment.NewLine + StrSystemDisabled2Admin; } else { TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_WHEN_SYSTEM_WAS_DISABLED, Catalog.GetString("User wanted to log in, but the System was disabled. ") + String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress), out AProcessID, ATransaction); TLoginLog.RecordUserLogout(AUserID, AProcessID, ATransaction); throw new ESystemDisabledException(String.Format(StrSystemDisabled1, SystemStatusDT[0].SystemDisabledReason) + Environment.NewLine + Environment.NewLine + String.Format(StrSystemDisabled2, StringHelper.DateToLocalizedString(SystemStatusDT[0].SystemAvailableDate.Value), SystemStatusDT[0].SystemAvailableDate.Value.AddSeconds(SystemStatusDT[0].SystemAvailableTime).ToShortTimeString())); } } // // (3b) Check if the license is valid // string LicenseCheckUrl = TAppSettingsManager.GetValue("LicenseCheck.Url", String.Empty, false); string LicenseUser = TAppSettingsManager.GetValue("Server.DBName"); if ((AUserID == "SYSADMIN") && TSession.HasVariable("ServerAdminToken")) { // don't check for the license, since this is called when upgrading the server as well. LicenseCheckUrl = String.Empty; } if ((LicenseCheckUrl != String.Empty) && (LicenseUser != "openpetra")) { string url = LicenseCheckUrl + LicenseUser; string result = THTTPUtils.ReadWebsite(url); bool valid = result.Contains("\"valid\":true"); bool gratis = result.Contains("\"gratis\":true"); if (!valid && !gratis) { TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_ATTEMPT_WHEN_SYSTEM_WAS_DISABLED, Catalog.GetString("User wanted to log in, but the license is expired. ") + String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress), out AProcessID, ATransaction); TLoginLog.RecordUserLogout(AUserID, AProcessID, ATransaction); throw new ELicenseExpiredException("LICENSE_EXPIRED"); } } // // (4) Save successful login! // LoginDateTime = DateTime.Now; UserDR.LastLoginDate = LoginDateTime; UserDR.LastLoginTime = Conversions.DateTimeToInt32Time(LoginDateTime); UserDR.FailedLogins = 0; // this needs resetting! // Upgrade the user's password hashing scheme if it is older than the current password hashing scheme if (APassword != String.Empty && UserDR.PwdSchemeVersion < TPasswordHelper.CurrentPasswordSchemeNumber) { TMaintenanceWebConnector.SetNewPasswordHashAndSaltForUser(UserDR, APassword, AClientComputerName, AClientIPAddress, ATransaction); } SaveUser(AUserID, (SUserTable)UserDR.Table, ATransaction); // TODO: Check for Security Group membership might need reviewal when security model of OpenPetra might get reviewed... if (PetraPrincipal.IsInGroup("SYSADMIN")) { TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_SUCCESSFUL_SYSADMIN, Catalog.GetString("User login - SYSADMIN privileges. ") + String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress), out AProcessID, ATransaction); } else { TLoginLog.AddLoginLogEntry(AUserID, TLoginLog.LOGIN_STATUS_TYPE_LOGIN_SUCCESSFUL, Catalog.GetString("User login. ") + String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress), out AProcessID, ATransaction); } PetraPrincipal.ProcessID = AProcessID; AProcessID = 0; // // (5) Check if a password change is requested for this user // if (UserDR.PasswordNeedsChange) { // The user needs to change their password before they can use OpenPetra PetraPrincipal.LoginMessage = SharedConstants.LOGINMUSTCHANGEPASSWORD; } return(true); }
public void TestHttpUtils200() { string content = THTTPUtils.ReadWebsite("https://www.openpetra.org"); StringAssert.Contains("Free Administration Software for Non-Profits", content, "should contain the text"); }
public void TestHttpUtils500() { string content = THTTPUtils.ReadWebsite("http://localhost/api/serverMServerAdmin.asmx/TServerAdminWebConnector_StopServer"); }
private void ReadWebsiteWith500Error() { THTTPUtils.ReadWebsite("http://localhost/api/serverMServerAdmin.asmx/TServerAdminWebConnector_StopServer"); }