var commnads = 'alias,apt-get,aptitude,aspell,awk,basename,bc,bg,bind,break,builtin,bzip2,cal,case,cat,cd,cfdisk,chattr,chgrp,chmod,chown,chroot,chkconfig,cksum,cmp,comm,command,continue,cp,cron,crontab,csplit,curl,cut,date,dc,dd,ddrescue,declare,df,diff,diff3,dig,dir,dircolors,dirname,dirs,dmesg,du,echo,egrep,eject,enable,env,eval,exec,exit,expect,expand,export,expr,false,fdformat,fdisk,fg,fgrep,file,find,fmt,fold,for,fsck,ftp,function,fuser,gawk,getopts,grep,groupadd,groupdel,groupmod,groups,gzip,hash,head,history,hostname,htop,iconv,id,if,ifconfig,ifdown,ifup,import,install,iostat,ip,jobs,join,kill,killall,less,let,link,ln,local,locate,logname,logout,look,lpc,lpr,lprm,lsattr,lsblk,ls,lsof,lspci,man,mkdir,mkfifo,mkfile,mknod,mktemp,more,most,mount,mtools,mtr,mv,mmv,nc,netstat,nft,nice,nl,nohup,notify-send,nslookup,open,op,passwd,paste,Perf,ping,pgrep,pkill,popd,pr,printenv,printf,ps,pushd,pv,pwd,quota,quotacheck,ram,rar,rcp,read,readonly,rename,return,rev,rm,rmdir,rsync,screen,scp,sdiff,sed,select,seq,set,shift,shopt,shutdown,sleep,slocate,sort,source,split,ss,ssh,stat,strace,su,sudo,sum,suspend,sync,tail,tar,tee,test,time,timeout,times,touch,top,tput,traceroute,trap,tr,true,tsort,tty,type,ulimit,umask,unalias,uname,unexpand,uniq,units,unrar,unset,unshar,until,useradd,userdel,usermod,users,uuencode,uudecode,vi,vmstat,w,wait,watch,wc,whereis,which,while,who,whoami,write,xargs,xdg-open,xz,yes,zip,.,!!,###'.split(','); if (commands.some(command => text_to_check.startsWith(command + ' '))) { //code goes here }
贝壳的 type 命令将检测内置命令,别名,函数,外部命令等。
type
child_process = require('child_process') ['lua','foobar'].forEach((cmd) => { result = child_process.spawnSync('sh', ['-c', `type ${cmd}`]) console.log(result.status + '\t' + result.stdout.toString()) })
0 lua is /usr/local/bin/lua 127 foobar: not found
实际上,恶意输入仍然是恶意的。
这是一个解决方法:引用命令 type cmd 字符串,但你必须处理命令本身的任何引号
type cmd
// 1. shell-quote any single quotes in the cmd cmd = "da$(echo 'hello world')te"; // 'da$(echo \'hello world\')te' escaped = cmd.replace(/'/g, `'"'"'`); // 'da$(echo \'"\'"\'hello world\'"\'"\')te' // 2. in the command string, quote the escaped cmd argument result = child_process.spawnSync('sh', ['-c', `type '${escaped}'`]); // .................................................^..........^ console.log(result.status, result.stdout.toString());
127 'da$(echo \'hello world\')te: not found\n'
并且,结合@ dee的答案,找到 的 命令 强> 一句话,你首先必须解析任何领先的变量赋值和/或重定向( https://www.gnu.org/software/bash/manual/bashref.html#Simple-Command-Expansion )和/或引导开括号或大括号和/或...基本上实现sh解析器。