Browse Source

Setup scripts (please review)

master
Claudio Luck 8 months ago
commit
8e575ab966
7 changed files with 513 additions and 0 deletions
  1. +54
    -0
      tools/Install_WinCore.ps1
  2. +76
    -0
      tools/Install_runner.ps1
  3. +33
    -0
      tools/Remove_Service.ps1
  4. +13
    -0
      tools/Reset_SATA.reg
  5. +57
    -0
      tools/WinRM.py
  6. +252
    -0
      tools/addpriv.ps1
  7. +28
    -0
      tools/register_runner.ps1

+ 54
- 0
tools/Install_WinCore.ps1 View File

@ -0,0 +1,54 @@
# DISM /Online /Get-TargetEditions
# DISM /Online /Set-Edition:ServerStandard /ProductKey:XXXXX-XXXXX-XXXXX-XXXXX-XXXXX /AcceptEula
Enable-PSRemoting -Force
Set-Service WinRM -StartMode Automatic
# Get-Item WSMan:\localhost\Listener
# Get-Item WSMan:\localhost\Client\TrustedHosts
# & winrm delete winrm/config/Listener?Address=*+Transport=HTTP
# & winrm create winrm/config/Listener?Address=*+Transport=HTTPS@{Hostname="$Env:Computername";CertificateThumbprint=
#
New-SelfSignedCertificate -DnsName $Env:Computername -CertStoreLocation Cert:\LocalMachine\My
# $cert = Import-PfxCertificate -FilePath C:\Setup\WinRMCert.pfx -CertStoreLocation Cert:\LocalMachine\My -Password (ConvertTo-SecureString -ApPlainText -String 123456 -Force)
$thumbprint = (Get-ChildItem Cert:\LocalMachine\my | where { $_.Subject -eq "CN=" + $Env:Computername }).Thumbprint
New-Item -Path WSMan:\localhost\Listener -Transport HTTPS -Address * -CertificateThumbPrint $thumbprint -Force
New-NetFirewallRule -Displayname "WinRM - Powershell remoting HTTPS-In" -Name "WinRM - Powershell remoting HTTPS-In" -Profile Any -LocalPort 5986 -Protocol TCP
Enable-NetFirewallRule -DisplayName "WinRM - Powershell remoting HTTPS-In"
Enable-NetFirewallRule -DisplayName "Windows Management Instrumentation (DCOM-In)"
#
Enable-NetFirewallRule -DisplayGroup "Remote Event Log Management"
Enable-NetFirewallRule -DisplayGroup "Remote Service Management"
Enable-NetFirewallRule -DisplayGroup "Remote Scheduled Tasks Management"
Enable-NetFirewallRule -DisplayGroup "Windows Defender Firewall Remote Management"
Enable-WSManCredSSP -Role Server -Force
Set-Item -Path WSMan:\localhost\Service\Auth\CredSSP -Value $true
Restart-Service -Force WinRM
Set-Item WSMan:\localhost\Client\TrustedHosts -Force -Concatenate -Value 192.168.77.172
Set-Item WSMan:\localhost\Client\TrustedHosts -Force -Concatenate -Value 192.168.77.139
# Install-WindowsFeature -Name Hyper-V -IncludeManagementTools
Install-WindowsFeature -Name Containers
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Install-Module -Name DockerMsftProvider -Repository PSGallery -Force
# Get-PackageProvider -ListAvailable
# Get-PackageSource -ProviderName DockerMsftProvider
Install-Package -Name Docker -ProviderName DockerMsftProvider -Force
Start-Service Docker
Set-Service Docker -StartMode Automatic
$env:PATH += ";$env:ProgramFiles\docker"
# Set up SSH
#
# Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
# Start-Service sshd
# Set-Service -Name sshd -StartMode Automatic

+ 76
- 0
tools/Install_runner.ps1 View File

@ -0,0 +1,76 @@
param (
[Parameter(Mandatory=$true)][string]$Runner = $(
Read-Host "Runner name (e.g. pEpSecRunner)" )
[string]$RunnerBinary = "gitlab-runner-windows-amd64.exe"
)
if ( -not $Runner.endswith("Runner") ) { $Runner = $Runner + "Runner" }
New-Item -ItemType Directory -Force -Path "$Env:ProgramFiles\GitLabCI" | Out-Null
if ((Get-Item "$Env:ProgramFiles\GitLabCI\gitlab-runner.exe") -eq $Null) {
Copy-Item "$RunnerBinary" -Destination "$Env:ProgramFiles\GitLabCI\gitlab-runner.exe"
}
$ServSuffixCount = 1
$ServSuffix = ""
do {
$s = Get-Service "GitLab$Runner$ServSuffix" -ea 0
if ($s -ne $Null) {
$ServSuffixCount += 1
$ServSuffix = "$ServSuffixCount"
}
} while ($s -ne $Null)
# Create User for runner
# Lifted from https://activedirectoryfaq.com/2017/08/creating-individual-random-passwords/
$PlainPassword = Get-Content -Path "$Env:UserProfile\Documents\GitLab$Runner$ServSuffix.pw.txt" -ea 0 | Out-Null
if ($PlainPassword -eq $Null) {
Add-Type -AssemblyName System.Web
$PlainPassword = $([System.Web.Security.Membership]::GeneratePassword(16, 4))
Set-Content -Path "$Env:UserProfile\Documents\GitLab$Runner$ServSuffix.pw.txt" -Value "$PlainPassword"
}
$Password = ConvertTo-SecureString -String $PlainPassword -AsPlainText -Force
$User = Get-LocalUser "GitLab$Runner$ServSuffix" -ea 0
If ($User -eq $Null) {
"Username=GitLab$Runner$ServSuffix"
"Password=$PlainPassword"
$User = New-LocalUser "GitLab$Runner$ServSuffix" -Password $Password -FullName "GitLab Runner $Runner$ServSuffix" `
-Description "GitLab Runner $Runner$ServSuffix."
# https://download.microsoft.com/download/8/e/c/8ec3a7d8-05b4-440a-a71e-ca3ee25fe057/rktools.exe
# (an alternative to using rktools.exe is available in addpriv.ps1)
& "C:\Tools\ResKit\ntrights.exe" +r SeServiceLogonRight -u "GitLab$Runner$ServSuffix" -m "\\$Env:ComputerName"
}
$homeShare = New-Item -ItemType Directory -Force -Path "$Env:SystemDrive\Build\GitLab$Runner$ServSuffix"
# Lifted from https://activedirectoryfaq.com/2017/09/powershell-create-home-directory-grant-permissions/
$FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify"
$AccessControlType = [System.Security.AccessControl.AccessControlType]::Allow
$InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$PropagationFlags = [System.Security.AccessControl.PropagationFlags]"InheritOnly"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($User.SID, $FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType)
$acl = Get-Acl $homeShare
$acl.AddAccessRule($AccessRule)
Set-Acl -Path $homeShare -AclObject $acl -ea Stop
$s = Get-Service "GitLab$Runner$ServSuffix" -ea 0
if ($s -eq $Null) {
# $SDDL = "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;SU)"
# -SecurityDescriptorSddl = $SDDL
# TODO: Remove-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Services\EventLog\Application\GitLabRunner" -Recurse -ea 0 | Out-Null
$ServCreds = New-Object System.Management.Automation.PSCredential(".\GitLab$Runner$ServSuffix", $Password)
New-Service -Name "GitLab$Runner$ServSuffix" `
-DisplayName "GitLab $Runner $ServSuffix" `
-Description "GitLab $Runner $ServSuffix" `
-BinaryPathName "`"$Env:ProgramFiles\GitLabCI\gitlab-runner.exe`" run --working-directory `"$($homeShare.FullName)`" --config `"$($homeShare.FullName)\config.toml`" --service `"GitLab$Runner$ServSuffix`"" `
-StartupType Automatic -Credential $ServCreds
Start-Service "GitLab$Runner$ServSuffix"
Set-Service -Name "GitLab$Runner$ServSuffix" -StartMode Automatic
}

+ 33
- 0
tools/Remove_Service.ps1 View File

@ -0,0 +1,33 @@
param (
[Parameter(Mandatory=$true)][string]$Runner = $(
Read-Host "Runner name (e.g. pEpSecRunner)" )
)
if ( -not $Runner.endswith("Runner") ) { $Runner = $Runner + "Runner" }
$ServSuffixCount = 1
$ServSuffix = ""
do {
$s = Get-Service "GitLab$Runner$ServSuffix" -ea 0
if ($s -ne $Null) {
Stop-Service "GitLab$Runner$ServSuffix" -ea 0
& "$Env:ProgramFiles\GitLabCI\gitlab-runner.exe" $GitLabRunnerCmd uninstall --service "GitLab$Runner$ServSuffix"
$wmi_s = Get-WmiObject -Class Win32_Service -Filter "Name='GitLab$Runner$ServSuffix'" -ea 0
if ($wmi_s -ne $Null) { $wmi_s.delete() }
$ServSuffixCount += 1
$ServSuffix = "$ServSuffixCount"
}
} while ($s -ne $Null)
$UserCount = 1
$UserSuffix = ""
do {
$User = Get-LocalUser "GitLab$Runner$UserSuffix" -ea 0
Remove-Item -LiteralPath "$Env:SystemDrive\Build\GitLab$Runner$UserSuffix" -Recurse -Force -ea 0
if ($User -ne $Null) {
Remove-LocalUser $User
}
$UserCount += 1
$UserSuffix = "$UserCount"
} while ($User -ne $Null)

+ 13
- 0
tools/Reset_SATA.reg View File

@ -0,0 +1,13 @@
Windows Registry Editor Version 5.00
;Created by Vishal Gupta for AskVG.com
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\msahci]
"Start"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\pciide]
"Start"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\iaStorV]
"Start"=dword:00000000

+ 57
- 0
tools/WinRM.py View File

@ -0,0 +1,57 @@
#!/usr/bin/env python3
import sys
import os
import winrm
us = 'Administrator'
try:
us = os.environ['us']
except:
pass
pw = None
pwf = None
try:
pwf = os.environ['pwf']
except:
pass
if pwf:
with open(pwf, 'rb') as pwfh:
pw = pwfh.read().rstrip()
try:
if pw is None:
pw = os.environ['pw']
except:
import getpass
pw = getpass.getpass("Password: ")
from winrm.protocol import Protocol
host = sys.argv[1]
del sys.argv[1]
p = Protocol(
endpoint='https://%s:5986/wsman' % host,
transport='ntlm',
username=us,
password=pw,
server_cert_validation='ignore')
shell_id = p.open_shell()
# command_id = p.run_command(shell_id, 'ipconfig', ['/all'],
# out_stream=sys.stdout, err_stream=sys.stderr)
# command_id = p.run_command(shell_id, 'ipconfig', ['/all'], console_mode_stdin=False)
command_id = p.run_command(shell_id, sys.argv[1], sys.argv[2:], console_mode_stdin=True)
std_out, std_err, status_code = p.get_command_output(shell_id, command_id)
p.cleanup_command(shell_id, command_id)
p.close_shell(shell_id)
if std_out:
print(std_out.decode('utf-8'))
if std_err:
print(std_err.decode('utf-8'))
sys.exit(status_code)

+ 252
- 0
tools/addpriv.ps1 View File

@ -0,0 +1,252 @@
param (
[Parameter(Mandatory=$true)][string]$Runner = $(
Read-Host "Runner name (e.g. pEpSecRunner)" )
)
if ( -not $Runner.endswith("Runner") ) { $Runner = $Runner + "Runner" }
Add-Type @'
using System;
using System.Collections.Generic;
using System.Text;
namespace MyLsaWrapper
{
using System.Runtime.InteropServices;
using System.Security;
using System.Management;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using LSA_HANDLE = IntPtr;
[StructLayout(LayoutKind.Sequential)]
struct LSA_OBJECT_ATTRIBUTES
{
internal int Length;
internal IntPtr RootDirectory;
internal IntPtr ObjectName;
internal int Attributes;
internal IntPtr SecurityDescriptor;
internal IntPtr SecurityQualityOfService;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct LSA_UNICODE_STRING
{
internal ushort Length;
internal ushort MaximumLength;
[MarshalAs(UnmanagedType.LPWStr)]
internal string Buffer;
}
sealed class Win32Sec
{
[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]
internal static extern uint LsaOpenPolicy(
LSA_UNICODE_STRING[] SystemName,
ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
int AccessMask,
out IntPtr PolicyHandle
);
[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]
internal static extern uint LsaAddAccountRights(
LSA_HANDLE PolicyHandle,
IntPtr pSID,
LSA_UNICODE_STRING[] UserRights,
int CountOfRights
);
[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true),
SuppressUnmanagedCodeSecurityAttribute]
internal static extern int LsaLookupNames2(
LSA_HANDLE PolicyHandle,
uint Flags,
uint Count,
LSA_UNICODE_STRING[] Names,
ref IntPtr ReferencedDomains,
ref IntPtr Sids
);
[DllImport("advapi32")]
internal static extern int LsaNtStatusToWinError(int NTSTATUS);
[DllImport("advapi32")]
internal static extern int LsaClose(IntPtr PolicyHandle);
[DllImport("advapi32")]
internal static extern int LsaFreeMemory(IntPtr Buffer);
}
/// <summary>
/// This class is used to grant "Log on as a service", "Log on as a batchjob", "Log on localy" etc.
/// to a user.
/// </summary>
public sealed class LsaWrapper : IDisposable
{
[StructLayout(LayoutKind.Sequential)]
struct LSA_TRUST_INFORMATION
{
internal LSA_UNICODE_STRING Name;
internal IntPtr Sid;
}
[StructLayout(LayoutKind.Sequential)]
struct LSA_TRANSLATED_SID2
{
internal SidNameUse Use;
internal IntPtr Sid;
internal int DomainIndex;
uint Flags;
}
[StructLayout(LayoutKind.Sequential)]
struct LSA_REFERENCED_DOMAIN_LIST
{
internal uint Entries;
internal LSA_TRUST_INFORMATION Domains;
}
enum SidNameUse : int
{
User = 1,
Group = 2,
Domain = 3,
Alias = 4,
KnownGroup = 5,
DeletedAccount = 6,
Invalid = 7,
Unknown = 8,
Computer = 9
}
enum Access : int
{
POLICY_READ = 0x20006,
POLICY_ALL_ACCESS = 0x00F0FFF,
POLICY_EXECUTE = 0X20801,
POLICY_WRITE = 0X207F8
}
const uint STATUS_ACCESS_DENIED = 0xc0000022;
const uint STATUS_INSUFFICIENT_RESOURCES = 0xc000009a;
const uint STATUS_NO_MEMORY = 0xc0000017;
IntPtr lsaHandle;
public LsaWrapper()
: this(null)
{ }
// // local system if systemName is null
public LsaWrapper(string systemName)
{
LSA_OBJECT_ATTRIBUTES lsaAttr;
lsaAttr.RootDirectory = IntPtr.Zero;
lsaAttr.ObjectName = IntPtr.Zero;
lsaAttr.Attributes = 0;
lsaAttr.SecurityDescriptor = IntPtr.Zero;
lsaAttr.SecurityQualityOfService = IntPtr.Zero;
lsaAttr.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES));
lsaHandle = IntPtr.Zero;
LSA_UNICODE_STRING[] system = null;
if (systemName != null)
{
system = new LSA_UNICODE_STRING[1];
system[0] = InitLsaString(systemName);
}
uint ret = Win32Sec.LsaOpenPolicy(system, ref lsaAttr,
(int)Access.POLICY_ALL_ACCESS, out lsaHandle);
if (ret == 0)
return;
if (ret == STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
{
throw new OutOfMemoryException();
}
throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
}
public void AddPrivileges(string account, string privilege)
{
IntPtr pSid = GetSIDInformation(account);
LSA_UNICODE_STRING[] privileges = new LSA_UNICODE_STRING[1];
privileges[0] = InitLsaString(privilege);
uint ret = Win32Sec.LsaAddAccountRights(lsaHandle, pSid, privileges, 1);
if (ret == 0)
return;
if (ret == STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
{
throw new OutOfMemoryException();
}
throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
}
public void Dispose()
{
if (lsaHandle != IntPtr.Zero)
{
Win32Sec.LsaClose(lsaHandle);
lsaHandle = IntPtr.Zero;
}
GC.SuppressFinalize(this);
}
~LsaWrapper()
{
Dispose();
}
// helper functions
IntPtr GetSIDInformation(string account)
{
LSA_UNICODE_STRING[] names = new LSA_UNICODE_STRING[1];
LSA_TRANSLATED_SID2 lts;
IntPtr tsids = IntPtr.Zero;
IntPtr tdom = IntPtr.Zero;
names[0] = InitLsaString(account);
lts.Sid = IntPtr.Zero;
Console.WriteLine("String account: {0}", names[0].Length);
int ret = Win32Sec.LsaLookupNames2(lsaHandle, 0, 1, names, ref tdom, ref tsids);
if (ret != 0)
throw new Win32Exception(Win32Sec.LsaNtStatusToWinError(ret));
lts = (LSA_TRANSLATED_SID2)Marshal.PtrToStructure(tsids,
typeof(LSA_TRANSLATED_SID2));
Win32Sec.LsaFreeMemory(tsids);
Win32Sec.LsaFreeMemory(tdom);
return lts.Sid;
}
static LSA_UNICODE_STRING InitLsaString(string s)
{
// Unicode strings max. 32KB
if (s.Length > 0x7ffe)
throw new ArgumentException("String too long");
LSA_UNICODE_STRING lus = new LSA_UNICODE_STRING();
lus.Buffer = s;
lus.Length = (ushort)(s.Length * sizeof(char));
lus.MaximumLength = (ushort)(lus.Length + sizeof(char));
return lus;
}
}
public class LsaWrapperCaller
{
public static void AddPrivileges(string account, string privilege)
{
using (LsaWrapper lsaWrapper = new LsaWrapper())
{
lsaWrapper.AddPrivileges(account, privilege);
}
}
}
}
'@
[MyLsaWrapper.LsaWrapperCaller]::AddPrivileges("GitLab$Runner", "SeServiceLogonRight")

+ 28
- 0
tools/register_runner.ps1 View File

@ -0,0 +1,28 @@
# register_runner.ps1
# Set-ExecutionPolicy Bypass -Scope Process
param (
[Parameter(Mandatory=$true)][string]$Runner = $(
Read-Host "Runner name (e.g. pEpSecRunner)" )
)
if ( -not $Runner.endswith("Runner") ) { $Runner = $Runner + "Runner" }
$ServSuffixCount = 1
$ServSuffix = ""
$Env:RUNNER_NAME = "GitLab$Runner$ServSuffix"
$PlainPassword = Get-Content -Path "$Env:UserProfile\Documents\GitLab$Runner$ServSuffix.pw.txt" -ea 0
# | Out-Null
$Password = ConvertTo-SecureString -String $PlainPassword -AsPlainText -Force
$User = Get-LocalUser "GitLab$Runner$ServSuffix" -ea 0
if (! $Env:CI_SERVER_URL) { $Env:CI_SERVER_URL = "https://gitlab.com/" }
if (! $Env:RUNNER_NAME) { $Env:RUNNER_NAME = $Env:COMPUTERNAME + "-" + $Env:USERNAME }
if (! $Env:REGISTRATION_TOKEN) { $Env:REGISTRATION_TOKEN = $Env:reg_token }
$Env:REGISTER_NON_INTERACTIVE = "true"
$UserCred = New-Object System.Management.Automation.PSCredential $User, $Password
Start-Process -FilePath "C:\Program Files\GitLabCI\gitlab-runner.exe" -ArgumentList ("register", "--executor", "windows-docker", "--config", "C:\Build\GitLab$Runner$ServSuffix\config.toml") -Credential $UserCred

Loading…
Cancel
Save