# Crappy Shatter Attack Hunter

import sys
import optparse
import os
import string
import csv
import win32api
import win32con
import pywintypes
import win32pipe
import logging

# our code imports
from dependencyhunter import DependencyHunter
from sham_winutils  import * 



def main(argv):
  print("retrieving high privilege windows on the current desktop")
  windowhits = 0 
  summary = ''
  vulnwindowsentries = getvulnwindows(isadmin())
  
  for thisentry in vulnwindowsentries:
    windowhits += 1
    print (repr(thisentry))
    print ("\n")
    
  print("")
  print("Finished checking windows, got %d potentially vulnerable processes on the current desktop" % windowhits)
  
  summary += str(windowhits) + " high privilege window vulns\n\n"
  print summary
  
  
  
def getvulnwindows(isadmin):
  '''
    Enumerates the current desktop for windows that are running with high privileges

    Parameters:
    isadmin - are we running in audit mode
    '''
  hunter = WindowHunter()
  vuln_entries = []
  current_user = getcurrentusername()

  if isadmin:
    logging.warn("Warning: checking windows on a desktop of a privileged user may produce false negatives, all windows under the current user are ignored. ")

  vulnprocesses = hunter.enumerate_highprivwindows()

  for processid in vulnprocesses:
    vulnwindows = ""
    processinfo = get_processinfo(processid)
    #print str(processinfo)


    for windowhandle,threadid in vulnprocesses[processid]["Windows"]:
      windowname = win32gui.GetWindowText(windowhandle)
      vulnwindows += windowname + '(' + str(windowhandle) + ') '

    user = vulnprocesses[processid]["User"]

    # entry doesn't count if we are running in audit mode, and the user is the current user
    # this might generate false negatives, but this is hard to test for any other way
    if not isadmin or user != current_user:
      vuln_entries.append({"entrylocation":processinfo["Name"] + "(" + str(processid) + ")",
                           "entry":processinfo["CommandLine"],
                           "imagepath":processinfo["ExecutablePath"], 
                           "vulnwindows":vulnwindows, 
                           "username": user})

  return vuln_entries


# The actual thing
if __name__ == "__main__":
  main(sys.argv)