PATH     Path to the file containing raw shellcode to inject
            PROCID   Process ID to inject into (default: current powershell process)
489591
def options(self, context, module_options):
        '''
            
        '''

        if not 'PATH' in module_options:
            context.log.error('PATH option is required!')
            exit(1)

        self.shellcode_path = os.path.expanduser(module_options['PATH'])
        if not os.path.exists(self.shellcode_path):
            context.log.error('Invalid path to shellcode!')
            exit(1)

        self.procid  = None

        if 'PROCID' in module_options.keys():
            self.procid = module_options['PROCID']

        self.ps_script = obfs_ps_script('powersploit/CodeExecution/Invoke-Shellcode.ps1')
1332313
def _get_shell_pid():
    """"""
    proc = Process(os.getpid())

    try:
        return proc.parent().pid
    except TypeError:
        return proc.parent.pid
615922
def getpcmd(pid):
    
    if os.name == "nt":
        # Use wmic command instead of ps on Windows.
        cmd = 'wmic path win32_process where ProcessID=%s get Commandline 2> nul' % (pid, )
        with os.popen(cmd, 'r') as p:
            lines = [line for line in p.readlines() if line.strip("\r\n ") != ""]
            if lines:
                _, val = lines
                return val
    elif sys.platform == "darwin":
        # Use pgrep instead of /proc on macOS.
        pidfile = ".%d.pid" % (pid, )
        with open(pidfile, 'w') as f:
            f.write(str(pid))
        try:
            p = Popen(['pgrep', '-lf', '-F', pidfile], stdout=PIPE)
            stdout, _ = p.communicate()
            line = stdout.decode('utf8').strip()
            if line:
                _, scmd = line.split(' ', 1)
                return scmd
        finally:
            os.unlink(pidfile)
    else:
        # Use the /proc filesystem
        # At least on android there have been some issues with not all
        # process infos being readable. In these cases using the `ps` command
        # worked. See the pull request at
        # https://github.com/spotify/luigi/pull/1876
        try:
            with open('/proc/{0}/cmdline'.format(pid), 'r') as fh:
                if six.PY3:
                    return fh.read().replace('\0', ' ').rstrip()
                else:
                    return fh.read().replace('\0', ' ').decode('utf8').rstrip()
        except IOError:
            # the system may not allow reading the command line
            # of a process owned by another user
            pass

    # Fallback instead of None, for e.g. Cygwin where -o is an "unknown option" for the ps command:
    return '[PROCESS_WITH_PID={}]'.format(pid)
130601
function dumpSourceToFile(sourcecode, errname, err_id, options, ex) {
    var dumpfile;

    try {
        var dumpPaths = [(options.outfile ? path.dirname(options.outfile) : null), options.inputPath, process.cwd()];
        var dumpName = path.basename(options.inputFilename || options.moduleName || (options.outfile ? path.dirname(options.outfile) : null) || options.defaultModuleName || errname)
        .replace(/\.[a-z]{1,5}$/i, '')          // remove extension .y, .yacc, .jison, ...whatever
        .replace(/[^a-z0-9_]/ig, '_');          // make sure it's legal in the destination filesystem: the least common denominator.
        if (dumpName === '' || dumpName === '_') {
            dumpName = '__bugger__';
        }
        err_id = err_id || 'XXX';

        var ts = new Date();
        var tm = ts.getUTCFullYear() +
            '_' + pad(ts.getUTCMonth() + 1) +
            '_' + pad(ts.getUTCDate()) +
            'T' + pad(ts.getUTCHours()) +
            '' + pad(ts.getUTCMinutes()) +
            '' + pad(ts.getUTCSeconds()) +
            '.' + pad(ts.getUTCMilliseconds(), 3) +
            'Z';

        dumpName += '.fatal_' + err_id + '_dump_' + tm + '.js';

        for (var i = 0, l = dumpPaths.length; i < l; i++) {
            if (!dumpPaths[i]) {
                continue;
            }

            try {
                dumpfile = path.normalize(dumpPaths[i] + '/' + dumpName);
                fs.writeFileSync(dumpfile, sourcecode, 'utf8');
                console.error("****** offending generated " + errname + " source code dumped into file: ", dumpfile);
                break;          // abort loop once a dump action was successful!
            } catch (ex3) {
                //console.error("generated " + errname + " source code fatal DUMPING error ATTEMPT: ", i, " = ", ex3.message, " -- while attempting to dump into file: ", dumpfile, "\n", ex3.stack);
                if (i === l - 1) {
                    throw ex3;
                }
            }
        }
    } catch (ex2) {
        console.error("generated " + errname + " source code fatal DUMPING error: ", ex2.message, " -- while attempting to dump into file: ", dumpfile, "\n", ex2.stack);
    }

    // augment the exception info, when available:
    if (ex) {
        ex.offending_source_code = sourcecode;
        ex.offending_source_title = errname;
        ex.offending_source_dumpfile = dumpfile;
    }    
}
1025466
def read_pid_from_pidfile(pidfile_path):
    
    pid = None
    try:
        pidfile = open(pidfile_path, 'r')
    except IOError:
        pass
    else:
        # According to the FHS 2.3 section on PID files in /var/run:
        # 
        #   The file must consist of the process identifier in
        #   ASCII-encoded decimal, followed by a newline character.
        # 
        #   Programs that read PID files should be somewhat flexible
        #   in what they accept; i.e., they should ignore extra
        #   whitespace, leading zeroes, absence of the trailing
        #   newline, or additional lines in the PID file.

        line = pidfile.readline().strip()
        try:
            pid = int(line)
        except ValueError:
            pass
        pidfile.close()

    return pid
573676
def getDataPath(_system=thisSystem, _FilePath=FilePath):
    
    if _system == "Windows":
        pathName = "~/Crypto101/"
    else:
        pathName = "~/.crypto101/"

    path = _FilePath(expanduser(pathName))
    if not path.exists():
        path.makedirs()

    return path
1293274
static String getPath(String pid) {
        String hex = DigestUtils.md5Hex(pid);
        return "" + hex.charAt(0) + hex.charAt(1) +
                '/' + hex.charAt(2) + hex.charAt(3);
    }
154405
function getOutputFilePath(input, outputDir, suffix) {
  var inputArr = input.split(path.sep);
  var originFileName = inputArr[inputArr.length - 1];
  var newFileName = originFileName.replace(/\.png$/, suffix + '.png');
  var outputFilePath = path.join(outputDir, newFileName);
  return outputFilePath;
}
356552
def get_pid(rundir, process_type=PROCESS_TYPE, name=None):
    
    pidPath = get_pidpath(rundir, process_type, name)
    log.log('run', 'pidfile for %s %s is %s' % (process_type, name, pidPath))

    if not os.path.exists(pidPath):
        return

    pidFile = open(pidPath, 'r')
    pid = pidFile.readline()
    pidFile.close()
    if not pid or int(pid) == 0:
        return

    return int(pid)
1109029
def script_path(nickname)
      base_path = nickname.gsub(/[^0-9a-zA-Z_]/,'_')
      base_path = File.join(@recipes_dir, base_path)
      candidate_path = RightScale::Platform.shell.format_script_file_name(base_path)
      i = 1
      path = candidate_path
      path = candidate_path + (i += 1).to_s while File.exists?(path)
      path
    end
17056
protected function writeProcessIdFile()
    {
        // Verify the process id is valid.
        if ($this->processId < 1) {
            $this->getLogger()->emergency('The process id is invalid.');

            return false;
        }

        // Get the application process id file path.
        $file = $this->config->get('application_pid_file');

        if (empty($file)) {
            $this->getLogger()->error('The process id file path is empty.');

            return false;
        }

        // Make sure that the folder where we are writing the process id file exists.
        $folder = dirname($file);

        if (!is_dir($folder) && !@ mkdir($folder, $this->get('folder_permission', 0755))) {
            $this->getLogger()->error('Unable to create directory: ' . $folder);

            return false;
        }

        // Write the process id file out to disk.
        if (!file_put_contents($file, $this->processId)) {
            $this->getLogger()->error('Unable to write proccess id file: ' . $file);

            return false;
        }

        // Make sure the permissions for the proccess id file are accurate.
        if (!chmod($file, $this->get('file_permission', 0644))) {
            $this->getLogger()->error('Unable to adjust permissions for the proccess id file: ' . $file);

            return false;
        }

        return true;
    }
902318
function(){
        var bundle = self.bundle;
        var PID = self.PID;
        var proc = self.proc;
        var path = self.path
        //Get PID path.
        if (
            typeof(bundle) != "undefined" && bundle != ""
            && typeof(PID) != "undefined" && PID != "" && PID != null
            && typeof(proc) != "undefined" && proc != "" && proc != null
        ) {
            try {
                var fileStream = fs.createWriteStream(path + PID);
                fileStream.once('open', function(fd) {
                    fileStream.write(bundle);
                    console.debug('registered ', self.proc.pid);
                    fileStream.end();
                    self.emit('proc#complete', false)
                });
            } catch (err) {
                self.emit('proc#complete', err)
            }

        } else {
            self.emit('proc#complete', new Error('encountered troubles while trying to save Process file'))
        }
    }
1215921
private String rawCreateFolder( CPath path, String parentId )
    {
        JSONObject body = new JSONObject();
        body.put( "title", path.getBaseName() );
        body.put( "mimeType", MIME_TYPE_DIRECTORY );
        JSONArray ids = new JSONArray();
        JSONObject idObj = new JSONObject();
        idObj.put( "id", parentId );
        ids.put( idObj );
        body.put( "parents", ids );

        HttpPost request = new HttpPost( FILES_ENDPOINT + "?fields=id" );
        request.setEntity( new JSONEntity( body ) );

        RequestInvoker<CResponse> ri = getApiRequestInvoker( request, path );
        JSONObject jresp = retryStrategy.invokeRetry( ri ).asJSONObject();
        return jresp.getString( "id" );
    }
495659
function Proc(bundle, proc, usePidFile){

    var self    = this;
    this.PID    = null;
    this.path   = null;
    this.master = false;//used only by master.
    this.bundle = bundle;
    this.proc   = proc;
    this.bundles = [];

    if ( typeof(usePidFile) == 'undefined') {
        var usePidFile = true
    }

    /**
     * Check target path
     * @param {string} path
     * @param {integer} PID Id of the PID to save
     * */

    var init = function() {
        //Default.
        var pathObj = new _( getPath('root') + '/tmp/pid/' );
        var path = pathObj.toString();

        //Create dir if needed.
        //console.debug("MKDIR  pathObj (pid:"+self.proc.pid+") - ", self.bundle);

        process.list = (process.list == undefined) ? [] : process.list;
        process.pids = (process.pids == undefined) ? {} : process.pids;

        self.register(self.bundle, self.proc.pid);

        if (usePidFile) {
            pathObj.mkdir( function(err, path){
                console.debug('path created ('+path+') now saving PID ' +  bundle);
                //logger.info('gina', 'PROC:INFO:1', 'path created ('+path+') now saving PID ' +  bundle, __stack);
                //Save file.
                if (!err) {
                    self.PID = self.proc.pid;
                    self.path = path + pathObj.sep;
                    //Add PID file.
                    setPID(self.bundle, self.PID, self.proc);
                    save(self.bundle, self.PID, self.proc)
                }
            })
        }
    };

    var isMaster = function() {
        return (self.master) ? true : false;
    };

    // var getShutdownConnectorSync = function(bundle) {
    //     var bundlesPath = getPath('bundlesPath');
    //     var connPath = _(bundlesPath +'/'+ bundle + '/config/connector.json');
    //     try {
    //         console.log('reading connPath: ', connPath);
    //         var content = fs.readFileSync(connPath);
    //         return JSON.parse(content).httpClient.shutdown
    //     } catch (err) {
    //         return undefined
    //     }
    // }
    /**
     * Going to force restart by third party (kill 9).
     *
     * @param {string} bundle
     * @param {string} env
     * @param {number} pid
     *
     * @callback callback
     * @param {boolean|string} err
     * */
    var respawn = function(bundle, env, pid, callback) {
        //var loggerInstance = getContext('logger');
        //loggerInstance["trace"]('Fatal error !');
        //console.debug("Exiting and re spawning : ", bundle, env);
        // TODO - Count the restarts and prevent unilimited loop
        // TODO - Send notification to admin or/and root to the Fatal Error Page.

        var root = getPath('root');
        try {
            var version = process.getVersion(bundle);
        } catch (err) {
            var bundle = process.argv[3];
            //var port = self.getBundlePortByBundleName(bundle);
            //console.log("Bundle ", bundle," already running or port[ "+port+" ] is taken by another process...");
            //loggerInstance["trace"]("Bundle [ "+ bundle +" ] already running or [ "+env+" ] port is use by another process...");
            console.debug("Bundle [ "+ bundle +" ] already running or [ "+env+" ] port is use by another process...");
            dismiss(process.pid);
        }


        var outPath = _(root + '/out.'+bundle+'.'+version+'.log');
        var errPath = _(root + '/out.'+bundle+'.'+version+'.log');
        var nodePath = getPath('node');
        var ginaPath = _(root + '/gina');

        // if (env == 'prod') { //won't loop forever for others env.
        //
        //     //var opt = process.getShutdownConnectorSync();
        //     var opt = getShutdownConnectorSync(bundle);
        //     //Should kill existing one..
        //     opt.path = '/' + bundle + '/restart/' + pid + '/' + env;
        //
        //     var HttpClient = require('gina.com').Http;
        //     var httpClient = new HttpClient();
        //
        //     if (httpClient) {
        //         //httpClient.query(opt);
        //         //We are not waiting for anything particular...do we ?
        //         httpClient.query(opt, function (err, msg) {
        //             //Now start new bundle.
        //             callback(err);
        //         });
        //     } else {
        //         var err = new Error('No shutdown connector found.');
        //         console.error(err);
        //         callback(err);
        //     }
        //
        // } else {
            callback(false);
        //}
    };

    var setPID = function(bundle, PID, proc) {

        if (bundle != 'gina') {
            proc.title = 'gina: '+ bundle;
        } else {
            proc.title = bundle;
        }

        //Set event.
        setDefaultEvents(bundle, PID, proc);
    };

    var setDefaultEvents = function(bundle, PID, proc) {


        if ( typeof(PID) != "undefined" && typeof(PID) == "number" ) {
            console.debug("setting listeners for ", PID, ':', bundle);

            proc.dismiss = dismiss;
            proc.isMaster = isMaster;


            proc.on('SIGTERM', function(code){
                proc.exit(code);
            });

            proc.on('SIGINT', function(code){

                if (code == undefined) var code = 0;
                console.info("\nGot exit code. Now killing: ", code);
                proc.exit(code);//tigger exit event.
            });

            //Will prevent the server from stopping.
            proc.on('uncaughtException', function(err) {

                console.error(err.stack);
                var bundle = self.bundle;
                //console.log("@=>", self.args);
                var env =  process.env.NODE_ENV || 'prod';
                var pid = self.getPidByBundleName(bundle);

                //Wake up buddy !.
                respawn(bundle, env, pid, function(err) {
                    //TODO - Send an email to the administrator/dev
                    //TODO - Have a delegate handler to allow the dev to do its stuff. Maybe it's already there if any dev can override.
                    //proc.exit(1) // don't kill !!! It will stop the server
                })
            });

            proc.on('exit', function(code){

                if ( typeof(code) == 'undefined') {
                    code = 0;
                }

                var bundle = self.bundle;
                var env =  process.env.NODE_ENV || 'prod';
                var pid = self.getPidByBundleName(bundle);

                //console.log('bundle ', bundle, ' vs ', pid, " => ", process.pid);

                //console.log("got exit code ", "("+code+")", pid, " VS ", pid, " <=> gina: ", process.pid);
                //code = code || 0;
                //var obj = logger.emerg('gina', 'UTILS:EMERG1', 'process exit code ' + code);
                //if (code == 0  && env != "debug" && env != "dev"/***/) {

                //for (var p=0; p<process.list.count(); p++) {
                //    dismiss(process.list[p].pid)
                //}

                // kill gina
                dismiss(process.list[process.list.count()-1].pid, "SIGKILL")
            });

            proc.on('SIGHUP', function(code){
                console.debug("Hanging up ! Code: "+ code+"\n"+ process.argv);

                var bundle = self.bundle;
                var env =  process.env.NODE_ENV || 'prod';
                var pid = self.getPidByBundleName(bundle);

                dismiss(process.pid, "SIGINT");
                dismiss(pid, "SIGINT");
            })
        }
    };


    var dismiss = function(pid, signal){
        if (pid == undefined) {
            var pid = self.PID;
        }

        try {

            for (var p in process.list) {
                fs.unlinkSync( _(self.path + process.list[p].pid) )
            }

        } catch (err) {
            //Means that it does not exists anymore.
        }
        try {
            console.debug('\n=> '+ JSON.stringify(process.list, null, 4));
            for (var p in process.list) {
                if ( process.list[p].name != 'gina' ) {
                    fs.unlinkSync( _(getPath('mountPath') + '/'  + process.list[p].name) )
                }
            }
        } catch (err) {
            //Means that it does not exists anymore.
        }

        process.kill(pid, signal);// soft...
        console.debug('\nsent '+ signal +' signal to end process [ '+ pid +' ]\n');
    };

    /**
     * Save PID file
     * @param {string} bundle
     * @param {integer} PID Id of the PID to save
     *
     * @private
     * */
    var save = function(){
        var bundle = self.bundle;
        var PID = self.PID;
        var proc = self.proc;
        var path = self.path
        //Get PID path.
        if (
            typeof(bundle) != "undefined" && bundle != ""
            && typeof(PID) != "undefined" && PID != "" && PID != null
            && typeof(proc) != "undefined" && proc != "" && proc != null
        ) {
            try {
                var fileStream = fs.createWriteStream(path + PID);
                fileStream.once('open', function(fd) {
                    fileStream.write(bundle);
                    console.debug('registered ', self.proc.pid);
                    fileStream.end();
                    self.emit('proc#complete', false)
                });
            } catch (err) {
                self.emit('proc#complete', err)
            }

        } else {
            self.emit('proc#complete', new Error('encountered troubles while trying to save Process file'))
        }
    };


    /**
     * Get PID
     * @param {string} bundle
     * @return {number} PID
     * */
    this.getPID = function(){

        try{
            return self.PID;
        } catch (err) {
            console.error('Could not get PID for bundle: '+ self.bundle + (err.stack||err.message));
            return null;
        }
    };

    this.getBundleNameByPid = function(pid){
        var list = process.list;

        for (var i=0; i<list.length; ++i) {
            //console.log("list ", list, ':',  list[i][pid]);
            if ( typeof(list[i][pid]) != "undefined")
                return list[i][pid]
        }
        return undefined
    };


    this.getPidByBundleName = function(bundle){
        var list = process.pids;
        //console.log("list ", list, ':',  list[bundle]);
        if ( typeof(list[bundle]) != "undefined")
            return list[bundle]
        else
            return undefined
    };

    this.setMaster = function(bool){
        if ( typeof(bool) == 'undefined' || bool == true) {
            self.master = true;
        } else {
            self.master = false;
        }
    };

    this.register = function(bundle, pid) {
        if ( bundle == 'gina' || bundle != 'gina' && self.bundles.indexOf(bundle) == -1 ) {
            if (bundle != 'gina') {
                self.bundles.push(bundle);
            }

            var list = {};
            list['pid'] = pid;
            list['name'] = bundle;
            process.list.push(list);//Running bundles.
            process.pids[bundle] = pid;

            list = null;
        }
    };

    this.onReady = function(cb) {
        self.once('proc#complete', function(err){
            cb(err)
        })
    }

    //Init.
    if ( typeof(this.bundle) == "undefined" ) {
        console.error('Invalid or undefined proc name . Proc naming Aborted')
    } else {
        init()
    }
}
356916
function getPathVariableName() {
    // windows calls it's path 'Path' usually, but this is not guaranteed.
    if (process.platform === 'win32') {
        for (const key of Object.keys(process.env))
            if (key.match(/^PATH$/i))
                return key;
        return 'Path';
    }
    return "PATH";
}
93829
def options(self, context, module_options):
        '''
            
        '''

        if not 'PATH' in module_options:
            context.log.error('PATH option is required!')
            exit(1)

        self.payload_path = os.path.expanduser(module_options['PATH'])
        if not os.path.exists(self.payload_path):
            context.log.error('Invalid path to EXE/DLL!')
            exit(1)

        self.procid  = None
        self.exeargs = None

        if 'PROCID' in module_options:
            self.procid = module_options['PROCID']

        if 'EXEARGS' in module_options:
            self.exeargs = module_options['EXEARGS']

        self.ps_script = obfs_ps_script('powersploit/CodeExecution/Invoke-ReflectivePEInjection.ps1')
211160
function _getPathFromPowerShell () {
  return new Promise(resolve => {
    const psArgs = 'Get-Command npm | Select-Object -ExpandProperty Definition'
    const args = [ '-NoProfile', '-NoLogo', psArgs ]
    const child = spawn('powershell.exe', args)

    let stdout = []
    let stderr = []

    child.stdout.on('data', (data) => {
      debug(`PowerShell: Stdout received: ${data.toString()}`)
      stdout.push(data.toString())
    })

    child.stderr.on('data', (data) => {
      debug(`PowerShell: Stderr received: ${data.toString()}`)
      stderr.push(data.toString())
    })

    child.on('exit', () => {
      const cmdPath = (stdout[0] && stdout[0].trim) ? stdout[0].trim() : null

      if (stderr.length === 0 && cmdPath && cmdPath.slice(cmdPath.length - 7) === 'npm.cmd') {
        // We're probably installed in a location like C:\Program Files\nodejs\npm.cmd,
        // meaning that we should not use the global prefix installation location
        const npmPath = cmdPath.slice(0, cmdPath.length - 8)
        debug(`PowerShell: _getPathFromPowerShell() resolving with: ${npmPath}`)
        resolve(npmPath)
      } else {
        resolve(null)
      }
    })

    child.stdin.end()
  })
}