terça-feira, 26 de dezembro de 2023

Decorator Powershell Design Patterns

 Powershell Design Patterns Decorator

```powershell

# Classe base 'Beverage'

class Beverage {

    [string]$description = "Unknown Beverage"

    [string] getDescription() {

        return $this.description

    }

    [decimal] cost() {

        return 0

    }

}

# Subclasses concretas de 'Beverage'

class HouseBlend : Beverage {

    HouseBlend() {

        $this.description = "House Blend Coffee"

    }

    [decimal] cost() {

        return .89

    }

}

class DarkRoast : Beverage {

    DarkRoast() {

        $this.description = "Dark Roast Coffee"

    }

    [decimal] cost() {

        return .99

    }

}

class Espresso : Beverage {

    Espresso() {

        $this.description = "Espresso"

    }

    [decimal] cost() {

        return 1.99

    }

}

class Decaf : Beverage {

    Decaf() {

        $this.description = "Decaf Coffee"

    }

    [decimal] cost() {

        return 1.05

    }

}

class Latte : Beverage {

    Latte() {

        $this.description = "Latte Coffee"

    }

    [decimal] cost() {

        return 1.25

    }

}

# Classe decoradora 'CondimentDecorator'

class CondimentDecorator : Beverage {

    [Beverage]$beverage

    CondimentDecorator([Beverage]$beverage) {

        $this.beverage = $beverage

    }

    [string] getDescription() {

        return $this.beverage.getDescription()

    }

}

# Subclasses concretas de 'CondimentDecorator'

class Milk : CondimentDecorator {

    Milk([Beverage]$beverage) : base($beverage) {

        $this.description = "Milk"

    }

    [string] getDescription() {

        return $this.beverage.getDescription() + ", Milk"

    }

    [decimal] cost() {

        return $this.beverage.cost() + .10

    }

}

class Mocha : CondimentDecorator {

    Mocha([Beverage]$beverage) : base($beverage) {

        $this.description = "Mocha"

    }

    [string] getDescription() {

        return $this.beverage.getDescription() + ", Mocha"

    }

    [decimal] cost() {

        return $this.beverage.cost() + .20

    }

}

class Soy : CondimentDecorator {

    Soy([Beverage]$beverage) : base($beverage) {

        $this.description = "Soy"

    }

    [string] getDescription() {

        return $this.beverage.getDescription() + ", Soy"

    }

    [decimal] cost() {

        return $this.beverage.cost() + .15

    }

}

class Whip : CondimentDecorator {

    Whip([Beverage]$beverage) : base($beverage) {

        $this.description = "Whip"

    }

    [string] getDescription() {

        return $this.beverage.getDescription() + ", Whip"

    }

    [decimal] cost() {

        return $this.beverage.cost() + .10

    }

}

class Caramel : CondimentDecorator {

    Caramel([Beverage]$beverage) : base($beverage) {

        $this.description = "Caramel"

    }

    [string] getDescription() {

        return $this.beverage.getDescription() + ", Caramel"

    }

    [decimal] cost() {

        return $this.beverage.cost() + .15

    }

}

# Definições de classes como antes...

# Hashtable para mapear tipos de bebidas a suas respectivas classes

$beverageTypes = @{

    "HouseBlend" = { [HouseBlend]::new() }

    "DarkRoast" = { [DarkRoast]::new() }

    "Espresso" = { [Espresso]::new() }

    "Decaf" = { [Decaf]::new() }

}

# Hashtable para mapear tipos de condimentos a suas respectivas classes

$condimentTypes = @{

    "Milk" = { param($beverage) [Milk]::new($beverage) }

    "Mocha" = { param($beverage) [Mocha]::new($beverage) }

    "Soy" = { param($beverage) [Soy]::new($beverage) }

    "Whip" = { param($beverage) [Whip]::new($beverage) }

}

# Função para criar a bebida base usando a hashtable

function CreateBaseBeverage([string]$beverageType) {

    if ($beverageTypes.ContainsKey($beverageType)) {

        return & $beverageTypes[$beverageType]

    } else {

        throw "Invalid beverage type: $beverageType"

    }

}

# Função para adicionar condimentos usando a hashtable

function AddCondiment([Beverage]$beverage, [string]$condimentType) {

    if ($condimentTypes.ContainsKey($condimentType)) {

        return & $condimentTypes[$condimentType] $beverage

    } else {

        throw "Invalid condiment type: $condimentType"

    }

}


# Criacao de novos tipos

$beverageTypes["Latte"] = { [Latte]::new() }

$condimentTypes["Caramel"] = { param($beverage) [Caramel]::new($beverage) }


# Solicitar entrada do usuário para a bebida base

$beverageChoice = Read-Host "Please enter the type of coffee (HouseBlend, DarkRoast, Espresso, Decaf)"

$beverage = CreateBaseBeverage $beverageChoice

# Laço para adicionar condimentos

do {

    $condimentChoice = Read-Host "Add a condiment (Milk, Mocha, Soy, Whip) or 'Done' to finish"

    if ($condimentChoice -ne 'Done') {

        $beverage = AddCondiment $beverage $condimentChoice

    }

} while ($condimentChoice -ne 'Done')

# Exibir descrição e custo da bebida finalizada

Write-Host "Your final beverage: " $beverage.getDescription()

Write-Host "Total cost: $" $beverage.cost()


```

terça-feira, 6 de dezembro de 2022

openssl self signed keys secureboot ovmf howto

 openssl self signed keys secureboot ovmf howto


# link: https://projectacrn.github.io/latest/tutorials/waag-secure-boot.html


# Generate PK Using OpenSSL:

openssl req -newkey rsa:2048 -nodes -keyout PKpriv.key -x509 -days 365 -out PK.crt


# Country Name (2 letter code) [AU]:CN

# State or Province Name (full name) [Some-State]:Shanghai

# Locality Name (eg, city) []:Shanghai

# Organization Name (eg, company) [Internet Widgits Pty Ltd]:Intel

# Organizational Unit Name (eg, section) []:Intel

# Common Name (e.g. server FQDN or YOUR name) []:

# Email Address []:


# You can also generate the self-signed certificate from an existing key, using the openssl req command, for example:


openssl req -key testpriv.key -new -x509 -days 365 -out PK.crt


# View the content of certificate using the openssl x509 command:


openssl x509 -text -noout -in PK2.crt


# Convert certificate from PEM to DER using the openssl x509 command.

# Only a DER format encoded certificate is supported. After conversion, save PK.der for use:


openssl x509 -in PK.crt -outform der -out PK.der


# Download KEK and DB From Microsoft¶

# KEK (Key Exchange Key):

# Microsoft Corporation KEK CA 2011: allows updates to DB and DBX.

# DB (Allowed Signature database):

# Microsoft Windows Production CA 2011: This CA in the Signature Database (DB) allows Windows to boot.

# Microsoft Corporation UEFI CA 2011: Microsoft signer for third party UEFI binaries via DevCenter program.



# Use QEMU to Inject Secure Boot Keys Into OVMF¶

# We follow the openSUSE: UEFI Secure boot using qemu-kvm document to import PK, KEK, and DB into OVMF, Ubuntu 16.04 used.

# Install KVM, QEMU

# Prepare the environment

# Create a OVMFKeys working directory:

mkdir OVMFKeys


# Copy the build out OVMF binary into OVMFKeys:


cp edk2/Build/OvmfX64/DEBUG_GCC5/FV/OVMF_CODE.fd OVMFKeys

cp edk2/Build/OvmfX64/DEBUG_GCC5/FV/OVMF_VARS.fd OVMFKeys

copy OVMF_CODE_QEMU.fd into OVMFKeys:


cp OVMF_CODE_QEMU.fd OVMFKeys


# Make a working directory for hda-contents:


cd OVMFKeys

mkdir hda-contents


# Copy PK, KEK and DB into hda-contents:


cp PKtestDER.cer hda-contents

cp MicCorKEKCA2011_2011-06-24.crt hda-contents

cp MicWinProPCA2011_2011-10-19.crt hda-contents


# Use QEMU to inject secure boot keys

# Run qemu-system-x86_64 to launch virtual machine:


qemu-system-x86_64 -L . \

  -drive if=pflash,format=raw,readonly=on,file=OVMF_CODE_4M.fd \

  -drive if=pflash,format=raw,file=winpxe_tele_VARS.fd \

  -hda fat:floppy:rw:hda-contents \

  -net none



cat /home/mip/Documents/OVMFKeys/winpxe_tele_VARS.fd /home/mip/Documents/OVMFKeys/OVMF_CODE_4M.fd > OVMF_custom_mip_secboot.fd


# ---------------------------------------------------------------


Obtaining the key

Generate Platform Key

PK can be generated by openssh. use the following command to sign your own PK. Note that PKpriv.key is the private key and you should preserve it carefully.


$ openssl req -newkey rsa:2048 -nodes -keyout PKpriv.key -x509 -days 365 -out PK.crt

$ openssl x509 -in PK.crt -outform der -out PK.der

Download KEK and DB

You need to download KEK and DB from Microsoft Database:


Microsoft Corporation KEK CA 2011

Microsoft Windows Production CA 2011

Insert UEFI keys

Make an img file in fat32 form containing the keys

$ dd if=/dev/zero of=keys.img bs=4M

$ mkfs.vfat keys.img

# losetup /dev/loopX keys.img

# mount /dev/loopX /mnt

# cp PK.der /mnt/PK.der

# cp MicCorKEKCA2011_2011-06-24.crt /mnt/KEK.crt

# cp MicWinProPCA2011_2011-10-19.crt /mnt/DB.crt

# umount /dev/loopX

# losetup -d /dev/loopX

Insert the keys

Start a virtual machine with the img file as a storage device. Enter UEFI configuration menu and Go to secure boot configuration (Device Manager / Secure Boot Configuration / Secure Boot Mode) and change from “Standard Mode” to “Custom Mode”. After change to “Custom Mode”, “Custom Secure Boot Options” will show up, click and enter. PK Options / Enroll PK / Enroll PK Using File and do the same for KEK and DB. ommit Changes and Exit


After import PK, KEK and DB, the secure boot state is now “Enabled”.


quarta-feira, 9 de março de 2022

 Como habilitar dotnet sdk no linux ubuntu:

sudo snap install dotnet-sdk --classic --channel=6.0

depois

sudo snap alias dotnet-sdk.dotnet dotnet

pode instalar também o dotnet runtime

sudo snap alias dotnet-runtime-60.dotnet dotnet

 Powershell Design Patterns Prototype

class Person {
[int] $Age
[DateTime] $BirthDate
[string] $Name
[IdInfo] $IdInfo

[Person] ShallowCopy() {
return [Person] $this.MemberwiseClone()
}

[Person] DeepCopy() {
[Person] $clone = [Person] $this.MemberwiseClone()
$clone.IdInfo = [IdInfo]::new($this.IdInfo.IdNumber)
$clone.Name = $($this.Name).ToString()
return $clone
}
}

class IdInfo {
[int] $IdNumber
IdInfo([int] $idNumber) {
$this.IdNumber = $idNumber
}
}

class Program {
Main() {
[Person] $p1 = [Person]::new()
$p1.Age = 42
$p1.BirthDate = "1977-01-01"
$p1.Name = "Jack Daniels"
$p1.IdInfo = [IdInfo]::new(777)

[Person] $p2 = $p1.ShallowCopy()
[Person] $p3 = $p1.DeepCopy()
Write-Host "Original values of p1, p2, p3:"
Write-Host " p1 instance values: "
$this.DisplayValues($p1)
Write-Host " p2 instance values:"
$this.DisplayValues($p2)
Write-Host " p3 instance values:"
$this.DisplayValues($p3)

$p1.Age = 32
$p1.BirthDate = "1983-01-01"
$p1.Name = "Frank"
$p1.IdInfo.IdNumber = 7878
Write-Host "\nValues of p1, p2 and p3 after changes to p1:"
Write-Host " p1 instance values: "
$this.DisplayValues($p1)
Write-Host " p2 instance values (reference values have changed):"
$this.DisplayValues($p2)
Write-Host " p3 instance values (everything was kept the same):"
$this.DisplayValues($p3)
}

[void] DisplayValues([Person] $p) {
Write-Host ("Name: {0:s}, Age: {1:d}, BirthDate: {2:dd/MM/yyyy}" -f $p.Name, $p.Age, $p.BirthDate)
Write-Host " ID"
}
}
[Program]::new().Main()

 Powershell Design Patterns Abstract Factory


class AbstractFactory {
CreateProductA() {}
CreateProductB() {}
}
class ConcreteFactory1 : AbstractFactory {
[AbstractProductA] CreateProductA() {
return [ConcreteProductA1]::new()
}
[AbstractProductB] CreateProductB() {
return [ConcreteProductB1]::new()
}
}
class ConcreteFactory2 : AbstractFactory {
[AbstractProductA] CreateProductA() {
return [ConcreteProductA2]::new()
}
[AbstractProductB] CreateProductB() {
return [ConcreteProductB2]::new()
}
}
class AbstractProductA {
UsefulFunctionA() {}
}
class ConcreteProductA1 : AbstractProductA {
[string] UsefulFunctionA() {
return "The result of the product A1."
}
}
class ConcreteProductA2 : AbstractProductA {
[string] UsefulFunctionA() {
return "The result of the product A2."
}
}
class AbstractProductB {
UsefulFunctionB() {}
AnotherUsefulFunctionB([AbstractProductA] $collaborator) {}
}
class ConcreteProductB1 : AbstractProductB {
[string] UsefulFunctionB() {
return "The result of the product B1."
}
[string] AnotherUsefulFunctionB([AbstractProductA] $collaborator) {
$result = $collaborator.UsefulFunctionA()
return "The result of the B1 collaborating with the ({0})" -f $result
}
}
class ConcreteProductB2 : AbstractProductB {
[string] UsefulFunctionB() {
return "The result of the product B2."
}
[string] AnotherUsefulFunctionB([AbstractProductA] $collaborator) {
$result = $collaborator.UsefulFunctionA()
return "The result of the B2 collaborating with the ({0})" -f $result
}
}
class Client {

[void] ClientMethod([AbstractFactory] $factory) {
$productA = $factory.CreateProductA()
$productB = $factory.CreateProductB()
Write-Host $productB.UsefulFunctionB()
Write-Host $productB.AnotherUsefulFunctionB($productA)
}
[void] Main() {
Write-Host "Client: Testing client code with the first factory type..."
$this.ClientMethod([ConcreteFactory1]::new())
Write-Host
Write-Host "Client: Testing the same client code with the second factory type..."
$this.ClientMethod([ConcreteFactory2]::new())
}
}
class Program {
Main() {
[Client]::new().Main()
}
}
[Program]::new().Main()

terça-feira, 8 de março de 2022

 Powershell Design Patterns Command


class Command {
# Declara uma interface para comandos abstratos como Execute().
Execute() {}
}

class Receiver {
# Sabe como executar um comando particular.
SwitchOn() {
Write-Host "Switch on from: " $this.GetType().Name
}
}

class OnCommand: Command {
[Receiver] $Receiver

OnCommand([Receiver] $Receiver) {
$this.Receiver = $Receiver
}
Execute() {
$this.Receiver.SwitchOn()
}
}

class Invoker {
[Command] $Command

Invoker([Command] $Command) {
$this.Command = $Command
}

Execute() {
$this.Command.Execute()
}
}

class TV: Receiver {
[String] toString() {
return $this.GetType().Name
}
}

class DVDPlayer: Receiver {
[String] toString() {
return $this.GetType().Name
}
}

class Main {
Main() {
# Receiver é quem recebe o sabe como realizar o comando.
[Receiver] $Receiver = [TV]::new()
# O Comando do tipo OnCommand recebe o receiver acima.
[Command] $OnCommand = [OnCommand]::new($Receiver)
# O invoker recebe o OnCommand acima, que tem o receiver
[Invoker] $Invoker = [Invoker]::new($OnCommand)
# O comando é chamado pelo Invoker.
$Invoker.Execute()
# On command for DVDPlayer with same invoker
[Receiver] $Receiver = [DVDPlayer]::new()
[Command] $OnCommand = [OnCommand]::new($Receiver)
[Invoker] $Invoker = [Invoker]::new($OnCommand)
$Invoker.Execute()
}
}

[Main]::new()

 Powershell Design Patterns Builder

class Car {}
class Manual {}

class Builder {
Reset() {}
SetSeats([int] $NumeroDeAssentos) {}
SetEngine([String] $TipoDeMotor) {}
SetTripComputer([String] $TipoComputadorBordo) {}
SetGPS([String] $TipoGPS) {}
}

class CarBuilder: Builder {
[Car] $Car
CarBuilder() {
$this.Reset()
}
Reset() {
$this.Car = [Car]::new()
}
SetSeats([int] $NumeroDeAssentos) {
Write-Host "O numero de assentos deste carro é: " $NumeroDeAssentos
}
SetEngine([String] $TipoDeMotor) {
Write-Host "O tipo de motor deste carro é: " $TipoDeMotor
}
SetTripComputer([String] $TipoComputadorBordo) {
Write-Host "O tipo de Computador de Bordo deste carro é: " $TipoComputadorBordo
}
SetGPS([String] $TipoGPS) {
Write-Host "O tipo de GPS deste carro é: " $TipoGPS
}

[Car] GetProduct() {
$Product = $this.Car
$this.Reset()
return $Product
}

}
class CarManualBuilder: Builder {
[Manual] $Manual
CarManualBuilder() {
$this.Reset()
}
Reset() {
$this.Manual = [Manual]::new()
}
SetSeats([int] $NumeroDeAssentos) {
Write-Host "O numero de assentos deste carro é: " $NumeroDeAssentos
}
SetEngine([String] $TipoDeMotor) {
Write-Host "O tipo de motor deste carro é: "$TipoDeMotor
}
SetTripComputer([String] $TipoComputadorBordo) {
Write-Host "O tipo de Computador de Bordo deste carro é: " $TipoComputadorBordo
}
SetGPS([String] $TipoGPS) {
Write-Host "O tipo de GPS deste carro é: " $TipoGPS
}

[Manual] GetProduct() {
$Product = $this.Manual
$this.Reset()
return $Product
}

}

class Director {

[Builder] $Builder

SetBuilder([Builder] $Builder) {
$this.Builder = $Builder
}
ConstructSportsCar([Builder] $Builder) {
$this.Builder = $Builder
$this.Builder.Reset()
$this.Builder.SetSeats(2)
$this.Builder.SetEngine("Super Motor")
$this.Builder.SetTripComputer("Super Computador")
$this.Builder.SetGPS("Super GPS")
}
ConstructSUV([Builder] $Builder) {
$this.Builder = $Builder
$this.Builder.Reset()
$this.Builder.SetSeats(6)
$this.Builder.SetEngine("Motor popular.")
$this.Builder.SetTripComputer("Computador popular.")
$this.Builder.SetGPS("GPS popular.")
}
}

class Application {
MakeCar() {
$Director = [Director]::new()
[Builder] $Builder = [CarBuilder]::new()
$Director.ConstructSportsCar($Builder)
[Car] $Car = $Builder.GetProduct()


[Builder] $Builder = [CarBuilder]::new()
$Director.ConstructSUV($Builder)
[Car] $Car = $Builder.GetProduct()

[Builder] $Builder = [CarManualBuilder]::new()
$Director.ConstructSportsCar($Builder)
# O produto final é frequentemente retornado de um
# objeto Builder uma vez que o diretor não está
# ciente e não é dependente de Builders e produtos
# concretos.
[Manual] $Manual = $Builder.GetProduct()
}

}

[Application] $Application = [Application]::new()
$Application.MakeCar()

Decorator Powershell Design Patterns

 Powershell Design Patterns Decorator ```powershell # Classe base 'Beverage' class Beverage {     [string]$description = "Unkno...