top of page

67 items found for ""

  • Basic Ansible Setup for Windows

    Introduction to Ansible Welcome to this introduction to managing Windows from Ansible, unlike Microsoft's management solutions, it's free and agentless! Imagine a single tool that automates the setup, configuration, and maintenance of multiple Windows and Linux servers. With its simplicity, Ansible lets you easily orchestrate your server infrastructure. No more manual tasks, no more sleepless nights—just smooth sailing through the seas of automation. Well, it will allow those repetitive tasks to be automated at least. Aims for Ansible This article aims to offer straightforward guidance on configuring Ansible for the management of a non-domain joined Windows Server via the execution of remote tasks. Subsequent articles will expand upon this foundation by incorporating features such as Vault's password management, domain-joined servers, and Kerberos authentication. What you will need to download Latest Ubuntu Desktop Download ISO https://ubuntu.com/download/desktop Visual Code for Linux https://code.visualstudio.com/docs/setup/linux Windows WinRM Configurator Script https://github.com/AlbanAndrieu/ansible-windows/blob/master/files/ConfigureRemotingForAnsible.ps1 Ansible Documentation https://docs.ansible.com/ansible/latest/index.html Ansible Host and Yaml Files https://github.com/Tenaka/Ansible/tree/main Pick your Linux of Choice (Ubuntu Desktop) I'll be opting for my less preferred Linux distribution, Ubuntu Desktop. However, I find it to be the most user-friendly choice for Microsoft-focused engineers. Rocky Linux is a viable alternative, though its configuration might involve additional steps. I won't go into a detailed step-by-step installation of Linux, but simply download the ISO, mount it within your preferred VM solution and install, following the default setup. Some Sort of Virtualization or Cloud I'll be opting for Hyper-V as my preferred virtualization platform to host both Ubuntu and Windows Server 2022. Its seamless integration with both Windows Server and Windows 11 client eliminates any compatibility or migration concerns I may face moving images between the 2. There are two recommended Hyper-V configurations for Linux installation. Opt for a Generation 2 VM to enable Secure Boot capability, and within the Security section of the VM, select 'Microsoft UEFI Certificate Authority'. Post-deployment, run the following command from PowerShell, once the Linux VM is powered down, select the resolution that aligns best with your monitor. Set-VMVideo Ansible2 -horizontalresolution:1900 -verticalresolution:1200 -ResolutionType Single Update Ubuntu After successfully deploying Ubuntu, it is crucial to install any updates to ensure the smooth execution of future installations by running the following command from a shell terminal. sudo apt-get update -y && apt-get upgrade -y Install Ansible Ansible is installed with the following command. sudo apt-get install ansible -y List currently installed collections, as you will see there's support for OS, Cloud, Network devices and much more. ansible-galaxy collection list To update the Windows community collection that's installed by default. ansible-galaxy collection install community.windows To install the latest stable collection by Ansible, run the following ansible-galaxy collection install ansible.windows Before continuing type ip address in the terminal and record for later use. Install Microsoft's Visual Code for Linux To assist with writing Yaml and to minimise the moving of files Microsoft's Visual Code for Linux will be installed on Ubuntu. If you can't outdo them, it seems the strategy is to join them. Well played Microsoft. Instructions can be found @ https://code.visualstudio.com/docs/setup/linux for Ubuntu and other distro's. For Ubuntu follow the next set of instructions. sudo apt-get install wget gpg wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > packages.microsoft.gpg sudo install -D -o root -g root -m 644 packages.microsoft.gpg /etc/apt/keyrings/packages.microsoft.gpg sudo sh -c 'echo "deb [arch=amd64,arm64,armhf signed-by=/etc/apt/keyrings/packages.microsoft.gpg] https://packages.microsoft.com/repos/code stable main" > /etc/apt/sources.list.d/vscode.list' rm -f packages.microsoft.gpg sudo apt install apt-transport-https sudo apt-get update sudo apt-get install code Launch Visual Code once it's installed, then create a new directory in the Documents directory named Ansible. That concludes the installation and configuration of Ubuntu and Ansible. Now, let's proceed to the setup of Windows. WinRM and Windows Server Configuring Windows for remote management from Ansible is a little involved with instructions available from the Anisble website: Windows Setup https://docs.ansible.com/ansible/latest/os_guide/windows_setup.html Nevertheless, there exists a pre-configured script accessible on Github: Windows Anisble Configurator Script https://github.com/AlbanAndrieu/ansible-windows/blob/master/files/ConfigureRemotingForAnsible.ps1 To get up and running with this basic implementation download the 'ConfigureRemotingForAnsible.ps1' and execute the script from PowerShell with Administrative rights. A cautionary note: the implemented configuration is open, granting remote WinRM access to any client. To address this, simply modify lines 417 and 423 by adding the specific remote IP of the Ansible server; in my case, it's 10.1.1.100. This updates the firewall from allowing any address to that of the one specified. 10.1.1.1 = Windows Server 10.1.1.100 = Ubuntu\Ansible ln 417 netsh advfirewall firewall add rule profile=any name="Allow WinRM HTTPS" dir=in localport=5986 protocol=TCP action=allow remoteIP=10.1.1.100 ln 423 netsh advfirewall firewall set rule name="Allow WinRM HTTPS" new profile=any remoteIP=10.1.1.100 To assess WinRM access from another Windows client, input the following commands in PowerShell. Remember to update the password and AnsibleIP with your system's information. In case the Windows Firewall imposes the above RemoteIP restriction, include the test client's IP in the 'Allow WinRM HTTPS' remote scope firewall rule. $username = "administrator" $password = ConvertTo-SecureString -String "ChangeMe1234" -AsPlainText -Force $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password $session_option = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck Invoke-Command -ComputerName AnisbleIP -UseSSL -ScriptBlock { ipconfig } -Credential $cred -SessionOption $session_option Confirm that the WinRM Service is running. Get-Service WinRM If the WinRM service isn't started execute the following to set the service to automatic and start. Set-Service -Name WinRM -StartupType Automatic -ErrorAction SilentlyContinue Get-Service -Name WinRM | Start-Service To get the WinRM configuration execute the following: winrm enumerate winrm/config/listener Listener Address = * Transport = HTTP Port = 5985 Hostname Enabled = true URLPrefix = wsman CertificateThumbprint ListeningOn = 10.1.1.1, 127.0.0.1, ::1, fe80::a81e:3b96:6d3b:3d6c%3 Listener Address = * Transport = HTTPS Port = 5986 Hostname = WIN-JE1B7QU8B8R Enabled = true URLPrefix = wsman CertificateThumbprint = FC24D87A798ECA4EA8BF4EE0C8CD7FD2CC51A67C ListeningOn = 10.1.1.1, 127.0.0.1, ::1, fe80::a81e:3b96:6d3b:3d6c%3 Ansible Environment In Ansible, host files and YAML are crucial in defining and organizing the infrastructure you intend to manage. Host Files: A host file in Ansible is where you specify the details of the servers or systems you want to manage. It typically includes information like IP addresses, hostnames, and grouping of hosts based on certain criteria (e.g., development, production). Host files help Ansible understand the inventory of systems it can control, making it an essential component for playbook execution. Without Ansible Vault passwords are hardcoded and clear text within the Hosts file. Vault will be covered in a subsequent article. [Windows] 10.1.1.1 [Windows: vars] ansible_user=administrator ansible_password="ChangeMe1234" ansible_connection=winrm ansible_winrm_scheme=https ansible_port=5986 ansible_winrm_server_cert_validation=ignore ansible_kerberos_delegation=false YAML (YAML Ain't Markup Language): YAML is a human-readable data serialization format often used for configuration files and data exchange between languages with different data structures. In Ansible, YAML is used to write playbooks, which are scripts that define the tasks to be executed on the managed hosts. It uses indentation to represent data hierarchy, making it easy to read. Writing can present a bit of a challenge as its hierarchal nature requires the structure to be indented and spaced correctly. In this example, the contents from the Ansible directory are copied to the targeted Windows Administrator's Desktop. --- - name: Copy hosts: Windows become: false gather_facts: false vars: source: "/home/user/Documents/Ansible" destination: "Desktop/" tasks: - name: copy ping ansible.windows.win_copy: src: "{{ source }}" dest: "{{ destination }}" Host and YAML files play a crucial role in making Ansible configurations clear, structured, and easy to manage. Host files define the inventory, while YAML defines the tasks and configurations to be applied to the hosts. Host File and Initial Test Ensure you're logged on to Ubuntu\Ansible and launch Visual Code. Navigate to '/home/user/Documents/Ansible' and create a file named 'hosts.ini. Taking the above host file as an example, incorporate the necessary details that match your Windows system and save the file. Or download the examples provided: https://github.com/Tenaka/Ansible/tree/main Let's create the most basic ping test to confirm access to Windows, create a file named 'ping.yml' and insert the following. --- - name: Ping Windows Test hosts: Windows gather_facts: false tasks: - name: Ping targets win_ping: Launch a shell and CD to '/home/user/Documents/Ansible'. Type and execute the following command ansible-playbook -i hosts.ini ping.yml Kudos on acing the Ansible setup for managing Windows! File Copies To and Fro Before delving into the YAML file, it's essential to acquaint yourself with the following path rules. The Windows path rules should be written in the following format. Good tempdir=C:\\Windows\\Temp Works tempdir='C:\\Windows\\Temp' tempdir="C:\\Windows\\Temp" Bad, but sometimes works tempdir=C:\Windows\Temp tempdir='C:\Windows\Temp' tempdir="C:\Windows\Temp" tempdir=C:/Windows/Temp Fails tempdir=C:\Windows\temp tempdir='C:\Windows\temp' tempdir="C:\Windows\temp" Copies the contents of the Ansible directory to the Desktop of the target Windows server. --- - name: Copy hosts: Windows become: false gather_facts: false vars: source: "/home/user/Documents/Ansible" destination: "Desktop/" tasks: - name: copy ping ansible.windows.win_copy: src: "{{ source }}" dest: "{{ destination }}" Copies a named file from the Windows Desktop up to the Ansible directory using 'fetch'. --- - name: Copy hosts: Windows become: false become_user: false gather_facts: false vars: source: "Desktop/test1.txt" destination: "/home/user/Documents/Ansible/test1.txt" tasks: - name: copy ping ansible.builtin.fetch: src: "{{ source }}" dest: "{{ destination }}" Further guidelines can be found @ https://docs.ansible.com/ansible/latest/os_guide/windows_usage.html Basic Commands This concludes the introduction by running a command line on the designated Windows server and saving the results to a text file. --- - name: cmds hosts: Windows become: false gather_facts: false tasks: - name: some cmd win_command: cmd.exe /c whoami.exe > "Desktop\whoami.txt" - name: ipconfig win_command: cmd.exe /c ipconfig /all > "Desktop\ipconfig.txt" Finally Done! Thanks for your time reading this intro to managing Windows from Ansible. Creating each article demands time and effort, diverting me from other learning pursuits. Your comments and shares are highly valued and greatly appreciated. Finally a big shout-out to Harv for opening my eyes to a life beyond SCCM.

  • Ansible Vault for Windows

    Welcome Back Hey there! Glad to have you back for the second Ansible article. This time around, we're diving into Ansible Vault and how to keep those Microsoft Windows passwords safe by encrypting them whilst they are at rest. If you missed out on the last article regarding the setup of Ansible and handling some basic tasks on a non-domain joined Windows Server, make sure to catch up on that first, by following this link. https://www.tenaka.net/post/basic-ansible-setup-for-windows What is Ansible Vault Ansible Vault is a feature that allows users to encrypt sensitive information, such as passwords and secret keys, within Ansible playbooks and files. This encryption ensures that the secrets are secure while they are at rest. To encrypt a secret, you simply use the "ansible-vault encrypt" command followed by the name of the file or "ansible-vault encrypt_string 'Secret'" followed by the name to be assigned to the secret. You'll then be prompted to enter and confirm a password or passphrase. Once encrypted, the secret is stored in a format that is unreadable without the decryption key, providing a secure way to protect sensitive information within Ansible projects. Ansible Vault uses AES symmetric encryption by using the same password or passphrase for both encryption and decryption. Basic Commands Below are a few fundamental commands for utilizing Ansible Vault: Create an encrypted file ansible-vault create newFile.yml Encrypt an existing file ansible-vault encrypt existingFile.yml View encrypted content of a file anisble-vault view existingFile.yml Edit the encrypted file ansible-vault edit existingFile.yml Decrypt an encrypted file ansible-vault decrypt existingFile.yml Change the password that encrypts\decrypts the secret (Rekeying) ansible-vault rekey existingFile.yml Create an encrypted string ansible-vault encrypt_string 'ChangeMe1234' --name ansible_password Help Yourselves.... A working set of files deploying ansible-vault with encrypted secrets can be found at the following link, do help yourselves. https://github.com/Tenaka/Ansible_Encrypted_Password Set Nano as the Default Editor To avoid ansible-vault opening new files with vi, let's designate Nano as the default editor. Type 'select-editor' and then choose option 1 Let's prove it works before Encrypting I won't immediately introduce encrypted passwords into the mix. Instead, we'll set up and test the files using plain text passwords. Later, I'll encrypt them, this will aid in troubleshooting. Ansible Jinja2 is a templating engine used to create dynamic content within Ansible playbooks. It allows for the use of variables, conditionals, loops, and filters to customize configurations based on the environment or data. The ansible_password="{{vault_ansible_password}}" is one such example and it's used in the hosts.ini file and resolves to the values in win.yml. If you have been following, Visual Code for Linux is installed, if not nano will suffice. First, navigate to the Ansible directory previously creating under the Documents directory and execute the following command: mkdir win-encrypt Change Directory (cd win-encrypt) into the directory and create the following 3 files, hosts.ini, ping.yml and win.yml. This will provide a simple ping test to the Windows Server on 10.1.1.1 with the Administrator account and a password of 'ChangeMe1234'. Ensure that 'ping.yml' adheres to the Yaml framework or a whole world of pain and 'why aren't you working' will ensue. The "no_log: true" parameter in Ansible is used to prevent sensitive data, such as passwords or API keys, from being displayed in the console output or logged to files. Including this now will make life difficult, waiting until your fully working. hosts.ini [win] 10.1.1.1 [win:vars] ansible_user=administrator ansible_connection=winrm ansible_password="{{vault_ansible_password}}" ansible_winrm_scheme=https ansible_port=5986 ansible_winrm_server_cert_validation=ignore ansible_kerberos_delegation=false ping.yml --- - name: Ping win Test hosts: win gather_facts: false vars_files: - win.yml tasks: - name: Ping targets win_ping: no_log: True win.yml vault_ansible_password: ChangeMe1234 Execute the following command to test the use of the clear text password: ansible-playbook -i hosts.ini ping.yml Let's get it Encrypted Once we've confirmed the clear text password works, we can proceed to encrypt the win.yml file using the following command. ansible-vault encrypt win.yml Enter the password used for encrypting the file, I'm using the ultra-secure 'Password1234'. In production don't do this..... Confirm the win.yml is encrypted with 'cat win.yml'. It should look something like the image below. Type the following command to test accessing Windows using the encrypted vault file: ansible-playbook -i host.ini ping.yml --ask-vault-pass Enter the password 'Password1234' at the prompt. Alternative Method to Encrypt the Password Another way to encrypt the password is by utilizing the encrypt-string option. Type the following command directing the output to winString.yml ansible-vault encrypt-string 'ChangeMe1234' --name vault_ansible_password > winString.yml I then renamed the existing win.yml and then renamed winString.yml to win.yml using the mv command. This is a Bad Idea....... Once we've secured the Windows passwords and grown weary of the password prompts or the playbooks are to be scheduled, we'll embed the ansible-vault password into a plaintext file, undoing our previous efforts. I've rooted enough Linux boxes to know this is a bad idea. However, today is all about encrypting the Windows passwords whilst at rest. Vault Password File Here we go, create a file named 'key' in the root of the Ansible directory and enter the vault password of 'Password1234': nano ../key Secure the key file to allow the owner Read and Write access. chmod 600 ../key Execute the playbook swapping out --ask-vault-pass for --vault-password-file ../key. ansible-playbook -i host.ini ping.yml --vault-password-file ../key Alternatively, if you prefer not to use --vault-password-file, create an ansible.cfg file within the win-encrypt directory using Nano, and input the following details. Run the playbook again without the vault password or by specifying the file location. Final Thoughts That wraps up this guide on employing ansible vault to secure Windows passwords while they're at rest. While Ansible Vault effectively secures Windows passwords, its effectiveness is compromised by storing the vault password in plain text. Despite its encryption capabilities, this vulnerability underscores the importance of implementing additional security measures to safeguard sensitive information effectively or another product in addition to ansible vault to manage secrets. Maybe that should be the aim of the next article, it's that or ansible managing domain computers with Kerberos. Drop a comment and let me know? Thank you for taking the time to read this article, your feedback, comments, and shares are immensely valued and deeply appreciated.

  • MDT with SQL Database Access. Issues (ZTI Error opening SQL Connection)

    Microsoft’s Deployment Toolkit (MDT) supports integration with SQL Server providing far better control over deployment options, eg Client A gets Task Sequence 1, whereas Client B gets Task Sequence 2, both are assigned their respective static IP's. Previously I completed a comprehensive series on deploying MDT (here) including SQL Server Express integration and baulk import of client data into SQL. In this article, I’ll address common connection issues that may arise between MDT and SQL Server and how to fault find those issues. If you had followed the guides, the subsequent steps are likely unnecessary. Nevertheless, it is beneficial to offer guidance on diagnosing connection issues. The current MDT server is equipped with SQL, but in my haste, I had overlooked certain post-integration steps. As a result, there is a noticeable delay at the 'CSetting' stage during the initial WinPE for client deployment. Certain prerequisites must be met, including the establishment of a functional MDT server and the installation and configuration of SQL Express with the necessary connection settings listed in CustomSettings. PXE boot a client to the point where it's possible to select a Task Sequence. As WinPE offers limited diagnostic functionality and tools, it's back to the basics with Notepad and logs. Press F8 to access the command prompt CD to 'X:\MININT\SMSOSD\OSDLogs\' or execute the following command: Notepad X:\MININT\SMSOSD\OSDLogs\ZTIGather.log Near the bottom of the log search for SQL Connection errors: ZTI error opening SQL Connection: Unable to establish database connection using [CSETTINGS] properties If you are not aware SQL uses the SQL Browser service on port UDP 1434 for application communications. Two potential issues warrant investigation. First, verify that the SQL Browser service is configured to start automatically by accessing services.msc. The second issue involves checking UDP port 1434 in the Inbound firewall rules. However, if you prefer to confirm the port, proceed with the following steps. Utilize either wf.msc or gpedit.msc to set up Windows Firewall Public Profile logging for dropped packets only following the example below. Restart and PXE the client to the Task Sequence window. On the MDT Server launch Notepad with Administrative permissions and open: C:\Windows\System32\Logfiles\Firewall\PFirewall.log Search for the IP of the client. Note the dropped packets on 1434. While on the MDT server, launch either gpedt.msc or wf.msc. Add an inbound UDP rule to allow port 1434. Return to the client, restart and then review the ZTIGather.log as previously demonstrated. The error is pretty self-explanatory. The MDT Service account requires login and access rights to the MDT SQL Database. Switch to the MDT Server and open SQL Server Management Studio. Browse to Security then Logins. Right click on Logins and select 'New Login' If you followed the preceding installation guides, you likely created a service account to grant access to the MDT share and its credentials are listed in CustomSettings.ini and BootStrap.ini. Add this account as a Windows Login to SQL. Adjust the User Mapping by granting db_dataread access to the MDT database for the service account. Review the ZTIGather.log after restarting the client for a final time and confirm the successful access to SQL. The settings for clients included in the MDT Database will now take precedence over CustomSettings.

  • PowerShell Code Signing with a Self-Signed Certificate

    Hey PowerShell enthusiasts! Ever wondered how to beef up your script security? Not every system gets the luxury of a Certificate Authority (CA)? Imagine your scheduled management scripts getting messed around by that one admin who loves tinker or worse, some bad actors. Today, let's tackle that risk head-on! We're diving into the world of self-signed certificates and code signing to keep your scripts safe and sound. Creating self-signed certificates for PowerShell script validation involves generating digital certificates locally and without relying on a Certificate Authority (CA). Using PowerShell's New-SelfSignedCertificate cmdlet, parameters like Subject and KeyUsage are specified. This process allows script integrity through code signing. Once created, the certificate can be used to digitally sign scripts with the `Set-AuthenticodeSignature` cmdlet, providing a level of assurance about the script's legitimacy and origin. Self-signed certificates may lack third-party validation, they boost script security by mitigating the risks of unauthorized changes. Still, be cautious; mishandling self-signed certificates could introduce vulnerabilities. Properly document and securely distribute certificates to maintain signed PowerShell script integrity in controlled environments. This guide is geared towards Active Directory Domains lacking a CA and DevOps keen on signing their PowerShell scripts. Don't worry; we're all about good practices here! To get started, make sure you have an offline Windows Server for crafting your Self-Signed certificate, a Windows 11 client (not extensively tested, but should work), and a separate client for testing the signed scripts with Admin access for tweaking Group Policy and importing certificates into the local machine store. Less chat more script..... Certificate Server Here are the key snippets from the script – the ones that matter. The script is downloadable from Github. https://github.com/Tenaka/Self-Signed-Certificates Declare working directories, either create the directories or allow the script to, not forgetting to add scripts that need signing to "C:\_PSScripts\". $certExport = "C:\_Certs\" $ScriptRepo = "C:\_PSScripts\" Set parameters. $params = @{ Subject = 'Self Signed PS Code Signing' DnsName = 'Self@Tenaka.net' FriendlyName = 'Self Signed PS Code Signing' NotAfter = (Get-Date).AddYears(5) Type = 'CodeSigning' CertStoreLocation = 'cert:\CurrentUser\My' KeyUsage = 'DigitalSignature' KeyAlgorithm = 'RSA' KeyLength = 2048 HashAlgorithm = 'sha256' } Create a new self-signed certificate based on the above parameters and send the details to 'newCodeSigningCert' variable for reference later. New-SelfSignedCertificate @params -OutVariable newCodeSigningCert Export the public key to the file system. Export-Certificate -Cert "cert:\CurrentUser\My\$($newCodeSigningCert.Thumbprint)" -FilePath "$($certExport)\CodeSigning.cer" Re-import certificate into Trusted Root otherwise it's not possible to validate any signed scripts. Import-Certificate -FilePath "$($certExport)\CodeSigning.cer" -Cert Cert:\LocalMachine\root Sign all scripts in C:\_PSScripts using a Foreach loop $gtPSscripts = Get-ChildItem -Path $ScriptRepo -filter *.ps1 -Recurse -Force foreach ($PSscriptItem in $gtPSscripts) {Set-AuthenticodeSignature $PSscriptItem.fullname -Certificate (Get-ChildItem "cert:\CurrentUser\My\$($newCodeSigningCert.Thumbprint)" -CodeSigningCert)} And there you have it! Snag those signed scripts and the exported certificate (.cer), then copy them over to the test client. Easy peasy! Check out any of the signed scripts, and you'll spot a signature block appended to the script. # SIG # Begin signature block # MIIFrQYJKoZIhvcNAQcCoIIFnjCCBZoCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # vhJhRK4rqe9AhAcGnbPDQg37+EgaN93UzTn2YIOVmbFrQcOwQfDJEzzVOrkLKJdX # yjdMD070/gJajAELBJDoxsY= # SIG # End signature block Test the Signed Scripts on a Client Let's assume the freshly signed scripts and certificate file reside in the same directories. Now open PowerShell with admin rights and execute the following commands. Declare the working directories. $certExport = "C:\_Certs\" $ScriptRepo = "C:\_PSScripts\" Import the certificate into the Trusted Root LocalMachine Certificate store. Import-Certificate -FilePath "$($certExport)\CodeSigning.cer" -Cert Cert:\LocalMachine\root To prevent the following prompt: Do you want to run software from this untrusted publisher? File C:\_PSScripts\gwmi-signed.ps1 is published by CN=Self Signed PS Code Signing and is not trusted on your system. Only run scripts from trusted publishers. [V] Never run [D] Do not run [R] Run once [A] Always run [?] Help (default is "D"): A Import the certificate into the Trusted Publishers LocalMachine Certificate store to prevent any prompts when executing the scripts. Import-Certificate -FilePath "$($certExport)\CodeSigning.cer" -Cert Cert:\LocalMachine\AuthRoot Launch Group Policy Editor or gpedit.msc. Browse to Computer Configuration, Administrative Templates, Windows Components, Windows PowerShell Enable 'Turn on Script Execution', select 'Allow Only Signed Scritps' in the drop-down and click OK. Run 'gpupdate /force' to apply the settings. If your scripts have a digital signature using your own certificate, they'll run smoothly in PowerShell. But the ones that aren't signed won't work. Perfect Script Security... mostly. Scripts that are signed and then updated without re-signing won't run either and you'll receive the error below. .\gwmi-signed.ps1 .\gwmi-signed.ps1 : File C:\_PSScripts\gwmi-signed.ps1 cannot be loaded. The file C:\Certs\gwmi-signed.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy. Bypassing the Execution Policy from PowerShell isn't possible. Set-ExecutionPolicy -ExecutionPolicy Bypass Execution Policy Change The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): y Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective ReadMe: PowerShell_ISE doesn't impose any limitations or restrictions. Unlike other environments, it doesn't enforce the Execution Policy, allowing the execution of any script, whether signed or not. Keep it Secret, Keep it Safe A PFX certificate, also called PKCS#12 or P12, is a file format used for keeping and moving cryptographic stuff like private keys and their matching public key certificates. It provides a secure way to store and share these sensitive elements. A PFX file typically includes: Private Key Public Key Certificate Certificate Chain Password Protection Once you use the New-SelfSignedCertificate command, the resulting certificate comes with both the public and private keys and can be exported as a PFX file containing the private key – basically, the whole shebang. That's why it's crucial to keep the signing server offline and well-guarded. It's also a good idea to back up the certificate, just for safety or to migrate to another host. The following commands will do just that Create a secure string password. $CertPassword = ConvertTo-SecureString -String "ChangeME1234" -Force -AsPlainText Export the private key as a pfx and password protect. Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($newCodeSigningCert.Thumbprint)" -FilePath "$($certExport)\selfsigncert.pfx" -Password $CertPassword Happy scripting! Remember, signing your PowerShell scripts with a self-signed certificate adds an extra layer of security to your code. Stay vigilant, keep those scripts locked and loaded with your personalized signature, and code on with confidence! Thanks for your time, really appreciate it! Take care and goodbye!

  • Intel NUC as a Home Lab Server

    Sweating the Assets It's time to bid farewell to the ageing NUC hardware, the current NUCs are from the 5th and 6th generations, dating back to 2016, and they've been in constant operation since their initial deployment. These systems are now struggling to keep up with the demands placed on them, especially NUC2, which regularly maxes out its CPU as it valiantly attempts to handle the workload of running SCCM and SCOM. There's a little nod to one of the best Syfy series ever, cruelly cut short, comment below if you know the name of the series. What's a NUC The Intel NUC (Next Unit of Computing) is an ideal choice for home labs due to its compact form factor, versatility, high performance and energy efficiency. Depending on the NUC variant this miniature PC can pack a powerful punch, ranging from a lowly i3 to an i9 processor and dedicated GPU in the form of the Intel Raptor Extreme, making it perfect for various lab setups and experimentation. Windows Server and Hyper-V I'm pretty agnostic as long as it's Microsoft, only kidding. Deploying Windows Servers as Hyper-V hosts in a home lab environment offers several advantages and a few disadvantages. The key advantages are: Multipurpose Functionality: Hyper-V hosts can serve as versatile servers, not limited to just virtualization. They can join the domain, be managed via System Center Configuration Manager (SCCM), and be monitored through System Center Operations Manager (SCOM). DFS Replication: Hyper-V hosts can host Distributed File System Replication (DFSR) File Servers for replicating user and group shares, enhancing data redundancy and availability. Deduplication: The virtual machines running on Hyper-V hosts can take advantage of deduplication, which helps save storage space by eliminating redundant data. However, there are some disadvantages to consider: Complexity: Managing enterprise-level services, such as SCCM and SCOM, can be complex and may require significant setup and maintenance effort, even in a home lab environment. Cost: Subscribing to Microsoft's Action Pack, so Servers don't time bomb after 90 days inflicts an annual cost of £450. Luckily for me, the company picks up the cost, this is not an option for everyone. Intel NUC 13 Hardware I acquired the new Intel NUC from www.scan.co.uk due to its competitive pricing, which proved to be a bit more budget-friendly in comparison to other websites. The hardware components that were acquired include a 2TB Samsung 990, which might be a bit overkill for running Windows OS and possibly hosting a virtual Domain Controller. In contrast, the 4TB 870 is intended to accommodate the bulk of the virtual machines (VMs). LN1359491 - Intel Arena Canyon i7 Tall NUC = £569.99 LN1192071 - 2x32G Corsair Vengence = £119.99 LN130047 - 2TB Samsung 990 PRO M.2 SSD = £161.99 LN1136891 - Samsung 4TB 870 EVO 2.5 = £189.98 Here's a quick how to install all the components: Install the Vengence RAM and the Samsung 990 Pro after carefully removing the base. Remove the 4 rubber grommets from the base. Slot the 4TB 870 EVO 2.5 connecting it to the SATA interface. Using the supplied screws secure the 2.5 SSD. Windows Server 2022 Installation Media Creating Windows boot media involves preparing a USB drive that can be used to install a Windows operating system. The initial and critically important step is to download the latest firmware and drivers, which you can access by following the provided link below. https://www.intel.com/content/www/us/en/products/sku/233114/intel-nuc-13-pro-board-nuc13anbi7/downloads.html It seems that the drivers included for the Intel NUC 13 Pro aren't compatible with Windows Server 2022. However, the Intel LAN Drivers tailored for the Intel 12th Gen NUC do work. Intel LAN-Win11-1.1.3.34 As an optional step, you can download the latest Windows Server 2022 Cumulative Update and copy it to the USB pen. This ensures that when network connectivity is established the most recent Windows patches are applied. USB Preparations You can download Windows Media in the form of an .iso file from Microsoft or the Partner site at a cost of £450 per year (includes many other benefits). Double click the iso to mount it on your computer. Copy the entire contents of the mounted image to an empty USB drive. Don't forget to include the necessary drivers and firmware files on the USB drive as well. Windows Server Installation Once you've connected the NUC's power supply, KVM, and the network, insert the USB pen with the bootable Windows installation files and drivers. Then, power on the NUC. Windows will boot and then follow the installation prompts. At the point of selecting the disk ensure it's the Samsun 990. I'm going to split the 2Tb and allocate 120Gb to the Windows OS partition. Set the Administrator password at the prompt and then log on. Install the drivers, firmware and any additional patches and reboot where necessary. Run 'diskmgmt.msc' to create any required partitions and assign drive letters. Run 'sysdm.cpl' and enable Remote Desktop access, allowing the NUC's KVM to be disconnected. Drivers for the Onboard NIC Now to resolve the connectivity issues and install the network drivers. At the run command type "Devmgmt.msc", select the network device and update drivers. Select 'Browse my computer for drivers' Select 'Let me pick from a list of available drivers on my computer' Select 'Have Disk...' and then browse to the Intel NIC drivers for the NUC Gen 12. Select the 'Killer E3100 2.5 Gigabit Ethernet Controller'. Select 'Yes' to the warning. Either set an IP address or allow DHCP to automatically assign an IP. Check for Windows Defender and any other missing updates. Hyper-V Setup Open PowerShell as Administrator (elevated) and execute the following command to install Hyper-V: Install-WindowsFeature -Name Hyper-V -IncludeManagementTools -Restart Once restarted configure the following Hyper-V settings: Create a new 'External' virtual switch, allowing management operations. Set the Virtual Hard Disks and Virtual Machines to point to the 4Tb 870 partition, mines on Z:\. Enable both Enhanced Session Mode check boxes. The NUC will be joined to the Domain with the LAPS, SCCM and SCOM agents installed automatically. The process of migrating VMs from the old NUCs is quite straightforward. Begin by removing any snapshots and shutting down the VMs. Then, proceed to perform a direct network copy of the VMs' directory structure to Z:\VM, followed by importing the VMs. Thanks For Your Time Thank you for taking the time to read this blog about the new Intel NUC for my home lab. We hope this information has been valuable. Stay tuned for more tech updates, and feel free to reach out if you have any questions or need further assistance.

  • Delegation of DNS with PowerShell

    DNS Delegation DNSAdmins is a default security group in Active Directory that delegates administrative control over the DNS Zones and some DNS servers settings to a specific user account or Group. Members of this group have permission to manage DNS zones and records and configure DNS server settings including Forwarders etc. However, it may not be desirable to delegate the entire DNSAdmin permission to a user via DNSAdmins and a more targeted approach of delegating zone management or creation could be necessary. The script (here), creates the required groups to delegate DNS Server management, the ability to create and delete zones and finally zone management. Group names will either be named DNSServer or DNSZone, where 'MicrosoftDNS' is used the group defines a top-level permission. Also, AD groups follow the suggested Microsoft naming convention of 'AT' or Action Task. Here are a few examples: AT_DNSServer_MicrosoftDNS_Manage is defined as the ability to change settings for the DNS Server eg create Forwarders or scavenging. AT_DNSZone_MicrosoftDNS_Manage is defined as the ability to create and delete Zones but not change any DNS Server settings. AT_DNSZone_Microsoft.com_Manage is defined as the ability to manage the Microsoft.com DNS Zone. Note: DNSAdmin group on its own does not have enough permissions and requires Server Operators, Administrators for the Domain or Domain Admin, basically local administrative rights over Domain Controllers. Setup The setup is pretty straightforward a virtual Domain Controller and Member Server. An OU for the delegated groups with a pre-existing group named AT_Server_User. This is to provide login via a user account to the Member Server with Remote Desktop User Rights Assignment and the delegated DNS group(s). Update the Member Server OU GPO with the following changes. Create 'Restricted Groups' for Administrators and add AT_Server_Admin. Create 'Restricted Groups' for Remote Desktop Users and add AT_Server_User. Add both Remote Desktop Users and AT_Server_User to the 'Allow log on through Remote Desktop Service' User Rights Assignment. Create a user account and add it to the AT_Server_User group. Deploy the DNS delegation script (here) with Domain Admin rights on the Domain Controller. After executing the script the delegation OU should be similar to the picture below with groups for both forward and reverse zones and 2 default MicrosoftDNS groups. DNS Server Delegation Members of AT_DNSServer_MicrosoftDNS_Manage are able to connect DNS and manage server settings but not create, delete or manage any existing zone. Due to the issue of requiring administrative rights on Domain Controllers, not all settings can be managed. Setting for interface options, DNSSec or Trustpoints requires further rights, most other DNS configuration options are available. All DNS Delegation groups require a minimum of READ to connect via the DNS snapin. DNS Server permissions can be found under System, MicrosoftDNS in dsa.msc DNS Zone Creation and Deletion To create and delete zones open adsiedit and type 'dc=domaindnszones,dc=fqdn'. Full control for AT_DNSZone_Manage is set against CN=MicrosoftDNS without inheritance. DNS Zone Management Finally, each zone is delegated to a named DNS zone group. use adsiedit, connect to the 'default naming context' to browse to each zone to interrogate permissions.

  • RGB Office Transformation, from Drab to Fab

    Finding ways to make the home office more appealing and enjoyable is a constant. I've tinkered with RGB lighting and had some success over the years, but without a vision, it was incomplete, there's still room for improvement and let us be honest you can't have enough RBG. I've taken inspiration from CyberPunk as well as watching plenty of YouTube videos on office setups for Gamers. I'm also a big fan of Japanese Anime and Alter Carbon season 1. Let's not mention season 2, which dumbed down, mangled and then discarded the best bits of books 2 and 3, I'd like to take you on a tour of the transformation from an uninspiring (boring) office, as demonstrated by the picture below, into a visually appealing office with the simple use of RGB lights and some work focus tech upgrades. The Lighting: Govee Glide Hexa Light Panels * 20 Panels - £380 Govee Alexa LED Strip Lights 10m - £31 LED Aluminum Profile U Shape 6Pack 1M - £22 FEAHRZEUG Smart LED Ambient Light Bars - £35 KSIPZE 30m Led Strip Lights RGB - £21 The Govee Hexa panels support 12 connected panels via 1 power supply. Or linking all 20 panels with both power leads attached. For me, this would have resulted in leads trailing down the wall. So, I've opted for 2 separate 10 panel configurations. The overall connectivity had its limitations, given that each panel had just one input and one output. This constraint restricted the scope for creating more intricate patterns. The cheaper and less LED dense KSIPZE strips were discreetly installed under the desk or in less conspicuous areas. While the Govee's higher density LED's were placed inside the diffusers. The hobby that I get paid for is IT, the upside is that it requires lots of gadgets and tech for testing and development. The downside, without a doubt, is the cost involved. However, I see it as an investment. The more I invest in making things quicker, more efficient, and more effective, the quicker I can complete projects. This helps me justify the following monitor upgrades..... The 34" monitors were been switched out for an LG 40WP95CP and LG 27UL550P. The LG 40WP95CP 40" monitor has a pixel density of approximately 140 PPI, compared to the typical range between 55 to 110 PPI. While this lower pixel density might be suitable for gaming, it's less than ideal for office-based productivity tasks where a higher pixel density often leads to sharper and more detailed on-screen content. The 27” is orientated in portrait for the long read and scripting. The only issue is that the refresh rates on both monitors reduces to 30Hz as the main workhorse laptop’s GPU isn’t up to the job. The reduction of refresh rate isn’t a massive issue as I’m not a PC gamer and YouTube doesn’t seem to be too badly affected. But it does tell me that more hardware is required, something water cooled with internal RBG. Of course, no CyberPunk office is complete without a cityscape and a very cool car Etsy Mcarlen P1 - Standard Post 50cm * 70cm - £74 EleksMaker Elekstube IPS Nixie Tube Digital Clock Now, onto my favourite part, the Nixie Tube clock. While it's not a genuine Nixie Tube due to their high cost, this is an excellent alternative, featuring six distinct clock faces, including a simulated Nixie Tube display. Amazon.com - £243 elekstube.com - £150 + £12 expedited delivery Thank you for taking the time reading this blog regarding the RGB office upgrades Stay tuned for more updates, as I'm hoping to add further enhancements, any ideas would be gratefully received.

  • How to Create GPOs with Restricted Groups using PowerShell.

    If you have ever tried 'PowerShell'ing' Group Policies, you know that support from Microsoft is sub-optimal, meaning that there is no support, of course, to fill this gap there are paid 3rd party offerings. The Task at Hand: A new 'Member Server' OU and various sub-OU's are needed, as well as their corresponding Group Policies, AD Groups and Restricted Groups. This feels like the millionth time I've manually accomplished this task and it's fairly repetitive and time consuming, alternatively, I can crack open PowerShell. The mantra is 'Why point and click when there's PowerShell' so let's get creative. Components of a Domain GPO: A Group Policy Object (GPO) is made up of various file types, strangely enough, the same as local GPO's configured via GPEdit.msc. Having scripted SecEdit, updating both User Rights AssignmenPats (URA) and Services previously the 'ask' should be straightforward. Basic file layout of a Domain GPO: C:\Windows\SYSVOL\domain\Policies\{GUID}\ Machine\Registry.pol User\Registry.pol Machine\Microsoft\Windows NT\SecEdit\GptTmpl.inf Machine\Microsoft\Windows NT\Audit\Audit.csv GPO security settings are written to GptTmpl.inf, an example of a GptTmpl.inf with Restricted Groups and User Rights Assignments from an SCCM installation including a SQL Member Server. The above looks a little confusing and here's a quick breakdown to help: *S-1-5-21-4000739697-4006183653-2191022337-1143 The SID of a Service Account [Group Membership] *S-1-5-32-544__Memberof = *S-1-5-32-544__Members = *S-1-5-21-4000739697-4006183653-2191022337-1143 *S-1-5-32-544 = Builtin\Administrators Group *S-1-5-32-573__Memberof = *S-1-5-32-573__Members = *S-1-5-21-4000739697-4006183653-2191022337-1171 *S-1-5-32-573 = Builtin\Event Log Readers *S-1-5-32-559__Memberof = *S-1-5-32-559__Members = *S-1-5-21-4000739697-4006183653-2191022337-1171 *S-1-5-32-559 = Builtin\Performance Log Users [Privilege Rights] SeServiceLogonRight = *S-1-5-21-4000739697-4006183653-2191022337-1170 SeServiceLogonRight = Log on as a service SeInteractiveLogonRight = *S-1-5-21-4000739697-4006183653-2191022337-1169 SeInteractiveLogonRight = Allow log on locally SeBatchLogonRight = *S-1-5-21-4000739697-4006183653-2191022337-1187 SeBatchLogonRight = Log on as Batch Overview of script actions: Execute the script directly on the Domain Controller with the PDC role. The script will create a 'Resources' OU off the root of the Domain, then sub-ou's 'Member Servers' and 'Restricted Groups'. For each application service eg Exchange, SharePoint etc, an additional OU is then created with corresponding AD groups for both Administrator and Remote Desktop User Groups. Finally, GPOs are created for each OU and the AD Groups SID are assigned to both the Restricted Groups and Remote Interactive User Rights Assignment. The script: https://github.com/Tenaka/GPOs Script Breakdown: The following are extracts from the script that is accessible from Github. Resolve the Domain Naming Context. $rootDSE = (Get-ADRootDSE).rootDomainNamingContext Resolve the path to Sysvol, just in case it was moved during Domain Controler installation. $smbSysvol = ((Get-SmbShare -name "sysvol").path).replace("SYSVOL\sysvol","sysvol") Set 'Resource' OU as a root for all subsequent OU's for member servers etc. $resRoot = "Resources" Stitch or join the Root DN and variables to create OU Distinguished Names. $resourceOU = "OU=$($resRoot),$($rootDSE)" $memSrvOU = "OU=$($memSrvRoot),OU=$($resRoot),$($rootDSE)" $ResGroupOU = "OU=$($ResGroupRoot),OU=$($resRoot),$($rootDSE)" Create an OU called 'Resources' as a top-level OU. New-ADOrganizationalUnit -Name $resRoot #-ProtectedFromAccidentalDeletion $false Create a variable based on the OU name for creating an AD group name. $rgRtAdminGp = "RG_$($MemSrvRoot)_Admin" Create a new Domain Global group based on the OU name for Admin and Remote user groups. Groups are created in the 'Restricted Groups' OU. New-ADGroup -Name $rgRtAdminGp –groupscope Global -Path $ResGroupOU -Description $rgRtAdminDescrip Get the SID of the new Group. $getRtRGAdminSid = $getRtRGAdmin.SID.Value Declare the variable for creating an OU. $GPOName = "GPO_$($MemSrvRoot)_RestrictedGroup" Create a new OU based on the variable and link to OU. New-GPO -Name $GPOName | New-GPLink -Target $getOUMS.DistinguishedName Set delegation permission on the OU so the AD group can edit their own policy. Set-GPPermission -Guid $getGpoId -PermissionLevel GpoEditDeleteModifySecurity -TargetType Group -TargetName $rgAdminGp Declared the path to the GPO directory. $sysvol = "$($smbSysvol)\domain\Policies\{$($getGpoId)}\Machine\Microsoft\Windows NT\SecEdit" Create a directory and GptTmpl.inf file. New-Item -Path $sysvol -ItemType Directory -Force New-Item -Path $sysvol -Name GptTmpl.inf -ItemType File -Force Declare variables based on the Group SIDs for Admin and Remote Groups. $addConAdmin = "*S-1-5-32-544__Members = *$($getRtRGAdminSid)" $addConRDP = "*S-1-5-32-555__Members = *$($getRtRGRDPSid)" $addConURARemote = "SeRemoteInteractiveLogonRight = *$($getRtRGAdminSid),*$($getRtRGRDPSid)" Update GptTmpl.inf. Add-Content -Path $gptFile -Value '[Group Membership]' Add-Content -Path $gptFile -Value '*S-1-5-32-544__Memberof =' Add-Content -Path $gptFile -Value $addConAdmin Add-Content -Path $gptFile -Value $addConURARemote Write the GPCMachineExtensionName attribute with the Client-Side Extension GUID of the areas of the GPO setting for the GPO. If not the settings won't display in the GPO Management tool and the target server won't be able to read the GPO. Set-ADObject -Identity $getGPOPath -Replace @{gPCMachineExtensionNames="[{827D319E-6EAC-11D2-A4EA-00C04F79F83A}{803E14A0-B4FB-11D0-A0D0-00A0C90F574B}]"} The Client-Side Extensions GUID can be extracted from Polices, there's no need to try and discover those GUIDS. Set the required policies and copy the GUIDs. The initial scenario of creating Restricted Groups GPO's is complete, with a few alterations, Administrative Template settings could be set by copying Registry.pol into the GPO. A better use would be setting up URAs for service accounts eg SQL and the Logon as a Service right dynamically as part of an automatic installation of Microsoft SQL Server. Enjoy and hope it proves useful and do give it a go prior to paying for a 3rd party tool. The script: https://github.com/Tenaka/GPOs Security Identities: https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers Mapping User Rights Assignments: https://www.tenaka.net/post/translate-user-rights-assignments-from-guids-to-group-names

  • Identify and Fix Unquoted Paths Vulnerability Automatically

    The unquoted paths vulnerability is a security flaw that occurs when a software application or service running on a system references executable files or scripts without enclosing the file path in quotation marks. This can lead to a potentially exploitable security gap because the operating system interprets the unquoted path incorrectly. ​ When a program with an unquoted path runs, the OS may attempt to execute the name of the directory with the space. C:\Program.exe C:\Program Files (x86)\Application.exe C:\Program Files (x86)\Application One\ An attacker can place a malicious executable in a directory with a similar name to the one referenced in the unquoted path. When the vulnerable program runs, it might mistakenly execute the malicious code, enabling unauthorized access, privilege escalation, or other security breaches. ​ To mitigate this vulnerability, developers should always use quotation marks around file paths in their code to ensure that the correct executable is executed, and users should keep their systems updated to patch any discovered unquoted paths. vulnerabilities. For demo purposes, the system has been intentionally afflicted with unquoted path vulnerabilities. This output is from a dedicated Unquoted script found @ https://github.com/Tenaka/UnQuoted-Paths This output is from a far more extensive suite of scripts that search many vulnerabilities and configuration errors and present the results in an HTML format that can be imported into Excel and can be found @ https://github.com/Tenaka/SecureReport. While the capacity to spot vulnerabilities is valuable, my approach focuses on automatically addressing these issues during deployments whilst also reviewing the output. Resolving security vulnerabilities is then built into MDT and SCCM (MECM) Task Sequences. Equally, the reporting and resolution of this issue can be accomplished manually by executing the scripts with Admin privileges from PowerShell. No manual intervention is required, any application that falls through the gaps eg a member of staff deploying an app without following the process, that's if the process exists. Back to Github to download the 2nd script that 'fixes' Unquoted paths. https://github.com/Tenaka/UnQuoted-Paths Output is provided to any actions taken both to PowerShell and a log file. The script adds the double-quotation marks both preceding and following the imagepath, ensuring that the path is properly enclosed within quotation marks.

  • Audit Applocker Rules and Export to Excel

    Introduction Reporting on AppLocker rules is crucial to maintaining security. It provides insight into allowed and blocked applications, aiding in policy refinement. The main challenge lies in the absence of a management graphical user interface (GUI) for rule administration and processing. Indeed, GPResult offers a visual display of individual policies, but it falls short in presenting a comprehensive overview of the combined and applied policies. A Quick Recap of Applocker A quick recap. AppLocker is a security feature available in Windows that provides user context application control. It uses policies based on file attributes like publisher, hash, and path to allow or deny software execution. By preventing unauthorized or potentially harmful programs from running, AppLocker helps safeguard systems against malware and unauthorized software installations, enhancing overall security. As Applocker only protects the user context it provides little safeguard against RCE. Applocker is also subject to numerous Living off the Land bypasses and should only ever be considered part of a layered approach to Windows security. Windows Defender Application Control is a far more robust kernel level application control mechanism. The Script The script for exporting Applocker rules can be found @ https://github.com/Tenaka/Applocker/blob/main/ApplockerReport.ps1 Why Export to HTML!!! If you hadn't realised the script initially creates an HTML report, but the original intention was to export Applocker Rules to .csv, then into Excel. Exporting to CSV proved limiting due to the lack of support for individual worksheets or pages. The report must also work on Clients, Servers and not be reliant on Excel or imported Excel PowerShell modules. Finally, I've an extensive configuration, security and vulnerability assessment report written in PowerShell, likewise creating an HTML report that also can be imported into Excel. The vulnerability assessment script can be found @ https://github.com/Tenaka/SecureReport The Report Download the script and execute it using PowerShell_ISE or native PowerShell. While I haven't conducted extensive testing with PowerShell, it should function in both environments. The report outputs to $env:USERPROFILE, the root of the user's profile path, named the date, hostname-report.htm "C:\Users\Fred\23-08-28-LP674504-Report.htm". The report will contain the effective policy applied to the endpoint. While appealing, the current format may not be the most practical to work with. However, you can import it as a web source into Excel, where each heading corresponds to an Excel worksheet. Here are a couple of examples followed by a quick how-to for importing into Excel. Excel Import Once the script concludes, the AppLocker Audit report will automatically open in the default web browser. Copy the URL path to the clipboard for use in the importing process. Open Excel and go to the Data tab, then select 'From Web'. Paste the file path into the URL box. In the navigation Window, select the Applocker Rule sets and then 'Load' and 'Load To...' on the drop down. Select 'Table' on the Import Data window. Importing the HTML file into Excel requires a brief moment, although it won't provide sufficient time to justify indulging in a coffee break. Upon completing the import process, an Excel spreadsheet is prepared and readily available for review. Hope this proves useful, feedback is always welcome and thanks for your time.

  • Change MDT Mapped Z: Drive

    When deploying a Windows operating system or installing MDT applications, a mapped network drive is usually mounted temporarily as Z:\. The letter "Z" is chosen because it is typically not used for local drives in most deployments, it's less likely to conflict with existing drive letters on the target computer. What occurs when an application necessitates the use of the Z:\ drive during the process of deploying an image through MDT? It's often better to overlook your initial reaction.....Z: Being engaged during the operating system installation. Applications can persist with preconfigured mapped network drives. The illustration provided represents a common example of a regular operating system deployment, and it's evident that the drive letter Z: is assigned to the MDT Deployment share. There appear to be two approaches to altering the fixed Z:\ drive mapping to a different designated letter, although there might be additional methods available as well. During my search for a solution, Google yielded no results, which could potentially be attributed to me asking the wrong questions. Late to the party and whilst writing this blog, ChatGPT provided a suggestion to address this issue, update the 'CustomSettings.ini' file by incorporating 'DriveLetter=Y'. Had it succeeded on the initial attempt, it would have presented a more graceful resolution, unfortunately, that wasn't the case, I haven't delved into the reasons behind the failure. Let's proceed with a working solution by modifying the hardcoded drive letter in ZTIUtility.vbs. I'm using PowerShell_ISE as it conveniently displays the line number. Browse to C:\MDTDeploymentShare\Scripts\ZTIUtility.vbs Search for "z" and on line 3003 or thereabouts, depending on the version of MDT installed, update the hardcoded drive 'Z' to something else, not C: or X: as these are also used by the OS and MDT. In this case, I've designated the letter 'T' as the new MDT mapped network drive. Regenerate the Boot images by Updating the Deployment Share. Choose 'Completely regenerate the boot images', then grab a coffee. Launch WDS and Replace the Image. Browse to the MDT Share and select the LiteTouchPE_x64.wim. Deploy a new Windows OS from MDT Pxe and the MDTDeploymentShare is now mapped as "T:\". If you found the content valuable, I encourage you to explore the MDT deployment guides and instructional resources available under the main website sections. Finally, I'm headed off to have strong words with the individual responsible for implementing an application that requires hardcoded drives for configuration components.

  • PowerShell's Custom Runtime for AWS Lambda's - Installation

    Introduction PowerShell custom runtime for AWS Lambda is an addition to the AWS Lambda services, offering developers and Microsoft engineers the ability to leverage PowerShell within the serverless environment. Unlike the standard runtimes supported by AWS Lambda, which include languages like Python, Node.js, and Java, the PowerShell custom runtime, developers can now build and deploy Lambda functions using their existing PowerShell skills. It allows for the integration of PowerShell's vast library of cmdlets and modules, enabling developers to leverage a wide range of pre-built functions and automation tasks. PowerShell's object-oriented scripting approach also provides a means for manipulating and managing AWS resources, making interacting with other AWS services like Amazon S3, Amazon DynamoDB, and AWS CloudFormation easier. Additionally, it's now possible to edit the PowerShell script directly within the published Lambda, which was not previously possible. The Truth of the Matter The issue, it's PowerShell, any real DevOps will be using anything but PowerShell as it's a scripting language, so there's limited support for PowerShell on AWS. However, if you're a Microsoft engineer who needs to manage the Windows Infrastructure on AWS then PowerShell will be your go to scripting language for Lambda functions. The PowerShell custom runtime setup provides 3 options for deployment, Linux or WSL, native PowerShell and Docker. The native PowerShell deployment doesn't work, at least I couldn't get it working and others have faced similar issues, with no resolution provided. The good news is that Windows Subsystem for Linux (WSL) deployment does successfully deploy and execute and this is what I'll be using. Requirements WSL 2 requires the Hyper-V Hypervisor, this rules out any AWS EC2 instance, Hyper-V isn't supported. A Windows 2022 or Windows 11 with the latest patches installed is required. I've Windows 11 installed on a Zenbook Space Edition laptop with the Hyper-V feature installed and virtualization enabled in the system's BIOS or UEFI. WSL 2 isn't directly installed on the laptop, it can be, I prefer keeping my clients free of clutter and instead opted for a Windows Server 2022 Hyper-V vm. Any issues the vm will be rolled back or redeployed. Now deploy a Gen2 Windows Server 2022 Hyper-V image named, ensure the latest Windows updates are applied. AWS Configuration An account named 'svc_lambda' has been created with Administrative access in IAM. The excessive rights are for ease of deployment, the permissions will be adjusted to those needed later. The account's Access and Secret have been exported for use during the creation of the PowerShell Runtime Lambda. Installation of Windows Subsystem for Linux version 2 WSL version 2 was not supported by Server 2022 or Windows 11 at release. Install the latest Windows patches to enable WSL2 support. I may have mentioned this a few times now. Power off the VM and from the host open an elevated Powershell session. Then type the following command to enable nested hypervisor. AWS-Mgmt01 is vm's name in the Hyper-V console and not its hostname. Set-VMProcessor -VMName AWS-Mgmt01 -ExposeVirtualizationExtensions $true Power on, AWS-Mgmt01, login and elevate a PowerShell session and execute the following command. This will install all components and features required. If the command fails to be recognised, then Windows updates aren't applied or the experience I had, they failed to install correctly. wsl --install Restart AWS-Mgmt01, log in and WSL should auto launch, if not run wsl --install from PowerShell. Type in a username and password at the prompt. Installation confirmation will show that the latest version of Ubuntu and WSL 2 are configured. In the Linux shell execute the following commands to update and install all required dependencies. sudo apt update -y && sudo apt upgrade -y sudo apt install glibc-source groff less unzip make -y AWS Serverless Application Model Installation AWS SAM (Serverless Application Model) is a framework provided by AWS that simplifies the development, deployment, and management of serverless applications. It extends the capabilities of AWS CloudFormation, allowing developers to define serverless application resources using a simplified YAML syntax and is next to install. Type pwd and it will return '/home/user'. Type: mkdir Downloads to create a working directory and cd into the directory. Download the SAM client for Linux, unzip and Install. wget https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip unzip aws-sam-cli-linux-x86_64.zip -d sam-installation sudo ./sam-installation/install Confirm version and successful installation. /usr/local/bin/sam --version Download the AWS Client for Linux, unzip and Install wget "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" unzip awscli-exe-linux-x86_64.zip sudo ./aws/install Confirm version and successful installation. /usr/local/bin/aws --version Download the AWS Lambda PowerShell Runtime. git clone https://github.com/awslabs/aws-lambda-powershell-runtime mv aws-lambda-powershell-runtime/ aws-sam cd aws-sam/examples/demo-runtime-layer-function Export the access and secret keys for the Lambda service account via AIM. Configure access for the Lambda-Svc user. aws configure AWS Access Key ID [None]: AKIA5IZEOZXQ4XXXXX AWS Secret Access Key [None]: 2O8hYlEtAzyw/KFLc4fGRXXXXXXXXXX Default region name [None]: us-east-2 Default output format [None]: Build the custom runtime . sam build --parallel Deploy Custom Runtime to AWS. sam deploy -g Stack Name [sam-app]: PowerShellLambdaRuntime AWS Region [us-east-2]: us-east-2 Confirm changes before deploy [y/N]: n Allow SAM CLI IAM role creation [Y/n]: y Disable rollback [y/N]: n Save arguments to configuration file [Y/n]: n The deployment will take a few minutes as it creates CloudFormation, an S3 bucket and finally the Lambda. Testing the Runtime Lambda Function From the AWS console, open Lambda and browse to Functions to confirm the successful deployment of the PowerShell Runtime Demo. It's at this point when native PowerShell is used, the whole runtime falls apart and fails to execute. Click on Test after reviewing the PowerShell code. This is a first not only can it be viewed, it's editable. Add an Event Name and Save. Click on Test and review the details. The Runtime is installed, but not much else..... This is just the beginning and a bit of a problem if you thought that it was a simple matter of creating new Lambda's and applying PwsRuntimeLayer. I'm the bearer of bad news, let me explain. Two layers were created for the demo, the DemoAWSToolsLayer and PwshRuntimeLayer. For PowerShell, the correct modules need importing and these are supplied in the Lambda layers. In this case, it's the DemoAWSToolsLayer that loads the required module for the Lambda demo. And in the Demo's case, it's only the AWS.Tools.Common module needed by the function to the Get-AWSRegion. Consequently, additional layers containing the necessary modules for the function are required. For instance, to create a Lambda function to stop an EC2 instance, both the AWS.Tools.Common and AWS.Tools.EC2 modules are needed. We will delve into this in the next blog (here). Links https://aws.amazon.com/blogs/compute/introducing-the-powershell-custom-runtime-for-aws-lambda/ https://aws.amazon.com/blogs/compute/extending-powershell-on-aws-lambda-with-other-services/ https://www.youtube.com/live/FAU0V_SM9eE?feature=share

bottom of page