domingo, 23 de fevereiro de 2014

O outro dia ao programar deparei-me com uns problemas:

- Como posso verificar o tipo de utilizador (User ou Administrator)?
- Como fazer que a aplicação acrescente no Registry uma chave quando se instala ou corre, para que o programa arranque sempre com o Windows independentemente do tipo de utilizador?
- E verificar se por acaso a chave já foi acrescentada no Registry?

Bom vamos a isto, espero que me consigam acompanhar e que me faça entender:

1º Parte do problema, como obter o tipo de utilizador logado no Windows:

WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
bool IsAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);

Com este pedaço de código obtemos o nome de sistema do utilizador, o tipo de conta que está a correr e se tem privilégios de administração do sistema. Consegue-se obter muita mais informação, mas para o objetivo pretendido chega.

2º Parte do problema, acrescentar no Registry uma chave:

O local de escrita de uma chave no Registry do Windows depende dos privilégios que o utilizador tem, isto é, para utilizadores com conta sem poderes de administração só podem ler e escrever na sua conta (CurrentUser):

RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("App", String.Format("\"{0}\"", Application.ExecutablePath));

Se o utilizador conseguir elevar os seu privilégios para administrador, consegue ler e escrever na sua conta, nas contas adjacentes se conseguir obter os SID's de utilizadores e na conta local da máquina (LocalMachine):

RegistryKey rkApp = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
rkApp.SetValue("App", String.Format("\"{0}\"", Application.ExecutablePath));

3ºParte e ultima parte do problema, verificar se a chave já foi acrescentada no Registry?

Talvez a parte mais fácil, um simples if  para resolver o caso:

  string val = (string)rkApp.GetValue("App");

   if (val == string.Empty || val == null){
    rkApp.SetValue("App", String.Format("\"{0}\"", Application.ExecutablePath));
   }
   else{}

Função com o código completo:

private static void SetStartup(){

 WindowsIdentity identity = WindowsIdentity.GetCurrent();
 WindowsPrincipal principal = new WindowsPrincipal(identity);
 bool IsAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);

 if (IsAdmin){

  using(RegistryKey rkApp = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
  if (rkApp != null){
  string val = (string)rkApp.GetValue("App");

   if (val == string.Empty || val == null){
    rkApp.SetValue("App", String.Format("\"{0}\"", Application.ExecutablePath));
   }
   else{}
  }
  else{
   rkApp.SetValue("App", String.Format("\"{0}\"", Application.ExecutablePath));
  }
 }
 else{
  using (RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))

  if (rkApp != null){
   string val = (string)rkApp.GetValue("App");

   if (val == string.Empty || val == null){
    rkApp.SetValue("App", String.Format("\"{0}\"", Application.ExecutablePath));
   }
   else{}
  }
  else{
   rkApp.SetValue("App", String.Format("\"{0}\"", Application.ExecutablePath));
  }
 }
}

Duvidas?

Bom espero que este pedaço de código ajude alguém a resolver o mesmo ou outro problema.

 
DSD7JC65XQ4Z

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Labels

Question Dump A30-327 ACE AccessData AccessData ACE AccessData Certified Examiner AccessData FTK FTK Segurança da Informação Software (ISC)² CISSP Certified Information System Security Professional Preparação para Certificação Browsers Ferramentas Windows Análise Forense Microsoft OSINT Ouya Redes Android Malware Open Source Open Source Intelligence Sysinternals Sysinternals Live Sysinternals tools Cache Cookies Fingerprint Games Internet Explorer Mozilla Firefox Notícia Pentesting Python Script Skype Vulnerabilidades .dd .net 3.5 1Z0-144 ARPwner AccessChk v5.11 AccessEnum v1.32 Auburn Base de Dados Bypass C# CERT CISP CMS CSIP Canonical Centro de Cibersegurança China China Software and Integrated Chip Promotions Ciência Forense Computacional Cloud Creepy Cyber Security Information Sharing Partnership Código Dev Developer Disassembler Exploits FOCA Favorites Fingerprinting Organizations with Collected Archives Firefox Foundstone FoxOne Scanner Futuremark GCHQ Galleta GameInformer Gamepop Gaming Geolocalization Github Gmail Google Chrome Hardware Hash Hotmail IDS IP IPS JSON Javascript Object Notation Format Kaspersky Lab Kon-boot Live View MAC OSX MAC OSX Bypass MI5 Malware Bancário McAfee labs Microsoft Office Mozilla Foundation Msiecfexport Netflix Nirsoft Nmap Notepad++ ODA Online DisAssembler Oracle Oracle 11G Oryon C Oryon C Portable Outlook Ouya Specs PL/SQL Pasco Passwords Phishing Poisoning Programar Programação RAW RPC Republica Popular da China SQL SQLite Sandbox Sandboxie Scan Security Meeting ShadowSEC Skype Log Viewer Smartphones SmoothSec Startup Terdot The Verge Timestamp Trojan UK Ubuntu UbuntuKylin OS Userrole Virtualização WIFI WebApp Webmails Windows Bypass Windows Registry Write Blocker XML Yahoo Zeus hash-identifier iFixIt index.dat profiles.ini sqlite3 th3j35t3r wig

Posts + Vistos

Com tecnologia do Blogger.