Ejemplo n.º 1
0
        //Should we allow FirebaseId to be set by a DTO parameter?  -would make things easier here....
        //or maybe better idea, set it at the template level
        //also, maybe see about reading subscriptions from the cache rather than from a db read request
        internal static bool IsThrottled(ADO Ado, HttpRequest hRequest, JSONRPC_API request, string samAccountName = null)
        {
            //We need MemcacheD to use this
            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["API_MEMCACHED_ENABLED"]))
            {
                return(false);
            }


            int    window;
            int    cutoff;
            string user       = null;
            bool   subscribed = false;

            //Did the user send a SubscriberKey in the header of the request?
            if (hRequest.Headers.AllKeys.Contains("SubscriberKey"))
            {
                //They send a SubscriberKey, but is it in our list of valid tokens?
                var keyListCache = MemCacheD.Get_BSO("PxStat.Subscription", "Subscriber_BSO", "RefreshSubscriberKeyCache", "RefreshSubscriberKeyCache");
                if (!keyListCache.hasData)
                {
                    //No cache - try creating one
                    new Subscriber_BSO().RefreshSubscriberKeyCache(Ado);
                    keyListCache = MemCacheD.Get_BSO("PxStat.Subscription", "Subscriber_BSO", "RefreshSubscriberKeyCache", "RefreshSubscriberKeyCache");
                }


                if (keyListCache.hasData)
                {
                    //Does the request contain a valid subscription token?
                    var keyValues = keyListCache.data.ToObject <List <string> >();

                    if (keyValues.Contains(hRequest.Headers.GetValues("SubscriberKey").FirstOrDefault()))
                    {
                        user       = hRequest.Headers.GetValues("SubscriberKey").FirstOrDefault();
                        subscribed = true;
                    }
                }
            }

            //An AD or Local user is deemed to be already subscribed
            if (samAccountName != null)
            {
                user       = samAccountName;
                subscribed = true;
            }

            //Different limits apply depending on whether the user is subscribed or not
            if (subscribed)
            {
                window = Configuration_BSO.GetCustomConfig(ConfigType.global, "throttle.subscribedWindowSeconds");
                cutoff = Configuration_BSO.GetCustomConfig(ConfigType.global, "throttle.subscribedCallLimit");
            }
            else
            {
                window = Configuration_BSO.GetCustomConfig(ConfigType.global, "throttle.nonSubscribedWindowSeconds");
                cutoff = Configuration_BSO.GetCustomConfig(ConfigType.global, "throttle.nonSubscribedCallLimit");
                user   = request.userAgent + request.ipAddress;
            }


            //Now we check the usage for the current requester
            List <DateTime> workingList = new List <DateTime>();
            var             cache       = MemCacheD.Get_BSO("PxStat.Security", "Throttle", "Read", user);

            if (cache.hasData)
            {
                List <DateTime> userHistory = JsonConvert.DeserializeObject <List <DateTime> >(cache.data.ToString());

                //We only count the entries inside the current window
                workingList = userHistory.Where(x => x > DateTime.Now.AddSeconds(window * -1)).ToList();
                if (workingList.Count() > cutoff + 1)
                {
                    Log.Instance.Info(String.Format("Throttle event for user {0}, {1} requests in {2} seconds", user, workingList.Count, window));
                    return(true);
                }
            }

            workingList.Add(DateTime.Now);
            MemCacheD.Store_BSO("PxStat.Security", "Throttle", "Read", user, workingList, default(DateTime));


            return(false);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Execute
        /// </summary>
        /// <returns></returns>
        protected override bool Execute()
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            if (!ReCAPTCHA.Validate(DTO.Captcha))
            {
                Response.error = Label.Get("error.authentication");
                return(false);
            }
            ActiveDirectory_ADO adAdo  = new ActiveDirectory_ADO();
            dynamic             adUser = adAdo.GetAdSpecificDataForEmail(DTO.CcnEmail);

            //Check if local access is available for AD users
            if (!Configuration_BSO.GetCustomConfig(ConfigType.global, "security.adOpenAccess") && adUser != null)
            {
                Response.error = Label.Get("error.authentication");
                return(false);
            }

            DTO.CcnUsername = DTO.CcnEmail;
            Login_BSO lBso = new Login_BSO(Ado);

            Account_ADO aAdo = new Account_ADO();

            ADO_readerOutput response = aAdo.Read(Ado, DTO.CcnEmail);

            string user;

            if (!response.hasData)
            {
                //Email address not in the login table, try to get the username from the email address via AD


                var adResult = adAdo.GetAdSpecificDataForEmail(DTO.CcnEmail);
                Log.Instance.Debug("AD user found from email - time ms: " + sw.ElapsedMilliseconds);

                if (adResult == null)
                {
                    Response.error = Label.Get("error.authentication");
                    return(false);
                }

                user = adResult.CcnUsername;

                //Now get the user details from the table

                response = aAdo.Read(Ado, user);
                if (!response.hasData)
                {
                    Response.error = Label.Get("error.authentication");
                    return(false);
                }

                if (response.data[0].CcnLockedFlag)
                {
                    Response.error = Label.Get("error.account.locked");
                    return(false);
                }
            }
            else
            {
                user = response.data[0].CcnUsername;
            }


            if (response.data[0].Lgn2Fa.Equals(DBNull.Value))
            {
                Response.error = Label.Get("error.authentication");

                return(false);
            }

            if (response.data[0].CcnLockedFlag)
            {
                Response.error = Label.Get("error.authentication");

                return(false);
            }

            int    ccnId    = response.data[0].CcnId;
            string login2Fa = response.data[0].Lgn2Fa;

            if (!API.TwoFA.Validate2fa(DTO.Totp, login2Fa))
            {
                Response.error = Label.Get("error.authentication");

                return(false);
            }

            response = lBso.Validate1Fa(DTO.Lgn1Fa, user);

            if (!response.hasData)
            {
                //No validation available via the Login table, try Active Directory
                long lValidatePassword = sw.ElapsedMilliseconds;
                if (!ActiveDirectory.IsPasswordValid(user, DTO.Lgn1Fa))
                {
                    Response.error = Label.Get("error.authentication");
                    return(false);
                }
                Log.Instance.Debug("Elaspsed time ValidatePassword: "******"AD validation time ms: " + sw.ElapsedMilliseconds);
                //Get the remaining details from the database
                response = aAdo.Read(Ado, user);

                if (!response.hasData)
                {
                    Response.error = Label.Get("error.authentication");
                    return(false);
                }
            }
            //If we have found an account, credentials are ok, but the account is locked, then we return an account locked error
            //could be AD too
            //IsUserAuthenticated needs to check if the user is locked too


            if (response.data[0].CcnLockedFlag)
            {
                Response.error = Label.Get("error.account.locked");
                return(false);
            }


            string sessionToken = Utility.GetRandomSHA256(ccnId.ToString());

            DateTime expiry = DateTime.Now.AddSeconds(Configuration_BSO.GetCustomConfig(ConfigType.global, "session.length"));

            if (!lBso.CreateSession(sessionToken, expiry, user))
            {
                Response.error = Label.Get("error.create");
                return(false);
            }

            Response.sessionCookie = new HttpCookie(API.Common.SessionCookieName)
            {
                Value = sessionToken
            };

            Response.data = API.JSONRPC.success;
            long l = sw.ElapsedMilliseconds;

            return(true);
        }
Ejemplo n.º 3
0
        private void SendEmail(Login_DTO_Create lDto, string token, string nextMethod)
        {
            string url       = Configuration_BSO.GetCustomConfig(ConfigType.global, "url.application") + "?method=" + nextMethod + "&email=" + lDto.CcnEmail + '&' + "name=" + Uri.EscapeUriString(lDto.CcnDisplayname) + '&' + "token=" + token;
            string link      = "<a href = " + url + ">" + Label.Get("email.body.header.anchor-text", lDto.LngIsoCode) + "</a>";
            string subject   = string.Format(Label.Get("email.subject.update-1fa", lDto.LngIsoCode), Configuration_BSO.GetCustomConfig(ConfigType.global, "title"));
            string to        = lDto.CcnEmail;
            string header    = string.Format(Label.Get("email.body.header.update-1fa", lDto.LngIsoCode), lDto.CcnDisplayname, Configuration_BSO.GetCustomConfig(ConfigType.global, "title"));
            string subHeader = string.Format(Label.Get("email.body.sub-header.update-1fa"), link);
            string footer    = string.Format(Label.Get("email.body.footer", lDto.LngIsoCode), lDto.CcnDisplayname);

            Email_BSO.SendLoginTemplateEmail(subject, new List <string>()
            {
                to
            }, header, url, footer, subHeader, lDto.LngIsoCode);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Create an analytic entry
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        internal int Create(Analytic_DTO dto)
        {
            List <ADO_inputParams> inputParamList = new List <ADO_inputParams>()
            {
                new ADO_inputParams()
                {
                    name = "@matrix", value = dto.matrix
                },
                new ADO_inputParams()
                {
                    name = "@NltMaskedIp", value = dto.NltMaskedIp
                },
                new ADO_inputParams()
                {
                    name = "@NltBotFlag", value = dto.NltBotFlag
                },
                new ADO_inputParams()
                {
                    name = "@NltM2m", value = dto.NltM2m
                },
                new ADO_inputParams()
                {
                    name = "@NltDate", value = dto.NltDate
                },
                new ADO_inputParams()
                {
                    name = "@LngIsoCode", value = Configuration_BSO.GetCustomConfig("language.iso.code")
                }
            };

            if (dto.NltOs != null)
            {
                inputParamList.Add(new ADO_inputParams()
                {
                    name = "@NltOs", value = dto.NltOs
                });
            }
            if (dto.NltBrowser != null)
            {
                inputParamList.Add(new ADO_inputParams()
                {
                    name = "@NltBrowser", value = dto.NltBrowser
                });
            }
            if (dto.NltReferer != null)
            {
                inputParamList.Add(new ADO_inputParams()
                {
                    name = "@NltReferer", value = dto.NltReferer
                });
            }
            if (dto.FrmType != null && dto.FrmVersion != null)
            {
                inputParamList.Add(new ADO_inputParams()
                {
                    name = "@FrmType", value = dto.FrmType
                });
                inputParamList.Add(new ADO_inputParams()
                {
                    name = "@FrmVersion", value = dto.FrmVersion
                });
            }

            var retParam = new ADO_returnParam()
            {
                name = "return", value = 0
            };


            Ado.ExecuteNonQueryProcedure("Security_Analytic_Create", inputParamList, ref retParam);


            return(retParam.value);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Execute
        /// </summary>
        /// <returns></returns>
        protected override bool Execute()
        {
            bool success = false;

            ActiveDirectory_ADO adAdo = new ActiveDirectory_ADO();
            ActiveDirectory_DTO adDto = adAdo.GetUser(Ado, DTO);

            dynamic adUser = adAdo.GetAdSpecificDataForEmail(DTO.CcnEmail);

            if (adUser?.CcnEmail != null)
            {
                //Check if local access is available for AD users
                if (!Configuration_BSO.GetCustomConfig(ConfigType.global, "security.adOpenAccess"))
                {
                    Response.error = Label.Get("error.authentication");
                    return(false);
                }
                DTO.CcnEmail       = adUser.CcnEmail;
                DTO.CcnDisplayname = adUser.CcnDisplayName;
                DTO.CcnUsername    = adUser.CcnUsername;
            }
            else
            {
                Account_ADO aAdo = new Account_ADO();
                var         user = aAdo.Read(Ado, new Account_DTO_Read()
                {
                    CcnUsername = DTO.CcnEmail
                });
                if (!user.hasData)
                {
                    Response.data = JSONRPC.success;
                    return(success);
                }

                if (user.data[0].CcnEmail.Equals(DBNull.Value) || user.data[0].CcnDisplayName.Equals(DBNull.Value))
                {
                    Response.data = JSONRPC.success;
                    return(true);
                }

                DTO.CcnDisplayname = user.data[0].CcnDisplayName;
                DTO.CcnEmail       = user.data[0].CcnEmail;
                DTO.CcnUsername    = DTO.CcnEmail;
            }


            Login_BSO lBso = new Login_BSO(Ado);

            string token = Utility.GetRandomSHA256(DTO.CcnUsername);

            lBso.UpdateInvitationToken2Fa(DTO.CcnUsername, token);

            if (token != null)
            {
                SendEmail(new Login_DTO_Create()
                {
                    CcnUsername = DTO.CcnUsername, CcnEmail = DTO.CcnEmail, LngIsoCode = DTO.LngIsoCode, CcnDisplayname = DTO.CcnDisplayname
                }, token, "PxStat.Security.Login_API.Update2FA");
                Response.data = JSONRPC.success;
                success       = true;
            }

            Response.data = JSONRPC.success;
            return(success);
        }
        /// <summary>
        /// Execute
        /// </summary>
        /// <returns></returns>
        protected override bool Execute()
        {
            Login_BSO lBso = new Login_BSO(Ado);


            ADO_readerOutput user;
            string           displayName = null;
            string           email       = null;
            string           ccnUsername = null;



            if (SamAccountName != null)
            {
                ActiveDirectory_ADO adAdo = new ActiveDirectory_ADO();
                ActiveDirectory_DTO adDto = adAdo.GetUser(Ado, new Account_DTO_Create()
                {
                    CcnUsername = SamAccountName
                });
                displayName = adDto.CcnDisplayName;
                email       = adDto.CcnEmail;
                ccnUsername = adDto.CcnUsername;
            }

            //Check if local access is available for AD users
            if (!Configuration_BSO.GetCustomConfig(ConfigType.global, "security.adOpenAccess") && ccnUsername != null)
            {
                Response.error = Label.Get("error.authentication");
                return(false);
            }

            if (ccnUsername == null)
            {
                if (Request.sessionCookie == null)
                {
                    Response.error = Label.Get("error.authentication");
                    return(false);
                }
                user = lBso.ReadBySession(Request.sessionCookie.Value);
                if (user.hasData)
                {
                    if (user.data[0].CcnEmail.Equals(DBNull.Value) || user.data[0].CcnDisplayName.Equals(DBNull.Value))
                    {
                        Response.data = JSONRPC.success;
                        return(true);
                    }
                    displayName = user.data[0].CcnDisplayName;
                    email       = user.data[0].CcnEmail;
                    ccnUsername = user.data[0].CcnUsername;
                }
            }

            if (ccnUsername == null)
            {
                Response.error = Label.Get("error.authentication");
                return(false);
            }


            string token = Utility.GetRandomSHA256(ccnUsername);

            lBso.UpdateInvitationToken2Fa(ccnUsername, token);

            if (token != null)
            {
                SendEmail(new Login_DTO_Create()
                {
                    CcnUsername = ccnUsername, LngIsoCode = DTO.LngIsoCode, CcnEmail = email, CcnDisplayname = displayName
                }, token, "PxStat.Security.Login_API.Update2FA");
                Response.data = JSONRPC.success;
                return(true);
            }


            Response.error = Label.Get("error.create");
            return(false);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates the analytic entry if one is deemed to be necessary
        /// This method relies on DeviceDetector.NET. Details at https://github.com/totpero/DeviceDetector.NET
        /// It is advisable to frequently check for updates, especially to the regexes folder (situated in the Resources folder of this project)
        /// </summary>
        /// <param name="Ado"></param>
        /// <param name="requestDTO"></param>
        /// <param name="hRequest"></param>
        /// <param name="request"></param>
        internal static void Create(ADO Ado, dynamic requestDTO, HttpRequest hRequest, JSONRPC_API request)
        {
            //If this method doesn't require analytic logging then exit the function here
            if (!MethodReader.MethodHasAttribute(request.method, "Analytic"))
            {
                return;
            }

            Analytic_DTO aDto = new Analytic_DTO();

            //Get a masked version of the ip address
            aDto.NltMaskedIp = getMaskedIp(request.ipAddress);

            //Get the matrix field from the calling DTO
            if (MethodReader.DynamicHasProperty(requestDTO, "jStatQueryExtension"))
            {
                aDto.matrix = requestDTO.jStatQueryExtension.extension.Matrix;
            }

            // Get the Referer
            aDto.NltReferer = hRequest.UrlReferrer == null || String.IsNullOrEmpty(hRequest.UrlReferrer.Host) ? Configuration_BSO.GetCustomConfig("analytic.referrer-not-applicable") : hRequest.UrlReferrer.Host;

            //The m2m parameter will not be translated into a DTO property so we just read it from the request parameters if it exists
            if (MethodReader.DynamicHasProperty(requestDTO, "m2m"))
            {
                aDto.NltM2m = requestDTO.m2m;
            }
            else
            {
                aDto.NltM2m = true;
            }

            // Get the DateTime
            aDto.NltDate = DateTime.Now;

            //Get Format information
            if (MethodReader.DynamicHasProperty(requestDTO, "jStatQueryExtension"))
            {
                if (MethodReader.DynamicHasProperty(requestDTO.jStatQueryExtension.extension.Format, "Type") && MethodReader.DynamicHasProperty(requestDTO.jStatQueryExtension.extension.Format, "Version"))
                {
                    aDto.FrmType    = requestDTO.jStatQueryExtension.extension.Format.Type;
                    aDto.FrmVersion = requestDTO.jStatQueryExtension.extension.Format.Version;
                }
            }


            //Get the device detector and populate the dto attributes
            DeviceDetector deviceDetector = GetDeviceDetector(request.userAgent);

            aDto.NltBotFlag = deviceDetector.IsBot();

            if (deviceDetector.GetBrowserClient().Match != null)
            {
                aDto.NltBrowser = deviceDetector.GetBrowserClient().Match.Name;
            }

            if (deviceDetector.GetOs().Match != null)
            {
                aDto.NltOs = deviceDetector.GetOs().Match.Name;
            }


            var valids = new Analytic_VLD().Validate(aDto);

            //validate whatever has been returned
            if (!valids.IsValid)
            {
                foreach (var fail in valids.Errors)
                {
                    Log.Instance.Debug("Analytic method failed validation:" + request.method + " :" + fail.ErrorMessage);
                }
                return;
            }

            //Create the analytic entry
            Analytic_ADO ado = new Analytic_ADO(Ado);

            if (ado.Create(aDto) == 0)
            {
                Log.Instance.Debug("Failed to create Analytic:" + request.method);
                return;
            }

            return;
        }
Ejemplo n.º 8
0
        internal static void Create(HttpRequest hRequest, string method, string userAgent, string ipaddress, string matrixCode, bool m2m, Format_DTO_Read format)
        {
            ADO Ado = new ADO("defaultConnection");

            try
            {
                Analytic_DTO aDto = new Analytic_DTO()
                {
                    NltMaskedIp = ipaddress, matrix = matrixCode, NltM2m = m2m, NltDate = DateTime.Now, FrmType = format.FrmType, FrmVersion = format.FrmVersion
                };


                // Get the Referer
                aDto.NltReferer = hRequest.UrlReferrer == null || String.IsNullOrEmpty(hRequest.UrlReferrer.Host) ? Configuration_BSO.GetCustomConfig("analytic.referrer-not-applicable") : hRequest.UrlReferrer.Host;


                //Get the device detector and populate the dto attributes
                DeviceDetector deviceDetector = GetDeviceDetector(hRequest.UserAgent);

                aDto.NltBotFlag = deviceDetector.IsBot();

                if (deviceDetector.GetBrowserClient().Match != null)
                {
                    aDto.NltBrowser = deviceDetector.GetBrowserClient().Match.Name;
                }

                if (deviceDetector.GetOs().Match != null)
                {
                    aDto.NltOs = deviceDetector.GetOs().Match.Name;
                }


                var valids = new Analytic_VLD().Validate(aDto);

                //validate whatever has been returned
                if (!valids.IsValid)
                {
                    foreach (var fail in valids.Errors)
                    {
                        Log.Instance.Debug("Analytic method failed validation:" + method + " :" + fail.ErrorMessage);
                    }
                    return;
                }

                //Create the analytic entry
                Analytic_ADO ado = new Analytic_ADO(Ado);

                if (ado.Create(aDto) == 0)
                {
                    Log.Instance.Debug("Failed to create Analytic:" + method);
                    return;
                }

                return;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Ado.Dispose();
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Execute
        /// </summary>
        /// <returns></returns>
        protected override bool Execute()
        {
            //A power user may not create an Administrator
            if (IsPowerUser() && DTO.PrvCode.Equals(Resources.Constants.C_SECURITY_PRIVILEGE_ADMINISTRATOR))
            {
                Log.Instance.Debug("A power user may not create an Administrator");
                Response.error = Label.Get("error.privilege");
                return(false);
            }

            //We need to check if the requested user is in Active Directory, otherwise we refuse the request.
            ActiveDirectory_ADO adAdo = new ActiveDirectory_ADO();

            ActiveDirectory_DTO adDto = adAdo.GetUser(Ado, DTO);

            if (adDto.CcnUsername == null)
            {
                Log.Instance.Debug("AD user not found");
                Response.error = Label.Get("error.create");
                return(false);
            }

            //Validation of parameters and user have been successful. We may now proceed to read from the database
            var adoAccount = new Account_ADO();

            //First we must check if the Account exists already (we can't have duplicates)
            if (adoAccount.Exists(Ado, DTO.CcnUsername))
            {
                //This Account exists already, we can't proceed
                Log.Instance.Debug("Account exists already");
                Response.error = Label.Get("error.duplicate");
                return(false);
            }

            //Create the Account - and retrieve the newly created Id
            int newId = adoAccount.Create(Ado, DTO, SamAccountName, true);

            if (newId == 0)
            {
                Log.Instance.Debug("adoAccount.Create - can't create Account");
                Response.error = Label.Get("error.create");
                return(false);
            }
            string    token = Utility.GetRandomSHA256(newId.ToString());
            Login_BSO lBso  = new Login_BSO(Ado);

            lBso.CreateLogin(new Login_DTO_Create()
            {
                CcnUsername = DTO.CcnUsername
            }, SamAccountName, null);

            //Check if local access is available for AD users
            if (Configuration_BSO.GetCustomConfig(ConfigType.global, "security.adOpenAccess"))
            {
                lBso.UpdateInvitationToken2Fa(DTO.CcnUsername, token);

                SendEmail(new Login_DTO_Create()
                {
                    CcnDisplayname = adDto.CcnDisplayName, CcnEmail = adDto.CcnEmail, CcnUsername = DTO.CcnUsername, LngIsoCode = DTO.LngIsoCode
                }, token, "PxStat.Security.Login_API.Create2FA");
            }

            Response.data = JSONRPC.success;
            return(true);
        }