miércoles, 26 de junio de 2013

Introducir a un usuario en grupo de administradores locales

Hola.

Puestos a publicar scripts, os publico uno rápido que tengo hecho y aunque es mejorable :). Es válido perfectamente en una empresa donde se pasa por un filtro el que un usuario sea administrador de su equipo o no:

$strDomain = "dominio"
$strComputer = Read-Host "Ordenador"
$strUser = Read-host "Usuario"

$computer = [ADSI]("WinNT://" + $strComputer + ",computer")
$group = $computer.psbase.children.find("Administradores")
$group.Name

function ListAdministrators

{$members = $group.psbase.invoke("Members") | %{$_.GetType().InvokeMember("Name",'GetProperty',$null,$_,$null)}
$members}

$group.Add("WinNT://" + $strDomain + "/" + $strUser)
ListAdministrators

 

La penúltima línea, la podéis modificar y crear un script con :

$group.Remove("WinNT://" + $strDomain + "/" + $strUser)

Para que el script pase a borrar el usuario del grupo.

Advierto que es muy mejorable, por ejemplo el hecho de que busque la cadena “Administradores”, ya que si el s.o. está en inglés ya la cadena es “Administrators”, pero bueno, siempre se puede hacer un if y esa clase de cosas.

martes, 25 de junio de 2013

Script completo para preparar equipo y lanzar Bitlocker.

Hola.

Hago público el script del que os he hablado estos días.

Este Script, está hecho para que encuentre los portátiles como los encuentre, vaya mandando el comando correspondiente e irá preparando el equipo hasta lanzar el comando que cifra la unidad C:. No hace falta decir que se puede llevar al logonscript del dominio o como es mi caso, lanzarlo de forma continuada en los próximos logon vía SCCM.

Cabe destacar, que para mi, es importante que se apliquen los cambios en la gpo del dominio para que se almacene la clave de bitlocker en directorio activo.

Por partes:

#Comprobamos que la partición de boot está creada por debajo del tamaño Default ya que también se suele crear de 100mb.

    if( $Partitionstatus.size -gt 314572800) { 
        VENTANAPARTREINICIO
        bdehdcfg -target default -restart -quiet
    } 

#comprobamos que hay conectividad con alguno de los DCs antes de lanzar el cifrado ya que las directivas nos obligan a guardar la clave de bitlocker (de todas formas, no habiendo conectividad no funcionaría porque la directiva así lo ordena).

Function CONEXIONREDCIFRADODISCO
{
    $Ping1DC = Test-Connection "!DC1" -Count 1 -Quiet
    $Ping2DC = Test-Connection "!DC2" -Count 1 -Quiet
    if (($Ping1DC -eq $true) -or ($Ping2DC -eq $true)) {
        VENTANANOREINICIO
        manage-bde -on c: -skiphardwaretest -recoverypassword
    }

}

#Comprobamos que el equipo forma parte del dominio, que bitlocker no cifra ya el disco, que la partición es menor y que el equipo es un portátil.

If (($compconfig.domain -eq "!dominio.local") -and ($bitlockstatus -ne "1") -and ($Partitionstatus.size -le 314572800) -and ($tipoequipo -eq "2")) {

 

#----------------------------------------------------------------------------------
#Script para preparar equipos portátiles y lanzar bitlocker en unidad c:
#
# Realizado por Miguel Hernández
#
#Para personalizar este script ha de buscar el signo ! .
#----------------------------------------------------------------------------------

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

$tpm = Get-WmiObject -class Win32_Tpm -namespace "root\CIMV2\Security\MicrosoftTpm"
$BitLockDrive = get-wmiobject -namespace root\CIMv2\Security\MicrosoftVolumeEncryption -class Win32_EncryptableVolume -filter "driveletter='c:'"
$Partitionstatus= Get-WmiObject Win32_DiskPartition -filter "bootpartition='True'"
$CompConfig = Get-WmiObject -Class Win32_ComputerSystem

##obtenemos el tipo de equipo = 1 {"Desktop"},2 {"Laptop"},3 {"Workstation"},4 {"EntServer"},5 {"SmallOfficeOrHomeServer"},6 {"AppliancePC"},7 {"PerformanceServer"},8 {"Maximum"},default {"NoConocido"}
$tipoequipo = $CompConfig.PCSystemType

#Obtenemos la información de si bitlocker ya cifra la unidad
$bitlockstatus = $BitLockDrive.protectionstatus

#-------------------------------------------------------------------------------
#Funciones
#-------------------------------------------------------------------------------

function VENTANAPARTREINICIO
{

#Ventana Form donde se comunica el reinicio

$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "IT Department."
$objForm.Size = New-Object System.Drawing.Size(300,220)
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
    {$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
    {$objForm.Close()}})

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(80,150)
$OKButton.Size = New-Object System.Drawing.Size(120,25)
$OKButton.Text = "Accept"
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)

$objLabel0 = New-Object System.Windows.Forms.Label
$objLabel0.Location = New-Object System.Drawing.Size(10,10)
$objLabel0.Size = New-Object System.Drawing.Size(280,30)
$objLabel0.Text = "Como parte del proceso de cifrado se va a preparar la unidad de disco de este equipo."
$objForm.Controls.Add($objLabel0)

$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(10,45)
$objLabel1.Size = New-Object System.Drawing.Size(280,30)
$objLabel1.Text = "Por favor, cierre todo los programas abiertos ya que al finalizar este proceso el ordenador se reiniciará."
$objForm.Controls.Add($objLabel1)

$objLabel0 = New-Object System.Windows.Forms.Label
$objLabel0.Location = New-Object System.Drawing.Size(10,85)
$objLabel0.Size = New-Object System.Drawing.Size(280,30)
$objLabel0.Text = "As part of Encrypting process it will be prepared the computer's hard drive."
$objForm.Controls.Add($objLabel0)

$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(10,115)
$objLabel1.Size = New-Object System.Drawing.Size(280,30)
$objLabel1.Text = "Please close all your opened programs because the computer will be restarted."
$objForm.Controls.Add($objLabel1)

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

}

function VENTANAREINICIO
{
#Ventana Form donde se comunica el reinicio

$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "IT Department."
$objForm.Size = New-Object System.Drawing.Size(300,220)
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
    {$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
    {$objForm.Close()}})

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(80,150)
$OKButton.Size = New-Object System.Drawing.Size(120,25)
$OKButton.Text = "Accept"
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)

$objLabel0 = New-Object System.Windows.Forms.Label
$objLabel0.Location = New-Object System.Drawing.Size(10,10)
$objLabel0.Size = New-Object System.Drawing.Size(280,30)
$objLabel0.Text = "Se va a proceder a la activación del cifrado de su disco."
$objForm.Controls.Add($objLabel0)

$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(10,40)
$objLabel1.Size = New-Object System.Drawing.Size(280,30)
$objLabel1.Text = "Tras reiniciar, si su equipo es HP tendrá que pulsar la tecla F1 y si es TOSHIBA la tecla F10."
$objForm.Controls.Add($objLabel1)

$objLabel0 = New-Object System.Windows.Forms.Label
$objLabel0.Location = New-Object System.Drawing.Size(10,75)
$objLabel0.Size = New-Object System.Drawing.Size(280,20)
$objLabel0.Text = "It will proceed to activate the hard drive encryption."
$objForm.Controls.Add($objLabel0)

$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(10,95)
$objLabel1.Size = New-Object System.Drawing.Size(280,40)
$objLabel1.Text = "After restarting your computer if it an HP you will need to press the F1 Key however if it is a TOSHIBA press the F10 key."
$objForm.Controls.Add($objLabel1)

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

}

function VENTANANOREINICIO
{
#Ventana Form donde se comunica el proceso

$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "IT Department."
$objForm.Size = New-Object System.Drawing.Size(300,220)
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
    {$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
    {$objForm.Close()}})

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(80,150)
$OKButton.Size = New-Object System.Drawing.Size(120,25)
$OKButton.Text = "Accept"
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)

$objLabel0 = New-Object System.Windows.Forms.Label
$objLabel0.Location = New-Object System.Drawing.Size(10,10)
$objLabel0.Size = New-Object System.Drawing.Size(280,20)
$objLabel0.Text = "Se va a lanzar el proceso de cifrado de su disco."
$objForm.Controls.Add($objLabel0)

$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(10,30)
$objLabel1.Size = New-Object System.Drawing.Size(280,40)
$objLabel1.Text = "Usted podrá trabajar con normalidad, aunque apreciará cambios en el espacio libre de su unidad de disco."
$objForm.Controls.Add($objLabel1)

$objLabel0 = New-Object System.Windows.Forms.Label
$objLabel0.Location = New-Object System.Drawing.Size(10,85)
$objLabel0.Size = New-Object System.Drawing.Size(280,20)
$objLabel0.Text = "It will proceed to activate the hard drive encryption."
$objForm.Controls.Add($objLabel0)

$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(10,105)
$objLabel1.Size = New-Object System.Drawing.Size(280,30)
$objLabel1.Text = "You can work normally although during this process the hard drive free space will changes."
$objForm.Controls.Add($objLabel1)

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

}

#Prepara el disco para bitlocker
function PREPDISCO 
{

    if( $Partitionstatus.size -gt 314572800) {
        VENTANAPARTREINICIO
        bdehdcfg -target default -restart -quiet
    } 
}

#Comprobamos que estamos en red.
Function CONEXIONREDCIFRADODISCO
{
    $Ping1DC = Test-Connection "!DC1" -Count 1 -Quiet
    $Ping2DC = Test-Connection "!DC2" -Count 1 -Quiet
    if (($Ping1DC -eq $true) -or ($Ping2DC -eq $true)) {
        VENTANANOREINICIO
        manage-bde -on c: -skiphardwaretest -recoverypassword
    }

}

#-------------------------------------------------------------------------------
#Ejecución script general
#-------------------------------------------------------------------------------

PREPDISCO

#Entrará en el if si el disco no está cifrado, la unidad de disco está preparada, es un portátil y está en dominio
If (($compconfig.domain -eq "!dominio.local") -and ($bitlockstatus -ne "1") -and ($Partitionstatus.size -le 314572800) -and ($tipoequipo -eq "2")) {
    if (($tpm.isEnabled_InitialValue -eq $true) -and ($tpm.isActivated_InitialValue -eq $true) -and ($tpm.IsOwned_InitialValue -eq $true)){
        #TPM está listo para habilitar bitlocker    
        CONEXIONREDCIFRADODISCO
    }
    elseif (($tpm.isEnabled_InitialValue -eq $true) -and ($tpm.isActivated_InitialValue -eq $true) -and ($tpm.IsOwned_InitialValue -eq $false)){
        #Se obtendrá propiedad de tpm"
        $valor=1
        manage-bde -tpm -takeownership %date%%random%%random%
        CONEXIONREDCIFRADODISCO
    }
    elseif (($tpm.isEnabled_InitialValue -eq $false) -and ($tpm.isActivated_InitialValue -eq $false) -and ($tpm.IsOwned_InitialValue -eq $false)){
        #TPM Se pondrá en ON y se forzará reinicio
        VENTANAREINICIO
        manage-bde -tpm -t
        shutdown -r -t 60 
    }
    elseif (($tpm.isEnabled_InitialValue -eq $false) -and ($tpm.isActivated_InitialValue -eq $false) -and ($tpm.IsOwned_InitialValue -eq $true)){
        #TPM Se pondrá en ON y se forzará reinicio
        VENTANAREINICIO
        manage-bde -tpm -t
        shutdown -r -t 60
    }
    elseif (($tpm.isEnabled_InitialValue -eq $true) -and ($tpm.isActivated_InitialValue -eq $false) -and ($tpm.IsOwned_InitialValue -eq $false)){
           #TPM está encendido peri no activado, se activará y forzará reinicio
        VENTANAREINICIO
        manage-bde -tpm -t
        shutdown -r -t 60
    }
}

lunes, 24 de junio de 2013

Aplicar script solo a un tipo de equipo / servidor

Hola.

Muchas veces, uno de los condicionantes a la hora de aplicar un script, es aplicarlo solo a equipos y no a servidores e incluso a portátiles y no a puestos de trabajo.

Si os encontráis en esta situación, incluso como medida de protección ante scripts que vayáis a aplicar a una directiva aplicada a, por ejemplo, la ou donde debería haber un tipo de equipos, incluso una directiva aplicada a una consulta wmi que aplique solo a ciertos equipos, mejor aseguraros en el propio script que este, solo se aplicará si encontramos el tipo de equipo deseado, por ejemplo así:

  • $CompConfig = Get-WmiObject -Class Win32_ComputerSystem
  • $tipoequipo = $CompConfig.PCSystemType

$tipoequipo puede ser:

  • 1 {"Desktop"},2 {"Laptop"},3 {"Workstation"},4 {"EntServer"},5 {"SmallOfficeOrHomeServer"},6 {"AppliancePC"},7 {"PerformanceServer"},8 {"Maximum"},default {"NoConocido"}

Si queréis el nombre, podéis añadir esto:

Switch ($tipoequipo) {
   1 {"Desktop"}
   2 {"Mobile / Laptop"}
   3 {"Workstation"}
   4 {"Enterprise Server"}
   5 {"Small Office and Home Office Server"}
   6 {"Appliance PC"}
   7 {"Performance Server"}
   8 {"Maximum"}
default {"Not a known Product Type"}
}

 

En cuanto a equipos de dominio podemos también extraer información:

$TipoOrdenador = Get-WmiObject Win32_ComputerSystem
$Rol = $TipoOrdenador.DomainRole

 

Switch ($Rol) {
   0 {"Standalone Workstation"}
   1 {"Member Workstation"}
   2 {"Standalone Server"}
   3 {"Member Server"}
   4 {"Backup Domain Controller"}
   5 {"Primary Domain Controller"}
   default {"Not a known Domain Role"}
}

 

Tras esto, el condicionante podría ser:

If (($tipoequipo -eq "Desktop") -and ($Roldeservidor -eq "Member Workstation")) then {

}

Saludos.

viernes, 21 de junio de 2013

Comprobación de requisitos y preparación de disco previo a la activación de bitlocker vía cmd y powershell

Hola.

Como requisito del proceso de cifrado del disco, es imprescindible que nuestro boot esté en una partición diferente a la partición que almacena nuestro o nuestros sistemas operativos.

Si disponéis de esta partición, podéis ver que en el administrador de discos, aparece sin letra y con un tamaño que ronda los 100 a 300mb.

Si no disponéis de esta partición y queréis activar bitlocker via scripting, por supuesto debéis crearla y el comando para que el sistema haga un shrink, traslade archivos de boot y modifique el bcdedit, es el siguiente:

  • bdehdcfg -target default -restart –quiet   #pongo default por hacerlo fácil, esto nos dará una partición de 314572800bytes que redondeando son  300mb.

A mi me aparece la necesidad de comprobar vía scripting que esta partición existe y he utilizado los siguientes comandos:

$Partitionstatus= Get-WmiObject Win32_DiskPartition -filter "bootpartition='True'"

if( $Partitionstatus.size -gt 314572800) {
    VENTANAPARTREINICIO  #función mía que lanza una ventan con aviso de reinicio
    bdehdcfg -target default -restart -quiet
}

saludos.

Posibles estados del chip TPM y gestión de bitlocker vía Cmd y Powershell

 

En este artículo, voy a intentar plasmar las posibles situaciones en las que podemos encontrar y posicionar el chip TPM, con el fin de activar Bitlocker en los equipos de nuestro parque.

Lo primero que debemos conocer es que el comando Manage-bde es el que nos permitirá ir cambiando el estado del chip, los comandos son:

  • manage-bde –tpm –t  #activa tpm
  • manage-bde –tpm –takeownership contraseña   #Para tomar propiedad del chip si no somos propietarios.
  • manage-bde –on c: –skiphardwaretest –recoverypassword  #Para lanzar bitlocker en la unidad c:

Lo segundo que debemos conocer es que como inevitablemente el scripting va a formar parte imprescindible del proceso, hay ciertos comandos y consultas wmi que nos harán conducir el proceso.

Primero y antes de nada, la consulta wmi y la clase que extraerá la información es:

$tpm = Get-WmiObject -class Win32_Tpm -namespace "root\CIMV2\Security\MicrosoftTpm"

De la información extraida en la variable $tpm, nos importa esto:

$tpm.isEnabled_InitialValue = True or False   #¿Está habilitado?.

$tpm.isActivated.InitialValue = True or False  #¿Está activado?.

$tpm.isOwned_InitialValued = True or False  #¿Somos el propietario?.

 

Y esto nos puede dar las siguientes condiciones y debemos entonces actuar como se describe:

(($tpm.isEnabled_InitialValue -eq $true) -and ($tpm.isActivated_InitialValue -eq $true) -and ($tpm.IsOwned_InitialValue -eq $true))  #entonces solo queda activar con “manage-bde –on c:….”

(($tpm.isEnabled_InitialValue -eq $true) -and ($tpm.isActivated_InitialValue -eq $true) -and ($tpm.IsOwned_InitialValue -eq $false))  #Debemos hacernos propietarios y activar 1. manage-bde –tpm –takeownership contraseña y 2. manage-bde –on c:…

 

#Requieren activación de tpm “ manage-bde –tpm –t” el resto de condiciones:

(($tpm.isEnabled_InitialValue -eq $false) -and ($tpm.isActivated_InitialValue -eq $false) -and ($tpm.IsOwned_InitialValue -eq $false))

(($tpm.isEnabled_InitialValue -eq $false) -and ($tpm.isActivated_InitialValue -eq $false) -and ($tpm.IsOwned_InitialValue -eq $false))

Y

(($tpm.isEnabled_InitialValue -eq $true) -and ($tpm.isActivated_InitialValue -eq $false) -and ($tpm.IsOwned_InitialValue -eq $false))

 

Saludos.