Thursday, April 22, 2021

Linux quick course

The Linux Command Tutorial: 

 The chown Command

https://www.youtube.com/watch?v=w9K_eeFL6oQ 

The rm Command

https://www.youtube.com/watch?v=MQ0r-kcBTQQ

The su Command

https://www.youtube.com/watch?v=9NVvCum4-Rg

The vi Command

https://www.youtube.com/watch?v=0YFL8uTfrdg

The grep Command

https://www.youtube.com/watch?v=O8UQOC468rA

The sudo Command

https://www.youtube.com/watch?v=1IPdHN2Qc0w

The mv Command

https://www.youtube.com/watch?v=pOQqqXFaKxc

The pwd Command

https://www.youtube.com/watch?v=1gjVk5BGLtw

The grep Command

https://www.youtube.com/watch?v=O8UQOC468rA

 

Sunday, December 27, 2020

Create a bootable USB stick with PowerShell (Create-BootableUSBStick)

 

Create a bootable USB stick with PowerShell (Create-BootableUSBStick)

Creating a bootable USB stick could be a tricky task. You’ll need a tool (eg. the Windows 7 USB/DVD tool) or you have to struggle with those old cmd commands like bootsect.exe. This is now over, because I’ve created a PowerShell function for the community that automates all the steps you need for creating your Windows 10 or Windows Server bootable USB stick.

Create-BootableUSBStick in Action

I want to show you first what we are going to achieve.

Plug in your USB stick. Then mount the operating system iso file (Windows 7/8/10, Windows Server). Double check the drive letters. We’ll need them further on.

In my case the USB stick is associated with E: and the ISO is mounted on F:. The following command sets up an bootable Windows USB stick:

1
Create-BootableUSBStick -USBDriveLetter E: -ImageFiles F:

1.PNG

Now wait a few minutes and your USB stick is ready to use!

The Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
function Create-BootableUSBStick {
 
# .SYNOPSIS
# Create-BootableUSBStick is an advanced PowerShell function to create a bootable USB stick for the installation of Windows OS.
 
# .DESCRIPTION
# The main idea is to avoid the use of 3rd party tools or tools like the Windows 7 USB tool.
 
# .PARAMETER
# USBDriveLetter
# Mandatory. Provide the drive letter where your usb is connected
 
# .PARAMETER
# ImageFiles
# Mandatory. Enter the drive letter of your mounted ISO (OS Files)
 
# .EXAMPLE
# Create-BootableUSBStick -USBDriveLetter F: -ImageFiles D:
 
# .NOTES
# Author:Patrick Gruenauer
 
[CmdletBinding()]
 
param
 
(
 
[Parameter()]
$USBDriveLetter,
 
[Parameter()]
$ImageFiles
 
)
 
$USBDriveLetterTrim=$USBDriveLetter.Trim(':')
 
Format-Volume -FileSystem NTFS -DriveLetter $USBDriveLetterTrim -Force
 
bootsect.exe /NT60 $USBDriveLetter
 
xcopy ($ImageFiles +'\') ($USBDriveLetter + '\') /e
 
Invoke-Item $USBDriveLetter
 
}

How to use it

Copy the code into your PowerShell ISE session and run the code. Then type the command and have fun with it.

If you want to make the function permanent available, so that the function is there every time you start PowerShell, you have to create a folder in C:\Program Files\WindowsPowerShell\Modules. Name it Create-BootableUSBStick. Then save the code as a .psm1 file in that folder. The screenshot below will be a great help.

2.png

Share this:

Wednesday, December 23, 2020

Printer mapping - batch script

 @echo off
net time \\dell /set /yes
net use o:\\dell\admin\office
net use s: \\dell\Sims$
net use t: \\dell\shared
start \\dell\office_laser_printer
start \\dell\ict_mono_laser_1
start \\dell\ict_mono_laser_2
start \\dell\ks1_colour_laser
start \\dell\ks1_mono_laser
start \\dell\lz_mono_laser

Tuesday, December 22, 2020

Printer mapping - vbs script

 'CREATE NETWORK OBJECTS
Set mWSHNetwork = CreateObject("WScript.Network")
Set mExisitingMappedDrives = mWSHNetwork.EnumNetworkDrives
Set existingPrinters = mWSHNetwork.EnumPrinterConnections
Set mFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set objExplorer = CreateObject("InternetExplorer.Application")
 

'PRINTERS (Ex. "\\<print server name>\<Queue Name>)
defaultPrinters = "\\<print server name>\Canon iR5000 - FC2 Left;
\\<print server name>\Canon iR5070 - Right;
\\<print server name>\RICOH MP 6001 Breakroom;
\\<print server name>\Canon iR5070 - NJ;
\\<print server name>\RICOH  MP 6001 Sales;
\\<print server name>\RICOH  MP 6001 Referral;
\\<print server name>\RICOH Aficio MP 6000 - Litigation Area "

Mapping printers - vbs script

 ' Printers.vbs - Windows Logon Script.
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection "\\FileServer01\HP4050"

Linux Hacking Exposed - Notes

 Linux Hacking Exposed

- attack NFS shares
- SQUID proxy (attacking proxy)
- Windows X System TCP port 6000->6003
xhost+
- sniffers: tcpdump
- vulnerable scripts: count.cgi, php.cgi, nph.cgi, nph-test.cgi
- netstat -an command
- nmap -sT -O localhost

- setuserid programs run with the effective user ID that owns the file

cp 'which id'
chown root ./id
chmod 755 ./id; chmod u+s ./id
ls -l ./id
id
./id

- find ways to abuse users with '.' in their PATH
- passwords stored in user files
- passwords stored in System Files
ex: /etc/ppp/chap-secrets file
/etc/wvdial.conf

Sudo:
- a tool for distributing administrative authority
- using sudo, is possible to grant specific users the ability to perform specific administrative tasks that normally require ROOT access

- symlink and hardlink attacks
- wc -l /etc/shadow

Tuesday, July 21, 2020

IT Powershell commands

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force
dir . | Unblock-File
Import-Module .\Microsoft.PowerApps.Administration.PowerShell.psm1 -Force
Import-Module .\Microsoft.PowerApps.PowerShell.psm1 -Force
Add-PowerAppsAccount

#############
Display a list of all environments
Get-AdminEnvironment

This returns a list of each environment across your tenant, with details of each (e.g., environment name (guid), display name, location, creator, etc).


Display details of your default environment
Get-AdminEnvironment –Default

Returns the details for only the default environment of the tenant.


Display details of a specific environment
Get-AdminEnvironment –EnvironmentName ‘EnvironmentName’

##################
Common entries (just to get started)

1. Navigate the Windows Registry like the file system:
cd hkcu:

2. Search recursively for a certain string within files:
dir –r | select string "searchforthis"

3. Find the five processes using the most memory:
ps | sort –p ws | select –last 5

4. Cycle a service (stop, and then restart it) like DHCP:
Restart-Service DHCP

5. List all items within a folder:
Get-ChildItem – Force

6. Recurse over a series of directories or folders:
Get-ChildItem –Force c:\directory –Recurse

7. Remove all files within a directory without being prompted for each:
Remove-Item C:\tobedeleted –Recurse

8. Restart the current computer:
(Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).Win32Shutdown(2)
Collecting information

9. Get information about the make and model of a computer:
Get-WmiObject -Class Win32_ComputerSystem

10. Get information about the BIOS of the current computer:
Get-WmiObject -Class Win32_BIOS -ComputerName .

11. List installed hotfixes -- QFEs, or Windows Update files:
Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName .

12. Get the username of the person currently logged on to a computer:
Get-WmiObject -Class Win32_ComputerSystem -Property UserName -ComputerName .

13. Find just the names of installed applications on the current computer:
Get-WmiObject -Class Win32_Product -ComputerName . | Format-Wide -Column 1

14. Get IP addresses assigned to the current computer:
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Format-Table -Property IPAddress

15. Get a more detailed IP configuration report for the current machine:
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Select-Object -Property [a-z]* -ExcludeProperty IPX*,WINS*

16. Find network cards with DHCP enabled on the current computer:
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "DHCPEnabled=true" -ComputerName .

17. Enable DHCP on all network adapters on the current computer:
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName . | ForEach-Object -Process {$_.EnableDHCP()}
Software management

18. Install an MSI package on a remote computer:
(Get-WMIObject -ComputerName TARGETMACHINE -List | Where-Object -FilterScript {$_.Name -eq "Win32_Product"}).Install(\\MACHINEWHEREMSIRESIDES\path\package.msi)

19. Upgrade an installed application with an MSI-based application upgrade package:
(Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='name_of_app_to_be_upgraded'").Upgrade(\\MACHINEWHEREMSIRESIDES\path\upgrade_package.msi)

20. Remove an MSI package from the current computer:
(Get-WmiObject -Class Win32_Product -Filter "Name='product_to_remove'" -ComputerName . ).Uninstall()
Machine management

21. Remotely shut down another machine after one minute:
Start-Sleep 60; Restart-Computer –Force –ComputerName TARGETMACHINE

22. Add a printer:
(New-Object -ComObject WScript.Network).AddWindowsPrinterConnection("\\printerserver\hplaser3")

23. Remove a printer:
(New-Object -ComObject WScript.Network).RemovePrinterConnection("\\printerserver\hplaser3 ")

24. Enter into a remote PowerShell session -- you must have remote management enabled:
enter-pssession TARGETMACHINE

25. Use the PowerShell invoke command to run a script on a remote servers:
invoke-command -computername machine1, machine2 -filepath c:\Script\script.ps1

Bonus command

To dismiss a process you can use the process ID or the process name. The -processname switch allows the use of wildcards. Here's how to stop the calculator:
Stop-Process -processname calc*

######################


If the current console is not elevated and the operation you're trying to do requires elevated privileges then you can start powershell with the "Run as administrator" option

PS> Start-Process powershell -Verb runAs

############
You can create a batch file (*.bat) that runs your powershell script with administrative privileges when double-clicked. In this way, you do not need to change anything in your powershell script.To do this, create a batch file with the same name and location of your powershell script and then put the following content in it:


@echo off

set scriptFileName=%~n0
set scriptFolderPath=%~dp0
set powershellScriptFileName=%scriptFileName%.ps1

powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%\`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"

#################

Import-Module "C:\Program Files\Microsoft Dynamics NAV\90\Service\NavAdminTool.ps1"

net localgroup administrators
or
invoke-command [net localgroup administrators] -comp chi-fp01

get-netlocalgroup -group "remote desktop users" -computername $sessions


cmdlet:
get-help update

##########
Check for the presence of patches with PowerShell
Get-Hotfix –id KB4012212
Get-Hotfix –id KB4012217,KB4015551,KB4019216

You can also execute the command against remote computers by using the –ComputerName parameter:
Get-Hotfix –id KB4012212 –computername Jon-Desktop

Disable vulnerable versions of SMB with PowerShell
On Windows 8 and Windows Server 2012 systems, there is a built-in cmdlet that deals with the SMB versions present and in operation on any given machine. It is called Set-SMBServerConfiguration. You probably will not need to use this very often, so I will just give you the command you need to turn SMB1 off:
Set-SmbServerConfiguration -EnableSMB1Protocol $false

For Windows 8.1, Windows 10, Windows Server 2012 R2 and Windows Server 2016 systems, run the following command instead:
Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol

################
Now imagine that you want to create an HTML report that lists the name of each service along with its status (regardless of whether the service is running). To do so, you could use the following command:
Get-Service | ConvertTo-HTML -Property Name, Status > C:\services.htm

For example, to export the list of system services to a CSV file, you could use the following command:
Get-Service | Export-CSV c:\service.csv

For example, to create a CSV file containing the name of each system service and its status, you could use the following command:
Get-Service | Select-Object Name, Status | Export-CSV c:\service.csv

For example, to see the Application log, you could use the following command:
Get-EventLog -Log "Application"

You can terminate a process based on its name or on its process ID. For example, you could terminate Notepad by using one of the following commands:
Stop-Process -Name notepad<br> Stop-Process -ID 2668
################
Data acquisition: Checking running services on a PC
Get-Service | Where-Object {$_.status -eq "running"}
or:
Get-Service | Where-Object {$_.status -eq "running"} | Sort-Object DisplayName


Troubleshooting: Searching event log for system errors
For example, if you want to take a look at the error messages in the “System” event display, enter the following:
Get-EventLog System | Where-Object {$_.entryType -Match "Error"}

Get-EventLog System -Newest 100 | Where-Object {$_.entryType -Match "Error"}

Remote management: Controlling services on remote computers
Get-WmiObject Win32_Bios -Computername


You can now access the internal system settings of the third-party computer remotely. The following example shows how to retrieve the methods of the Windows Update Client service to find out which cmdlets can be used to start, stop, and restart it:
Get-WmiObject -Computername -Class Win32_Service -Filter "Name='wuauserv'"

##################
Say, for instance, you wanted to know how the Get-Service command works, you can use the Get-Help command like so:
Powershell

Get-Help -Name Get-Service

But Get-Help does even more. Say you want to find a list of all commands. You'd enter the following:

Get-Help *

Unlock AD account:
Unlock-ADAccount [-Identity] <ADAccount> [-AuthType <ADAuthType> {Negotiate | Basic} ] [-Credential ,PSCr

So, rather than entering all of the variables noted up top, you could just enter the following:
Powershell

Unlock-ADAccount -identity

For identity, you'll either enter the Active Directory distinguished name, the GUID, security identifier, or SAM account name for the account in question.

Set-ADAccountPassword [-Identity] <ADAccount> [-AuthType {<Negotiate> | <Basic>}] [-Credential <PSCredential>] [-NewPassword <SecureString>] [-OldPassword <SecureString>] [-Partition <string>] [-PassThru <switch>] [-Reset <switch>] [-Server <string>] [-Confirm] [-WhatIf] [<CommonParameters>]

If you were to enter Get-ADUser –Filter {Name –like “Martin*”}, for instance, you'd find every user with the first name Martin in your Active Directory.

Get-eventlog security -newest 100 |
where {$_.entrytype -eq "failureAudit"}

get-service

get-process

stop-process

Set-ExecutionPolicy Unrestricted

##########################

To get all A records in a zone you can do this:
Get-DnsRecord -RecordType A -ZoneName FQDN -Server ServerName

To get this into a text file:
Get-DnsRecord -RecordType A -ZoneName FQDN -Server ServerName | % {Add-Content -Value $_ -Path filename.txt}

Get-WmiObject -Namespace Root\MicrosoftDNS -Query "SELECT * FROM MicrosoftDNS_AType WHERE ContainerName='domain.com'"
WMI is good to remember when you can't download DnsShell for some reason, or if you're on an older version of Powershell that doesn't have the baked-in Cmdlets, or if you're targeting an older version of Windows Server.


##########################
The DnsServer module available in Windows Server 2012, Powershell v3 has the following commands that might be useful to you:

Get-DnsServerZone
Get-DnsServerResourceRecord

The first will get you all the zones The second will get you the records for whatever zone you pass to it

They are basically the equivalent of DNSCMD's /EnumZones and /EnumRecords.

So... You could write something like this to get ALL of the records from ALL zones:

$Zones = @(Get-DnsServerZone)
ForEach ($Zone in $Zones) {
    Write-Host "`n$Zone.ZoneName" -ForegroundColor "Yellow"
    $Zone | Get-DnsServerResourceRecord
}

Also, I'm fairly sure that server 2012 keeps an actual zonefile for each zone now? So you should have a file copy for all your zones.

If you're working with 2008 R2, then you can use this script which I use to back up all of my zones to files:

$zones = @( `
    dnscmd /enumzones | `
    select-string -pattern "\b(?i)((?=[a-z0-9-]{1,63}\.)(xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}\b" | %{$_.Matches} | %{$_.Value};
);

ForEach ($domain in $zones) {
    $backup = "dnscmd . /zoneExport $domain $domain";
    Invoke-Expression $backup | Out-Null
    Write-Host "Backing up $domain" -ForegroundColor "White"
};

ForEach ($item in (gci C:\Windows\System32\dns)) {
    Write-Host "Renaming $item" -ForegroundColor "White"   
Rename-item $item.fullname ([string]$item + ".dns")
}

Write-Host "Back up complete." -ForegroundColor "Cyan"
cmd /c pause | out-null

########################