Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Need help - DllImport exception (Security)

streamwriter import

  • Please log in to reply
No replies to this topic

#1 Parabola

Parabola

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 221 posts

Posted 18 January 2011 - 06:54 AM

I need some help with a simple script I have. It impersonates the local administrator to check running processes for a certain program (a prereq. for another program being launched through AppV). If it's not running, it runs it. Really simple. Reason it has to impersonate local admin is we are running this on clinical machines that are locked down- no access to task manager.
The application (and the script it runs prelaunch) are deployed to about 10K PCs.... and is working fine. Except on about 3 of them.
These machines are getting an error that I can't catch in a try catch statement, since they are coming from DllImports...

I have tried completely re-imaging these machines, and making sure the .NET framework was up to date. I've checked everything.
Here's the real fun part:
If I run the script from the .application deployment... it works. However, if I run the .exe (either from bin/x86 folder, or from the actual publish folder [app.exe.deploy > app.exe]) I get the error.
But- considering the way it is deployed, I really can't have it run the click once deployment.
Here's the error:

C:\WINDOWS\system32>"\\texas\appv\Content\CareConnect_EPIC_AppV\Temp\Application
Files\runSTRMIT_1_0_0_29\runSTRMIT.exe"

Unhandled Exception: System.Security.SecurityException: Request failed.
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly a
sm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, Secur
ityAction action, Object demand, IPermission permThatFailed)
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Object **
emblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle
rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet gran
ts, PermissionSet refused, PermissionSet demands, RuntimeMethodHandle rmh, Objec
t assemblyOrString, SecurityAction action, Boolean throwException)
at System.Security.CodeAccessSecurityEngine.CheckSetHelper(CompressedStack cs
, PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMet
hodHandle rmh, Assembly asm, SecurityAction action)
at runSTRMIT.Program.Main(String[] args)
The action that failed was:
LinkDemand
The type of the first permission that failed was:
System.Security.PermissionSet
The demand was for:
<PermissionSet class="System.Security.PermissionSet"
version="1"
Unrestricted="true"/>

The granted set of the failing assembly was:
<PermissionSet class="System.Security.PermissionSet"
version="1">
<IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Read="USERNAME"/>
<IPermission class="System.Security.Permissions.FileDialogPermission, mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Unrestricted="true"/>
<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Vers
ion=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Read="\\TEXAS\APPV\Content\CareConnect_EPIC_AppV\Temp\Application Files\runSTRMI
T_1_0_0_29\"
PathDiscovery="\\TEXAS\APPV\Content\CareConnect_EPIC_AppV\Temp\Application Files
\runSTRMIT_1_0_0_29\"/>
<IPermission class="System.Security.Permissions.IsolatedStorageFilePermission, m
scorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Allowed="AssemblyIsolationByUser"
UserQuota="9223372036854775807"
Expiry="9223372036854775807"
Permanent="True"/>
<IPermission class="System.Security.Permissions.ReflectionPermission, mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="ReflectionEmit"/>
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Ve
rsion=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="Assertion, Execution, BindingRedirects"/>
<IPermission class="System.Security.Permissions.UIPermission, mscorlib, Version=
2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Unrestricted="true"/>
<IPermission class="System.Security.Permissions.UrlIdentityPermission, mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Url="file://texas/appv/Content/CareConnect_EPIC_AppV/Temp/Application Files/runS
TRMIT_1_0_0_29/runSTRMIT.exe"/>
<IPermission class="System.Security.Permissions.ZoneIdentityPermission, mscorlib
, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Zone="Intranet"/>
<IPermission class="System.Net.DnsPermission, System, Version=2.0.0.0, Culture=n
eutral, PublicKeyToken=b77a5c561934e089"
version="1"
Unrestricted="true"/>
<IPermission class="System.Drawing.Printing.PrintingPermission, System.Drawing,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
version="1"
Level="DefaultPrinting"/>
</PermissionSet>


And the Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.IO;
using System.Security;

namespace runSTRMIT
{
    class Program
    {

        static void Main(string[] args)
        {
            bool running = false;
            bool impers = false;
            try
            {
                try
                {
                    Console.WriteLine("Checking Processes as local user");
                    foreach (Process clsProcess in Process.GetProcessesByName("Client"))
                    {
                        if (clsProcess.ProcessName.Length > 0)
                        {
                            running = true;
                        }
                    }
                }
                catch
                {
                    Console.WriteLine("Failed");
                    try
                    {
                        Console.WriteLine("Trying local admin: Administrator");
                        if (!fake.Impersonate("Administrator", "************", Environment.MachineName))
                        {
                            Console.WriteLine("Administrator Failed!");
                            if (!fake.Impersonate("shawl", "************", Environment.MachineName))
                            {
                                log("Impersonation Failed!");
                            }
                            else
                            {
                                impers = true;
                            }
                        }
                        else
                        {
                            impers = true;
                        }

                        foreach (Process clsProcess in Process.GetProcessesByName("Client"))
                        {
                            if (clsProcess.ProcessName.Length > 0)
                            {
                                running = true;
                            }
                        }
                    }
                    catch
                    {
                        Console.WriteLine("X:X");
                    }
                }
                if (impers)
                {
                    fake.UnImpersonate();
                }
                if (running)
                {
                    Console.WriteLine("STRM-IT is already running");

                }
                else
                {
                    Console.WriteLine("STRM-IT is not running");
                    Console.WriteLine("Launching");
                    Process p = Process.Start("C:\\Program Files\\Microsoft Application Virtualization Client\\sfttray.exe", "/launch \"STRM-IT Client 5.0.0.20\"");
                }
                
            }
            catch (Exception ex)
            {
                
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
            
        }
        static void log(string note)
        {
            try
            {
                using (StreamWriter logFile = new StreamWriter("\\\\texas\\appv\\content\\CareConnect_EPIC_AppV\\LogFiles\\" + Environment.MachineName + ".txt", true))
                {
                    logFile.WriteLine(DateTime.Now + ": " + note);
                    logFile.WriteLine(Environment.MachineName + ":  " + Environment.UserDomainName + "\\" + Environment.UserName);
                    logFile.Close();
                }
            }
            catch
            {

            }

        }
        

        
    }

    class fake
    {
        public static bool Impersonate(string logon, string password, string
        domain)
        {
            try
            {

                WindowsIdentity tempWindowsIdentity;
                IntPtr token = IntPtr.Zero;
                IntPtr tokenDuplicate = IntPtr.Zero;
                SecurityPermissionAttribute permat = new SecurityPermissionAttribute(SecurityAction.Demand);
                SecurityPermission perm = new SecurityPermission(PermissionState.Unrestricted);
                IPermission Iperm = permat.CreatePermission();
                Iperm.Demand();
                perm.Demand();
                
                
                if (LogonUser(logon, 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 (null != impersonationContext) return true;
                    }
                }

                return false;
            }
            catch (SecurityException **)
            {
                Console.WriteLine(**.Message);
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }

        }

        public static void UnImpersonate()
        {
            try
            {
                impersonationContext.Undo();
            }
            catch (Exception ex)
            {

            }
        }
        

        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
         public static extern int LogonUser(
        string lpszUserName,
        String lpszDomain,
        String lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        ref IntPtr phToken);

        
    
    
        [DllImport("advapi32.dll",
        CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]
         public extern static int DuplicateToken(
        IntPtr hToken,
        int impersonationLevel,
        ref IntPtr hNewToken);

        private const int LOGON32_LOGON_INTERACTIVE = 2;
        private const int LOGON32_LOGON_NETWORK_CLEARTEXT = 4;
        private const int LOGON32_PROVIDER_DEFAULT = 0;
        private static WindowsImpersonationContext impersonationContext;
   

    }

    
}

Yes, I had the passwords in there... not concerned with that right now. I just need to figure out how to catch the stupid exception, at this point it doesn't even matter if I just make the program ignore it.


EDIT: BTW, code is very ugly now, because I have made so many changes, thrown in extra try catch statements, etc,trying anything to get it to work. So please, bear with it :)
  • 0
Programmer (n): An organism that can turn caffeine into code.
Programming would be so much easier without all the users.





Also tagged with one or more of these keywords: streamwriter, import

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download