Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

# Copyright (c) 2014, Chris Church <chris@ninemoreminutes.com> 

# Copyright (c) 2017 Ansible Project 

# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) 

from __future__ import (absolute_import, division, print_function) 

__metaclass__ = type 

 

DOCUMENTATION = ''' 

name: powershell 

plugin_type: shell 

version_added: "" 

short_description: Windows Powershell 

description: 

- The only option when using 'winrm' as a connection plugin 

options: 

remote_tmp: 

description: 

- Temporary directory to use on targets when copying files to the host. 

default: '%TEMP%' 

ini: 

- section: powershell 

key: remote_tmp 

vars: 

- name: ansible_remote_tmp 

admin_users: 

description: 

- List of users to be expected to have admin privileges, this is unused 

in the PowerShell plugin 

type: list 

default: [] 

set_module_language: 

description: 

- Controls if we set the locale for moduels when executing on the 

target. 

- Windows only supports C(no) as an option. 

type: bool 

default: 'no' 

choices: 

- 'no' 

environment: 

description: 

- Dictionary of environment variables and their values to use when 

executing commands. 

type: dict 

default: {} 

''' 

# FIXME: admin_users and set_module_language don't belong here but must be set 

# so they don't failk when someone get_option('admin_users') on this plugin 

 

import base64 

import os 

import re 

import shlex 

 

from ansible.errors import AnsibleError 

from ansible.module_utils._text import to_text 

from ansible.plugins.shell import ShellBase 

 

 

_common_args = ['PowerShell', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted'] 

 

# Primarily for testing, allow explicitly specifying PowerShell version via 

# an environment variable. 

_powershell_version = os.environ.get('POWERSHELL_VERSION', None) 

64 ↛ 65line 64 didn't jump to line 65, because the condition on line 64 was never trueif _powershell_version: 

_common_args = ['PowerShell', '-Version', _powershell_version] + _common_args[1:] 

 

exec_wrapper = br''' 

begin { 

$DebugPreference = "Continue" 

$ErrorActionPreference = "Stop" 

Set-StrictMode -Version 2 

 

function ConvertTo-HashtableFromPsCustomObject ($myPsObject){ 

$output = @{}; 

$myPsObject | Get-Member -MemberType *Property | % { 

$val = $myPsObject.($_.name); 

If ($val -is [psobject]) { 

$val = ConvertTo-HashtableFromPsCustomObject $val 

} 

$output.($_.name) = $val 

} 

return $output; 

} 

# stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives 

# exec runspace, capture output, cleanup, return module output 

 

# NB: do not adjust the following line- it is replaced when doing non-streamed module output 

$json_raw = '' 

} 

process { 

$input_as_string = [string]$input 

 

$json_raw += $input_as_string 

} 

end { 

If (-not $json_raw) { 

Write-Error "no input given" -Category InvalidArgument 

} 

$payload = ConvertTo-HashtableFromPsCustomObject (ConvertFrom-Json $json_raw) 

 

# TODO: handle binary modules 

# TODO: handle persistence 

 

$min_os_version = [version]$payload.min_os_version 

if ($min_os_version -ne $null) { 

$actual_os_version = [System.Environment]::OSVersion.Version 

if ($actual_os_version -lt $min_os_version) { 

$msg = "This module cannot run on this OS as it requires a minimum version of $min_os_version, actual was $actual_os_version" 

Write-Output (ConvertTo-Json @{failed=$true;msg=$msg}) 

exit 1 

} 

} 

 

$min_ps_version = [version]$payload.min_ps_version 

if ($min_ps_version -ne $null) { 

$actual_ps_version = $PSVersionTable.PSVersion 

if ($actual_ps_version -lt $min_ps_version) { 

$msg = "This module cannot run as it requires a minimum PowerShell version of $min_ps_version, actual was $actual_ps_version" 

Write-Output (ConvertTo-Json @{failed=$true;msg=$msg}) 

exit 1 

} 

} 

 

$actions = $payload.actions 

 

# pop 0th action as entrypoint 

$entrypoint = $payload.($actions[0]) 

$payload.actions = $payload.actions[1..99] 

 

$entrypoint = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($entrypoint)) 

 

# load the current action entrypoint as a module custom object with a Run method 

$entrypoint = New-Module -ScriptBlock ([scriptblock]::Create($entrypoint)) -AsCustomObject 

 

Set-Variable -Scope global -Name complex_args -Value $payload["module_args"] | Out-Null 

 

# dynamically create/load modules 

ForEach ($mod in $payload.powershell_modules.GetEnumerator()) { 

$decoded_module = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($mod.Value)) 

New-Module -ScriptBlock ([scriptblock]::Create($decoded_module)) -Name $mod.Key | Import-Module -WarningAction SilentlyContinue | Out-Null 

} 

 

$output = $entrypoint.Run($payload) 

 

Write-Output $output 

} 

 

''' # end exec_wrapper 

 

leaf_exec = br''' 

Function Run($payload) { 

$entrypoint = $payload.module_entry 

 

$entrypoint = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($entrypoint)) 

 

$ps = [powershell]::Create() 

 

$ps.AddStatement().AddCommand("Set-Variable").AddParameters(@{Scope="global";Name="complex_args";Value=$payload.module_args}) | Out-Null 

$ps.AddCommand("Out-Null") | Out-Null 

 

# redefine Write-Host to dump to output instead of failing- lots of scripts use it 

$ps.AddStatement().AddScript("Function Write-Host(`$msg){ Write-Output `$msg }") | Out-Null 

 

ForEach ($env_kv in $payload.environment.GetEnumerator()) { 

$escaped_env_set = "`$env:{0} = '{1}'" -f $env_kv.Key,$env_kv.Value.Replace("'","''") 

$ps.AddStatement().AddScript($escaped_env_set) | Out-Null 

} 

 

# dynamically create/load modules 

ForEach ($mod in $payload.powershell_modules.GetEnumerator()) { 

$decoded_module = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($mod.Value)) 

$ps.AddStatement().AddCommand("New-Module").AddParameters(@{ScriptBlock=([scriptblock]::Create($decoded_module));Name=$mod.Key}) | Out-Null 

$ps.AddCommand("Import-Module").AddParameters(@{WarningAction="SilentlyContinue"}) | Out-Null 

$ps.AddCommand("Out-Null") | Out-Null 

} 

 

# force input encoding to preamble-free UTF8 so PS sub-processes (eg, Start-Job) don't blow up 

$ps.AddStatement().AddScript("[Console]::InputEncoding = New-Object Text.UTF8Encoding `$false") | Out-Null 

 

$ps.AddStatement().AddScript($entrypoint) | Out-Null 

 

$output = $ps.Invoke() 

 

$output 

 

# PS3 doesn't properly set HadErrors in many cases, inspect the error stream as a fallback 

If ($ps.HadErrors -or ($PSVersionTable.PSVersion.Major -lt 4 -and $ps.Streams.Error.Count -gt 0)) { 

[System.Console]::Error.WriteLine($($ps.Streams.Error | Out-String)) 

$exit_code = $ps.Runspace.SessionStateProxy.GetVariable("LASTEXITCODE") 

If(-not $exit_code) { 

$exit_code = 1 

} 

# need to use this instead of Exit keyword to prevent runspace from crashing with dynamic modules 

$host.SetShouldExit($exit_code) 

} 

} 

''' # end leaf_exec 

 

become_wrapper = br''' 

Set-StrictMode -Version 2 

$ErrorActionPreference = "Stop" 

 

$helper_def = @" 

using Microsoft.Win32.SafeHandles; 

using System; 

using System.Collections.Generic; 

using System.Diagnostics; 

using System.IO; 

using System.Linq; 

using System.Runtime.InteropServices; 

using System.Security.AccessControl; 

using System.Security.Principal; 

using System.Text; 

using System.Threading; 

 

namespace Ansible 

{ 

[StructLayout(LayoutKind.Sequential)] 

public class SECURITY_ATTRIBUTES 

{ 

public int nLength; 

public IntPtr lpSecurityDescriptor; 

public bool bInheritHandle = false; 

public SECURITY_ATTRIBUTES() 

{ 

nLength = Marshal.SizeOf(this); 

} 

} 

 

[StructLayout(LayoutKind.Sequential)] 

public class STARTUPINFO 

{ 

public Int32 cb; 

public IntPtr lpReserved; 

public IntPtr lpDesktop; 

public IntPtr lpTitle; 

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 28)] 

public byte[] _data1; 

public Int32 dwFlags; 

public Int16 wShowWindow; 

public Int16 cbReserved2; 

public IntPtr lpReserved2; 

public SafeFileHandle hStdInput; 

public SafeFileHandle hStdOutput; 

public SafeFileHandle hStdError; 

public STARTUPINFO() 

{ 

cb = Marshal.SizeOf(this); 

} 

} 

 

[StructLayout(LayoutKind.Sequential)] 

public class STARTUPINFOEX 

{ 

public STARTUPINFO startupInfo; 

public IntPtr lpAttributeList; 

public STARTUPINFOEX() 

{ 

startupInfo = new STARTUPINFO(); 

startupInfo.cb = Marshal.SizeOf(this); 

} 

} 

 

[StructLayout(LayoutKind.Sequential)] 

public struct PROCESS_INFORMATION 

{ 

public IntPtr hProcess; 

public IntPtr hThread; 

public int dwProcessId; 

public int dwThreadId; 

} 

 

[StructLayout(LayoutKind.Sequential)] 

public struct SID_AND_ATTRIBUTES 

{ 

public IntPtr Sid; 

public int Attributes; 

} 

 

public struct TOKEN_USER 

{ 

public SID_AND_ATTRIBUTES User; 

} 

 

[StructLayout(LayoutKind.Sequential)] 

public struct JOBOBJECT_BASIC_LIMIT_INFORMATION 

{ 

public UInt64 PerProcessUserTimeLimit; 

public UInt64 PerJobUserTimeLimit; 

public LimitFlags LimitFlags; 

public UIntPtr MinimumWorkingSetSize; 

public UIntPtr MaximumWorkingSetSize; 

public UInt32 ActiveProcessLimit; 

public UIntPtr Affinity; 

public UInt32 PriorityClass; 

public UInt32 SchedulingClass; 

} 

 

[StructLayout(LayoutKind.Sequential)] 

public class JOBOBJECT_EXTENDED_LIMIT_INFORMATION 

{ 

public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation = new JOBOBJECT_BASIC_LIMIT_INFORMATION(); 

[MarshalAs(UnmanagedType.ByValArray, SizeConst=48)] 

public byte[] IO_COUNTERS_BLOB; 

[MarshalAs(UnmanagedType.ByValArray, SizeConst=4)] 

public UIntPtr[] LIMIT_BLOB; 

} 

 

[Flags] 

public enum StartupInfoFlags : uint 

{ 

USESTDHANDLES = 0x00000100 

} 

 

[Flags] 

public enum CreationFlags : uint 

{ 

CREATE_BREAKAWAY_FROM_JOB = 0x01000000, 

CREATE_DEFAULT_ERROR_MODE = 0x04000000, 

CREATE_NEW_CONSOLE = 0x00000010, 

CREATE_SUSPENDED = 0x00000004, 

CREATE_UNICODE_ENVIRONMENT = 0x00000400, 

EXTENDED_STARTUPINFO_PRESENT = 0x00080000 

} 

 

public enum HandleFlags : uint 

{ 

None = 0, 

INHERIT = 1 

} 

 

[Flags] 

public enum LogonFlags 

{ 

LOGON_WITH_PROFILE = 0x00000001, 

LOGON_NETCREDENTIALS_ONLY = 0x00000002 

} 

 

public enum LogonType 

{ 

LOGON32_LOGON_INTERACTIVE = 2, 

LOGON32_LOGON_NETWORK = 3, 

LOGON32_LOGON_BATCH = 4, 

LOGON32_LOGON_SERVICE = 5, 

LOGON32_LOGON_UNLOCK = 7, 

LOGON32_LOGON_NETWORK_CLEARTEXT = 8, 

LOGON32_LOGON_NEW_CREDENTIALS = 9 

} 

 

public enum LogonProvider 

{ 

LOGON32_PROVIDER_DEFAULT = 0, 

} 

 

public enum TokenInformationClass 

{ 

TokenUser = 1, 

TokenType = 8, 

TokenImpersonationLevel = 9, 

TokenElevationType = 18, 

TokenLinkedToken = 19, 

} 

 

public enum TokenElevationType 

{ 

TokenElevationTypeDefault = 1, 

TokenElevationTypeFull, 

TokenElevationTypeLimited 

} 

 

[Flags] 

public enum ProcessAccessFlags : uint 

{ 

PROCESS_QUERY_INFORMATION = 0x00000400, 

} 

 

public enum SECURITY_IMPERSONATION_LEVEL 

{ 

SecurityImpersonation, 

} 

 

public enum TOKEN_TYPE 

{ 

TokenPrimary = 1, 

TokenImpersonation 

} 

 

enum JobObjectInfoType 

{ 

ExtendedLimitInformation = 9, 

} 

 

[Flags] 

enum ThreadAccessRights : uint 

{ 

SUSPEND_RESUME = 0x0002 

} 

 

[Flags] 

public enum LimitFlags : uint 

{ 

JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800, 

JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000 

} 

 

class NativeWaitHandle : WaitHandle 

{ 

public NativeWaitHandle(IntPtr handle) 

{ 

this.SafeWaitHandle = new SafeWaitHandle(handle, false); 

} 

} 

 

public class Win32Exception : System.ComponentModel.Win32Exception 

{ 

private string _msg; 

public Win32Exception(string message) : this(Marshal.GetLastWin32Error(), message) { } 

public Win32Exception(int errorCode, string message) : base(errorCode) 

{ 

_msg = String.Format("{0} ({1}, Win32ErrorCode {2})", message, base.Message, errorCode); 

} 

public override string Message { get { return _msg; } } 

public static explicit operator Win32Exception(string message) { return new Win32Exception(message); } 

} 

 

public class CommandResult 

{ 

public string StandardOut { get; internal set; } 

public string StandardError { get; internal set; } 

public uint ExitCode { get; internal set; } 

} 

 

public class Job : IDisposable 

{ 

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 

private static extern IntPtr CreateJobObject( 

IntPtr lpJobAttributes, 

string lpName); 

 

[DllImport("kernel32.dll", SetLastError = true)] 

private static extern bool SetInformationJobObject( 

IntPtr hJob, 

JobObjectInfoType JobObjectInfoClass, 

JOBOBJECT_EXTENDED_LIMIT_INFORMATION lpJobObjectInfo, 

int cbJobObjectInfoLength); 

 

[DllImport("kernel32.dll", SetLastError = true)] 

private static extern bool AssignProcessToJobObject( 

IntPtr hJob, 

IntPtr hProcess); 

 

[DllImport("kernel32.dll")] 

private static extern bool CloseHandle( 

IntPtr hObject); 

 

private IntPtr handle; 

 

public Job() 

{ 

handle = CreateJobObject(IntPtr.Zero, null); 

if (handle == IntPtr.Zero) 

throw new Win32Exception("CreateJobObject() failed"); 

 

JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedJobInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION(); 

// on OSs that support nested jobs, one of the jobs must allow breakaway for async to work properly under WinRM 

extendedJobInfo.BasicLimitInformation.LimitFlags = LimitFlags.JOB_OBJECT_LIMIT_BREAKAWAY_OK | LimitFlags.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; 

 

if (!SetInformationJobObject(handle, JobObjectInfoType.ExtendedLimitInformation, extendedJobInfo, Marshal.SizeOf(extendedJobInfo))) 

throw new Win32Exception("SetInformationJobObject() failed"); 

} 

 

public void AssignProcess(IntPtr processHandle) 

{ 

if (!AssignProcessToJobObject(handle, processHandle)) 

throw new Win32Exception("AssignProcessToJobObject() failed"); 

} 

 

public void Dispose() 

{ 

if (handle != IntPtr.Zero) 

{ 

CloseHandle(handle); 

handle = IntPtr.Zero; 

} 

 

GC.SuppressFinalize(this); 

} 

} 

 

public class BecomeUtil 

{ 

[DllImport("advapi32.dll", SetLastError = true)] 

private static extern bool LogonUser( 

string lpszUsername, 

string lpszDomain, 

string lpszPassword, 

LogonType dwLogonType, 

LogonProvider dwLogonProvider, 

out IntPtr phToken); 

 

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 

private static extern bool CreateProcessWithTokenW( 

IntPtr hToken, 

LogonFlags dwLogonFlags, 

[MarshalAs(UnmanagedType.LPTStr)] 

string lpApplicationName, 

StringBuilder lpCommandLine, 

CreationFlags dwCreationFlags, 

IntPtr lpEnvironment, 

[MarshalAs(UnmanagedType.LPTStr)] 

string lpCurrentDirectory, 

STARTUPINFOEX lpStartupInfo, 

out PROCESS_INFORMATION lpProcessInformation); 

 

[DllImport("kernel32.dll")] 

private static extern bool CreatePipe( 

out SafeFileHandle hReadPipe, 

out SafeFileHandle hWritePipe, 

SECURITY_ATTRIBUTES lpPipeAttributes, 

uint nSize); 

 

[DllImport("kernel32.dll", SetLastError = true)] 

private static extern bool SetHandleInformation( 

SafeFileHandle hObject, 

HandleFlags dwMask, 

int dwFlags); 

 

[DllImport("kernel32.dll", SetLastError = true)] 

private static extern bool GetExitCodeProcess( 

IntPtr hProcess, 

out uint lpExitCode); 

 

[DllImport("kernel32.dll", SetLastError = true)] 

private static extern bool CloseHandle( 

IntPtr hObject); 

 

[DllImport("user32.dll", SetLastError = true)] 

private static extern IntPtr GetProcessWindowStation(); 

 

[DllImport("user32.dll", SetLastError = true)] 

private static extern IntPtr GetThreadDesktop( 

int dwThreadId); 

 

[DllImport("kernel32.dll", SetLastError = true)] 

private static extern int GetCurrentThreadId(); 

 

[DllImport("advapi32.dll", SetLastError = true)] 

private static extern bool GetTokenInformation( 

IntPtr TokenHandle, 

TokenInformationClass TokenInformationClass, 

IntPtr TokenInformation, 

uint TokenInformationLength, 

out uint ReturnLength); 

 

[DllImport("psapi.dll", SetLastError = true)] 

private static extern bool EnumProcesses( 

[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U4)] 

[In][Out] IntPtr[] processIds, 

uint cb, 

[MarshalAs(UnmanagedType.U4)] 

out uint pBytesReturned); 

 

[DllImport("kernel32.dll", SetLastError = true)] 

private static extern IntPtr OpenProcess( 

ProcessAccessFlags processAccess, 

bool bInheritHandle, 

IntPtr processId); 

 

[DllImport("advapi32.dll", SetLastError = true)] 

private static extern bool OpenProcessToken( 

IntPtr ProcessHandle, 

TokenAccessLevels DesiredAccess, 

out IntPtr TokenHandle); 

 

[DllImport("advapi32.dll", SetLastError = true)] 

private static extern bool ConvertSidToStringSidW( 

IntPtr pSID, 

[MarshalAs(UnmanagedType.LPTStr)] 

out string StringSid); 

 

[DllImport("advapi32", SetLastError = true)] 

private static extern bool DuplicateTokenEx( 

IntPtr hExistingToken, 

TokenAccessLevels dwDesiredAccess, 

IntPtr lpTokenAttributes, 

SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, 

TOKEN_TYPE TokenType, 

out IntPtr phNewToken); 

 

[DllImport("advapi32.dll", SetLastError = true)] 

private static extern bool ImpersonateLoggedOnUser( 

IntPtr hToken); 

 

[DllImport("advapi32.dll", SetLastError = true)] 

private static extern bool RevertToSelf(); 

 

[DllImport("kernel32.dll", SetLastError = true)] 

private static extern SafeFileHandle OpenThread( 

ThreadAccessRights dwDesiredAccess, 

bool bInheritHandle, 

int dwThreadId); 

 

[DllImport("kernel32.dll", SetLastError = true)] 

private static extern int ResumeThread( 

SafeHandle hThread); 

 

public static CommandResult RunAsUser(string username, string password, string lpCommandLine, 

string lpCurrentDirectory, string stdinInput, LogonFlags logonFlags, LogonType logonType) 

{ 

SecurityIdentifier account = null; 

if (logonType != LogonType.LOGON32_LOGON_NEW_CREDENTIALS) 

{ 

account = GetBecomeSid(username); 

} 

 

STARTUPINFOEX si = new STARTUPINFOEX(); 

si.startupInfo.dwFlags = (int)StartupInfoFlags.USESTDHANDLES; 

 

SECURITY_ATTRIBUTES pipesec = new SECURITY_ATTRIBUTES(); 

pipesec.bInheritHandle = true; 

 

// Create the stdout, stderr and stdin pipes used in the process and add to the startupInfo 

SafeFileHandle stdout_read, stdout_write, stderr_read, stderr_write, stdin_read, stdin_write; 

if (!CreatePipe(out stdout_read, out stdout_write, pipesec, 0)) 

throw new Win32Exception("STDOUT pipe setup failed"); 

if (!SetHandleInformation(stdout_read, HandleFlags.INHERIT, 0)) 

throw new Win32Exception("STDOUT pipe handle setup failed"); 

 

if (!CreatePipe(out stderr_read, out stderr_write, pipesec, 0)) 

throw new Win32Exception("STDERR pipe setup failed"); 

if (!SetHandleInformation(stderr_read, HandleFlags.INHERIT, 0)) 

throw new Win32Exception("STDERR pipe handle setup failed"); 

 

if (!CreatePipe(out stdin_read, out stdin_write, pipesec, 0)) 

throw new Win32Exception("STDIN pipe setup failed"); 

if (!SetHandleInformation(stdin_write, HandleFlags.INHERIT, 0)) 

throw new Win32Exception("STDIN pipe handle setup failed"); 

 

si.startupInfo.hStdOutput = stdout_write; 

si.startupInfo.hStdError = stderr_write; 

si.startupInfo.hStdInput = stdin_read; 

 

// Setup the stdin buffer 

UTF8Encoding utf8_encoding = new UTF8Encoding(false); 

FileStream stdin_fs = new FileStream(stdin_write, FileAccess.Write, 32768); 

StreamWriter stdin = new StreamWriter(stdin_fs, utf8_encoding, 32768); 

 

// Create the environment block if set 

IntPtr lpEnvironment = IntPtr.Zero; 

 

// To support async + become, we have to do some job magic later, which requires both breakaway and starting suspended 

CreationFlags startup_flags = CreationFlags.CREATE_UNICODE_ENVIRONMENT | CreationFlags.CREATE_BREAKAWAY_FROM_JOB | CreationFlags.CREATE_SUSPENDED; 

 

PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); 

 

// Get the user tokens to try running processes with 

List<IntPtr> tokens = GetUserTokens(account, username, password, logonType); 

 

bool launch_success = false; 

foreach (IntPtr token in tokens) 

{ 

if (CreateProcessWithTokenW( 

token, 

logonFlags, 

null, 

new StringBuilder(lpCommandLine), 

startup_flags, 

lpEnvironment, 

lpCurrentDirectory, 

si, 

out pi)) 

{ 

launch_success = true; 

break; 

} 

} 

 

if (!launch_success) 

throw new Win32Exception("Failed to start become process"); 

 

// If 2012/8+ OS, create new job with JOB_OBJECT_LIMIT_BREAKAWAY_OK 

// so that async can work 

Job job = null; 

if (Environment.OSVersion.Version >= new Version("6.2")) 

{ 

job = new Job(); 

job.AssignProcess(pi.hProcess); 

} 

ResumeProcessById(pi.dwProcessId); 

 

CommandResult result = new CommandResult(); 

try 

{ 

// Setup the output buffers and get stdout/stderr 

FileStream stdout_fs = new FileStream(stdout_read, FileAccess.Read, 4096); 

StreamReader stdout = new StreamReader(stdout_fs, utf8_encoding, true, 4096); 

stdout_write.Close(); 

 

FileStream stderr_fs = new FileStream(stderr_read, FileAccess.Read, 4096); 

StreamReader stderr = new StreamReader(stderr_fs, utf8_encoding, true, 4096); 

stderr_write.Close(); 

 

stdin.WriteLine(stdinInput); 

stdin.Close(); 

 

string stdout_str, stderr_str = null; 

GetProcessOutput(stdout, stderr, out stdout_str, out stderr_str); 

UInt32 rc = GetProcessExitCode(pi.hProcess); 

 

result.StandardOut = stdout_str; 

result.StandardError = stderr_str; 

result.ExitCode = rc; 

} 

finally 

{ 

if (job != null) 

job.Dispose(); 

} 

 

return result; 

} 

 

private static SecurityIdentifier GetBecomeSid(string username) 

{ 

NTAccount account = new NTAccount(username); 

try 

{ 

SecurityIdentifier security_identifier = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier)); 

return security_identifier; 

} 

catch (IdentityNotMappedException ex) 

{ 

throw new Exception(String.Format("Unable to find become user {0}: {1}", username, ex.Message)); 

} 

} 

 

private static List<IntPtr> GetUserTokens(SecurityIdentifier account, string username, string password, LogonType logonType) 

{ 

List<IntPtr> tokens = new List<IntPtr>(); 

List<String> service_sids = new List<String>() 

{ 

"S-1-5-18", // NT AUTHORITY\SYSTEM 

"S-1-5-19", // NT AUTHORITY\LocalService 

"S-1-5-20" // NT AUTHORITY\NetworkService 

}; 

 

IntPtr hSystemToken = IntPtr.Zero; 

string account_sid = ""; 

if (logonType != LogonType.LOGON32_LOGON_NEW_CREDENTIALS) 

{ 

GrantAccessToWindowStationAndDesktop(account); 

// Try to get SYSTEM token handle so we can impersonate to get full admin token 

hSystemToken = GetSystemUserHandle(); 

account_sid = account.ToString(); 

} 

bool impersonated = false; 

 

try 

{ 

IntPtr hSystemTokenDup = IntPtr.Zero; 

if (hSystemToken == IntPtr.Zero && service_sids.Contains(account_sid)) 

{ 

// We need the SYSTEM token if we want to become one of those accounts, fail here 

throw new Win32Exception("Failed to get token for NT AUTHORITY\\SYSTEM"); 

} 

else if (hSystemToken != IntPtr.Zero) 

{ 

// We have the token, need to duplicate and impersonate 

bool dupResult = DuplicateTokenEx( 

hSystemToken, 

TokenAccessLevels.MaximumAllowed, 

IntPtr.Zero, 

SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, 

TOKEN_TYPE.TokenPrimary, 

out hSystemTokenDup); 

int lastError = Marshal.GetLastWin32Error(); 

CloseHandle(hSystemToken); 

 

if (!dupResult && service_sids.Contains(account_sid)) 

throw new Win32Exception(lastError, "Failed to duplicate token for NT AUTHORITY\\SYSTEM"); 

else if (dupResult && account_sid != "S-1-5-18") 

{ 

if (ImpersonateLoggedOnUser(hSystemTokenDup)) 

impersonated = true; 

else if (service_sids.Contains(account_sid)) 

throw new Win32Exception("Failed to impersonate as SYSTEM account"); 

} 

// If SYSTEM impersonation failed but we're trying to become a regular user, just proceed; 

// might get a limited token in UAC-enabled cases, but better than nothing... 

} 

 

string domain = null; 

 

if (service_sids.Contains(account_sid)) 

{ 

// We're using a well-known service account, do a service logon instead of the actual flag set 

logonType = LogonType.LOGON32_LOGON_SERVICE; 

domain = "NT AUTHORITY"; 

password = null; 

switch (account_sid) 

{ 

case "S-1-5-18": 

tokens.Add(hSystemTokenDup); 

return tokens; 

case "S-1-5-19": 

username = "LocalService"; 

break; 

case "S-1-5-20": 

username = "NetworkService"; 

break; 

} 

} 

else 

{ 

// We are trying to become a local or domain account 

if (username.Contains(@"\")) 

{ 

var user_split = username.Split(Convert.ToChar(@"\")); 

domain = user_split[0]; 

username = user_split[1]; 

} 

else if (username.Contains("@")) 

domain = null; 

else 

domain = "."; 

} 

 

IntPtr hToken = IntPtr.Zero; 

if (!LogonUser( 

username, 

domain, 

password, 

logonType, 

LogonProvider.LOGON32_PROVIDER_DEFAULT, 

out hToken)) 

{ 

throw new Win32Exception("LogonUser failed"); 

} 

 

if (!service_sids.Contains(account_sid)) 

{ 

// Try and get the elevated token for local/domain account 

IntPtr hTokenElevated = GetElevatedToken(hToken); 

tokens.Add(hTokenElevated); 

} 

 

// add the original token as a fallback 

tokens.Add(hToken); 

} 

finally 

{ 

if (impersonated) 

RevertToSelf(); 

} 

 

return tokens; 

} 

 

private static IntPtr GetSystemUserHandle() 

{ 

uint array_byte_size = 1024 * sizeof(uint); 

IntPtr[] pids = new IntPtr[1024]; 

uint bytes_copied; 

 

if (!EnumProcesses(pids, array_byte_size, out bytes_copied)) 

{ 

throw new Win32Exception("Failed to enumerate processes"); 

} 

// TODO: Handle if bytes_copied is larger than the array size and rerun EnumProcesses with larger array 

uint num_processes = bytes_copied / sizeof(uint); 

 

for (uint i = 0; i < num_processes; i++) 

{ 

IntPtr hProcess = OpenProcess(ProcessAccessFlags.PROCESS_QUERY_INFORMATION, false, pids[i]); 

if (hProcess != IntPtr.Zero) 

{ 

IntPtr hToken = IntPtr.Zero; 

// According to CreateProcessWithTokenW we require a token with 

// TOKEN_QUERY, TOKEN_DUPLICATE and TOKEN_ASSIGN_PRIMARY 

// Also add in TOKEN_IMPERSONATE so we can get an impersontated token 

TokenAccessLevels desired_access = TokenAccessLevels.Query | 

TokenAccessLevels.Duplicate | 

TokenAccessLevels.AssignPrimary | 

TokenAccessLevels.Impersonate; 

 

if (OpenProcessToken(hProcess, desired_access, out hToken)) 

{ 

string sid = GetTokenUserSID(hToken); 

if (sid == "S-1-5-18") 

{ 

CloseHandle(hProcess); 

return hToken; 

} 

} 

 

CloseHandle(hToken); 

} 

CloseHandle(hProcess); 

} 

 

return IntPtr.Zero; 

} 

 

private static string GetTokenUserSID(IntPtr hToken) 

{ 

uint token_length; 

string sid; 

 

if (!GetTokenInformation(hToken, TokenInformationClass.TokenUser, IntPtr.Zero, 0, out token_length)) 

{ 

int last_err = Marshal.GetLastWin32Error(); 

if (last_err != 122) // ERROR_INSUFFICIENT_BUFFER 

throw new Win32Exception(last_err, "Failed to get TokenUser length"); 

} 

 

IntPtr token_information = Marshal.AllocHGlobal((int)token_length); 

try 

{ 

if (!GetTokenInformation(hToken, TokenInformationClass.TokenUser, token_information, token_length, out token_length)) 

throw new Win32Exception("Failed to get TokenUser information"); 

 

TOKEN_USER token_user = (TOKEN_USER)Marshal.PtrToStructure(token_information, typeof(TOKEN_USER)); 

 

if (!ConvertSidToStringSidW(token_user.User.Sid, out sid)) 

throw new Win32Exception("Failed to get user SID"); 

} 

finally 

{ 

Marshal.FreeHGlobal(token_information); 

} 

 

return sid; 

} 

 

private static void GetProcessOutput(StreamReader stdoutStream, StreamReader stderrStream, out string stdout, out string stderr) 

{ 

var sowait = new EventWaitHandle(false, EventResetMode.ManualReset); 

var sewait = new EventWaitHandle(false, EventResetMode.ManualReset); 

string so = null, se = null; 

ThreadPool.QueueUserWorkItem((s) => 

{ 

so = stdoutStream.ReadToEnd(); 

sowait.Set(); 

}); 

ThreadPool.QueueUserWorkItem((s) => 

{ 

se = stderrStream.ReadToEnd(); 

sewait.Set(); 

}); 

foreach (var wh in new WaitHandle[] { sowait, sewait }) 

wh.WaitOne(); 

stdout = so; 

stderr = se; 

} 

 

private static uint GetProcessExitCode(IntPtr processHandle) 

{ 

new NativeWaitHandle(processHandle).WaitOne(); 

uint exitCode; 

if (!GetExitCodeProcess(processHandle, out exitCode)) 

throw new Win32Exception("Error getting process exit code"); 

return exitCode; 

} 

 

private static IntPtr GetElevatedToken(IntPtr hToken) 

{ 

uint requestedLength; 

 

IntPtr pTokenInfo = Marshal.AllocHGlobal(sizeof(int)); 

 

try 

{ 

if (!GetTokenInformation(hToken, TokenInformationClass.TokenElevationType, pTokenInfo, sizeof(int), out requestedLength)) 

throw new Win32Exception("Unable to get TokenElevationType"); 

 

var tet = (TokenElevationType)Marshal.ReadInt32(pTokenInfo); 

 

// we already have the best token we can get, just use it 

if (tet != TokenElevationType.TokenElevationTypeLimited) 

return hToken; 

 

GetTokenInformation(hToken, TokenInformationClass.TokenLinkedToken, IntPtr.Zero, 0, out requestedLength); 

 

IntPtr pLinkedToken = Marshal.AllocHGlobal((int)requestedLength); 

 

if (!GetTokenInformation(hToken, TokenInformationClass.TokenLinkedToken, pLinkedToken, requestedLength, out requestedLength)) 

throw new Win32Exception("Unable to get linked token"); 

 

IntPtr linkedToken = Marshal.ReadIntPtr(pLinkedToken); 

 

Marshal.FreeHGlobal(pLinkedToken); 

 

return linkedToken; 

} 

finally 

{ 

Marshal.FreeHGlobal(pTokenInfo); 

} 

} 

 

private static void GrantAccessToWindowStationAndDesktop(SecurityIdentifier account) 

{ 

const int WindowStationAllAccess = 0x000f037f; 

GrantAccess(account, GetProcessWindowStation(), WindowStationAllAccess); 

const int DesktopRightsAllAccess = 0x000f01ff; 

GrantAccess(account, GetThreadDesktop(GetCurrentThreadId()), DesktopRightsAllAccess); 

} 

 

private static void GrantAccess(SecurityIdentifier account, IntPtr handle, int accessMask) 

{ 

SafeHandle safeHandle = new NoopSafeHandle(handle); 

GenericSecurity security = 

new GenericSecurity(false, ResourceType.WindowObject, safeHandle, AccessControlSections.Access); 

security.AddAccessRule( 

new GenericAccessRule(account, accessMask, AccessControlType.Allow)); 

security.Persist(safeHandle, AccessControlSections.Access); 

} 

 

private static void ResumeThreadById(int threadId) 

{ 

var threadHandle = OpenThread(ThreadAccessRights.SUSPEND_RESUME, false, threadId); 

if (threadHandle.IsInvalid) 

throw new Win32Exception(String.Format("Thread ID {0} is invalid", threadId)); 

 

try 

{ 

if (ResumeThread(threadHandle) == -1) 

throw new Win32Exception(String.Format("Thread ID {0} cannot be resumed", threadId)); 

} 

finally 

{ 

threadHandle.Dispose(); 

} 

} 

 

private static void ResumeProcessById(int pid) 

{ 

var proc = Process.GetProcessById(pid); 

 

// wait for at least one suspended thread in the process (this handles possible slow startup race where 

// primary thread of created-suspended process has not yet become runnable) 

var retryCount = 0; 

while (!proc.Threads.OfType<ProcessThread>().Any(t => t.ThreadState == System.Diagnostics.ThreadState.Wait && 

t.WaitReason == ThreadWaitReason.Suspended)) 

{ 

proc.Refresh(); 

Thread.Sleep(50); 

if (retryCount > 100) 

throw new InvalidOperationException(String.Format("No threads were suspended in target PID {0} after 5s", pid)); 

} 

 

foreach (var thread in proc.Threads.OfType<ProcessThread>().Where(t => t.ThreadState == System.Diagnostics.ThreadState.Wait && 

t.WaitReason == ThreadWaitReason.Suspended)) 

ResumeThreadById(thread.Id); 

} 

 

private class GenericSecurity : NativeObjectSecurity 

{ 

public GenericSecurity(bool isContainer, ResourceType resType, SafeHandle objectHandle, AccessControlSections sectionsRequested) 

: base(isContainer, resType, objectHandle, sectionsRequested) { } 

public new void Persist(SafeHandle handle, AccessControlSections includeSections) { base.Persist(handle, includeSections); } 

public new void AddAccessRule(AccessRule rule) { base.AddAccessRule(rule); } 

public override Type AccessRightType { get { throw new NotImplementedException(); } } 

public override AccessRule AccessRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited, 

InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) 

{ throw new NotImplementedException(); } 

public override Type AccessRuleType { get { return typeof(AccessRule); } } 

public override AuditRule AuditRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited, 

InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) 

{ throw new NotImplementedException(); } 

public override Type AuditRuleType { get { return typeof(AuditRule); } } 

} 

 

private class NoopSafeHandle : SafeHandle 

{ 

public NoopSafeHandle(IntPtr handle) : base(handle, false) { } 

public override bool IsInvalid { get { return false; } } 

protected override bool ReleaseHandle() { return true; } 

} 

 

private class GenericAccessRule : AccessRule 

{ 

public GenericAccessRule(IdentityReference identity, int accessMask, AccessControlType type) : 

base(identity, accessMask, false, InheritanceFlags.None, PropagationFlags.None, type) 

{ } 

} 

} 

} 

"@ 

 

$exec_wrapper = { 

Set-StrictMode -Version 2 

$DebugPreference = "Continue" 

$ErrorActionPreference = "Stop" 

 

Function ConvertTo-HashtableFromPsCustomObject($myPsObject) { 

$output = @{} 

$myPsObject | Get-Member -MemberType *Property | % { 

$val = $myPsObject.($_.name) 

if ($val -is [psobject]) { 

$val = ConvertTo-HashtableFromPsCustomObject -myPsObject $val 

} 

$output.($_.name) = $val 

} 

return $output 

} 

 

# stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives 

# exec runspace, capture output, cleanup, return module output 

 

$json_raw = [System.Console]::In.ReadToEnd() 

 

If (-not $json_raw) { 

Write-Error "no input given" -Category InvalidArgument 

} 

 

$payload = ConvertTo-HashtableFromPsCustomObject -myPsObject (ConvertFrom-Json $json_raw) 

 

# TODO: handle binary modules 

# TODO: handle persistence 

 

$actions = $payload.actions 

 

# pop 0th action as entrypoint 

$entrypoint = $payload.($actions[0]) 

$payload.actions = $payload.actions[1..99] 

 

$entrypoint = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($entrypoint)) 

 

# load the current action entrypoint as a module custom object with a Run method 

$entrypoint = New-Module -ScriptBlock ([scriptblock]::Create($entrypoint)) -AsCustomObject 

 

Set-Variable -Scope global -Name complex_args -Value $payload["module_args"] | Out-Null 

 

# dynamically create/load modules 

ForEach ($mod in $payload.powershell_modules.GetEnumerator()) { 

$decoded_module = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($mod.Value)) 

New-Module -ScriptBlock ([scriptblock]::Create($decoded_module)) -Name $mod.Key | Import-Module -WarningAction SilentlyContinue | Out-Null 

} 

 

$output = $entrypoint.Run($payload) 

 

Write-Output $output 

} # end exec_wrapper 

 

Function Dump-Error ($excep) { 

$eo = @{failed=$true} 

 

$eo.msg = $excep.Exception.Message 

$eo.exception = $excep | Out-String 

$host.SetShouldExit(1) 

 

$eo | ConvertTo-Json -Depth 10 -Compress 

} 

 

Function Parse-EnumValue($enum, $flag_type, $value, $prefix) { 

$raw_enum_value = "$prefix$($value.ToUpper())" 

try { 

$enum_value = [Enum]::Parse($enum, $raw_enum_value) 

} catch [System.ArgumentException] { 

$valid_options = [Enum]::GetNames($enum) | ForEach-Object { $_.Substring($prefix.Length).ToLower() } 

throw "become_flags $flag_type value '$value' is not valid, valid values are: $($valid_options -join ", ")" 

} 

return $enum_value 

} 

 

Function Parse-BecomeFlags($flags) { 

$logon_type = [Ansible.LogonType]::LOGON32_LOGON_INTERACTIVE 

$logon_flags = [Ansible.LogonFlags]::LOGON_WITH_PROFILE 

 

if ($flags -eq $null -or $flags -eq "") { 

$flag_split = @() 

} elseif ($flags -is [string]) { 

$flag_split = $flags.Split(" ") 

} else { 

throw "become_flags must be a string, was $($flags.GetType())" 

} 

 

foreach ($flag in $flag_split) { 

$split = $flag.Split("=") 

if ($split.Count -ne 2) { 

throw "become_flags entry '$flag' is in an invalid format, must be a key=value pair" 

} 

$flag_key = $split[0] 

$flag_value = $split[1] 

if ($flag_key -eq "logon_type") { 

$enum_details = @{ 

enum = [Ansible.LogonType] 

flag_type = $flag_key 

value = $flag_value 

prefix = "LOGON32_LOGON_" 

} 

$logon_type = Parse-EnumValue @enum_details 

} elseif ($flag_key -eq "logon_flags") { 

$logon_flag_values = $flag_value.Split(",") 

$logon_flags = 0 -as [Ansible.LogonFlags] 

foreach ($logon_flag_value in $logon_flag_values) { 

if ($logon_flag_value -eq "") { 

continue 

} 

$enum_details = @{ 

enum = [Ansible.LogonFlags] 

flag_type = $flag_key 

value = $logon_flag_value 

prefix = "LOGON_" 

} 

$logon_flag = Parse-EnumValue @enum_details 

$logon_flags = $logon_flags -bor $logon_flag 

} 

} else { 

throw "become_flags key '$flag_key' is not a valid runas flag, must be 'logon_type' or 'logon_flags'" 

} 

} 

 

return $logon_type, [Ansible.LogonFlags]$logon_flags 

} 

 

Function Run($payload) { 

# NB: action popping handled inside subprocess wrapper 

 

Add-Type -TypeDefinition $helper_def -Debug:$false 

 

$username = $payload.become_user 

$password = $payload.become_password 

try { 

$logon_type, $logon_flags = Parse-BecomeFlags -flags $payload.become_flags 

} catch { 

Dump-Error -excep $_ 

return $null 

} 

 

# NB: CreateProcessWithTokenW commandline maxes out at 1024 chars, must bootstrap via filesystem 

$temp = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), [System.IO.Path]::GetRandomFileName() + ".ps1") 

$exec_wrapper.ToString() | Set-Content -Path $temp 

$rc = 0 

 

Try { 

# do not modify the ACL if the logon_type is LOGON32_LOGON_NEW_CREDENTIALS 

# as this results in the local execution running under the same user's token, 

# otherwise we need to allow (potentially unprivileges) the become user access 

# to the tempfile (NB: this likely won't work if traverse checking is enaabled). 

if ($logon_type -ne [Ansible.LogonType]::LOGON32_LOGON_NEW_CREDENTIALS) { 

$acl = Get-Acl -Path $temp 

 

Try { 

$acl.AddAccessRule($(New-Object System.Security.AccessControl.FileSystemAccessRule($username, "FullControl", "Allow"))) 

} Catch [System.Security.Principal.IdentityNotMappedException] { 

throw "become_user '$username' is not recognized on this host" 

} Catch { 

throw "failed to set ACL on temp become execution script: $($_.Exception.Message)" 

} 

Set-Acl -Path $temp -AclObject $acl | Out-Null 

} 

 

$payload_string = $payload | ConvertTo-Json -Depth 99 -Compress 

 

$lp_command_line = New-Object System.Text.StringBuilder @("powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -File $temp") 

$lp_current_directory = "$env:SystemRoot" 

 

$result = [Ansible.BecomeUtil]::RunAsUser($username, $password, $lp_command_line, $lp_current_directory, $payload_string, $logon_flags, $logon_type) 

$stdout = $result.StandardOut 

$stderr = $result.StandardError 

$rc = $result.ExitCode 

 

[Console]::Out.WriteLine($stdout.Trim()) 

[Console]::Error.WriteLine($stderr.Trim()) 

} Catch { 

$excep = $_ 

Dump-Error $excep 

} Finally { 

Remove-Item $temp -ErrorAction SilentlyContinue 

} 

$host.SetShouldExit($rc) 

} 

''' 

 

async_wrapper = br''' 

Set-StrictMode -Version 2 

$ErrorActionPreference = "Stop" 

 

# build exec_wrapper encoded command 

# start powershell with breakaway running exec_wrapper encodedcommand 

# stream payload to powershell with normal exec, but normal exec writes results to resultfile instead of stdout/stderr 

# return asyncresult to controller 

 

$exec_wrapper = { 

$DebugPreference = "Continue" 

$ErrorActionPreference = "Stop" 

Set-StrictMode -Version 2 

 

function ConvertTo-HashtableFromPsCustomObject ($myPsObject){ 

$output = @{}; 

$myPsObject | Get-Member -MemberType *Property | % { 

$val = $myPsObject.($_.name); 

If ($val -is [psobject]) { 

$val = ConvertTo-HashtableFromPsCustomObject $val 

} 

$output.($_.name) = $val 

} 

return $output; 

} 

# stream JSON including become_pw, ps_module_payload, bin_module_payload, become_payload, write_payload_path, preserve directives 

# exec runspace, capture output, cleanup, return module output 

 

$json_raw = [System.Console]::In.ReadToEnd() 

 

If (-not $json_raw) { 

Write-Error "no input given" -Category InvalidArgument 

} 

 

$payload = ConvertTo-HashtableFromPsCustomObject (ConvertFrom-Json $json_raw) 

 

# TODO: handle binary modules 

# TODO: handle persistence 

 

$actions = $payload.actions 

 

# pop 0th action as entrypoint 

$entrypoint = $payload.($actions[0]) 

$payload.actions = $payload.actions[1..99] 

 

$entrypoint = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($entrypoint)) 

 

# load the current action entrypoint as a module custom object with a Run method 

$entrypoint = New-Module -ScriptBlock ([scriptblock]::Create($entrypoint)) -AsCustomObject 

 

Set-Variable -Scope global -Name complex_args -Value $payload["module_args"] | Out-Null 

 

# dynamically create/load modules 

ForEach ($mod in $payload.powershell_modules.GetEnumerator()) { 

$decoded_module = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($mod.Value)) 

New-Module -ScriptBlock ([scriptblock]::Create($decoded_module)) -Name $mod.Key | Import-Module -WarningAction SilentlyContinue | Out-Null 

} 

 

$output = $entrypoint.Run($payload) 

 

Write-Output $output 

 

} # end exec_wrapper 

 

 

Function Run($payload) { 

# BEGIN Ansible.Async native type definition 

$native_process_util = @" 

using Microsoft.Win32.SafeHandles; 

using System; 

using System.ComponentModel; 

using System.Diagnostics; 

using System.IO; 

using System.Linq; 

using System.Runtime.InteropServices; 

using System.Text; 

using System.Threading; 

 

namespace Ansible.Async { 

 

public static class NativeProcessUtil 

{ 

[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode, BestFitMapping=false)] 

public static extern bool CreateProcess( 

[MarshalAs(UnmanagedType.LPTStr)] 

string lpApplicationName, 

StringBuilder lpCommandLine, 

IntPtr lpProcessAttributes, 

IntPtr lpThreadAttributes, 

bool bInheritHandles, 

uint dwCreationFlags, 

IntPtr lpEnvironment, 

[MarshalAs(UnmanagedType.LPTStr)] 

string lpCurrentDirectory, 

STARTUPINFOEX lpStartupInfo, 

out PROCESS_INFORMATION lpProcessInformation); 

 

[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] 

public static extern uint SearchPath ( 

string lpPath, 

string lpFileName, 

string lpExtension, 

int nBufferLength, 

[MarshalAs (UnmanagedType.LPTStr)] 

StringBuilder lpBuffer, 

out IntPtr lpFilePart); 

 

[DllImport("kernel32.dll")] 

public static extern bool CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize); 

 

[DllImport("kernel32.dll", SetLastError=true)] 

public static extern IntPtr GetStdHandle(StandardHandleValues nStdHandle); 

 

[DllImport("kernel32.dll", SetLastError=true)] 

public static extern bool SetHandleInformation(IntPtr hObject, HandleFlags dwMask, int dwFlags); 

 

[DllImport("kernel32.dll", SetLastError=true)] 

public static extern bool InitializeProcThreadAttributeList(IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref int lpSize); 

 

[DllImport("kernel32.dll", SetLastError=true)] 

public static extern bool UpdateProcThreadAttribute( 

IntPtr lpAttributeList, 

uint dwFlags, 

IntPtr Attribute, 

IntPtr lpValue, 

IntPtr cbSize, 

IntPtr lpPreviousValue, 

IntPtr lpReturnSize); 

 

public static string SearchPath(string findThis) 

{ 

StringBuilder sbOut = new StringBuilder(1024); 

IntPtr filePartOut; 

 

if(SearchPath(null, findThis, null, sbOut.Capacity, sbOut, out filePartOut) == 0) 

throw new FileNotFoundException("Couldn't locate " + findThis + " on path"); 

 

return sbOut.ToString(); 

} 

 

[DllImport("kernel32.dll", SetLastError=true)] 

static extern SafeFileHandle OpenThread( 

ThreadAccessRights dwDesiredAccess, 

bool bInheritHandle, 

int dwThreadId); 

 

[DllImport("kernel32.dll", SetLastError=true)] 

static extern int ResumeThread(SafeHandle hThread); 

 

public static void ResumeThreadById(int threadId) 

{ 

var threadHandle = OpenThread(ThreadAccessRights.SUSPEND_RESUME, false, threadId); 

if(threadHandle.IsInvalid) 

throw new Exception(String.Format("Thread ID {0} is invalid ({1})", threadId, 

new Win32Exception(Marshal.GetLastWin32Error()).Message)); 

 

try 

{ 

if(ResumeThread(threadHandle) == -1) 

throw new Exception(String.Format("Thread ID {0} cannot be resumed ({1})", threadId, 

new Win32Exception(Marshal.GetLastWin32Error()).Message)); 

} 

finally 

{ 

threadHandle.Dispose(); 

} 

} 

 

public static void ResumeProcessById(int pid) 

{ 

var proc = Process.GetProcessById(pid); 

 

// wait for at least one suspended thread in the process (this handles possible slow startup race where 

// primary thread of created-suspended process has not yet become runnable) 

var retryCount = 0; 

while(!proc.Threads.OfType<ProcessThread>().Any(t=>t.ThreadState == System.Diagnostics.ThreadState.Wait && 

t.WaitReason == ThreadWaitReason.Suspended)) 

{ 

proc.Refresh(); 

Thread.Sleep(50); 

if (retryCount > 100) 

throw new InvalidOperationException(String.Format("No threads were suspended in target PID {0} after 5s", pid)); 

} 

 

foreach(var thread in proc.Threads.OfType<ProcessThread>().Where(t => t.ThreadState == System.Diagnostics.ThreadState.Wait && 

t.WaitReason == ThreadWaitReason.Suspended)) 

ResumeThreadById(thread.Id); 

} 

} 

 

[StructLayout(LayoutKind.Sequential)] 

public class SECURITY_ATTRIBUTES 

{ 

public int nLength; 

public IntPtr lpSecurityDescriptor; 

public bool bInheritHandle = false; 

 

public SECURITY_ATTRIBUTES() { 

nLength = Marshal.SizeOf(this); 

} 

} 

 

[StructLayout(LayoutKind.Sequential)] 

public class STARTUPINFO 

{ 

public Int32 cb; 

public IntPtr lpReserved; 

public IntPtr lpDesktop; 

public IntPtr lpTitle; 

public Int32 dwX; 

public Int32 dwY; 

public Int32 dwXSize; 

public Int32 dwYSize; 

public Int32 dwXCountChars; 

public Int32 dwYCountChars; 

public Int32 dwFillAttribute; 

public Int32 dwFlags; 

public Int16 wShowWindow; 

public Int16 cbReserved2; 

public IntPtr lpReserved2; 

public IntPtr hStdInput; 

public IntPtr hStdOutput; 

public IntPtr hStdError; 

 

public STARTUPINFO() { 

cb = Marshal.SizeOf(this); 

} 

} 

 

[StructLayout(LayoutKind.Sequential)] 

public class STARTUPINFOEX { 

public STARTUPINFO startupInfo; 

public IntPtr lpAttributeList; 

 

public STARTUPINFOEX() { 

startupInfo = new STARTUPINFO(); 

startupInfo.cb = Marshal.SizeOf(this); 

} 

} 

 

[StructLayout(LayoutKind.Sequential)] 

public struct PROCESS_INFORMATION 

{ 

public IntPtr hProcess; 

public IntPtr hThread; 

public int dwProcessId; 

public int dwThreadId; 

} 

 

[Flags] 

enum ThreadAccessRights : uint 

{ 

SUSPEND_RESUME = 0x0002 

} 

 

[Flags] 

public enum StartupInfoFlags : uint 

{ 

USESTDHANDLES = 0x00000100 

} 

 

public enum StandardHandleValues : int 

{ 

STD_INPUT_HANDLE = -10, 

STD_OUTPUT_HANDLE = -11, 

STD_ERROR_HANDLE = -12 

} 

 

[Flags] 

public enum HandleFlags : uint 

{ 

None = 0, 

INHERIT = 1 

} 

} 

"@ # END Ansible.Async native type definition 

 

# calculate the result path so we can include it in the worker payload 

$jid = $payload.async_jid 

$local_jid = $jid + "." + $pid 

 

$results_path = [System.IO.Path]::Combine($env:LOCALAPPDATA, ".ansible_async", $local_jid) 

 

$payload.async_results_path = $results_path 

 

[System.IO.Directory]::CreateDirectory([System.IO.Path]::GetDirectoryName($results_path)) | Out-Null 

 

Add-Type -TypeDefinition $native_process_util -Debug:$false 

 

# FUTURE: create under new job to ensure all children die on exit? 

 

# FUTURE: move these flags into C# enum? 

# start process suspended + breakaway so we can record the watchdog pid without worrying about a completion race 

Set-Variable CREATE_BREAKAWAY_FROM_JOB -Value ([uint32]0x01000000) -Option Constant 

Set-Variable CREATE_SUSPENDED -Value ([uint32]0x00000004) -Option Constant 

Set-Variable CREATE_UNICODE_ENVIRONMENT -Value ([uint32]0x000000400) -Option Constant 

Set-Variable CREATE_NEW_CONSOLE -Value ([uint32]0x00000010) -Option Constant 

Set-Variable EXTENDED_STARTUPINFO_PRESENT -Value ([uint32]0x00080000) -Option Constant 

 

$pstartup_flags = $CREATE_BREAKAWAY_FROM_JOB -bor $CREATE_UNICODE_ENVIRONMENT -bor $CREATE_NEW_CONSOLE ` 

-bor $CREATE_SUSPENDED -bor $EXTENDED_STARTUPINFO_PRESENT 

 

# execute the dynamic watchdog as a breakway process to free us from the WinRM job, which will in turn exec the module 

$si = New-Object Ansible.Async.STARTUPINFOEX 

 

# setup stdin redirection, we'll leave stdout/stderr as normal 

$si.startupInfo.dwFlags = [Ansible.Async.StartupInfoFlags]::USESTDHANDLES 

$si.startupInfo.hStdOutput = [Ansible.Async.NativeProcessUtil]::GetStdHandle([Ansible.Async.StandardHandleValues]::STD_OUTPUT_HANDLE) 

$si.startupInfo.hStdError = [Ansible.Async.NativeProcessUtil]::GetStdHandle([Ansible.Async.StandardHandleValues]::STD_ERROR_HANDLE) 

 

$stdin_read = $stdin_write = 0 

 

$pipesec = New-Object Ansible.Async.SECURITY_ATTRIBUTES 

$pipesec.bInheritHandle = $true 

 

If(-not [Ansible.Async.NativeProcessUtil]::CreatePipe([ref]$stdin_read, [ref]$stdin_write, $pipesec, 0)) { 

throw "Stdin pipe setup failed, Win32Error: $([System.Runtime.InteropServices.Marshal]::GetLastWin32Error())" 

} 

If(-not [Ansible.Async.NativeProcessUtil]::SetHandleInformation($stdin_write, [Ansible.Async.HandleFlags]::INHERIT, 0)) { 

throw "Stdin handle setup failed, Win32Error: $([System.Runtime.InteropServices.Marshal]::GetLastWin32Error())" 

} 

$si.startupInfo.hStdInput = $stdin_read 

 

# create an attribute list with our explicit handle inheritance list to pass to CreateProcess 

[int]$buf_sz = 0 

 

# determine the buffer size necessary for our attribute list 

If(-not [Ansible.Async.NativeProcessUtil]::InitializeProcThreadAttributeList([IntPtr]::Zero, 1, 0, [ref]$buf_sz)) { 

$last_err = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() 

If($last_err -ne 122) { # ERROR_INSUFFICIENT_BUFFER 

throw "Attribute list size query failed, Win32Error: $last_err" 

} 

} 

 

$si.lpAttributeList = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($buf_sz) 

 

# initialize the attribute list 

If(-not [Ansible.Async.NativeProcessUtil]::InitializeProcThreadAttributeList($si.lpAttributeList, 1, 0, [ref]$buf_sz)) { 

throw "Attribute list init failed, Win32Error: $([System.Runtime.InteropServices.Marshal]::GetLastWin32Error())" 

} 

 

$handles_to_inherit = [IntPtr[]]@($stdin_read) 

$pinned_handles = [System.Runtime.InteropServices.GCHandle]::Alloc($handles_to_inherit, [System.Runtime.InteropServices.GCHandleType]::Pinned) 

 

# update the attribute list with the handles we want to inherit 

If(-not [Ansible.Async.NativeProcessUtil]::UpdateProcThreadAttribute($si.lpAttributeList, 0, 0x20002 <# PROC_THREAD_ATTRIBUTE_HANDLE_LIST #>, ` 

$pinned_handles.AddrOfPinnedObject(), [System.Runtime.InteropServices.Marshal]::SizeOf([type][IntPtr]) * $handles_to_inherit.Length, ` 

[System.IntPtr]::Zero, [System.IntPtr]::Zero)) { 

throw "Attribute list update failed, Win32Error: $([System.Runtime.InteropServices.Marshal]::GetLastWin32Error())" 

} 

 

# need to use a preamble-free version of UTF8Encoding 

$utf8_encoding = New-Object System.Text.UTF8Encoding @($false) 

$stdin_fs = New-Object System.IO.FileStream @($stdin_write, [System.IO.FileAccess]::Write, $true, 32768) 

$stdin = New-Object System.IO.StreamWriter @($stdin_fs, $utf8_encoding, 32768) 

 

$pi = New-Object Ansible.Async.PROCESS_INFORMATION 

 

$encoded_command = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($exec_wrapper.ToString())) 

 

# FUTURE: direct cmdline CreateProcess path lookup fails- this works but is sub-optimal 

$exec_cmd = [Ansible.Async.NativeProcessUtil]::SearchPath("powershell.exe") 

$exec_args = New-Object System.Text.StringBuilder @("`"$exec_cmd`" -NonInteractive -NoProfile -ExecutionPolicy Bypass -EncodedCommand $encoded_command") 

 

# TODO: use proper Win32Exception + error 

If(-not [Ansible.Async.NativeProcessUtil]::CreateProcess($exec_cmd, $exec_args, 

[IntPtr]::Zero, [IntPtr]::Zero, $true, $pstartup_flags, [IntPtr]::Zero, $env:windir, $si, [ref]$pi)) { 

#throw New-Object System.ComponentModel.Win32Exception 

throw "Worker creation failed, Win32Error: $([System.Runtime.InteropServices.Marshal]::GetLastWin32Error())" 

} 

 

# FUTURE: watch process for quick exit, capture stdout/stderr and return failure 

 

$watchdog_pid = $pi.dwProcessId 

 

[Ansible.Async.NativeProcessUtil]::ResumeProcessById($watchdog_pid) 

 

# once process is resumed, we can send payload over stdin 

$payload_string = $payload | ConvertTo-Json -Depth 99 -Compress 

$stdin.WriteLine($payload_string) 

$stdin.Close() 

 

# populate initial results before we resume the process to avoid result race 

$result = @{ 

started=1; 

finished=0; 

results_file=$results_path; 

ansible_job_id=$local_jid; 

_ansible_suppress_tmpdir_delete=$true; 

ansible_async_watchdog_pid=$watchdog_pid 

} 

 

$result_json = ConvertTo-Json $result 

Set-Content $results_path -Value $result_json 

 

return $result_json 

} 

 

''' # end async_wrapper 

 

async_watchdog = br''' 

Set-StrictMode -Version 2 

$ErrorActionPreference = "Stop" 

 

Add-Type -AssemblyName System.Web.Extensions 

 

Function Log { 

Param( 

[string]$msg 

) 

 

If(Get-Variable -Name log_path -ErrorAction SilentlyContinue) { 

Add-Content $log_path $msg 

} 

} 

 

Function Deserialize-Json { 

Param( 

[Parameter(ValueFromPipeline=$true)] 

[string]$json 

) 

 

# FUTURE: move this into module_utils/powershell.ps1 and use for everything (sidestep PSCustomObject issues) 

# FUTURE: won't work w/ Nano Server/.NET Core- fallback to DataContractJsonSerializer (which can't handle dicts on .NET 4.0) 

 

Log "Deserializing:`n$json" 

 

$jss = New-Object System.Web.Script.Serialization.JavaScriptSerializer 

return $jss.DeserializeObject($json) 

} 

 

Function Write-Result { 

Param( 

[hashtable]$result, 

[string]$resultfile_path 

) 

 

$result | ConvertTo-Json | Set-Content -Path $resultfile_path 

} 

 

Function Run($payload) { 

$actions = $payload.actions 

 

# pop 0th action as entrypoint 

$entrypoint = $payload.($actions[0]) 

$entrypoint = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($entrypoint)) 

 

$payload.actions = $payload.actions[1..99] 

 

$resultfile_path = $payload.async_results_path 

$max_exec_time_sec = $payload.async_timeout_sec 

 

Log "deserializing existing resultfile args" 

# read in existing resultsfile to merge w/ module output (it should be written by the time we're unsuspended and running) 

$result = Get-Content $resultfile_path -Raw | Deserialize-Json 

 

Log "deserialized result is $($result | Out-String)" 

 

Log "creating runspace" 

 

$rs = [runspacefactory]::CreateRunspace() 

$rs.Open() 

 

Log "creating Powershell object" 

 

$job = [powershell]::Create() 

$job.Runspace = $rs 

 

$job.AddScript($entrypoint) | Out-Null 

$job.AddStatement().AddCommand("Run").AddArgument($payload) | Out-Null 

 

Log "job BeginInvoke()" 

 

$job_asyncresult = $job.BeginInvoke() 

 

Log "waiting $max_exec_time_sec seconds for job to complete" 

 

$signaled = $job_asyncresult.AsyncWaitHandle.WaitOne($max_exec_time_sec * 1000) 

 

$result["finished"] = 1 

 

If($job_asyncresult.IsCompleted) { 

Log "job completed, calling EndInvoke()" 

 

$job_output = $job.EndInvoke($job_asyncresult) 

$job_error = $job.Streams.Error 

 

Log "raw module stdout: \r\n$job_output" 

If($job_error) { 

Log "raw module stderr: \r\n$job_error" 

} 

 

# write success/output/error to result object 

 

# TODO: cleanse leading/trailing junk 

Try { 

$module_result = Deserialize-Json $job_output 

# TODO: check for conflicting keys 

$result = $result + $module_result 

} 

Catch { 

$excep = $_ 

 

$result.failed = $true 

$result.msg = "failed to parse module output: $excep" 

} 

 

# TODO: determine success/fail, or always include stderr if nonempty? 

Write-Result $result $resultfile_path 

 

Log "wrote output to $resultfile_path" 

} 

Else { 

$job.BeginStop($null, $null) | Out-Null # best effort stop 

# write timeout to result object 

$result.failed = $true 

$result.msg = "timed out waiting for module completion" 

Write-Result $result $resultfile_path 

 

Log "wrote timeout to $resultfile_path" 

} 

 

# in the case of a hung pipeline, this will cause the process to stay alive until it's un-hung... 

#$rs.Close() | Out-Null 

} 

 

''' # end async_watchdog 

 

from ansible.plugins import AnsiblePlugin 

 

 

class ShellModule(ShellBase): 

 

# Common shell filenames that this plugin handles 

# Powershell is handled differently. It's selected when winrm is the 

# connection 

COMPATIBLE_SHELLS = frozenset() 

# Family of shells this has. Must match the filename without extension 

SHELL_FAMILY = 'powershell' 

 

env = dict() 

 

# We're being overly cautious about which keys to accept (more so than 

# the Windows environment is capable of doing), since the powershell 

# env provider's limitations don't appear to be documented. 

safe_envkey = re.compile(r'^[\d\w_]{1,255}$') 

 

# TODO: add binary module support 

 

def assert_safe_env_key(self, key): 

if not self.safe_envkey.match(key): 

raise AnsibleError("Invalid PowerShell environment key: %s" % key) 

return key 

 

def safe_env_value(self, key, value): 

if len(value) > 32767: 

raise AnsibleError("PowerShell environment value for key '%s' exceeds 32767 characters in length" % key) 

# powershell single quoted literals need single-quote doubling as their only escaping 

value = value.replace("'", "''") 

return to_text(value, errors='surrogate_or_strict') 

 

def env_prefix(self, **kwargs): 

# powershell/winrm env handling is handled in the exec wrapper 

return "" 

 

def join_path(self, *args): 

parts = [] 

for arg in args: 

arg = self._unquote(arg).replace('/', '\\') 

parts.extend([a for a in arg.split('\\') if a]) 

path = '\\'.join(parts) 

if path.startswith('~'): 

return path 

return '\'%s\'' % path 

 

def get_remote_filename(self, pathname): 

# powershell requires that script files end with .ps1 

base_name = os.path.basename(pathname.strip()) 

name, ext = os.path.splitext(base_name.strip()) 

if ext.lower() not in ['.ps1', '.exe']: 

return name + '.ps1' 

 

return base_name.strip() 

 

def path_has_trailing_slash(self, path): 

# Allow Windows paths to be specified using either slash. 

path = self._unquote(path) 

return path.endswith('/') or path.endswith('\\') 

 

def chmod(self, paths, mode): 

raise NotImplementedError('chmod is not implemented for Powershell') 

 

def chown(self, paths, user): 

raise NotImplementedError('chown is not implemented for Powershell') 

 

def set_user_facl(self, paths, user, mode): 

raise NotImplementedError('set_user_facl is not implemented for Powershell') 

 

def remove(self, path, recurse=False): 

path = self._escape(self._unquote(path)) 

if recurse: 

return self._encode_script('''Remove-Item "%s" -Force -Recurse;''' % path) 

else: 

return self._encode_script('''Remove-Item "%s" -Force;''' % path) 

 

def mkdtemp(self, basefile=None, system=False, mode=None, tmpdir=None): 

# Windows does not have an equivalent for the system temp files, so 

# the param is ignored 

basefile = self._escape(self._unquote(basefile)) 

basetmpdir = tmpdir if tmpdir else self.get_option('remote_tmp') 

 

script = ''' 

$tmp_path = [System.Environment]::ExpandEnvironmentVariables('%s') 

$tmp = New-Item -Type Directory -Path $tmp_path -Name '%s' 

$tmp.FullName | Write-Host -Separator '' 

''' % (basetmpdir, basefile) 

return self._encode_script(script.strip()) 

 

def expand_user(self, user_home_path, username=''): 

# PowerShell only supports "~" (not "~username"). Resolve-Path ~ does 

# not seem to work remotely, though by default we are always starting 

# in the user's home directory. 

user_home_path = self._unquote(user_home_path) 

if user_home_path == '~': 

script = 'Write-Host (Get-Location).Path' 

elif user_home_path.startswith('~\\'): 

script = 'Write-Host ((Get-Location).Path + "%s")' % self._escape(user_home_path[1:]) 

else: 

script = 'Write-Host "%s"' % self._escape(user_home_path) 

return self._encode_script(script) 

 

def exists(self, path): 

path = self._escape(self._unquote(path)) 

script = ''' 

If (Test-Path "%s") 

{ 

$res = 0; 

} 

Else 

{ 

$res = 1; 

} 

Write-Host "$res"; 

Exit $res; 

''' % path 

return self._encode_script(script) 

 

def checksum(self, path, *args, **kwargs): 

path = self._escape(self._unquote(path)) 

script = ''' 

If (Test-Path -PathType Leaf "%(path)s") 

{ 

$sp = new-object -TypeName System.Security.Cryptography.SHA1CryptoServiceProvider; 

$fp = [System.IO.File]::Open("%(path)s", [System.IO.Filemode]::Open, [System.IO.FileAccess]::Read); 

[System.BitConverter]::ToString($sp.ComputeHash($fp)).Replace("-", "").ToLower(); 

$fp.Dispose(); 

} 

ElseIf (Test-Path -PathType Container "%(path)s") 

{ 

Write-Host "3"; 

} 

Else 

{ 

Write-Host "1"; 

} 

''' % dict(path=path) 

return self._encode_script(script) 

 

def build_module_command(self, env_string, shebang, cmd, arg_path=None): 

# pipelining bypass 

if cmd == '': 

return '-' 

 

# non-pipelining 

 

cmd_parts = shlex.split(cmd, posix=False) 

cmd_parts = list(map(to_text, cmd_parts)) 

if shebang and shebang.lower() == '#!powershell': 

if not self._unquote(cmd_parts[0]).lower().endswith('.ps1'): 

cmd_parts[0] = '"%s.ps1"' % self._unquote(cmd_parts[0]) 

cmd_parts.insert(0, '&') 

elif shebang and shebang.startswith('#!'): 

cmd_parts.insert(0, shebang[2:]) 

elif not shebang: 

# The module is assumed to be a binary 

cmd_parts[0] = self._unquote(cmd_parts[0]) 

cmd_parts.append(arg_path) 

script = ''' 

Try 

{ 

%s 

%s 

} 

Catch 

{ 

$_obj = @{ failed = $true } 

If ($_.Exception.GetType) 

{ 

$_obj.Add('msg', $_.Exception.Message) 

} 

Else 

{ 

$_obj.Add('msg', $_.ToString()) 

} 

If ($_.InvocationInfo.PositionMessage) 

{ 

$_obj.Add('exception', $_.InvocationInfo.PositionMessage) 

} 

ElseIf ($_.ScriptStackTrace) 

{ 

$_obj.Add('exception', $_.ScriptStackTrace) 

} 

Try 

{ 

$_obj.Add('error_record', ($_ | ConvertTo-Json | ConvertFrom-Json)) 

} 

Catch 

{ 

} 

Echo $_obj | ConvertTo-Json -Compress -Depth 99 

Exit 1 

} 

''' % (env_string, ' '.join(cmd_parts)) 

return self._encode_script(script, preserve_rc=False) 

 

def wrap_for_exec(self, cmd): 

return '& %s' % cmd 

 

def _unquote(self, value): 

'''Remove any matching quotes that wrap the given value.''' 

value = to_text(value or '') 

m = re.match(r'^\s*?\'(.*?)\'\s*?$', value) 

if m: 

return m.group(1) 

m = re.match(r'^\s*?"(.*?)"\s*?$', value) 

if m: 

return m.group(1) 

return value 

 

def _escape(self, value, include_vars=False): 

'''Return value escaped for use in PowerShell command.''' 

# http://www.techotopia.com/index.php/Windows_PowerShell_1.0_String_Quoting_and_Escape_Sequences 

# http://stackoverflow.com/questions/764360/a-list-of-string-replacements-in-python 

subs = [('\n', '`n'), ('\r', '`r'), ('\t', '`t'), ('\a', '`a'), 

('\b', '`b'), ('\f', '`f'), ('\v', '`v'), ('"', '`"'), 

('\'', '`\''), ('`', '``'), ('\x00', '`0')] 

if include_vars: 

subs.append(('$', '`$')) 

pattern = '|'.join('(%s)' % re.escape(p) for p, s in subs) 

substs = [s for p, s in subs] 

 

def replace(m): 

return substs[m.lastindex - 1] 

 

return re.sub(pattern, replace, value) 

 

def _encode_script(self, script, as_list=False, strict_mode=True, preserve_rc=True): 

'''Convert a PowerShell script to a single base64-encoded command.''' 

script = to_text(script) 

 

if script == u'-': 

cmd_parts = _common_args + ['-'] 

 

else: 

if strict_mode: 

script = u'Set-StrictMode -Version Latest\r\n%s' % script 

# try to propagate exit code if present- won't work with begin/process/end-style scripts (ala put_file) 

# NB: the exit code returned may be incorrect in the case of a successful command followed by an invalid command 

if preserve_rc: 

script = u'%s\r\nIf (-not $?) { If (Get-Variable LASTEXITCODE -ErrorAction SilentlyContinue) { exit $LASTEXITCODE } Else { exit 1 } }\r\n'\ 

% script 

script = '\n'.join([x.strip() for x in script.splitlines() if x.strip()]) 

encoded_script = to_text(base64.b64encode(script.encode('utf-16-le')), 'utf-8') 

cmd_parts = _common_args + ['-EncodedCommand', encoded_script] 

 

if as_list: 

return cmd_parts 

return ' '.join(cmd_parts)