Pular para o conteúdo principal

Postagem em destaque

BlackTDN :: Autenticação 2FA para Usuário Root no WSL

--- # naldodj-wsl-2FA ## Autenticação 2FA para Usuário Root no WSL ### Introdução O Windows Subsystem for Linux (WSL) é uma ferramenta poderosa que permite aos desenvolvedores executar um ambiente Linux diretamente no Windows. No entanto, a segurança é uma preocupação importante, especialmente quando se trata de acessar o usuário root. Neste post, vamos mostrar como configurar a autenticação de dois fatores (2FA) para o usuário root ao acessar o WSL, garantindo uma camada adicional de segurança. ### Objetivo Vamos configurar um script de login que valida a senha do root e usa autenticação 2FA baseada em Time-based One-Time Password (TOTP), usando ferramentas comuns como `openssl`, `oathtool`, e `perl`. ### Passo 1: Instalar as Ferramentas Necessárias Primeiro, precisamos garantir que temos todas as ferramentas necessárias instaladas. Isso inclui `openssl`, `oathtool`, e `perl`. ```bash sudo apt-get update sudo apt-get install openssl oathtool perl ``` Para os scripts em Lua.

Protheus :: apconnxcontrol.ocx & PowerShell – Forçando a Desconexão de Usuário

Hoje veremos que usando o componente COM do protheus, podemos, através do Windows PowerShell Obter o estado de conexão dos usuários e forçar a sua desconexão.

Em primeiro lugar faz-se necessária a instalação do componente e, para isso, utilizaremos o programa regsvr32.exe que, normalmente, encontra-se em c:\WINDOWS\system32\regsvr32.exe.

Instalando o compomente:

Pelo console do DOS ou do PowerShell vá para o diretório onde está instalado o client do Protheus, no meu caso em: D:\totvs\p10\ndj\appclient.

image

image

Procure o arquivo apconnxcontrol.ocx, se não encontrar existe alguma coisa errada, “que não está certa”, na sua instalação (contate “Juan”).

Utilize agora o programa regsvr32.exe para instalar/registrar o componente. regsvr32.exe sem parâmetros irá mostrar a seguinte saída:

image

Vamos ao registro.

image

image

image

Feito o registro do componente vamos utiliza-lo. Usarei o PowerGui Script Editor para esse fim (poderá fazê-lo diretamente no console do PowerShell).

#Instanciando um novo objeto com 
$TObj = New-Object -Com apconnxcontrol.apconnx;

#Definindo as variaveis para Conexao
$TEnv = "NDJ_01";
$TSrv = "127.0.0.1";
$TPort = 4321;
$TUser = "TOTVS";
$TPWD = "SIGA";

#Atribuindo as variaveis para Conexao às Propriedades do objeto
$TObj.Environment = $TEnv;
$TObj.Password = $TPWD;
$TObj.Port = $TPort;
$TObj.Server = $TSrv;
$TObj.User = $TUser;

#Conectando
$TObj.Connect();

 


   1: #Instanciando um novo objeto com 
   2: $TObj  = New-Object -Com apconnxcontrol.apconnx;
   3:  
   4: #Definindo as variaveis para Conexao
   5: $TEnv  = "NDJ_01";
   6: $TSrv  = "127.0.0.1";
   7: $TPort = 4321;
   8: $TUser = "TOTVS";
   9: $TPWD  = "SIGA";
  10:  
  11: #Atribuindo as variaveis para Conexao às Propriedades do objeto
  12: $TObj.Environment = $TEnv;
  13: $TObj.Password    = $TPWD;
  14: $TObj.Port        = $TPort;
  15: $TObj.Server      = $TSrv;
  16: $TObj.User        = $TUser; 
  17:  
  18: #Conectando
  19: $TObj.Connect();

image


image


Se tudo OK, a última saída do console será: True


image


Vamos agora ver com o que podemos brincar. Obtendos os Métodos e Propriedades do Objeto COM:





$TObj | Get-Member -MemberType Properties

image


A saída do console para as propriedades:





PS C:\Documents and Settings\marinaldo.jesus.NALDO-PC\Meus documentos> $TObj | Get-Member -MemberType Properties

TypeName: System.__ComObject#{36abe2f0-84fb-490e-9f73-bfdd33cf8162}

Name MemberType Definition
---- ---------- ----------
BackColor Property OLE_COLOR BackColor () {get} {set}
Caption Property string Caption () {get} {set}
CaptionColor Property OLE_COLOR CaptionColor () {get} {set}
CaptionSize Property int CaptionSize () {get} {set}
Connected Property bool Connected () {get}
Cursor Property short Cursor () {get} {set}
DateFormat Property string DateFormat () {get} {set}
DoubleBuffered Property bool DoubleBuffered () {get} {set}
EnableConnections Property bool EnableConnections () {get} {set}
Enabled Property bool Enabled () {get} {set}
Environment Property string Environment () {get} {set}
FontSize Property int FontSize () {get} {set}
ForeColor Property OLE_COLOR ForeColor () {get} {set}
LastError Property string LastError () {get}
Modulo Property string Modulo () {get} {set}
Password Property string Password () {get} {set}
Port Property int Port () {get} {set}
ResultType Property short ResultType () {get}
Server Property string Server () {get} {set}
ShowCaption Property bool ShowCaption () {get} {set}
ShowErrors Property bool ShowErrors () {get} {set}
User Property string User () {get} {set}
Visible Property bool Visible () {get} {set}
VisibleDockClientCount Property int VisibleDockClientCount () {get}




e, agora para os Métodos:





$TObj | Get-Member -MemberType Methods














image


image





Name                             MemberType Definition                                                 
---- ---------- ----------
AboutBox Method void AboutBox ()
AddArrayParam Method bool AddArrayParam (Variant)
AddDateParamAsDouble Method bool AddDateParamAsDouble (double)
AddDateParamAsString Method bool AddDateParamAsString (string)
AddJavaArrayParam Method bool AddJavaArrayParam (string, Variant)
AddLogicalParam Method bool AddLogicalParam (bool)
AddNullParam Method bool AddNullParam ()
AddNumericParam Method bool AddNumericParam (double)
AddStringParam Method bool AddStringParam (string)
BuildNumber Method string BuildNumber ()
CallProc Method bool CallProc (string)
Clear Method void Clear ()
Connect Method bool Connect ()
Disconnect Method void Disconnect ()
DisconnectUser Method bool DisconnectUser (string, string, string, string, bool)
DrawTextBiDiModeFlagsReadingOnly Method int DrawTextBiDiModeFlagsReadingOnly ()
GetUserInfo Method string GetUserInfo (string, string, string, string)
GetUsers Method string GetUsers ()
GetUserScreen Method bool GetUserScreen (string, string, string, string, string)
InitiateAction Method void InitiateAction ()
IsRightToLeft Method bool IsRightToLeft ()
Paint Method void Paint ()
PrepareEnv Method bool PrepareEnv (string, string, string, Variant)
ResultAsArray Method Variant ResultAsArray ()
ResultAsDate Method double ResultAsDate ()
ResultAsDateString Method string ResultAsDateString ()
ResultAsLogical Method bool ResultAsLogical ()
ResultAsNumeric Method double ResultAsNumeric ()
ResultAsString Method string ResultAsString ()
SendMessage Method bool SendMessage (string, string, string, string, string)
StartJob Method bool StartJob (string, string, bool)
TextOut Method void TextOut (string)
UseRightToLeftReading Method bool UseRightToLeftReading ()
UseRightToLeftScrollBar Method bool UseRightToLeftScrollBar ()
UsersCount Method int UsersCount ()

Usando o Método UsersCount() para verificar o número de usuários conectados:





$TObj.UsersCount()

image





PS C:\Documents and Settings\marinaldo.jesus.NALDO-PC\Meus documentos> $TObj.UsersCount();2

image


No exemplo, eu, via Protheus Remote e via PowerShell (através do PowerGui Script Editor). Vejamos agora, usando o Método GetUsers() , as informações dos usuários conectados:





$TObj.GetUsers();

image





PS C:\Documents and Settings\marinaldo.jesus.NALDO-PC\Meus documentos> $TObj.GetUsers();marinaldo.jesus;NALDO-PC;4764;
;2732;1769103725;naldo.jesus
image

Vamos Obter as informações de conexão para o usuário ‘marinaldo.jesus’ usando GetUserInfo(string, string, string, string) onde a saída da função anterior servirá como entrada para a função atual.





$TObj.GetUserInfo('marinaldo.jesus','NALDO-PC','4764','');

image 






PS C:\Documents and Settings\marinaldo.jesus.NALDO-PC\Meus documentos> $TObj.GetUserInfo('marinaldo.jesus','NALDO-PC','4764','');
SIGAMDI;ndj_01;102940;0;Emp :01/01 Logged :TOTVS                     MDI       Obj : MDI Window;Mon Jan 09 0
2:50:01 2012
;00:11:41


image


E vamos forçar a desconexão desse usuário com: DisconnectUser(string, string, string, string, bool)





$TObj.DisconnectUser('marinaldo.jesus','NALDO-PC','4764','',$true);

image






PS C:\Documents and Settings\marinaldo.jesus.NALDO-PC\Meus documentos> $TObj.DisconnectUser('marinaldo.jesus','NALDO-PC','4764','',$true);
True


image


Nesse Primeiro Exemplo, enviamos um Kill informando que é para aguardar pelo termino do Processamento


image


Já, passando o último parâmetro como $false, solicitamos a desconexão IMEDIATA.





$TObj.DisconnectUser('marinaldo.jesus','NALDO-PC','4764','',$false);

image


image


Finalizando a Conexão com o Protheus : Disconnect()





$TObj.Disconnect()










image


Lembrando que, para remover o registro do componente, basta executar regsvr32.exe com o parâmetro /u





D:\totvs\p10\ndj\appclient>regsvr32.exe /u apconnxcontrol.ocx

image


[]s
иαldσ dj

Comentários

  1. Cara, que artigo interessante, parabéns novamente...

    Queria saber como descobre estes componentes... (lets share ?) hehe...

    ResponderExcluir
  2. Ao tentar instanciar o objeto, me ocorria o seguinte erro:

    PS C:\Windows\system32> $TObj = New-Object -Com APConnXControl.APConnX;
    New-Object : Falha na recuperação de factory de classes COM do componente com CLSID {B1C965EB-64A4-4084-83D1-26902EF88DE5} devido ao seguinte erro: 80040154.
    Em linha:1 caractere:20
    + $TObj = New-Object <<<< -Com APConnXControl.APConnX;
    + CategoryInfo : ResourceUnavailable: (:) [New-Object], COMException
    + FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand

    Descobri que é por que o OCX está em 32bits, e eu estava executando o PowerShell 64bits.

    Se rodar do PowerShell 32 bits funciona normal. Agora vamos ver se a TOTVS libera uma versão 64bits também.

    ResponderExcluir
  3. No Visual Studio 2017 acontece o mesmo problema do Arthur.
    Se rodar no PS x86 funciona muito bem, mas ao tentar consumir este componente no Visual Studio acaba dando problema.

    ResponderExcluir

Postar um comentário

Postagens mais visitadas