Search This Blog

Showing posts with label UglyHack. Show all posts
Showing posts with label UglyHack. Show all posts

Thursday, June 05, 2025

Make Win 10 or 11 Pro / Ent LTSC

@echo off

:: first go get the skus.zip - in the issues are the ones for W11 too
echo  Starting conversion to LTSC... 

:: If not launched as admin, relaunch
net.exe session 2>NUL 1>&2
if not %errorlevel%==0 (echo  You are NOT ADMIN. Relaunching... 
powershell Start -File "cmd '/K %~f0 runas'" -Verb RunAs
goto out)

:start
    pushd "%CD%"
    CD /D "%~dp0"
    echo  Take ownership of the skus subfolders 
    "%windir%\system32\takeown.exe" /F "%windir%\system32\spp\tokens\skus\csvlk-pack" /R /A /D Y
    "%windir%\system32\icacls.exe" "%windir%\system32\spp\tokens\skus\csvlk-pack" /T /grant Administrators:F
    "%windir%\system32\takeown.exe" /F "%windir%\system32\spp\tokens\skus\IoTEnterpriseS" /R /A /D Y
    "%windir%\system32\icacls.exe" "%windir%\system32\spp\tokens\skus\IoTEnterpriseS" /T /grant Administrators:F
    "%windir%\system32\takeown.exe" /F "%windir%\system32\spp\tokens\skus\IoTEnterpriseSK" /R /A /D Y
    "%windir%\system32\icacls.exe" "%windir%\system32\spp\tokens\skus\IoTEnterpriseSK" /T /grant Administrators:F
    "%windir%\system32\takeown.exe" /F "%windir%\System32\spp\tokens\EnterpriseS" /R /A /D Y
    "%windir%\system32\icacls.exe" "%windir%\system32\spp\tokens\skus\EnterpriseS" /T /grant Administrators:F
    echo. 

    echo  Extract and copy the new skus 
    FOR /F "tokens=1,2,3 delims= " %%A IN ('wmic os get Caption') DO @IF %%C EQU 10 "%windir%\System32\tar.exe" -v -x -f skus10.zip -C %windir%\system32\spp\tokens\skus
    FOR /F "tokens=1,2,3 delims= " %%A IN ('wmic os get Caption') DO @IF %%C EQU 11 "%windir%\System32\tar.exe" -v -x -f skus11.zip -C %windir%\system32\spp\tokens\skus
    
    echo  Reinstall the new licenses - be patient, this will take a minute 
    cscript.exe %windir%\system32\slmgr.vbs /rilc
    echo  Uninstall the actual product key 
    cscript.exe %windir%\system32\slmgr.vbs /upk
    echo  Remove the KMS 
    cscript.exe %windir%\system32\slmgr.vbs /ckms
    echo  Remove the old product key from registry 
    cscript.exe %windir%\system32\slmgr.vbs /cpky
    echo  Install LTSC Product key 
    :: use key from https://learn.microsoft.com/en-us/windows-server/get-started/kms-client-activation-keys - it requires a KMS Server, otherwise you will have to manually change the license from KMS to MAK
    cscript.exe %windir%\system32\slmgr.vbs /ipk M7XTQ-FN8P6-TTKYV-9D4CC-J462D
   

:end
    :: cleanup
    del /f /q "skus*.zip" 2>nul
    :: check the Windows version
    wmic os get Caption | findstr "Microsoft"
    echo  Now we should reboot... 
    choice /t 30 /c yn /d n /n /m "press  "Y"  in the next 30 seconds if you want to reboot"
    if errorlevel 2 goto :out
    if errorlevel 1 shutdown.exe -r -f -t 0

:out
    :: reset the colors
    echo.

Friday, May 02, 2025

Remove .appx from some newly converted to LTSC computers


$ErrorActionPreference= 'silentlycontinue'

$cred = Get-Credential -Message "Please enter admin credentials valid on target computers";
if($cred -isnot [PSCredential]) {Write-Host -ForegroundColor Red -BackgroundColor DarkBlue "No valid credentials provided. Exiting!" ; exit 1}

foreach($comp in Get-Content -Path C:\temp\complist.txt) {
 Write-Host -ForegroundColor Blue -NoNewline " `nStart on $comp : "
 $sess = New-PSSession -Credential $cred $comp
 if ($?) { Write-Host -ForegroundColor Green "session to $comp established";
  Invoke-Command -Session $sess -scriptblock { Get-AppxPackage -AllUsers | Remove-AppxPackage -ErrorAction Continue; Get-AppxProvisionedPackage -Online | Remove-AppxProvisionedPackage -Online; }
  if ($?) {  Write-Host -ForegroundColor Green "RAN on $sess" } else { Write-Host -ForegroundColor Red "FAIL on $sess" }
 }else{ Write-Host -ForegroundColor Red "Unable to connect to $comp" }
}

Write-Host -ForegroundColor Yellow -BackgroundColor DarkGreen "`nScript Done!`n"
exit

Tuesday, March 04, 2025

Import multiple CSV files into separate Excel worksheets

 #import multiple CSV files into separate Excel worksheets
$wrkfldr='C:\temp'

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$wb = $excel.Workbooks.Add()

Get-ChildItem $wrkfldr\*.csv | ForEach-Object {
    if ((Import-Csv $_.FullName).Length -gt 0) {
        $csvBook = $excel.Workbooks.Open($_.FullName)
        $csvBook.ActiveSheet.Copy($wb.Worksheets($wb.Worksheets.Count))
        $csvBook.Close()
    }
}

Wednesday, February 05, 2025

RPI network reconnect

to be run */10 * * * * from cron

#!/bin/bash

wlan='wlan0'
gateway='192.168.1.1'

ping -c2 $gateway 2>&1 >/dev/null; rc=$?
if [[ $rc -eq 0 ]] ; then
        echo `date +"%b %d %T "`$0": The network is up."
else
        echo `date +"%b %d %T "`$0": Network down! Attempting reconnection."
        if [ -f /storage/.cache/nonet ]; then
                rm -f /storage/.cache/nonet
                reboot
        fi
        ifdown $wlan
        rmmod brcmfmac
        sleep 2
        modprobe brcmfmac brcmfmac_wcc
        ifup --force $wlan
        sleep 2
        connmanctl connect wifi_dc345a1743d_6e6545675289d3567_managed_psk &>/dev/null
        sleep 10
        ping -c2 $gateway 2>&1 >/dev/null; rc=$?
        if [[ $rc -ne 0 ]] ; then
                echo "1" > /storage/.cache/nonet
        fi
fi
exit 0

 

Friday, January 03, 2025

Deploy port forward script on multiple computers

# deploy-cond_portforward.ps1
# a stand-alone script that deploys the port-forward to a list of target computers
# v1.0 - 2024-10-08 s.t. - initial release


# EDIT THIS - create a temporary list of all computer on which we want to deploy
$complstfileToAdd = @'
AH00001
RA00003
BM0001-W10
'@
Set-Content "$env:TEMP\comps.txt" $complstfileToAdd

# create the .ps1 file that will execute the portforward - this file must be tailored to each host after deployment
$psfileToAdd = @'
# condprtforward.ps1
# a powershell script to check the portforwading on iBox and re-add if not present
# To be run by powershell from Task Scheduler */10min with SYSTEM rights and arguments "-noprofile -executionpolicy bypass -file C:\WINDOWS\cond_portfwd.ps1"
# Version 1.0 - 2024 s.t.

# EDIT THIS - define IP and ports
$lclip = "127.0.0.1"
$lclport = "65535"
$2ndlclprt = ""
$rmtip = "127.0.0.2"
$rmtport = "65535"
$2ndrmtprt = ""

# check if run with admin rights
if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))  
{  
  $arguments = "& '" +$myinvocation.mycommand.definition + "'"
  Start-Process powershell -Verb runAs -ArgumentList $arguments
  Break
}

#test if the portforward is already active
if (Test-NetConnection $lclip -Port $lclport -WarningAction SilentlyContinue -InformationLevel Quiet) {
 Write-Host "got_response, $lclport is open"
} else {
#add rules
 Write-Host "add_rules $lclip : $lclport $rmtip : $rmtport"
 netsh interface portproxy reset
 netsh advfirewall firewall add rule name="PortProxy Custom 1" dir=in action=allow protocol=TCP localport=$lclport
 netsh interface portproxy add v4tov4 listenport=$lclport listenaddress=$lclip connectport=$rmtport connectaddress=$rmtip
 
 if($2ndrmtprt) {
  Write-Host "2nd port is defined, adding 2nd rule"
  netsh advfirewall firewall add rule name="PortProxy Custom 2" dir=in action=allow protocol=TCP localport=$2ndlclprt
  netsh interface portproxy add v4tov4 listenport=$2ndlclprt listenaddress=$lclip connectport=$2ndrmtport connectaddress=$rmtip
  }
}
##Write-Host "end"
##Start-Sleep 5
'@
Set-Content "$env:TEMP\cond_portfwd.ps1" $psfileToAdd

# create the scheduled task .xml file that will be "imported" in order to create the task
$xmlfileToAdd = @'
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2024-10-08T00:00:00.0000000</Date>
    <Author>Administrator</Author>
    <Description>Launch and maintain Port Forward</Description>
    <URI>\PortForward</URI>
  </RegistrationInfo>
  <Triggers>
    <BootTrigger>
      <Repetition>
        <Interval>PT10M</Interval>
        <StopAtDurationEnd>false</StopAtDurationEnd>
      </Repetition>
      <Enabled>true</Enabled>
    </BootTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>S-1-5-18</UserId>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
    <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe</Command>
      <Arguments>-noprofile -executionpolicy bypass -file C:\WINDOWS\cond_portfwd.ps1</Arguments>
    </Exec>
  </Actions>
</Task>
'@
Set-Content "$env:TEMP\PortForward.xml" $xmlfileToAdd

# start the deployment. first ask for some admin credentials valid on targets
$cred = Get-Credential -Message "Please enter admin credentials valid on target computers";
if($cred -isnot [PSCredential]) {Write-Host -ForegroundColor Red -BackgroundColor DarkBlue "No valid credentials provided. Exiting!" ; exit 1}
# copy the files to each target computer. no need to see the errors, we have our own errorreporting
$ErrorActionPreference= 'silentlycontinue'
foreach($line in Get-Content $env:TEMP\comps.txt) {
Write-Host -ForegroundColor Gray "`nStart running on $line"
$comp = New-PSSession -Credential $cred $line
if ($?) { Write-Host -ForegroundColor Green "Session to $comp established" }else{ Write-Host -ForegroundColor Red "Unable to connect to $line" }
Copy-Item -ToSession $comp $env:TEMP\cond_portfwd.ps1 -Destination C:\WINDOWS\cond_portfwd.ps1 -Force
if ($?) {  Write-Host -ForegroundColor Green ".ps1 file copied" }else{ Write-Host -ForegroundColor Red ".ps1 file NOT copied on $line" }
Copy-Item -ToSession $comp "$env:TEMP\PortForward.xml" -Destination "C:\WINDOWS\TEMP\PortForward.xml" -Force
if ($?) {  Write-Host -ForegroundColor Green ".xml file copied" }else{ Write-Host -ForegroundColor Red ".xml file NOT copied on $line" }
# create the scheduled task from the .xml file
Invoke-Command -ComputerName $line -Credential $cred { $Task = Get-Content "C:\WINDOWS\TEMP\PortForward.xml" -raw ; Register-ScheduledTask -Xml $Task -TaskName 'PortForward' -User SYSTEM -Force }
if ($?) {  Write-Host -ForegroundColor Green "Scheduledtask created"}else{ Write-Host -ForegroundColor Red "Scheduledtask NOT created on $line" }
}

# local cleanup
Remove-Item "$env:TEMP\comps.txt"
Remove-Item "$env:TEMP\PortForward.xml"
Remove-Item "$env:TEMP\cond_portfwd.ps1"

# reminder
Write-Host -ForegroundColor Yellow -BackgroundColor DarkBlue "`nOn each of the target computers please edit C:\WINDOWS\cond_portfwd.ps1"

exit

Saturday, November 16, 2024

Disable windows update

 @echo off
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v DoNotConnectToWindowsUpdateInternetLocations /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v AcceptTrustedPublisherCerts /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v DisableDualScan /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v SetProxyBehaviorForUpdateDetection /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v WUServer /t REG_MULTI_SZ /d https://localhost:8531 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v WUStatusServer /t REG_MULTI_SZ /d https://localhost:8531 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v UpdateServiceUrlAlternate /t REG_MULTI_SZ /d http://localhost:8005 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v FillEmptyContentUrls /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v SetPolicyDrivenUpdateSourceForDriverUpdates /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v SetPolicyDrivenUpdateSourceForFeatureUpdates /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v SetPolicyDrivenUpdateSourceForOtherUpdates /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v SetPolicyDrivenUpdateSourceForQualityUpdates /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v DoNotEnforceEnterpriseTLSCertPinningForUpdateDetection /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate /v ElevateNonAdmins /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v UseWUServer /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v NoAutoUpdate /t REG_DWORD /d 1 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v AutoInstallMinorUpdates /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v DetectionFrequencyEnabled /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v RebootWarningTimeoutEnabled /t REG_DWORD /d 0 /f >NUL
REG ADD HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v RescheduleWaitTimeEnabled /t REG_DWORD /d 0 /f >NUL
sc config "UsoSvc" start= disabled >NUL
sc stop "UsoSvc" >NUL
sc config "WaaSMedicSvc" start= disabled >NUL
sc stop "WaaSMedicSvc" >NUL
sc config "wuauserv" start= demand >NUL
sc stop "wuauserv" >NUL
taskkill /IM wusa.exe >NUL
move /y C:\WINDOWS\system32\wusa.exe C:\WINDOWS\system32\wusa.org >NUL
copy /y true.exe C:\WINDOWS\system32\wusa.exe >NUL

Friday, August 04, 2023

Generate pseudo-random, incremental serial numbers for motherboards

 

@echo off

    setlocal enableextensions disabledelayedexpansion

 

for /f "tokens=1,* delims=:" %%a in ('

        findstr /l /b /c:":::persist:::" "%~f0"

') do set "%%~b"

if not defined savedValue (

        set "savedValue=%random%" && ( call :persist.write savedValue )

)

    set /a savedValue=%savedValue%+1  && ( call :persist.write savedValue )

    ;;echo DEBUG: Recorded data %savedValue%

    set ss=DW173878110%savedValue%

    set bs=BTDN8389450%savedValue%

    set su=00020003000400050006000700080i%savedValue%

AMIDEWINx64.EXE /CM "My Corporation" /BM "My Corporation" /BV J83500-205 /BP NUC7i7DNB  /SM "My Corporation" /SV J85489-205 /SP NUC7i7DNHE /SS %ss% /BS %bs% /SU %su%

    timeout 10 /nobreak >nul

goto :eof

 

:persist.write varName

    if "%~1"=="" goto :eof

    for %%a in ("%temp%\%~nx0.%random%%random%%random%.tmp") do (

        findstr /l /v /b /c:":::persist::: %~1=" "%~f0" > "%%~fa"

        >"%~f0" (

            type "%%~fa"

            setlocal enabledelayedexpansion

            echo(:::persist::: %~1=!%~1!

            endlocal

        )

        del /q "%%~fa"

    )

    goto :eof

 

Friday, May 05, 2023

Pingresults

Ping a host once every X seconds and save the result in a csv:

 

 

@echo off
SETLOCAL

if [%1]==[/?] goto :help

::Set the address to ping
set address=%1
if [%1]==[] goto :fatal

::Set the destination filename
set filename=%2
if [%2]==[] set filename=pingres.csv

::Set delay between pings (seconds)
set delay=%3
if [%3]==[] set delay=30

:: some info
echo.
echo Running %0 %address% %filename% %delay% - press "Q" for at least %delay%s to quit.
echo.

:: Prepare csv header
echo Time, Target, Lag > %filename%

:loop
::Ping
for /F "tokens=7 delims== " %%l in ('ping -n 1 %address%^|findstr /i "time="') do set lag=%%l

::echo Current ping for %address%: %ping%
<nul set /p =.

::Set Timestamp
set curTime= %date:~0,4%/%DATE:~5,2%/%DATE:~8,3%-%time:~0,2%:%time:~3,2%:%time:~6,2%

::Write in .csv
echo %curTime%, %address%, %lag% >> %filename%

::delay
timeout /T %delay% /nobreak >nul

::keypress
choice /c QWERTY /d Y /t 1 /n >nul
if %errorlevel%==1 ( exit /B 0)

goto :loop

:help
echo.
echo Usage: %0 target resultfile delay
echo if not specified, resultfile is "pingres.csv" and delay is 30s

:fatal
echo.
echo You need to provide at least the hostname/IP of the target
echo type %0 /? for help
exit /B 1

ENDLOCAL

Monday, November 02, 2020

Check if WiFi is still connected on rpi

 #!/bin/bash


gateway='192.168.0.1'

lockfile='/var/run/chk-wifi.pid'

wlan='wlan0'



if [ -e $lockfile ]; then

    echo `date +%F\ %T\ `$0": A lockfile exists... Lets check to see if it is still valid"

    pid=`cat $lockfile`

    if kill -0 &>1 > /dev/null $pid; then

     echo `date +%F\ %T\ `$0": Process still running, Lockfile valid."

     exit 1

    else

     echo `date +%F\ %T\ `$0": Invalid Lockfile, Removing."

     rm $lockfile

    fi

fi


#echo `date +%F\ %T\ `$0": Setting Lockfile"

echo $$ > $lockfile


#echo `date +%F\ %T\ `$0": Performing network check for $wlan"

ping -c2 $gateway 2>&1

rc=$?

if [[ $rc -eq 0 ]] ; then

        echo `date +%F\ %T\ `$0": The network is up."

else

        echo `date +%F\ %T\ `$0": Network down! Attempting reconnection."

        ifdown $wlan

#        echo `date +%F\ %T\ `$0": Cycling rpi3 onboard wifi driver"

        rmmod brcmfmac

        sleep 2

#        echo `date +%F\ %T\ `$0": Most probable cause in rpi1-2 is USB jamming, cycling the power on USB"

#        echo 0 > /sys/devices/platform/soc/20980000.usb/buspower

#        sleep 2

#        echo 1 > /sys/devices/platform/soc/20980000.usb/buspower

#        sleep 1

#        echo `date +%F\ %T\ `$0": Bringing back the WiFi"

        modprobe brcmfmac

        ifup --force $wlan

#        sleep 1

#        echo `date +%F\ %T\ `$0": New IP: $(ifconfig $wlan | grep 'inet addr')"

#        echo `date +%F\ %T\ `$0": "$(hostname -I)

fi


#echo `date +%F\ %T\ `$0": Remove lock & exit"

rm $lockfile

exit 0


Friday, May 03, 2019

Parental control

Because you can't let the kids on YouTube 24/7 and some games are really addictive :)

The router must run OpenWRT or DD-WRT.

The kids devices must be assigned IP's from a certain range, let's say 192.168.1.128/28 by adding some lines similar to the following one into Additional Dnsmasq Options:
dhcp-host=set:red,AA:BB:CC:00:DD:22,kids-tv,192.168.1.130,43200m


A series of scripts must be put in /jffs/ and called by a cron job:

cat add_fw
#!/bin/sh
iptables -I FORWARD 1 -s 192.168.1.128/28 -j DROP
iptables -I FORWARD 2 -s 192.168.1.128/28 -m conntrack -j DROP --ctstate RELATED,ESTABLISHED

cat del_fw
#!/bin/sh
iptables -D FORWARD -s 192.168.1.128/28 -j DROP
iptables -D FORWARD -s 192.168.1.128/28 -m conntrack -j DROP --ctstate RELATED,ESTABLISHED

cat disable_game
#!/bin/sh
# DNS Rules
sed -e 's/^#//' -i /tmp/games-block.conf
sed -e 's/^#//' -i /tmp/yt-block.conf
restart_dns
# Force kids DNS to local
iptables -t nat -A PREROUTING -i br0 -s 192.168.1.128/28 -p udp --dport 53 -j DNAT --to 192.168.1.1
iptables -t nat -A PREROUTING -i br0 -s 192.168.1.128/28 -p tcp --dport 53 -j DNAT --to 192.168.1.1
# Block all ports over :500
iptables -I FORWARD 5 -p tcp --source 192.168.1.128/28 --dport 500:65535 -j DROP

cat allow_game
#!/bin/sh
# Remove DNS rules
sed 's/^\([^#]\)/#\1/g' -i /tmp/games-block.conf
sed 's/^\([^#]\)/#\1/g' -i /tmp/yt-block.conf
restart_dns
# Remove Force kids DNS to local
iptables -t nat -D PREROUTING -i br0 -s 192.168.1.128/28 -p udp --dport 53 -j DNAT --to 192.168.1.1
iptables -t nat -D PREROUTING -i br0 -s 192.168.1.128/28 -p tcp --dport 53 -j DNAT --to 192.168.1.1
# Unblock all ports over :500
iptables -D FORWARD -p tcp --source 192.168.1.128/28 --dport 500:65535 -j DROP


I do have an extra script that allow access to YouTube, without allowing games, this one is called only from a html page that I'll explain in a later post:

cat allow_yt
#!/bin/sh
sed 's/^\([^#]\)/#\1/g' -i /tmp/yt-block.conf
restart_dns


Those scripts are called by cron jobs that makes sure we don't have internet during the sleep hours and games & YouTube are permitted only during the weekend:
00 21 * * 0-4 root /jffs/add_fw
30 22 * * 5,6 root /jffs/add_fw
00 08 * * * root /jffs/del_fw
30 17 * * 5 root /jffs/allow_game
30 17 * * 0 root /jffs/disable_game


In order to block the DNS requests, the following Additional Dnsmasq Options needs to be added:
conf-file=/tmp/yt-block.conf
conf-file=/tmp/games-block.conf


The files /tmp/yt-block.conf and /tmp/games-block.conf are created by the startup script:
stopservice dnsmasq
echo "#address=/.roblox.com/192.168.1.1
#address=/.rbxcdn.com/192.168.1.1
#address=/.epicgames.com/192.168.1.1
#address=/.fortnitegame.com/192.168.1.1
#address=/.easyanticheat.com/192.168.1.1
#address=/.pixelgunserver.com/192.168.1.1
#address=/.applovin.com/192.168.1.1
#address=/.clashroyaleapp.com/192.168.1.1
#address=/.applifier.com/192.168.1.1
#address=/.chartboost.com/192.168.1.1
#address=/.fyber.com/192.168.1.1
#address=/.twitch.tv/192.168.1.1
#address=/.ttvnw.net/192.168.1.1
#address=/.leagueoflegends.com/192.168.1.1
#address=/.pvp.net/192.168.1.1
#address=/.riotgames.com/192.168.1.1
#address=/.garenanow.com/192.168.1.1
#address=/.ea.com/192.168.1.1
#address=/.respawn.com/192.168.1.1
#address=/.origin.com/192.168.1.1" > /tmp/games-block.conf
echo "#address=/.youtube.com/192.168.1.1
#address=/youtube.googleapis.com/192.168.1.1
#address=/youtubei.googleapis.com/192.168.1.1
#address=/.ytimg.com/192.168.1.1
#address=/ytimg.l.google.com/192.168.1.1
#address=/youtube.l.google.com/192.168.1.1
#address=/.googlevideo.com/192.168.1.1
#address=/.youtube-nocookie.com/192.168.1.1
#address=/.youtu.be/192.168.1.1" > /tmp/yt-block.conf
startservice dnsmasq


An "easy" way to run those scripts besides the scheduled cron jobs, is from the DD-WRT Administration -> Commands page:

Saturday, February 02, 2019

Chromium - Cast: "No Devices Found"

Starting chromium from the console you get "Component extension with id pkedcjkdefgpdelpbcmbmeomcjbeemfm not in whitelist and is not being loaded as a result."

- pkedcjkdefgpdelpbcmbmeomcjbeemfm is the Chrome Media Router, without it, you can go to chrome://flags and Enable the #load-media-router-component-extension as much as you want, no chromecast device will ever be detected.

My solution: 

1: copy pkedcjkdefgpdelpbcmbmeomcjbeemfm folder from a google-chrome profile ( ~/.config/google-chrome/Default/Extensions/pkedcjkdefgpdelpbcmbmeomcjbeemfm) to the chromium profile ~/.config/chromium/Default/Extensions/pkedcjkdefgpdelpbcmbmeomcjbeemfm
( If you copy from a windows installation, make sure the files are chmod 600, the folders are 700 and you are the right owner)

2: in Chromium, go to chrome://extensions/, enable "Developer Mode", then "Load Unpacked" and point to ~/.config/chromium/Default/Extensions/pkedcjkdefgpdelpbcmbmeomcjbeemfm

3: Now Chrome Media Router is loaded and the chromecast devices will be detected:

Tuesday, September 05, 2017

Deploy .pfx cert embedded in script (a sort of 'cat << EOF' for windows)

@echo off
::
::  
:: In order to prepare the certificate please run
:: 'certutil -encode the_pfx_cert base_64_cert`
:: then paste the base_64_cert in the section below
:: Please note that the certificate password has to be given as start paramater to this script!
:: (eq: "cert-inst.bat S3cr3tPassw0rd")

:: If the cert was already installed, exit
REG QUERY HKCU\SOFTWARE\neXt /v CertInstalled
If %errorlevel%==0 goto :eof

:: define the temp name of the extracted cert
set extractedfile=%temp%\extract-%random%.txt

:: set the password needed to decode the cert
set certpasswd=%~1

:: separate the cert from this script
call:extractembedded embeddedfile %extractedfile%

:: process the extracted file
certutil -decode %extractedfile% %extractedfile%.pfx

certutil -f -user -p %certpasswd% -importpfx %extractedfile%.pfx

:: clean-up
::del %extractedfile% %extractedfile%.pfx

:: leave a trace in the registry, so the cert will not be installed again and again
REG ADD HKCU\SOFTWARE\neXt /v CertInstalled /t REG_DWORD /d 1

:: clean exit
exit /b

:: begin of the embed cert & extraction procedure
:: After the next line, please paste the "base_64_cert" created by certutil -encode
goto:embeddedfile
-----BEGIN CERTIFICATE-----
MIIMngIBAzCCDGQGCSqG
[...]
k05EzAQIFXJaGHOuxZcCAggA
-----END CERTIFICATE-----
:embeddedfile
:: before the previous line you can find the end of the "base_64_cert"

:: cert extraction procedure
:extractembedded
setlocal EnableDelayedExpansion
set embedbegin=goto:%~1
set embedend=:%~1
set embedcert=%~2
if exist %embedcert% del %embedcert%
set tmprndfile=%temp%\%random%.%random%
findstr /n ^^ "%~f0" > %tmprndfile%
call :seekembed < %tmprndfile%
del %tmprndfile%
exit /B
:seekembed
set oneline=:eof
set /P oneline=
if !oneline! == :eof goto nostart
set oneline=!oneline:*:=!
if not !oneline! == %embedbegin% goto seekembed
:getline
set oneline=:eof
set /P oneline=
if !oneline! == :eof goto nostop
set oneline=!oneline:*:=!
if !oneline! == %embedend% goto :eof
echo/!oneline!>> %embedcert%
goto getline
:nostart
echo Error finding start delimiter %embedbegin%
goto :eof
:nostop
echo Error finding stop delimiter %embedend%
goto :eof

Monday, May 01, 2017

Limit number of unix logins

cat .profile

#!/bin/sh
limit=3

session=`ps -ef | grep '\-sh' | grep $USER | grep -v grep`
number=`echo $session | wc -l`

if [ $number -ge $limit ]; then
echo "No more logins / Il n'y a plus de login. You are already logged as:
$session "

sleep 5
exit 0
fi




# to timeout after 15min of inactivity and forbid users to change the tmout:
echo "TMOUT=900
readonly TMOUT
export TMOUT" > /etc/profile.d/tmout.sh && chmox +x /etc/profile.d/tmout.sh

Wednesday, February 01, 2017

Dell Latitude Keyboard light

The backlit keys interface seems to be broken, so you need to mask the controlling service: systemctl mask systemd-backlight@leds\:dell\:\:kbd_backlight.service
then go to BIOS and and change the keyboard led timeout from 10s to 5s for AC Power and Battery mode - "For some reason if the kbd_backlight service is not masked, it somehow forces the bios led timeout back to 10s, and then the keyboard led always remains lit."

Wednesday, September 02, 2015

Map remote printer

map a local printer to TS session when "bring local printers to TS" fails miserably and start the App only after the printer is available

@echo off
setlocal enableextensions enabledelayedexpansion
set result=0
ser printer=oj100
Title Adding Printer. Be patient...
echo Adding printer. Do not start App yet...
ping -n 2 1.1.1.1 >nul 2>nul
taskkill /fi "username eq %username%" /im app.exe 2>nul
%userprofile%\delprint.vbs
ping -n 2 1.1.1.1 >nul 2>nul
echo Please wait. Starting Installation...
echo ..
for /F "tokens=2 delims=/: " %%f in ('%userprofile%\gettscip.exe') do (
echo Your IP is: %%f
:loop
net use \\%%f\ipc$ /d /y >nul 2>nul
ping -n 1 1.1.1.1 >nul 2>nul
net use \\%%f\ipc$ && set result=1
echo Result: !result!
if not !result! equ 1 goto :loop
Echo Add printer. This is going to take up to 5 minutes, be patient...
rundll32 printui.dll,PrintUIEntry /in /n "\\%%f\!printer!" /u /q /Gw
echo Setting default printer...
echo.
rundll32 printui.dll,PrintUIEntry /y /n  "\\%%f\!printer!" /q
echo.
)
Echo Starting App...
ping -n 3 1.1.1.1 >nul 2>nul
taskkill /fi "username eq %username%" /im app.exe >nul 2>nul
endlocal
C:\Users\Public\Desktop\App.lnk

Tuesday, March 03, 2015

Recursive owner and rights changing on subfolders

We assume the username==folder_name
the specific version for vista+ profiles:


@echo off
Echo (c) 2012 s@toma.gXXX
Set rprofiles=D:\path\to\profiles
For /f "delims=.V2" %%* in ('dir %rprofiles% /B') Do (
echo target is %rprofiles%\%%*.V2 User is %USERDOMAIN%\%%*
takeown /f "%rprofiles%\%%*.V2" /r
icacls "%rprofiles%\%%*.V2" /setowner %USERDOMAIN%\%%* /T /C
icacls "%rprofiles%\%%*.V2" /grant:r %USERDOMAIN%\%%*:F Administrateurs:F System:F /T
rem dir /B /W "%rprofiles%\%%*.V2"
rem ping -n 1 -w 1000 1.1.1.1 >nul
)

or the simple version:

cd d:\path\to\folders\
For /f "Tokens=*" %* in ('dir /B') Do  @cacls %* /E /C /T /G "%*":F

Tuesday, November 04, 2014

Windows Shell for TS - without Domain Controller

On the RD Session Host Configuration ,the following (compiled as c:\windows\tssession.exe) script is executed as initial shell:

;(c)2014  sorinakis@g**il.com

;msgbox, Username: %A_UserName%
AuthUsers = Administrator|administrator
Loop Parse, AuthUsers, |
{
 ifEqual, A_LoopField, %A_Username%
 {
  Sleep, 500
  Run, explorer.exe
  ;MsgBox EXPLORER Executed.
  GoTo, End
 }
else
 {
  ;MsgBox In the ELSE branch.
  Sleep, 500
  Run, D:\Partages\apps\LCM\Bin\wrun32.exe -ws -c D:\Partages\apps\LCM\etc\CBLCONFI-RZ_APP.ini utmenu
  Sleep 500
  WinMaximize, ahk_class AcucobolWClass
  IfWinExist, Cie(01)
  {
   WinMaximize,  Cie(01)
   Sleep, 500
   WinWaitClose, Cie(01)
   Sleep, 500
   Run, shutdown /l
  }
  Return
 }
}
End:
Sleep, 100
;MsgBox At the END.

Sunday, August 10, 2014

Tune UP (in fact down) Windows 2008 R2

sssc config lanmanworkstation depend= bowser/mrxsmb10/nsi
sc config mrxsmb20 start= disabled

netsh int tcp set global rss=disabled
netsh int tcp set global chimney=disabled
netsh int tcp set global autotuninglevel=disabled
netsh int ip set global taskoffload=disablednetsh int tcp set global autotuninglevel=disablednetsh int tcp set global ecncapability=disablednetsh int tcp set global timestamps=disablednetsh advf set allp state off


:: reg add "HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters" /v DisableTaskOffload /t REG_DWORD /d "1" /f

reg add "HKLM\SYSTEM\CurrentControlSet\services\LanmanWorkstation\Parameters" /v DisableBandwidthThrottling /t REG_DWORD /d "1" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\WinHttp" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Internet Settings" /v TcpAutotuning /t REG_DWORD /d "0" /f
reg add "HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters" /v EnableTCPA /t REG_DWORD /d "0" /f

Friday, July 11, 2014

Watermark Printer

This is a very crude version of a "Watermark Printer" - it prints on a "preprinted paper" (e.g. something containing the company logo)


@echo off

:: ------------------------------------------------------------------

:: install redmon in %userprofile%\appdata\redmon
:: put this script in %userprofile%\appdata\redmon\email.bat
:: create new printer with port RPT1:
:: configure port redirect to %userprofile%\appdata\redmon\redrun.exe
:: port arguments
%userprofile%\appdata\redmon\email.bat  %%1

:: ------------------------------------------------------------------
:: Ghostscript configuraton
set GS_INSTALL="
%userprofile%\appdata\redmon\gs"
set GS_VERSION=8.63
:: LibTIFF configuraton
set LIBTIFF_INSTALL=
%userprofile%\appdata\redmon\GnuWin32
:: PDF viewer configuraton (no need to set, if PDF is a registered file type)
set PDF_READER=
:: Watermark background config
set BACKGROUND="
%userprofile%\appdata\redmon\\Watermark.pdf"
:: PDFTK location
set PDFTK="
%userprofile%\appdata\redmon\"
:: ------------------------------------------------------------------
:: temporary PDF directory
set PDF_DIR=%TEMP%\1
:: delete old temporary PDF directories if required
for /d %%D in ("%TEMP%\1\") do if not "%%D"=="%TEMP%\1\" rd /s /q "%%D"
:: create if required
if not exist "%PDF_DIR%" md "%PDF_DIR%"
echo myass > %PDF_DIR%\blah
:: check if file is given
if not "%~1" == "" goto CHECK_FOUND
echo ERROR: No file name given!
goto END
::----------
:CHECK_FOUND
:: check for file existence
if exist "%*" goto SET_FNE
echo ERROR: File "%*" not found!
goto END
::------
:SET_FNE
:: set input file, name and extension
call :set_input_file_name_ext "%*"
:: check file type
if "%INPUT_EXT%" == "" set INPUT_NAME=%~n1.ps
if "%INPUT_EXT%" == "" set INPUT_EXT=.ps
if "%INPUT_EXT%" == ".ps" goto PROCESS_PS
if "%INPUT_EXT%" == ".tiff" goto PROCESS_TIFF
if "%INPUT_EXT%" == ".tif" goto PROCESS_TIFF
if "%INPUT_EXT%" == ".pdf" goto PROCESS_PDF
echo ERROR: File type "%INPUT_EXT%" not supported!
goto END
:: --------
:PROCESS_PS
:: set file names
set PS_FILE=%INPUT_FILE%
set PDF_FILE=%PDF_DIR%\%INPUT_NAME%.pdf
:: convert to PDF
"%GS_INSTALL%\gs%GS_VERSION%\bin\gswin32c.exe" -dSAFER -dNumRenderingThreads#%NUMBER_OF_PROCESSORS% -sDEVICE#pdfwrite -o "%PDF_FILE%" -c .setpdfwrite -f "%PS_FILE%"
goto DISPLAY
:: ----------
:PROCESS_TIFF
:: set file names
set TIFF_FILE=%INPUT_FILE%
set PDF_FILE=%PDF_DIR%\%INPUT_NAME%.pdf
:: convert to PDF
"%LIBTIFF_INSTALL%\bin\tiff2pdf.exe" -o "%PDF_FILE%" -f "%TIFF_FILE%"
goto DISPLAY
:: ---------
:PROCESS_PDF
:: set file name
set PDF_FILE=%INPUT_FILE%
::
:: ------------------------------------------------------------------
:DISPLAY
:: open PDF file in reader
:: start /b "%PDF_READER%" "%PDF_FILE%"
::
:: apply background
%PDFTK%\pdftk.exe "%PDF_FILE%" background %BACKGROUND% output "%PDF_DIR%\output.pdf"
:: call OUTLOOK - ugly for the moment
"C:\Program Files (x86)\Microsoft Office\OFFICE14\OUTLOOK.EXE" /a "%PDF_DIR%\output.pdf"

:: ------------------------------------------------------------------
:END
exit
::
:: ------------------------------------------------------------------
:: Subroutine: set_input_file_name_ext
:: Arguments:  %1 = "path/name.ext"
:: Purpose:    set environment vars to input file, name and extension
:: ------------------------------------------------------------------
:set_input_file_name_ext
set INPUT_FILE=%~1
set INPUT_NAME=%~n1
set INPUT_EXT=%~x1
goto :eof
:: ------------------------------------------------------------------