public static bool IsLoopbackAddress(string hostnameOrIp)
        {
            hostnameOrIp = RemoveScopeIdFromIp(hostnameOrIp).Trim().ToLower();

            string internalAddress;

            if (HttpContext.Current == null)
            {
                // Can't cache this in services because settings change as diferent sandboxes are served
                internalAddress = RuntimePlatformSettings.Misc.InternalAddress.GetValue();
            }
            else
            {
                if (cachedInternalAddress == null)
                {
                    internalAddress = cachedInternalAddress = RuntimePlatformSettings.Misc.InternalAddress.GetValue();
                }
                else
                {
                    internalAddress = cachedInternalAddress;
                }
            }
            var toRetrun = hostnameOrIp.IsOneOf("127.0.0.1", "::1", "localhost", internalAddress);

            OSTrace.Debug("IsLoopbackAddress - hostnameOrIp: " + hostnameOrIp + " - internalAddress: " + internalAddress + " result: " + toRetrun);
            return(toRetrun);
        }
Example #2
0
    internal static string MD5HashWithPrivateSalt(string str)
    {
        var toReturn = MD5PasswordHelper.HexDeriveUsingUTF16(str, SharedKeys.PrivateSalt());

        OSTrace.Debug("MD5HashWithPrivateSalt returned:" + toReturn);
        return(toReturn);
    }
 public void ClearCache()
 {
     OSTrace.Debug("StaticEntityRuntime.ClearCache: Clearing cache for " + ObjectKeyUtils.DatabaseValue(EntityKey) + ".");
     _recordsMetaByName.Clear();
     _recordsMetaByKey.Clear();
     foreach (Hashtable recordsById in _recordsByIdByLocale.Values)
     {
         recordsById.Clear();
     }
 }
Example #4
0
        public static void InvokeRegister(Transaction tran, string type)
        {
            try {
                Type       t = Type.GetType(type, true);
                MethodInfo m = t.GetMethod("RegisterInfo");
                if (m == null)
                {
                    OSTrace.Debug("Unable to locate method Register in type " + t);
                    return;
                }

                m.Invoke(null, new object[] { tran });
            } catch (Exception e) {
                OSTrace.Error("Error Invoking Register", e);
                // #774299 - The exception is not propagated to avoid having broken references stopping the application load.
                // If a reference is required, a runtime error will be thrown when the application tries to access it.
            }
        }
 protected void LoadAllEntriesMetadata()
 {
     using (OSTrace.Timer("StaticEntityRuntime.LoadAllEntriesMetadata: Loading metadata for " + ObjectKeyUtils.DatabaseValue(EntityKey) + ".")) {
         using (Transaction tran = DatabaseAccess.ForSystemDatabase.GetReadOnlyTransaction()) {
             using (IDataReader reader = DBRuntimePlatform.Instance.GetStaticRecordsByEntity(tran, EntityKey, EspaceId)) {
                 int count = 0;
                 while (reader.Read())
                 {
                     StaticRecordMetadata record = newStaticRecord();
                     record.Read(reader);
                     AddToMetadataCache(record);
                     count++;
                 }
                 OSTrace.Debug("StaticEntityRuntime.LoadAllEntriesMetadata: Loaded " + count + " metadata records.");
             }
         }
     }
 }
        public LoginInfo ReadLoginInfoFromRequest()
        {
            var cookies     = HttpContext.Current.Request.Cookies;
            var cookieNames = cookies.AllKeys;

            HttpOnlyLoginCookieValue httpCookieValue = null;

            if (!cookieNames.Contains(cookieNamer.HttpOnlyLoginCookieName))
            {
                OSTrace.Debug("[Request cookies] No http cookie found");
            }
            else
            {
                string cookieValue = cookies.Get(cookieNamer.HttpOnlyLoginCookieName).Value;
                if (!HttpOnlyLoginCookieValue.TryParse(cookieValue, out httpCookieValue))
                {
                    OSTrace.Debug("[Request cookies] Http cookie value: {0}", cookieValue);
                }
            }

            UserAccessibleLoginCookieValue userCookie = null;

            if (!cookieNames.Contains(cookieNamer.UserAccessibleLoginCookieName))
            {
                OSTrace.Debug("[Request cookies] No user cookie found");
            }
            else
            {
                string cookieValue = cookies.Get(cookieNamer.UserAccessibleLoginCookieName).Value;
                if (!UserAccessibleLoginCookieValue.TryParse(cookieValue, out userCookie))
                {
                    OSTrace.Debug("[Request cookies] User cookie value: {0}", cookieValue);
                }
            }

            var csrfHeaderValue = HttpContext.Current.Request.Headers.Get(cookieNamer.CSRFHeaderName);
            var csrfToken       = csrfHeaderValue == null ? null : new CSRFToken(csrfHeaderValue);

            var loginInfo = new LoginInfo(configuration, csrfToken, httpCookieValue, userCookie);

            return(loginInfo);
        }
        public static string GeneratePassword(int ssLength, bool ssAlphanumeric)
        {
            string allowedChars;

            if (ssAlphanumeric)
            {
                allowedChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            }
            else
            {
                allowedChars = "0123456789";
            }
            try {
                return(RuntimeCommon.Cryptography.PasswordHelper.PasswordWithLimitationsHelper.GeneratePasswordWithCharacterLimitations(ssLength, allowedChars));
            } catch (Exception e) {
                // since GeneratePassword is a BuiltInFunction, it is not expected to throw an exception when bad stuff happens
                OSTrace.Debug("Empty password generated, because of Exception in generation.", e);
                return(string.Empty);
            }
        }
        private static IEnumerable <T> GetImplementations()
        {
            IEnumerable <T> cached;

            lock (typeof(T)) {
                cached = (IEnumerable <T>)ExtensionPointLoaderCache.Get(typeof(T));
                if (cached == null)
                {
                    ExtensionPointLoaderCache.Put(typeof(T), cached = GetProviders());
                    int extensionsCount = cached.Count();
                    if (extensionsCount == 0)
                    {
                        OSTrace.Debug("ExtensionPointLoader: Loaded {0} {1} extensions.", extensionsCount, typeof(T).Name);
                    }
                    else
                    {
                        OSTrace.Debug("ExtensionPointLoader: Loaded {0} {1} extensions:\n\t{2}", extensionsCount, typeof(T).Name, cached.Select(t => t.GetType().FullName).StrCat("\n\t"));
                    }
                }
            }
            return(cached);
        }
        public void WriteLoginInfoToResponse(LoginInfo loginInfo)
        {
            if (loginInfo == null || !loginInfo.IsDirty)
            {
                return;
            }

            loginInfo.Sign();

            bool sendAsPersistentCookie = loginInfo.IsPersistent || loginInfo.IsAnonymous;
            int  persistentCookieAge    = (int)configuration.PersistentLoginCookieExpiration.TotalSeconds;

            var httpOnly = new HttpCookie(cookieNamer.HttpOnlyLoginCookieName, loginInfo.HttpCookieValue);

            httpOnly.Path     = "/";
            httpOnly.HttpOnly = true;
            httpOnly.Secure   = true;
            if (sendAsPersistentCookie)
            {
                httpOnly.SetMaxAge(persistentCookieAge);
            }

            var user = new HttpCookie(cookieNamer.UserAccessibleLoginCookieName, loginInfo.UserCookieValue);

            user.Path   = "/";
            user.Secure = true;
            if (sendAsPersistentCookie)
            {
                user.SetMaxAge(persistentCookieAge);
            }

            OSTrace.Debug("[Response cookies] Http cookie value: {0}; User cookie value: {1}", httpOnly.Value, user.Value);

            HttpContext.Current.Response.Cookies.Set(httpOnly);
            HttpContext.Current.Response.Cookies.Set(user);
        }
Example #10
0
 private static void ThrowTokenValidationFailed(string context)
 {
     OSTrace.Debug("SecurityTokenManager validation failed: " + context);
     throw new Exception("Token validation failed");
 }
Example #11
0
        public virtual IHttpActionResult Log(Payload.LogMessage[] logs, long clientTimeInMillis)
        {
            AppInfo   appInfo  = null;
            HeContext context  = null;
            int       espaceId = 0;
            int       tenantId = 0;
            string    sessionId;
            int       userId = 0;

            try {
                appInfo = AppInfo.GetAppInfo();
                if (!IsApplicationEnabled(appInfo))
                {
                    return(GetErrorResponseResult("Application Backend Unavailable", HttpStatusCode.ServiceUnavailable));
                }

                TimeSpan dateDiff = TimeSpan.Zero;
                if (clientTimeInMillis > 0)
                {
                    dateDiff = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(clientTimeInMillis).Subtract(DateTime.UtcNow);
                }

                ValidateRequestSecurity();

                GatherLogInformation(/*updateSessionFromCookie*/ true, appInfo, out context, out espaceId, out tenantId, out sessionId, out userId);
                var allowAuditing      = appInfo == null /*because of tests */ || appInfo.Properties.AllowAuditing;
                var clientTraceEnabled = appInfo == null /*because of tests */ || appInfo.Properties.ClientSideTracingEnabled;

                if (logs.Length > maxLogsPerBatch)
                {
                    return(GetErrorResponseResult("Too many logs in a batch.", HttpStatusCode.ServiceUnavailable));
                }

                if (!CanProcessLogRequest(logs, allowAuditing, clientTraceEnabled))
                {
                    return(GetErrorResponseResult("Too many requests", HttpStatusCode.ServiceUnavailable));
                }

                foreach (var log in logs)
                {
                    string logType = log.LogType;

                    DateTime date = DateTime.Parse(log.Instant);
                    if (clientTimeInMillis > 0)
                    {
                        date = Conversions.DateTimeToUniversal(date).Subtract(dateDiff);
                    }
                    date = Conversions.DateTimeToLocal(date);

                    if (StringUtils.EqualsIgnoreCase(logType, "general"))
                    {
                        if (allowAuditing)
                        {
                            WriteToGeneralLog(log, date, sessionId, espaceId, tenantId, userId);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(logType, "trace"))
                    {
                        if (clientTraceEnabled)
                        {
                            OSTrace.Debug("[" + date.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "] " + log.Module_Name + " - " + log.Message);
                        }
                    }
                    else if (StringUtils.EqualsIgnoreCase(logType, "error"))
                    {
                        string environmentInformation = ErrorLog.GetStackEnvironmentInfo(appInfo, context);
                        environmentInformation += "\nClient-Side Log";
                        if (log.ErrorStack != null)   // Limit stack to the lower storage size
                        {
                            log.ErrorStack = RuntimePlatformUtils.Trunc(log.ErrorStack, ErrorLog.MAX_STACK_SMALL_STORAGE_SIZE);
                        }
                        ErrorLog.StaticWrite(date, sessionId, espaceId, tenantId, userId, log.Message, log.ErrorStack, environmentInformation, log.Module_Name);
                    }
                    else
                    {
                        ErrorLog.LogApplicationError("Invalid log type: " + logType, /*stack*/ null, context, "Module Services");
                        return(GetErrorResponseResult("Invalid log type", HttpStatusCode.InternalServerError));
                    }
                }
            } catch (Exception ex) {
                DatabaseAccess.FreeupResources(false);

                var licensingException = ex as LicensingException;
                if (licensingException != null)
                {
                    // Error was already logged inside AppInfo's GetAppInfo
                    return(GetErrorResponseResult("Application Backend Unavailable", HttpStatusCode.ServiceUnavailable));
                }

                var exposeRestException = ex as ExposeRestException;
                if (exposeRestException != null)
                {
                    ErrorLog.LogApplicationError(exposeRestException, appInfo, context, "Module Services");
                    return(GetErrorResponseResult(exposeRestException.Message, exposeRestException.StatusCode));
                }

                ErrorLog.LogApplicationError(ex, appInfo, context, "Module Services");
                return(GetErrorResponseResult("Internal Server Error", HttpStatusCode.InternalServerError));
            }

            return(Ok());
        }
        /// <summary>
        /// Downloads Text content from the specified URL
        /// </summary>
        /// <param name="ssUrl">URL to get the content from</param>
        /// <param name="method">The request method.</param>
        /// <param name="contentType">The request contentType header</param>
        /// <param name="userAgent">The request userAgent.</param>
        /// <param name="cookie">Cookie to use in the request.</param>
        /// <param name="parameters">Query parameters for the request.</param>
        /// <param name="headers">HTTP headers for the request.</param>
        /// <param name="ssContent">Actual text content downloaded from URL</param>
        /// <param name="ssContentEncoding">The Content enconding.</param>
        public static void HttpGetContent(Uri ssUrl, string method, string contentType, string userAgent, Cookie cookie, QueryParameter[] parameters, IDictionary <HttpRequestHeader, string> headers, out string ssContent, out string ssContentEncoding)
        {
            ssContent = "";
            OSTrace.Debug("EmailHelder.HttpGetContent: url: {0}".F(ssUrl));
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(ssUrl);

            if (method != null)
            {
                req.Method = method;
            }
            if (contentType != null)
            {
                req.ContentType = contentType;
            }
            req.AllowAutoRedirect = true;
            req.UserAgent         = userAgent;
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    req.Headers.Add(header.Key, header.Value);
                }
            }
            req.CookieContainer = new CookieContainer();
            if (cookie != null)
            {
                req.CookieContainer.Add(cookie);
            }

            if (parameters != null)
            {
                string urlEncodedParameters = parameters.Select(p => p.Name + "=" + HttpUtility.UrlEncode(p.Value)).StrCat("&");

                using (var requestWriter = new StreamWriter(req.GetRequestStream())) {
                    requestWriter.Write(urlEncodedParameters);
                }
            }

            using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) {
                Encoding encoding = null;

                // try get charset from response Content Type
                try {
                    Match charsetMatch = ScriptableEmailFunctions.GetRegex("charset=\"?(.*)\"?", RegexOptions.IgnoreCase).Match(resp.ContentType);
                    if (charsetMatch.Success)
                    {
                        encoding = Encoding.GetEncoding(charsetMatch.Groups[1].Value);
                    }
                } catch {
                }
                if (encoding == null)
                {
                    encoding = Encoding.ASCII;
                }
                using (var sr = new StreamReader(resp.GetResponseStream(), encoding)) {
                    ssContent = sr.ReadToEnd();
                    OSTrace.Debug("EmailHelder.HttpGetContent: url: {0} ssContentLength: {1} status: {2}".F(ssUrl, ssContent.Length, resp.StatusCode));
                }
                ssContentEncoding = resp.ContentEncoding;
            }
        } // HttpGet
Example #13
0
 private void trace(string methodName, string procedureName, long currentThreadId)
 {
     OSTrace.Debug("{0} with Name {1} for Thread: {2}", methodName, procedureName, currentThreadId);
 }