MSSQL on kubernetes (non azure)

1. Copy the code below into a file named mssql.yaml
2. Apply the deployment file to your kubernetes cluster using:

sed -i s/TXlDMG05bCZ4UEBzc3cwcmQ=/$(pwgen -s 120 1 | base64 -w 0)/ mssql.yaml;
kubectl apply -f mssql.yaml

Note: username and password are base64 encoded and NOT encrypted.
Therefore do not store your credentials this way in a production environment, use

read -sep "Enter mssql sa password: " mssql_sa_pass; kubectl create secret generic mssql2 --from-literal=password=$mssql_sa_pass --type=kubernetes.io/basic-auth

instead of adding it to the deployment yaml file.

apiVersion: v1
data:
  username: c2EK
  password: TXlDMG05bCZ4UEBzc3cwcmQ=
kind: Secret
metadata:
  name: mssql
type: kubernetes.io/basic-auth
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mssql-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mssql
  template:
    metadata:
      labels:
        app: mssql
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - name: mssql
        image: mcr.microsoft.com/mssql/server:latest
        ports:
        - containerPort: 1433
        env:
        - name: MSSQL_PID
          value: "Developer"
        - name: ACCEPT_EULA
          value: "Y"
        - name: SA_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mssql
              key: password 
        volumeMounts:
        - name: mssql
          mountPath: /var/opt/mssql
      volumes:
      - name: mssql
        hostPath:
          path: /srv/mssql
          type: DirectoryOrCreate
      initContainers:
      - name: install
        image: busybox
        command:
        - chown
        - "10001:10001"
        - "/work-dir"
        volumeMounts:
        - name: mssql
          mountPath: "/work-dir"
---
apiVersion: v1
kind: Service
metadata:
  name: mssql-deployment
spec:
  selector:
    app: mssql
  ports:
    - protocol: TCP
      port: 1433
      targetPort: 1433
  type: LoadBalancer


WordPress nginx config

server {
listen 80;
listen [::]:80;
root "/var/www/vHOST";
server_name vHOST;
index index.html index.php;
client_max_body_size 2G;

rewrite ^/wp-json/.*$ index.php$uri last;

location ~ ^/.*/$ {
try_files $uri $uri/ /index.php?$uri;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php(/|$) {
include fastcgi.conf;
fastcgi_param SCRIPT_FILENAME "/var/www/vHOST/$fastcgi_script_name";
# With php7.0-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# With php7.0-fpm:
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
}

Bypass chrome tls security checks

Normally things like invalid certificates throw an error within google chrome, and if the page has hsts in place, there is no way to bypass that.
For normal users this is a good thing, but if you’re the developer/admin and have logged out yourself because of a miss configured server or you’re a pentester and want to access the contents of a wrongly configured web server, this can be frustrating.

And there is a way to access the pages, even though it is not available in the normal google chrome version.
You need to use the selenium driver. Therefore in turn you need the WebDriver library and the chromedriver.

1. Download the latest WebDriver https://www.nuget.org/api/v2/package/Selenium.WebDriver/
2. Download the latest ChromeDriver https://chromedriver.storage.googleapis.com/index.html (Keep in mind, that Version 2.10 is higher than 2.9)
3. Open PowerShell and import the WebDriver using “Import-Module” (or more specifically the correct dll for your installed .net version)
4. Unzip the chromedriver and place it inside of “./bin/selenium.chromedriver/”
5. Use PowerShell or C# to launch a new browser instance

$options = [OpenQA.Selenium.Chrome.ChromeOptions]::new()
$options.setBinary('./bin/selenium.chromedriver')
[OpenQA.Selenium.Chrome.ChromeDriver]::new($options)

Or use this script to install it inside of your current directory:

function Install-PSArchive {
    param()
    $null = Install-PackageProvider -Name PowerShellGet -Force -Scope CurrentUser
    Install-Module -Name 'Microsoft.PowerShell.Archive' -Force -Repository PSGallery -Scope CurrentUser -WarningAction SilentlyContinue
}

function Install-Selenium {
    param($ChromeSeleniumVersion = '2.45')
    Invoke-WebRequest -Uri 'https://www.nuget.org/api/v2/package/Selenium.WebDriver/' -UseBasicParsing -OutFile './selenium.webDriver.nupkg.zip'
    Expand-Archive -Path ./selenium.webDriver.nupkg.zip -Force
    $null = New-Item -Name './lib/selenium.webDriver' -ItemType Directory -Force
    Copy-Item -Path ./selenium.webDriver.nupkg/lib/netstandard2.0/WebDriver.dll -Destination ./lib/selenium.webDriver -Force
    Copy-Item -Path ./selenium.webDriver.nupkg/lib/netstandard2.0/WebDriver.xml -Destination ./lib/selenium.webDriver -Force
    Remove-Item -Recurse -Force -Path './selenium.webDriver.nupkg'
    Remove-Item -Recurse -Force -Path './selenium.webDriver.nupkg.zip'

    $ChromeSeleniumURLLinux = 'https://chromedriver.storage.googleapis.com/{0}/chromedriver_linux64.zip' -f $ChromeSeleniumVersion
    $ChromeSeleniumURLMacOS = 'https://chromedriver.storage.googleapis.com/{0}/chromedriver_mac64.zip' -f $ChromeSeleniumVersion
    $ChromeSeleniumURLWindows = 'https://chromedriver.storage.googleapis.com/{0}/chromedriver_win32.zip' -f $ChromeSeleniumVersion
    If ($IsWindows) {
        Invoke-WebRequest -Uri $ChromeSeleniumURLWindows -OutFile 'chromedriver.zip'
    }
    elseif ($IsLinux) {
        Invoke-WebRequest -Uri $ChromeSeleniumURLLinux -OutFile 'chromedriver.zip'
    }
    elseif ($IsMacOS) {
        Invoke-WebRequest -Uri $ChromeSeleniumURLMacOS -OutFile 'chromedriver.zip'
    }
    else {
        Write-Error -Message 'Platform not supported.'
    }
    $null = New-Item -Name './bin/selenium.chromedriver' -Force -ItemType Directory
    Expand-Archive -Path 'chromedriver.zip' -Force -DestinationPath ./bin/selenium.chromedriver
    Remove-Item -Recurse -Force -Path './chromedriver.zip'
    If ($IsLinux -or $IsMacOS) {
        chmod a+x ./bin/selenium.chromedriver/chromedriver
    }
}

function Install-HtmlAgilityPack {
    param()
    Invoke-WebRequest -Uri 'https://www.nuget.org/api/v2/package/HtmlAgilityPack/' -OutFile ./HtmlAgilityPack.zip
    Expand-Archive -Path './HtmlAgilityPack.zip' -Force
    $null = New-Item -Name './lib/HtmlAgilityPack' -ItemType Directory -Force
    Copy-Item -Path ./HtmlAgilityPack/lib/netstandard2.0/HtmlAgilityPack.dll -Destination ./lib/HtmlAgilityPack -Force
    Copy-Item -Path ./HtmlAgilityPack/lib/netstandard2.0/HtmlAgilityPack.xml -Destination ./lib/HtmlAgilityPack -Force
    Remove-Item -Force -Recurse -Path './HtmlAgilityPack'
    Remove-Item -Force -Recurse -Path './HtmlAgilityPack.zip'
}

Install-PSArchive
Import-Module -Name 'Microsoft.PowerShell.Archive'
Install-Selenium
Import-Module './lib/selenium.webDriver/WebDriver.dll'

## If you need to parse some html inside of your scripts and want to have cross platform functionality (or if internet explorer is not enabled), you also need to install HtmlAgilityPack, as powershell on windows relies upon it for parsing html into objects.
Install-HtmlAgilityPack
Import-Module './lib/HtmlAgilityPack/HtmlAgilityPack.dll'

Using Amazon Windows Images

If you tried to use some windows images on aws, you may have noticed, that they have no password specified. In fact, there agent fails to set one.

I’ve tried multiple ways to reset the password, after the support told me, that in order to help me I first need to buy a higher support level…

The one that was the simplest and easiest is usually the utilman.exe trick, but as aws does not allow to interact with the console session, this is out of scope.

So I’ve tried different autostart locations, but most are only invoked after a user has logged on.

Therefore mounting the volume on another instance and editing the registry to add a custom service was one possibility and it worked great.

What you need to do:

    1. Spawn one of the buggy instances and one of “2016 Base Datacenter”
    2. Start the buggy instance once, to check if amazon has fixed the bug to receive the admin password.
    3. If this bug is still there, stop this instance again (not terminate!)
    4. Go to volume and disconnect, and attach to the server 2016 server instance as ‘xvdf’
    5. Remote into the 2016 image as usual
    6. Open the disk manager
    7. Switch the 2nd drive online (and keep the window open for later)
    8. Open Regedit
    9. Load the System hive from the offline windows as ‘offline.SYSTEM’.
    10. Copy the following text into a text file a.reg on the desktop.
      Windows Registry Editor Version 5.00
      
      [HKEY_LOCAL_MACHINE\offline.SYSTEM\ControlSet001\Services\test]
      "Type"=dword:00000010
      "Start"=dword:00000002
      "ErrorControl"=dword:00000000
      "ImagePath"=hex(2):22,00,43,00,3a,00,5c,00,57,00,69,00,6e,00,64,00,6f,00,77,00,\
        73,00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,5c,00,63,00,6d,\
        00,64,00,2e,00,65,00,78,00,65,00,22,00,20,00,2f,00,43,00,20,00,6e,00,65,00,\
        74,00,20,00,75,00,73,00,65,00,72,00,20,00,41,00,64,00,6d,00,69,00,6e,00,69,\
        00,73,00,74,00,72,00,61,00,74,00,6f,00,72,00,20,00,50,00,40,00,73,00,73,00,\
        77,00,30,00,72,00,64,00,00,00
      "DisplayName"="test"
      "ObjectName"="LocalSystem"
      "Description"="Test"
      "FailureActions"=hex:10,0e,00,00,00,00,00,00,00,00,00,00,15,00,00,00,14,00,00,\
        00,01,00,00,00,88,13,00,00,01,00,00,00,88,13,00,00,01,00,00,00,88,13,00,00,\
        01,00,00,00,88,13,00,00,01,00,00,00,88,13,00,00,01,00,00,00,88,13,00,00,01,\
        00,00,00,88,13,00,00,01,00,00,00,88,13,00,00,01,00,00,00,88,13,00,00,01,00,\
        00,00,88,13,00,00,01,00,00,00,88,13,00,00,01,00,00,00,88,13,00,00,01,00,00,\
        00,88,13,00,00,01,00,00,00,88,13,00,00,01,00,00,00,88,13,00,00,01,00,00,00,\
        88,13,00,00,01,00,00,00,88,13,00,00,01,00,00,00,88,13,00,00,01,00,00,00,88,\
        13,00,00,01,00,00,00,88,13,00,00,00,00,00,00,88,13,00,00
      
    11. Apply this registry keys to the registry by double clicking it.
    12. Unload the hive
    13. Switch the drive offline again
    14. Make sure rdp from the buggy instance is only available from your ip (not 0.0.0.0) before continuing.
    15. Detach the drive from the 2016 image.
    16. Attach the drive to the buggy image as ‘/dev/sda1’ (yes, it is windows, but you need to specify this here, or the instance is unable to start)
    17. Start the buggy instance.
    18. Connect to it with “Administrator” and “P@ssw0rd”
    19. Open Regedit and delete ‘HKLM\SYSTEM\ControlSet001\Services\test’
    20. Set a secure Password
    21. Install OpenSSH https://github.com/PowerShell/Win32-OpenSSH/wiki/Install-Win32-OpenSSH
    22. Add your public key to “C:/Users/Administrators/.ssh/authorized_keys”
    23. Remove the ports TCP-3389 and UDP-3389 from your security group. It is not recommended to have rdp publicly available to the internet (if you still want to connect over public set up a remote desktop gateway, as it is intended to be accessible publicly and in combination with ADFS allows onetime passwords for pre-authentication.

Hacking an SQL-Server

Basically if you’re admin you own everything.

So how would you access an SQL-Server if you don’t have SQL-Permissions but you’re administrator on the system the SQL-server is running on?

Basically you can abuse the fact, that the sql-server has to have at least one account with the necessary permissions. Often this is the local system user.

  1. So just become system using psexec (or anything else): psexec -s cmd.exe
  2. Search for your local SQL-Instance: osql -L
  3. Connect to your SQL-Server using your current (system) credentials: osql -S <InstanceName> -E
  4. If the connection is successful, just enable the sa account and set a new password for it. After that you can use the SQL-Management Studio to administer all permissions:
    /* Enable SQL-User authentication and set sa password */
    ALTER LOGIN sa ENABLE;
    GO
    /* Reset the password, requires CONTROL SERVER permission */
    ALTER LOGIN sa WITH PASSWORD = '<newPassword>';
    GO
    /* just set sa password (alternative way)*/
    sp_password NULL, '<newPassword>', 'sa';
    GO
    
    /* To add an windows user to the admins role do this */
    CREATE LOGIN [DOMAIN\USER] FROM WINDOWS;
    GO
    EXEC sp_addsrvrolemember 'DOMAIN\USER', 'sysadmin';
    GO
    

    If the above is throwing an access denied error for you try a different user for example the mssql service user use process hacker to run a cmd prompt in the context of that user and try again. If also that fails, check if there is any application accessing the database that could have an account with too much permissions e. g. Server Admin instead of db_owner and try that one.

  5. If that all does not help, you have one last way of getting into the database, but that causes a downtime.
  6. Stop your SQL-Server Services (Server, Browser, Agent, …) and open an elevated cmd.
  7. Navigate to the folder containing the executable of the service and start it with the parameter “-m” for single user mode without authentication. After the server is back up do Step 4 and after that stop the server and restart the services you stopped earlier.

WARNING: BY DOING STEP 7 EVERYBODY COULD GAIN FULL ACCESS TO YOUR SERVER, DEPENDING ON YOUR INFRASTRUCTURE YOU MAY WANT TO BLOCK REMOTE CONNECTIONS ON THE WINDOWS FIREWALL WHILE PERFORMING THIS STEP

Encrypted LVM remote unlock

Sometimes you want to have a strong Disk encryption but be still able to unlock it remotely. Sure, this is a compromise between security and usability, but here is what I come up with.
Before you follow my instructions, I allude you to carefully consider what that means for your thread model and system security.

0. You start with an normal lvm encrypted operating system.
1. Install dropbear and busybox
2. Edit the file /etc/initramfs-tools/initramfs.conf and add/modify Device and Network settings accordingly:
DROPBEAR=y
DEVICE=eth0
IP=192.168.2.19::192.168.2.1:255.255.255.0:PC-Name:eth0:off

The last line requires some explanation. It consists of:
Preboot-IPv4:rarp-Server:Gateway-IPv4:Subnetmask:Preboot-Hostname:Interface:autoconfigurationMethod
https://help.ubuntu.com/community/DisklessUbuntuHowto#Static_IP
To bypass the ssh host checks (which would fail, because effectively the preboot environment is an autonomous os, independent of the other), you should select a different IP than that of the fully booted system.
3. Place your ssh-public key into the initramf’s root users home directory
rm /etc/initramfs-tools/root/.ssh/*
vi /etc/initramfs-tools/root/.ssh/authorized_keys

For privacy reasons (if you don’t want someone to associate this device with you through the use of your public key) you may want to use a separate key-pare, as this public key.
4. After you’ve added your public key, you need to regenerate the initramfs image using:
update-initramfs -u
5. After that reboot using
systemctl reboot
6. Now while the System is waiting for you to enter the password, go to a different client and connect using your private key (User: root) and your predefined IP address.
7. To unlock your device and continue booting (which will uninitialize the initramfs leaving you within a shell without any mounted file systems or applications) you have to somehow insert the Plain-text password into /lib/cryptsetup/passfifo (without a line break at the end)
The easyest (but also unsafest) way is a simple echo:
echo -n "EncryptionKey" > /lib/cryptsetup/passfifo

iptables to rsyslog

log all dropped connections to syslog

iptables -N LOGGING
iptables -A INPUT -j LOGGING
iptables -A OUTPUT -j LOGGING
iptables -j LOG --log-prefix "iptables: "
iptables -A LOGGING -j DROP

check that this line is in /etc/rsyslog.conf

$ModLoad imklog

after that create the file /etc/rsyslog.d/01-iptables.conf with the content:

:msg, startswith, "iptables: " -/var/log/iptables.log
& ~
:msg, regex, "^\[ *[0-9]*\.[0-9]*\] iptables: " -/var/log/iptables.log
& ~

line 1 and line 3 are filters and log file locations, if they match the log is written to the specified log file.
line 2 and 4 tell rsyslog “don’t process future rules (if the one before matches), it’s done for this log entry”

now the only thing left is to create a log rotation rule
create the file /etc/logrotate.d/iptables with this content:

/var/log/iptables.log {
	rotate 7
	daily
	missingok
	notifempty
	delaycompress
	compress
	postrotate
		invoke-rc.d rsyslog rotate > /dev/null
		iptables-save >> /var/log/iptables.log
	endscript
}

netstat for Powershell

If you cannot use “Get-NetTCPConnection” here is the same using the good old “netstat -a” 😉

netstat -a | Select-Object -Skip 3 | ForEach-Object {$_ -replace '\s+', ' '} | ForEach-Object {$_ -replace 'Lokale Adresse','Lokale_Adresse'} | ForEach-Object {$_ -replace '^ ', ''} | ConvertFrom-Csv -Delimiter " "

netstat -a | Select-Object -Skip 3 | ForEach-Object {$_ -replace '\s+', ' '} | ForEach-Object {$_ -replace 'Lokale Adresse','Lokale_Adresse'} | ForEach-Object {$_ -replace '^ ', ''} | ConvertFrom-Csv -Delimiter " " | Where-Object {($_.Remoteadresse -notlike "$env:computername*") -and ($_.Remoteadresse -ne "*:*")}