CACIC_Library.pas 34.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
{*------------------------------------------------------------------------------
   Package of both methods/properties to be used by CACIC Clients

   @version CACIC_Library 2009-01-07 23:00 harpiain
   @package CACIC_Agente
   @subpackage CACIC_Library
   @author Adriano dos Santos Vieira <harpiain at gmail.com>
   @copyright Copyright (C) Adriano dos Santos Vieira. All rights reserved.
   @license GNU/GPL, see LICENSE.php
   CACIC_Library is free software and parts of it may contain or be derived from
   the GNU General Public License or other free or open source software license.
   See COPYRIGHT.php for copyright notices and details.

   CACIC_Library - Coding style
   for Constants
      - characters always in uppercase
      - use underscore for long name
      e.g.
        const CACIC_VERSION = '2.4.0';

   for Variables
      - characters always in lowercase
      - start with "g" character for global
      - start with "v" character for local
      - start with "p" character for methods parameters
      - start with "P" character for pointers
      - use underscore for better read
      e.g.
        var g_global : string;
        var v_local  : string;

   for Objects
      - start with "o" character
      e.g.
        oCacicObject : TCACIC_Common;

   for Methods
      - start with lowercase word
      - next words start with capital letter
      e.g.
        function getCacicPath() : string;
        procedure setCacicPath( pPath: string );
-------------------------------------------------------------------------------}

unit CACIC_Library;

interface

uses 
	Windows,
    Classes,
    SysUtils,
    StrUtils,
    MD5,
    DCPcrypt2,
    DCPrijndael,
    DCPbase64,
    ActiveX,
    ComObj;
type

{ ------------------------------------------------------------------------------
  Tipo de dados para obter informacoes extendidas dos Sistema Operacional
  ver MSDN: http://msdn.microsoft.com/en-us/library/ms724833(VS.85).aspx
-------------------------------------------------------------------------------}
  TOSVersionInfoEx = packed record
    dwOSVersionInfoSize: DWORD;
    dwMajorVersion: DWORD;
    dwMinorVersion: DWORD;
    dwBuildNumber: DWORD;
    dwPlatformId: DWORD;
    szCSDVersion: array[0..127] of AnsiChar;
    wServicePackMajor: WORD;
    wServicePackMinor: WORD;
    wSuiteMask: WORD;
    wProductType: Byte;
    wReserved: Byte;
  end;

{*------------------------------------------------------------------------------
 Classe para obter informações do sistema windows
-------------------------------------------------------------------------------}
   TCACIC_Windows = class
       private

       protected
         /// Mantem a identificação do sistema operacional
         g_osVersionInfo: TOSVersionInfo;
         /// Mantem a identificação extendida do sistema operacional
         g_osVersionInfoEx: TOSVersionInfoEx;
         /// TRUE se houver informação extendida do SO, FALSE caso contrário
         g_osVersionInfoExtended: boolean;

       public
         function  isWindowsVista()                                     : boolean;
         function  isWindowsGEVista()                                   : boolean;
         function  isWindowsXP()                                        : boolean;
         function  isWindowsGEXP()                                      : boolean;
         function  isWindowsNTPlataform()                               : boolean;
         function  isWindows2000()                                      : boolean;
         function  isWindowsNT()                                        : boolean;
         function  isWindows9xME()                                      : boolean;
         function  getWindowsStrId()                                    : string;
         function  getWinDir()                                          : string;
         function  getHomeDrive()                                         : string;
         function  isWindowsAdmin()                                     : boolean;
         function  createSampleProcess(p_cmd: string; p_wait: boolean; p_showWindow : word = SW_HIDE): boolean;
         procedure showTrayIcon(p_visible:boolean);
         procedure addApplicationToFirewall(p_EntryName:string;p_ApplicationPathAndExe:string; p_Enabled : boolean);         
   end;

{*------------------------------------------------------------------------------
 Classe para tratamento de debug
-------------------------------------------------------------------------------}
   TCACIC_Debug = class
       private

       protected
         /// TRUE se em mode de debug, FALSE caso contrário
         g_debug: boolean;

       public
         procedure debugOn();
         procedure debugOff();
         function inDebugMode() : boolean;
   end;
{*------------------------------------------------------------------------------
 Classe geral da biblioteca
-------------------------------------------------------------------------------}
   TCACIC = class(TCACIC_Windows)
       constructor Create();
       destructor Destroy; override;
       private

       protected
         /// Mantem o caminho físico de instalação do agente cacic
         g_cacic_path: string;
         g_boolCipher : boolean;

       public
         Windows : TCACIC_Windows; /// objeto de informacoes de windows
         Debug   : TCACIC_Debug; /// objeto de tratamento de debug
         procedure setCacicPath(p_cacic_path: string);
         procedure setBoolCipher(p_boolCipher : boolean);
         function  deCrypt(p_Data : String)                           : String;
         function  enCrypt(p_Data : String)                           : String;
         function  explode(p_String, p_Separador : String)            : TStrings;
         function  implode(p_Array : TStrings ; p_Separador : String) : String;
         function  getCacicPath()                                     : String;
         function  getCipherKey()                                     : String;
         function  getBoolCipher()                                    : boolean;
         function  getIV()                                            : String;
         function  getKeySize()                                       : integer;
         function  getBlockSize()                                     : integer;
         function  getDatFileName()                                   : String;
         function  getSeparatorKey()                                  : String;
         function  getFileHash(strFileName : String)                  : String;
         function  isAppRunning( p_app_name: PAnsiChar )              : boolean;
         function  padWithZeros(const str : string; size : integer)   : String;
         function  trimEspacosExcedentes(p_str: string)               : String;

   end;

// Declaração de constantes para a biblioteca
const
  CACIC_PROCESS_WAIT   = true; // aguardar fim do processo
  CACIC_PROCESS_NOWAIT = false; // não aguardar o fim do processo

// Some constants that are dependant on the cipher being used
// Assuming MCRYPT_RIJNDAEL_128 (i.e., 128bit blocksize, 256bit keysize)
const
  CACIC_KEYSIZE        = 32; // 32 bytes = 256 bits
  CACIC_BLOCKSIZE      = 16; // 16 bytes = 128 bits

// Chave AES. Recomenda-se que cada empresa altere a sua chave.
// Esta chave é passada como parâmetro para o Gerente de Coletas que, por sua vez,
// passa para o Inicializador de Coletas e este passa para os coletores...
const
  CACIC_CIPHERKEY      = 'CacicBrasil';
  CACIC_IV             = 'abcdefghijklmnop';
  CACIC_SEPARATORKEY   = '=CacicIsFree='; // Usada apenas para o cacic2.dat

// Arquivo local para armazenamento de configurações e informações coletadas
const
  CACIC_DATFILENAME    = 'cacic2.dat';


{
 Controle de prioridade de processo
 http://msdn.microsoft.com/en-us/library/ms683211(VS.85).aspx
}
const BELOW_NORMAL_PRIORITY_CLASS = $00004000;
  {$EXTERNALSYM BELOW_NORMAL_PRIORITY_CLASS}

var
  P_OSVersionInfo: POSVersionInfo;

implementation

{*------------------------------------------------------------------------------
  Construtor para a classe

  Objetiva inicializar valores a serem usados pelos objetos da
  classe.
-------------------------------------------------------------------------------}
constructor TCACIC.Create();
begin
  FillChar(Self.g_osVersionInfoEx, SizeOf(Self.g_osVersionInfoEx), 0);
  {$TYPEDADDRESS OFF}
  P_OSVersionInfo := @Self.g_osVersionInfoEx;
  {$TYPEDADDRESS ON}

  Self.g_osVersionInfoEx.dwOSVersionInfoSize:= SizeOf(TOSVersionInfoEx);
  Self.g_osVersionInfoExtended := GetVersionEx(P_OSVersionInfo^);
  if (not Self.g_osVersionInfoExtended) then begin
     Self.g_osVersionInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
     GetVersionEx(Self.g_osVersionInfo);
  end;
  Self.Windows := TCACIC_Windows.Create();
  Self.Debug := TCACIC_Debug.Create();
end;

{*------------------------------------------------------------------------------
  Destrutor para a classe

  Objetiva finalizar valores usados pelos objetos da classe.
-------------------------------------------------------------------------------}
destructor TCACIC.Destroy();
begin
   FreeMemory(P_OSVersionInfo);
   inherited;
end;

{*------------------------------------------------------------------------------
  Retorna a pasta de instalação do MS-Windows
-------------------------------------------------------------------------------}
function TCACIC_Windows.getWinDir : string;
var
  WinPath: array[0..MAX_PATH + 1] of char;
begin
  GetWindowsDirectory(WinPath,MAX_PATH);
  Result := StrPas(WinPath)+'\';
end;

{*------------------------------------------------------------------------------
  Retorna a unidade de instalação do MS-Windows
-------------------------------------------------------------------------------}
function TCACIC_Windows.getHomeDrive() : string;
begin
  Result := MidStr(getWinDir,1,3); //x:\
end;

{*------------------------------------------------------------------------------
  Insere exceção na FireWall nativa do MS-Windows

  @param p_EntryName             String  Nome da exceção
  @param p_ApplicationPathAndExe String  Caminho e nome da aplicação
  @param p_Enabled               Boolean Estado da exceção
-------------------------------------------------------------------------------}
procedure TCACIC_Windows.addApplicationToFirewall(p_EntryName:string;p_ApplicationPathAndExe:string; p_Enabled : boolean);
var   fwMgr,app:OleVariant;
      profile:OleVariant;
Const NET_FW_PROFILE_DOMAIN = 0;
      NET_FW_PROFILE_STANDARD = 1;
      NET_FW_IP_VERSION_ANY = 2;
      NET_FW_IP_PROTOCOL_UDP = 17;
      NET_FW_IP_PROTOCOL_TCP = 6;
      NET_FW_SCOPE_ALL = 0;
      NET_FW_SCOPE_LOCAL_SUBNET = 1;
begin
  CoInitialize(nil);

  fwMgr := CreateOLEObject('HNetCfg.FwMgr');
  profile := fwMgr.LocalPolicy.CurrentProfile;
  app := CreateOLEObject('HNetCfg.FwAuthorizedApplication');
  app.ProcessImageFileName := p_ApplicationPathAndExe;
  app.Name := p_EntryName;
  app.Scope := NET_FW_SCOPE_ALL;
  app.IpVersion := NET_FW_IP_VERSION_ANY;
  app.Enabled := p_Enabled;
  profile.AuthorizedApplications.Add(app);

  CoUninitialize;
end;

{*------------------------------------------------------------------------------
  Retorna array de elementos com base em separador

  @param p_String    String contendo campos e valores separados por caracter ou string
  @param p_Separador String separadora de campos e valores
-------------------------------------------------------------------------------}
Function TCACIC.explode(p_String, p_Separador : String) : TStrings;
var
    strItem       : String;
    ListaAuxUTILS : TStrings;
    NumCaracteres,
    TamanhoSeparador,
    I : Integer;
Begin
    ListaAuxUTILS    := TStringList.Create;
    strItem          := '';
    NumCaracteres    := Length(p_String);
    TamanhoSeparador := Length(p_Separador);
    I                := 1;
    While I <= NumCaracteres Do
      Begin
        If (Copy(p_String,I,TamanhoSeparador) = p_Separador) or (I = NumCaracteres) Then
          Begin
            if (I = NumCaracteres) then strItem := strItem + p_String[I];
            ListaAuxUTILS.Add(trim(strItem));
            strItem := '';
            I := I + (TamanhoSeparador-1);
          end
        Else
            strItem := strItem + p_String[I];

        I := I + 1;
      End;
    Explode := ListaAuxUTILS;
end;

{*------------------------------------------------------------------------------
  Retorna string com campos e valores separados por caracter ou string

  @param p_Array     Array contendo campos e valores
  @param p_Separador String separadora de campos e valores
-------------------------------------------------------------------------------}
Function TCACIC.implode(p_Array : TStrings ; p_Separador : String) : String;
var intAux : integer;
    strAux : string;
Begin
    strAux := '';
    For intAux := 0 To p_Array.Count -1 do
      Begin
        if (strAux<>'') then strAux := strAux + p_Separador;
        strAux := strAux + p_Array[intAux];
      End;
    Implode := strAux;
end;

{*------------------------------------------------------------------------------
  Elimina espacos excedentes na string

  @param p_str String a excluir espacos
-------------------------------------------------------------------------------}
function TCACIC.trimEspacosExcedentes(p_str: String): String;
begin
  if(ansipos('  ', p_str ) <> 0 ) then
    repeat
      p_str := StringReplace( p_str, '  ', ' ', [rfReplaceAll] );
    until ( ansipos( '  ', p_str ) = 0 );

  Result := p_str;
end;

{*------------------------------------------------------------------------------
  Atribui valor booleano à variável indicadora do status da criptografia

  @param p_boolCipher Valor booleano para atribuição à variável para status da
                      criptografia.
-------------------------------------------------------------------------------}
procedure TCACIC.setBoolCipher(p_boolCipher : boolean);
Begin
  Self.g_boolCipher := p_boolCipher;
End;
{*------------------------------------------------------------------------------
  Obtém o status da criptografia (TRUE -> Ligada  /  FALSE -> Desligada)

  @return boolean contendo o status para a criptografia
-------------------------------------------------------------------------------}
function TCACIC.getBoolCipher() : boolean;
Begin
  Result := Self.g_boolCipher;
End;

{*------------------------------------------------------------------------------
  Atribui o caminho físico de instalação do agente cacic

  @param p_cacic_path Caminho físico de instalação do agente cacic
-------------------------------------------------------------------------------}
procedure TCACIC.setCacicPath(p_cacic_path: string);
begin
  Self.g_cacic_path := p_cacic_path;
end;

{*------------------------------------------------------------------------------
  Obter o caminho fisico de instalacao do agente cacic

  @return String contendo o caminho físico
-------------------------------------------------------------------------------}
function TCACIC.getCacicPath(): string;
begin
   Result := Self.g_cacic_path;
end;

{*------------------------------------------------------------------------------
  Verifica se a aplicação está em execução

  @param p_app_name Nome da aplicação a ser verificada
  @return TRUE se em execução, FALSE caso contrário
-------------------------------------------------------------------------------}
function TCACIC.isAppRunning( p_app_name: PAnsiChar ): boolean;
var
	MutexHandle: THandle;

begin
   MutexHandle := CreateMutex(nil, TRUE, p_app_name);
   if (MutexHandle = 0) OR (GetLastError = ERROR_ALREADY_EXISTS)
      then Result := true
      else Result := false;
end;

{*------------------------------------------------------------------------------
  Coloca o sistema em modo de debug

-------------------------------------------------------------------------------}
procedure TCACIC_Debug.debugOn();
begin
  Self.g_debug := true;
end;

{*------------------------------------------------------------------------------
  Desliga o modo de debug do sistema

-------------------------------------------------------------------------------}
procedure TCACIC_Debug.debugOff();
begin
  Self.g_debug := false;
end;

{*------------------------------------------------------------------------------
  Coloca o sistema em modo de debug

  @return String contendo o caminho físico
-------------------------------------------------------------------------------}
function TCACIC_Debug.inDebugMode() : boolean;
begin
   Result := Self.g_debug;
end;

{*------------------------------------------------------------------------------
  Verifica se é Windows Vista ou superior

  @return TRUE se Windows Vista ou superior, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista, isWindowsGEVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsGEVista() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
      if((g_osVersionInfoEx.dwMajorVersion >= 6) and (g_osVersionInfoEx.dwMinorVersion >= 0)) then
         Result := true;
   end
   else
      if((g_osVersionInfo.dwMajorVersion >= 6) and (g_osVersionInfo.dwMinorVersion >= 0)) then
         Result := true;
end;

{*------------------------------------------------------------------------------
  Verifica se é Windows Vista

  @return TRUE se Windows Vista, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsVista() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
     if((g_osVersionInfoEx.dwMajorVersion = 6) and (g_osVersionInfoEx.dwMinorVersion = 0)) then
        Result := true;
   end
   else
     if((g_osVersionInfo.dwMajorVersion = 6) and (g_osVersionInfo.dwMinorVersion = 0)) then
        Result := true;
end;

{*------------------------------------------------------------------------------
  Verifica se é Windows XP ou superior

  @return TRUE se Windows XP ou superior, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsGEXP() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
     if((g_osVersionInfoEx.dwMajorVersion >= 5) and (g_osVersionInfoEx.dwMinorVersion >= 1)) then
        Result := true;
   end
   else
     if((g_osVersionInfo.dwMajorVersion >= 5) and (g_osVersionInfo.dwMinorVersion >= 1)) then
        Result := true;
end;

{*------------------------------------------------------------------------------
  Verifica se é Windows XP

  @return TRUE se Windows XP, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsXP() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
     if((g_osVersionInfoEx.dwMajorVersion = 5) and (g_osVersionInfoEx.dwMinorVersion = 1)) then
        Result := true;
   end
   else
     if((g_osVersionInfo.dwMajorVersion = 5) and (g_osVersionInfo.dwMinorVersion = 1)) then
        Result := true;
end;

{*------------------------------------------------------------------------------
  Verifica se é Windows 2000

  @return TRUE se Windows 2000, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindows2000() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
     if((g_osVersionInfoEx.dwMajorVersion = 5) and (g_osVersionInfoEx.dwMinorVersion = 0)) then
        Result := true;
   end
   else
     if((g_osVersionInfo.dwMajorVersion = 5) and (g_osVersionInfo.dwMinorVersion = 0)) then
        Result := true;
end;

{*------------------------------------------------------------------------------
  Verifica se é Windows NT

  @return TRUE se Windows NT, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsNT() : boolean;
begin
   Result := false;
   if(Self.g_osVersionInfoExtended) then begin
      if((g_osVersionInfoEx.dwMajorVersion = 4) and (g_osVersionInfoEx.dwMinorVersion = 0)) then
         Result := true;
   end
   else
      if((g_osVersionInfo.dwMajorVersion = 4) and (g_osVersionInfo.dwMinorVersion = 0)) then
         Result := true;
end;

{*------------------------------------------------------------------------------
  Verifica se a plataforma do sistema é de windows 9x ou ME

  @return TRUE se plataforma de Windows 9x/ME, FALSE caso contrário
  @see isWindowsNTPlataform, isWindows9xME, isWindowsNT, isWindows2000
  @see isWindowsXP, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindows9xME() : boolean;
begin
  if (Self.g_osVersionInfoExtended) then
     Result := (Self.g_osVersionInfoEx.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS)
  else
     Result := (Self.g_osVersionInfo.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS);
end;

{*------------------------------------------------------------------------------
  Obter identificação extensa do sistema operacional

  @return String de identificação do sistema operacional
  @example 1.4.10.A
-------------------------------------------------------------------------------}
function TCACIC_Windows.getWindowsStrId() : string;
var
   v_version_id: string;
begin
  v_version_id := 'S.O.unknown';
  try
	  if (Self.g_osVersionInfoExtended) then
		 if(Self.isWindows9xME) then
			v_version_id := IntToStr(Self.g_osVersionInfoEx.dwPlatformId) + '.' +
				   IntToStr(Self.g_osVersionInfoEx.dwMajorVersion) + '.' +
				   IntToStr(Self.g_osVersionInfoEx.dwMinorVersion) +
				   ifThen(trim(Self.g_osVersionInfoEx.szCSDVersion)='',
						 '',
						 '.'+trim(Self.g_osVersionInfoEx.szCSDVersion))
		 else
			v_version_id := IntToStr(Self.g_osVersionInfoEx.dwPlatformId) + '.' +
				   IntToStr(Self.g_osVersionInfoEx.dwMajorVersion) + '.' +
				   IntToStr(Self.g_osVersionInfoEx.dwMinorVersion) + '.' +
				   IntToStr(Self.g_osVersionInfoEx.wProductType) + '.' +
				   IntToStr(Self.g_osVersionInfoEx.wSuiteMask)
	  else
		 v_version_id := IntToStr(Self.g_osVersionInfo.dwPlatformId) + '.' +
				   IntToStr(Self.g_osVersionInfo.dwMajorVersion) + '.' +
				   IntToStr(Self.g_osVersionInfo.dwMinorVersion) +
				   ifThen(trim(Self.g_osVersionInfo.szCSDVersion)='',
						 '',
						 '.'+trim(Self.g_osVersionInfo.szCSDVersion));
  except
  end;
  Result := v_version_id;

end;

{*------------------------------------------------------------------------------
  Verifica se a plataforma do sistema é de Windows NT

  @return TRUE se plataforma de Windows NT, FALSE caso contrário
  @see isWindows9xME, isWindowsVista
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsNTPlataform() : boolean;
begin
  if(Self.g_osVersionInfoExtended)
    then Result := (Self.g_osVersionInfoEx.dwPlatformId = VER_PLATFORM_WIN32_NT)
    else Result := (Self.g_osVersionInfo.dwPlatformId = VER_PLATFORM_WIN32_NT);
end;

{*------------------------------------------------------------------------------
  Verifica se é administrador do sistema operacional se em plataforma NT

  @return TRUE se administrador do sistema, FALSE caso contrário
-------------------------------------------------------------------------------}
function TCACIC_Windows.isWindowsAdmin(): Boolean;

const
   constSECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5));
   constSECURITY_BUILTIN_DOMAIN_RID = $00000020;
   constDOMAIN_ALIAS_RID_ADMINS = $00000220;

var
   hAccessToken: THandle;
   ptgGroups: PTokenGroups;
   dwInfoBufferSize: DWORD;
   psidAdministrators: PSID;
   x: Integer;
   bSuccess: BOOL;
    
begin
  if (not Self.isWindowsNTPlataform()) then // Se nao NT (ex: Win95/98)
       // Se nao eh NT nao tem ''admin''
       Result   := True
  else begin
	  Result   := False;
	  bSuccess := OpenThreadToken(GetCurrentThread, TOKEN_QUERY, True, hAccessToken);
	  if not bSuccess then begin
  		 if GetLastError = ERROR_NO_TOKEN then
	        bSuccess := OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, hAccessToken);
	  end;
	  if bSuccess then begin
		GetMem(ptgGroups, 1024);
		bSuccess := GetTokenInformation(hAccessToken, TokenGroups, ptgGroups, 1024, dwInfoBufferSize);
		CloseHandle(hAccessToken);
		if bSuccess then begin
		  AllocateAndInitializeSid(constSECURITY_NT_AUTHORITY, 2,
								   constSECURITY_BUILTIN_DOMAIN_RID,
								   constDOMAIN_ALIAS_RID_ADMINS,
								   0, 0, 0, 0, 0, 0, psidAdministrators);
		  {$R-}
		  for x := 0 to ptgGroups.GroupCount - 1 do
          if EqualSid(psidAdministrators, ptgGroups.Groups[x].Sid) then begin
			       Result := True;
			       Break;
			    end;
		  {$R+}
		  FreeSid(psidAdministrators);
		end;
		FreeMemory(ptgGroups);
	  end;
  end;
end;

{*------------------------------------------------------------------------------
  Executa commandos, substitui o WinExec

  @autor: Marcos Dell Antonio
  @param p_cmd        Comando a ser executado
  @param p_wait       TRUE se deve aguardar término da excução, FALSE caso contrário
-------------------------------------------------------------------------------}
{function TCACIC_Windows.createSampleProcess(p_cmd: string; p_wait: boolean ): boolean;
begin
end;
}
{*------------------------------------------------------------------------------
  Executa commandos, substitui o WinExec

  @autor: Marcos Dell Antonio
  @param p_cmd        Comando a ser executado
  @param p_wait       TRUE se deve aguardar término da excução, FALSE caso contrário
  @param p_showWindow Constante que define o tipo de exibição da janela do aplicativo
-------------------------------------------------------------------------------}
function TCACIC_Windows.createSampleProcess(p_cmd: string; p_wait: boolean; p_showWindow : word = SW_HIDE): boolean;
var
  SUInfo: TStartupInfo;
  ProcInfo: TProcessInformation;
begin
  FillChar(SUInfo, SizeOf(SUInfo), #0);
  SUInfo.cb      := SizeOf(SUInfo);
  SUInfo.dwFlags := STARTF_USESHOWWINDOW;
  SUInfo.wShowWindow := p_showWindow;

  Result := CreateProcess(nil,
                          PChar(p_cmd),
                          nil,
                          nil,
                          false,
                          CREATE_NEW_CONSOLE or
                          BELOW_NORMAL_PRIORITY_CLASS,
                          nil,
                          nil,
                          SUInfo,
                          ProcInfo);

  if (Result) then
  begin
    if(p_wait) then begin
       WaitForSingleObject(ProcInfo.hProcess, INFINITE);
       CloseHandle(ProcInfo.hProcess);
       CloseHandle(ProcInfo.hThread);
    end;
  end;
end;

{*------------------------------------------------------------------------------
  Para cálculo de HASH de determinado arquivo.

  @autor: Anderson Peterle
  @param p_strFileName - Nome do arquivo para extração do HashCode
-------------------------------------------------------------------------------}
function TCACIC.GetFileHash(strFileName : String) : String;
Begin
  Result := 'Arquivo "'+strFileName+'" Inexistente!';
  if (FileExists(strFileName)) then
    Result := MD5Print(MD5File(strFileName));
End;

{*------------------------------------------------------------------------------
  Mostra ou oculta o cacic na "systray" do windows

  @autor: Diversos - compilado de vários exemplos obtidos na internet
  @param p_visible TRUE se deve mostrar na systray, FALSE caso contrário
-------------------------------------------------------------------------------}
procedure TCACIC_Windows.showTrayIcon(p_visible:boolean);
 Var
   v_tray, v_child : hWnd;
   v_char : Array[0..127] of Char;
   v_string : String;

 Begin
   v_tray := FindWindow('Shell_TrayWnd', NIL);
   v_child := GetWindow(v_tray, GW_CHILD);
   While v_child <> 0
      do Begin
         If GetClassName(v_child, v_char, SizeOf(v_char)) > 0
            Then Begin
                v_string := StrPAS(v_char);
                If UpperCase(v_string) = 'TRAYNOTIFYWND'
                   then begin
                       If p_visible
                          then ShowWindow(v_child, 1)
                          else ShowWindow(v_child, 0);
                   end;
            End;
         v_child := GetWindow(v_child, GW_HWNDNEXT);
      End;
 End;

{*------------------------------------------------------------------------------
  Obter a chave para criptografia simétrica

  @return String contendo a chave simétrica
-------------------------------------------------------------------------------}
function TCACIC.getCipherKey(): string;
begin
   Result := CACIC_CIPHERKEY;
end;

{*------------------------------------------------------------------------------
  Obter o vetor de inicialização para criptografia

  @return String contendo o vetor de inicialização
-------------------------------------------------------------------------------}
function TCACIC.getIV(): string;
begin
   Result := CACIC_IV;
end;

{*------------------------------------------------------------------------------
  Obter o valor para tamanho da chave de criptografia

  @return Integer contendo o tamanho para chave de criptografia
-------------------------------------------------------------------------------}
function TCACIC.getKeySize(): Integer;
begin
   Result := CACIC_KEYSIZE;
end;

{*------------------------------------------------------------------------------
  Obter o valor para tamanho do bloco de criptografia

  @return Integer contendo o tamanho para bloco de criptografia
-------------------------------------------------------------------------------}
function TCACIC.getBlockSize(): Integer;
begin
   Result := CACIC_BLOCKSIZE;
end;

{*------------------------------------------------------------------------------
  Obter o nome do arquivo de informações de configurações e dados locais

  @return String contendo o nome do arquivo de configurações e dados locais
-------------------------------------------------------------------------------}
function TCACIC.getDatFileName(): string;
begin
   Result := CACIC_DATFILENAME;
end;

{*------------------------------------------------------------------------------
  Obter o separador para criação de listas locais

  @return String contendo o separador de campos e valores
-------------------------------------------------------------------------------}
function TCACIC.getSeparatorKey(): string;
begin
   Result := CACIC_SEPARATORKEY;
end;

// Encrypt a string and return the Base64 encoded result
function TCACIC.enCrypt(p_Data : String) : String;
var
  l_Cipher : TDCP_rijndael;
  l_Data, l_Key, l_IV : string;
begin
  Try
    if self.g_boolCipher then
      Begin
        // Pad Key, IV and Data with zeros as appropriate
        l_Key   := PadWithZeros(CACIC_CIPHERKEY,CACIC_KEYSIZE);
        l_IV    := PadWithZeros(CACIC_IV,CACIC_BLOCKSIZE);
        l_Data  := PadWithZeros(p_Data,CACIC_BLOCKSIZE);

        // Create the cipher and initialise according to the key length
        l_Cipher := TDCP_rijndael.Create(nil);
        if Length(CACIC_CIPHERKEY) <= 16 then
          l_Cipher.Init(l_Key[1],128,@l_IV[1])
        else if Length(CACIC_CIPHERKEY) <= 24 then
          l_Cipher.Init(l_Key[1],192,@l_IV[1])
        else
          l_Cipher.Init(l_Key[1],256,@l_IV[1]);

        // Encrypt the data
        l_Cipher.EncryptCBC(l_Data[1],l_Data[1],Length(l_Data));

        // Free the cipher and clear sensitive information
        l_Cipher.Free;
        FillChar(l_Key[1],Length(l_Key),0);

        // Return the Base64 encoded result
        Result := Base64EncodeStr(l_Data);
      End
    Else
      // Return the original value
      Result := p_Data;
  Except
//    LogDiario('Erro no Processo de Criptografia');
  End;
end;

function TCACIC.deCrypt(p_Data : String) : String;
var
  l_Cipher : TDCP_rijndael;
  l_Data, l_Key, l_IV : string;
begin
  Try
    if self.g_boolCipher then
      Begin
        // Pad Key and IV with zeros as appropriate
        l_Key := PadWithZeros(CACIC_CIPHERKEY,CACIC_KEYSIZE);
        l_IV  := PadWithZeros(CACIC_IV,CACIC_BLOCKSIZE);

        // Decode the Base64 encoded string
        l_Data := Base64DecodeStr(p_Data);

        // Create the cipher and initialise according to the key length
        l_Cipher := TDCP_rijndael.Create(nil);
        if Length(CACIC_CIPHERKEY) <= 16 then
          l_Cipher.Init(l_Key[1],128,@l_IV[1])
        else if Length(CACIC_CIPHERKEY) <= 24 then
          l_Cipher.Init(l_Key[1],192,@l_IV[1])
        else
          l_Cipher.Init(l_Key[1],256,@l_IV[1]);

        // Decrypt the data
        l_Cipher.DecryptCBC(l_Data[1],l_Data[1],Length(l_Data));

        // Free the cipher and clear sensitive information
        l_Cipher.Free;
        FillChar(l_Key[1],Length(l_Key),0);

        // Return the result (unCrypted)
        Result := trim(l_Data);
      End
    Else
      // Return the original value
      Result := p_Data
  Except
//    LogDiario('Erro no Processo de Decriptografia');
  End;
end;

// Pad a string with zeros so that it is a multiple of size
function TCACIC.padWithZeros(const str : string; size : integer) : string;
var origsize, i : integer;
begin
  Result := str;
  origsize := Length(Result);
  if ((origsize mod size) <> 0) or (origsize = 0) then
  begin
    SetLength(Result,((origsize div size)+1)*size);
    for i := origsize+1 to Length(Result) do
      Result[i] := #0;
  end;
end;

end.