Committer: root <root@fruw.org>

This commit is contained in:
root
2023-07-29 16:42:28 +05:00
parent d46885fdc8
commit 6afc76eb9c
74 changed files with 5643 additions and 0 deletions

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,3 @@
# active-directory
Автоматизированные создание и ввод пользователей в домен.

View File

@ -0,0 +1,156 @@
# Разрешаем запуск скрипта и запускаем его
# Set-ExecutionPolicy Unrestricted -force ; cd ~\Desktop\ ; .\ad-users.ps1
Import-Module ActiveDirectory
# Указываем директорию
$dir = "$(pwd)\Users"
new-item -path "$dir" -ItemType Directory -force >$null
# Переменные DC
$dc_first = "demo"
$dc_second = "lab"
# Переменные OU
$ou_main = "DemoOffice"
$ou_users = "Users"
$ou_computers = "Computers"
# Переменные для настройки сети
$mask = "255.255.255.0"
$gw = '192.168.10.1'
$dns = '192.168.10.100'
$eth = 'Ethernet0'
# Переменные PATH
$dc_path = "DC=$dc_first,DC=$dc_second"
$main_path = "OU=$ou_main,DC=$dc_first,DC=$dc_second"
$users_path = "OU=$ou_users,OU=$ou_main,DC=$dc_first,DC=$dc_second"
$computers_path = "OU=$ou_computers,OU=$ou_main,DC=$dc_first,DC=$dc_second"
# Проверка OU
try
{
Get-ADOrganizationalUnit -SearchBase "$main_path" -Filter * >$null
Get-ADOrganizationalUnit -SearchBase "$users_path" -Filter * >$null
Get-ADOrganizationalUnit -SearchBase "$computers_path" -Filter * >$null
}
catch
{
New-ADOrganizationalUnit -Name "$ou_main" -Path $dc_path
New-ADOrganizationalUnit -Name "$ou_users" -Path $main_path
New-ADOrganizationalUnit -Name "$ou_computers" -Path $main_path
}
# Вводим переменные
if ("$args[0]" -eq "[0]"){
$numb = "1"
} else {
$numb = $args[0]
}
$count=1..$numb
$users = @()
Foreach ($i in $count)
{
$Row = "" | Select Username,Admin,IP,PC
$Row.Username = Read-Host "Введите имя пользователя номер $i"
$Row.Admin = Read-Host "Должен ли пользователь $i иметь права администратора? (Y - да, N - нет)"
if ($Row.Admin -eq "y")
{$Row.Admin = "Yes"}
else {$Row.Admin = "No"}
$Row.PC = Read-Host "Введите имя компьютера номер $i"
$Row.IP = Read-Host "Введите IP адрес для пользователя номер $i"
$Users += $Row
}
$pass = Read-Host 'Enter the password'
# Цикл с пользователями
foreach ($user in $users) {
$name = $user.Username
$ip = $user.ip
$pc = $user.pc
$Username = @{
Name = "$name"
GivenName = "$name"
UserPrincipalName = "$name@$dc_first.$dc_second"
Path = $users_path
ChangePasswordAtLogon = $true
AccountPassword = "$pass" | ConvertTo-SecureString -AsPlainText -Force
Enabled = $true
}
# Создание пользователей
New-ADUser @Username
Set-ADUser $name -PasswordNeverExpires:$True
if ($user.Admin -eq "Yes")
{Add-ADGroupMember "Domain admins" $name}
# Создание скрпитов для компьютеров "локально"
$securepassword = '$pass' + " | ConvertTo-SecureString -AsPlainText -Force"
$credential = "New-Object System.Management.Automation.PSCredential -ArgumentList" + ' $name, $securepassword'
$out = '# Разрешаем запуск скрипта и запускаем его
# Set-ExecutionPolicy Unrestricted -force ; cd ~\Desktop\ ;' + " .\$name.ps1" + '
$name = "' + "$name" + '"
' + '$pass = "' + "$pass" + '"
' + '$securepassword = ' + "$securepassword
" + '$credential = ' + "$credential
Disable-NetAdapterBinding -Name '*' -ComponentID ms_tcpip6
netsh interface ip set address name=$eth static $ip $mask $gw
netsh interface ip set dns $eth static $dns " + '>$null' + "
Timeout /T 5
Add-Computer -DomainName $dc_first.$dc_second -NewName $pc -OUPath " + '"' + "$computers_path" + '"' + " -Credential" + ' $credential
$ans = Read-Host "Перезагрузить ПК?"
if ($ans -eq "y")
{Restart-Computer -Force}'
$con="Проводное соединение 1"
$outl = '#!/usr/bin/env bash
if [[ $(whoami) == "root" ]]; then
' + '
ip=' + '"' + $ip + '"' + '
mask=' + '"' + 24 + '"' + '
gw=' + '"' + $gw + '"' + '
dns=' + '"' + $dns + '"' + '
pc=' + '"' + $pc + '"' + '
dc_first=' + '"' + $dc_first + '"' + '
dc_second=' + '"' + $dc_second + '"' + '
con=' + '"' + $con + '"' + '
name=' + '"' + $name + '"' + '
#Установка пакетов
apt install astra-ad-sssd-client -y
#Вводим краткое доменное имя
hostnamectl set-hostname "$pc"
# Задаем адрес шлюза
nmcli con mod "$con" ip4 $ip/$mask gw4 $gw
# Задаем адреса DNS
nmcli con mod "$con" ipv4.dns "$dns"
# Отключаем DHCP, переводим в "ручной" режим настройки
nmcli con mod "$con" ipv4.method manual
nmcli con mod "$con" ipv6.method ignore
nmcli -p con show "$con" | grep ipv4
# Перезапускаем соединение для применения новых настроек
nmcli con down "$con" ; nmcli con up "$con"
#Вход в домен Active Directory
astra-ad-sssd-client -d demo.lab -u Administrator -p ' + "$pass" + ' -y
# sudo
echo "$name ALL=(ALL:ALL) ALL" | sudo EDITOR="tee -a" visudo
#Перезагрузка
read -p "Перезагрузить ПК? " in
if [[ "$in" == "y" ]]; then
sudo reboot
fi
#Выполнено не от рута
else
echo "Запусти скрипт через sudo!"
fi'
# Указываем директорию и записываем данные пользователя
write-output $out | out-file -append -encoding utf8 "$dir\$name.ps1"
# Указываем директорию и записываем данные пользователя
write-output $outl | out-file -append -encoding utf8 "$dir\$name.sh"
((Get-Content "$dir\$name.sh") -join "`n") + "`n" | Set-Content -NoNewline -encoding utf8 "$dir\$name.sh"
}

9
powershell/clock/LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,3 @@
# clock
Добавляет секунды в часы

View File

@ -0,0 +1,9 @@
$wshell = New-Object -ComObject Wscript.Shell
if (Get-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowSecondsInSystemClock 2>$null){
Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowSecondsInSystemClock
$wshell.Popup("The registry entry was deleted.")
}else{
New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced -Name ShowSecondsInSystemClock -PropertyType DWord -Value 1 >$null
$wshell.Popup("The registry entry was created.")
}
taskkill /f /im explorer.exe >$null; start explorer.exe

View File

@ -0,0 +1,2 @@
# cve-sort

View File

@ -0,0 +1,30 @@
#!/usr/bin/env bash
echo "CVE;Вердиткт;Критичность уязвимости;Вектор атаки;Комментарий" > cve-out.csv
MAX_CVE=$(wc -l cve-in | grep -o [0-9]*)
for CVE in $(cat cve-in)
do
let "CURRENT_CVE++"
CURL_CVE=$(curl -s https://services.nvd.nist.gov/rest/json/cves/2.0?cveId=$CVE)
ATTACK_VECTOR=$(echo $CURL_CVE | grep -o '"accessVector":"[^"]*' | egrep -o '[^"]*$')
BASE_SCORE=$(printf "%.0f" $(echo $CURL_CVE | egrep -o '"baseScore":[0-9]?[0-9]\.[0-9]' \
| egrep -o '[0-9]?[0-9]\.[0-9]' | head -1))
DESCRIPTION=$(echo $CURL_CVE | grep -o '"value":"[^"]*' | egrep -o '[^"]*$')
if [[ "$ATTACK_VECTOR" == *"PHYSICAL"* ]]
then
VERDICT="НЕ ОБНОВЛЯТЬ!"
elif [[ "$BASE_SCORE" -le 3 ]]
then
VERDICT="НЕ ОБНОВЛЯТЬ!"
elif [[ "$BASE_SCORE" -gt 7 ]]
then
VERDICT="ОБНОВЛЯТЬ!"
elif [[ "$ATTACK_VECTOR" != *"LOCAL"* ]]
then
VERDICT="ОБНОВЛЯТЬ!"
else
VERDICT="НЕ ОБНОВЛЯТЬ!"
fi
echo "$CVE;$VERDICT;$BASE_SCORE;$ATTACK_VECTOR;$DESCRIPTION" >> cve-out.csv
echo "$CURRENT_CVE/$MAX_CVE - $CVE"
sleep 20
done

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 fruworg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,30 @@
Write-Host '
_______________ _____________.____ ________ ________ ____ __.
\_ _____/\ \/ /\______ \ | \_____ \ \_____ \ | |/ _|
| __)_ \ / | ___/ | / | \ / | \| <
| \ / \ | | | |___/ | \/ | \ | \
/_______ //___/\ \ |____| |_______ \_______ /\_______ /____|__ \
\/ \_/ \/ \/ \/ \/
'
Add-Type -AssemblyName "Microsoft.Office.Interop.Outlook" | Out-Null
$olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $Outlook.GetNameSpace("MAPI")
$Folder = $namespace.Folders("im@fruw.org").Folders("foldername")
$Path = "$(pwd)\exp-look.csv"
$i = $max = $Folder.Items.Count
$Writed = 0
if (!(Test-Path -Path $Path)) {
'Тест1;Тест2' | Out-File $Path -Encoding UTF8
}
for(;$i -gt 0;$i--){
if ($Folder.Items[$i].Unread){
$Writed++
$Folder.Items[$i].Unread = $False
$Percent = 100-($i/$max*100)
Write-Progress -Activity "Работаем!" -Status "Осталось прочитать $i у.е." -PercentComplete $Percent
$MailInfo = $Folder.Items[$i] | Select-Object -Property Body, Subject, ReceivedTime, SenderName, SenderEmailAddress
$MailInfo | Out-File $Path -Append -Encoding UTF8
}}
Read-Host -Prompt " Выполнено! Внесено в таблицу $Writed у.е.
Нажмите Enter для того, чтобы выйти"

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,7 @@
### tm-ssl
Создаёт цепочку сертификатов и устанавливает их автоматически.
```
root
∟ server
∟ client
```

View File

@ -0,0 +1,283 @@
# Скачиваем софт по ссылкам ниже
# https://es.ukrtb.ru/nextcloud/s/xwBAsTqWqT8QyBT/download/OpenSSL.msi
# https://es.ukrtb.ru/nextcloud/s/PoxqfCWkXtrdgw7/download/putty.msi
# https://es.ukrtb.ru/nextcloud/s/ybKx8rpJX8fbZtS/download/WinSCP.exe
# Делаем ручное подключение (Астра)
# plink iwtm@192.168.1.10 -pw xxXX1234
# Запускаем скрипт
# Set-ExecutionPolicy Unrestricted -force; cd ~\Desktop\; .\tm-ssl.ps1
# Павершелл следует запускать от имени администратора
Write-Host "`nПроверка привелегий администратора:"
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Warning "Запустите павершелл от имени администратора.`n"
Break
}
else {
Write-Host "Скрипт запущен от имени администратора.`n" -ForegroundColor Green
}
# Остановка скрипта при ошибке
$ErrorActionPreference = "Stop"
# Указываем пути
$path = "C:\Program Files\OpenSSL-Win64\bin"
$hpath = "$(pwd)\tm-ssl"
$wpath = "C:\Program Files (x86)\WinSCP"
$lpath = "$hpath\linux"
$cpath = "$hpath\certs"
$dpath = "tmp"
# Названия сертификатов
$root = "root"
$intermediate = "intermediate"
$server = "iwtm"
$client = "arm"
# Данные для линупса
$cnf = "iw"
if (!($ip = Read-Host "Введите IP IWTM [192.168.1.10]")) { $ip = "192.168.1.10" }
if (!($luser = Read-Host "Введите пользователя IWTM [iwtm]")) { $luser = "iwtm" }
if (!($lpassword = Read-Host "Введите пароль IWTM [xxXX1234]")) { $lpassword = "xxXX1234" }
# Промежуточный = серверный
if (!($servint = Read-Host "`nСделать серверный сертификат промежуточным [y]")) { $servint = "y" }
if ($servint -eq "y"){
$intermediate = $server
}
# Данные для сертификата
if (!($country = Read-Host "`nВведите страну [RU]")) { $country = "RU" }
if (!($state = Read-Host "Введите штат [RB]")) { $state = "RB" }
if (!($city = Read-Host "Введите город [Ufa]")) { $city = "Ufa" }
if (!($corp = Read-Host "Введите организацию [UKRTB]")) { $corp = "UKRTB" }
if (!($unit = Read-Host "Введите отдел [IT]")) { $unit = "IT" }
if (!($hostname = Read-Host "Введите хостнейм [iwtm]")) { $hostname = "iwtm" }
if (!($domain = Read-Host "Введите домен [demo.lab]")) { $domain = "demo.lab" }
if (!($password = Read-Host "Введите пароль .p12 [xxXX1234]")) { $password = "xxXX1234" }
$site = "$hostname.$domain"
# Конфиг опенссл
$config = "
[ ca ]
default_ca = CA_default
[ CA_default ]
certs = ./
serial = serial
database = index
new_certs_dir = ./
certificate = $root.crt
private_key = $root.key
default_days = 36500
default_md = sha256
preserve = no
email_in_dn = no
nameopt = default_ca
certopt = default_ca
policy = policy_match
[ policy_match ]
commonName = supplied
countryName = optional
stateOrProvinceName = optional
organizationName = optional
organizationalUnitName = optional
emailAddress = optional
[ req ]
input_password = $password
prompt = no
distinguished_name = default
default_bits = 2048
default_keyfile = priv.pem
default_md = sha256
req_extensions = v3_req
encyrpt_key = no
x509_extensions = v3_ca
[ default ]
commonName = default
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
basicConstraints = critical,CA:true
[ v3_intermediate_ca ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, digitalSignature, cRLSign, keyCertSign
subjectAltName = @alt_names
[ v3_req ]
basicConstraints = CA:FALSE
subjectKeyIdentifier = hash
subjectAltName = @alt_names
[ alt_names ]
DNS.1 = $site
IP.1 = $ip"
# Удаляем файлы, которые могли остаться от прошлого запуска скрипта
cd $path
Remove-Item * -Include *.sh,*.cnf,*.key,*.csr,*.crt,*.p12,*.pem,seria*,inde* -Force
if (Test-Path "$hpath") {
rm -r -fo "$hpath"
}
# Создаём файл с номером и индексом скрипта, конфиг опенссл и скрипт для линукса
out-file -append -encoding utf8 "index"
write-output "01" | out-file -append -encoding ASCII "serial"
write-output $config | out-file -append -encoding utf8 "$cnf.cnf"
# Продолжение скрипта при ошибке
$ErrorActionPreference = "Continue"
# Обработка ошибок
$TempFile = New-TemporaryFile
function Error-Break{
# Если в файлы нет Signature ok + MAC + он не пустой, то if выполняется
if ((!(Select-String -Path "$TempFile" -Pattern 'Signature ok') -and (!(Select-String -Path "$TempFile" -Pattern 'MAC'))) -xor ([String]::IsNullOrWhiteSpace((Get-content $TempFile)))){
# Вывод ошибок
$err = Get-Content -Path $TempFile
Write-Error "$err"
# break
break
}
}
# Имя сертификата
$name = $root
# Создаём корневой ключ
.\openssl genrsa -out "$root.key" 2> $TempFile; Error-Break
# Создаём корневой самоподписанный сертификат
.\openssl req -x509 -new -nodes -key "$root.key" -sha256 -days 1024 -out "$root.crt" -config "$cnf.cnf" -subj "/C=$country/ST=$state/L=$city/O=$corp/OU=$unit/CN=$name/emailAddress=$name@$domain" *> $TempFile; Error-Break
Write-Host "`nКорневой сертификат создан." -ForegroundColor Green
# Имя сертификата
$name = $intermediate
# Создаёи промежуточный ключ
.\openssl genrsa -out "$intermediate.key" *> $TempFile; Error-Break
# Создаём запрос на подпись
.\openssl req -new -sha256 -config "$cnf.cnf" -key "$intermediate.key" -out "$intermediate.csr" *> $TempFile; Error-Break
# Подписываем сертификат корневым
.\openssl ca -config "$cnf.cnf" -extensions v3_intermediate_ca -days 2650 -batch -in "$intermediate.csr" -out "$intermediate.crt" -subj "/C=$country/ST=$state/L=$city/O=$corp/OU=$unit/CN=$name/emailAddress=$name@$domain" *> $TempFile; Error-Break
# Промежуточный =/= серверный + создание серверного сертификата
if ($servint -ne "y"){
Write-Host "Промежуточный сертификат создан." -ForegroundColor Green
# Имя сертификата
$name = $server
# Создаём ключ клиента
.\openssl genrsa -out "$server.key" *> $TempFile; Error-Break
# Создаём запрос на подпись
.\openssl req -new -key "$server.key" -out "$server.csr" -config "$cnf.cnf" *> $TempFile; Error-Break
# Подписываем сертификат промежуточным
.\openssl x509 -req -in "$server.csr" -CA "$intermediate.crt" -CAkey "$intermediate.key" -CAcreateserial -sha256 -days 2650 -days 2650 -set_serial 01 -out "$server.crt" -extensions v3_req -extfile "$cnf.cnf" -subj "/C=$country/ST=$state/L=$city/O=$corp/OU=$unit/CN=$name/emailAddress=$name@$domain" *> $TempFile; Error-Break
}
Write-Host "Серверный сертификат создан." -ForegroundColor Green
# Создание клиентского сертификата
# Имя сертификата
$name = $client
# Создаём ключ клиента
.\openssl genrsa -out "$client.key" *> $TempFile; Error-Break
# Создаём запрос на подпись
.\openssl req -new -key "$client.key" -out "$client.csr" -config "$cnf.cnf" *> $TempFile; Error-Break
# Подписываем сертификат промежуточный
(.\openssl x509 -req -in "$client.csr" -CA "$intermediate.crt" -CAkey "$intermediate.key" -CAcreateserial -sha256 -days 2650 -out "$client.crt" -extensions v3_req -extfile "$cnf.cnf" -subj "/C=$country/ST=$state/L=$city/O=$corp/OU=$unit/CN=$name/emailAddress=$name@$domain") *> $TempFile; Error-Break
Write-Host "Клиентский сертификат создан." -ForegroundColor Green
# Остановка скрипта при ошибке
$ErrorActionPreference = "Stop"
$thumbprint = $(Get-PfxCertificate -FilePath "$client.crt" | select -expand Thumbprint).ToLower()
# Экспортируем промежуточный сертификат и ключ
.\openssl pkcs12 -export -in "$server.crt" -inkey "$server.key" -out "$server.p12" -password pass:"$password"
# Экспортируем для бравузера
.\openssl pkcs12 -export -in "$client.crt" -inkey "$client.key" -out "$client.p12" -password pass:"$password"
# Экспортируем всё
.\openssl pkcs12 -export -in "$server.crt" -inkey "$server.key" -in "$client.crt" -inkey "$client.key" -in "$root.crt" -inkey "$root.key" -out out.p12 -password pass:"$password"
&{
# Создаём директории для сертификатов и линупса
New-Item -path "$cpath" -ItemType Directory -force
New-Item -path "$lpath" -ItemType Directory -force
} >$null
Write-Host "`nДиректории созданы успешно." -ForegroundColor Green
$ssl_client_fingerprint = '$ssl_client_fingerprint'
# Скрипт для линукса
$linux = "#!/usr/bin/env bash
openssl pkcs12 -in /$dpath/$server.p12 -nokeys -out /opt/iw/tm5/etc/certification/$server.crt -password pass:$password
openssl pkcs12 -in /$dpath/$server.p12 -nocerts -nodes -out /opt/iw/tm5/etc/certification/$server.key -password pass:$password
rm /$dpath/$server.p12
cd /etc/nginx/conf.d
cp iwtm.conf -n iwtm.conf.bak || mv iwtm.conf.bak iwtm.conf
sed -i '9s/web-server.pem/$server.crt/' iwtm.conf
sed -i '10s/web-server.key/$server.key/' iwtm.conf
sed -i '12i ssl_verify_client optional_no_ca;' iwtm.conf
sed -i '21i if ( $ssl_client_fingerprint != $thumbprint ) { return 496; }' iwtm.conf
"
write-output $linux | out-file -append -encoding utf8 "$cnf.sh"
# Преобразуем скрипт для линукса в *nix формат
((Get-Content "$cnf.sh") -join "`n") + "`n" | Set-Content -NoNewline "$cnf.sh"
# Перемещаем скрипт для линукса и .p12
Move-Item -path ".\$cnf.sh" -destination "$lpath\$cnf.sh" -force
Move-Item -path ".\$server.p12" -destination "$lpath\$server.p12" -force
# Перемещаем остальное добро
Get-ChildItem -Path ".\*.pfx" -Recurse | Move-Item -Destination "$cpath" -force
Get-ChildItem -Path ".\*.p12" -Recurse | Move-Item -Destination "$cpath" -force
Get-ChildItem -Path ".\*.key" -Recurse | Move-Item -Destination "$cpath" -force
Get-ChildItem -Path ".\*.csr" -Recurse | Move-Item -Destination "$cpath" -force
Get-ChildItem -Path ".\*.crt" -Recurse | Move-Item -Destination "$cpath" -force
# Подчищаем за собой
Remove-Item * -Include *.cnf,*.pem,seria*,inde* -Force
# Устанавливаем сертификаты в шиндоус
&{
Import-Certificate -FilePath "$cpath\$root.crt" -CertStoreLocation Cert:\LocalMachine\Root
if ($servint -eq "y"){
Import-Certificate -FilePath "$cpath\$server.crt" -CertStoreLocation Cert:\LocalMachine\CA
}else{
Import-Certificate -FilePath "$cpath\$intermediate.crt" -CertStoreLocation Cert:\LocalMachine\CA
Import-Certificate -FilePath "$cpath\$server.crt" -CertStoreLocation Cert:\LocalMachine\My
}
Import-Certificate -FilePath "$cpath\$client.crt" -CertStoreLocation Cert:\LocalMachine\My
} >$null
Write-Host "Сертификаты установлены." -ForegroundColor Green
# Перемещаем скрипт и сертификаты в линупс
&{
cd $wpath
.\WinSCP.exe sftp://${luser}:${lpassword}@${ip}/$dpath/ /upload $lpath\$server.p12 $lpath\$cnf.sh /defaults
Read-Host "`nКогда WinSCP успешно передаст файлы, нажмите [ENTER]"
# Запускаем скрипт удалённо
echo y | plink -batch $luser@$ip -pw $lpassword "exit" *> $null
plink -batch $luser@$ip -pw $lpassword "sudo bash /$dpath/$cnf.sh"; Error-Break
# Чистим за собой
plink -batch $luser@$ip -pw $lpassword "sudo rm /$dpath/$cnf.sh"; Error-Break
plink -batch $luser@$ip -pw $lpassword "history -c"; Error-Break
} 2>$null
Write-Host "IWTM сконфигурирован." -ForegroundColor Green
# Записываем данные в DNS
&{Remove-DnsServerResourceRecord -ZoneName $domain -Name $hostname -RRType A -force} 2> $null
Add-DnsServerResourceRecordA -Name $hostname -IPv4Address $ip -ZoneName $domain -TimeToLive 01:00:00
Write-Host "DNS запись создана.`n" -ForegroundColor Green
Write-Warning "Перезагрузи NGINX и установи в бразуер сертификат.`n"

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 fruworg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,64 @@
#Перед началом необходимо выполнить следующие команды:
#Install-module PSExcel
#Get-command -module psexcel
clear
Write-Host "
.__ .__
___ __| | _________ ___ |__|_____
\ \/ / | / ___/\ \/ / ______ | \____ \
> <| |__\___ \ > < /_____/ | | |_> >
/__/\_ \____/____ >/__/\_ \ |__| __/
\/ \/ \/ |__|
"
if ($Args.count -ne 0){
$Value = $Args
} else {
$Value = Read-Host " Введите имена файлов"
Write-Host ""
$Value = $Value -split " "
}
for ($i=0; $i -lt $Value.count; $i++){
$Path = "$(pwd)\" + [string]$Value[$i] + ".xlsx"
try{
$File = Import-XLSX -Path $Path
$Out = $File.IP -match "\d" -replace "ip address "
$Out = $Out -replace " 255\.0\.0\.0", "/8"
$Out = $Out -replace " 255\.128\.0\.0", "/9"
$Out = $Out -replace " 255\.192\.0\.0", "/10"
$Out = $Out -replace " 255\.224\.0\.0", "/11"
$Out = $Out -replace " 255\.240\.0\.0", "/12"
$Out = $Out -replace " 255\.248\.0\.0", "/13"
$Out = $Out -replace " 255\.252\.0\.0", "/14"
$Out = $Out -replace " 255\.254\.0\.0", "/15"
$Out = $Out -replace " 255\.255\.0\.0", "/16"
$Out = $Out -replace " 255\.255\.128", "/17"
$Out = $Out -replace " 255\.255\.192\.0", "/18"
$Out = $Out -replace " 255\.255\.224\.0", "/19"
$Out = $Out -replace " 255\.255\.240\.0", "/20"
$Out = $Out -replace " 255\.255\.252\.0", "/22"
$Out = $Out -replace " 255\.255\.254\.0", "/23"
$Out = $Out -replace " 255\.255\.255\.0", "/24"
$Out = $Out -replace " 255\.255\.255\.128", "/25"
$Out = $Out -replace " 255\.255\.255\.192", "/26"
$Out = $Out -replace " 255\.255\.255\.224", "/27"
$Out = $Out -replace " 255\.255\.255\.240", "/28"
$Out = $Out -replace " 255\.255\.255\.248", "/29"
$Out = $Out -replace " 255\.255\.255\.252", "/30"
$Out | Out-File .\except.txt -Append -Encoding UTF8
cat .\except.txt | select -Unique | sc .\except.txt
$nerr = $nerr + " $Path
"
}
catch{
$err = $err + " $Path
"}
}
if ($nerr -match "[A-z]"){
Write-Host -ForegroundColor Gree " Файлы ниже обработаны:
$nerr"}
if ($err -match "[A-z]"){
Write-Host -ForegroundColor Red " Файлы ниже не найдены:
$err"
}
Read-Host -Prompt " Выполнено! Нажмите Enter"