scapy hexdump() - hex

i wonder which hexdump() scapy uses, since i would like to modify it, but i simply cant find anything.
what i DO find is:
def hexdump(self, lfilter=None):
for i in range(len(self.res)):
p = self._elt2pkt(self.res[i])
if lfilter is not None and not lfilter(p):
continue
print "%s %s %s" % (conf.color_theme.id(i,"%04i"),
p.sprintf("%.time%"),
self._elt2sum(self.res[i]))
hexdump(p)
but that simply is an alternative for pkt.hexdump(), which does a pkt.summary() with a following hexdump(pkt)
could anyone tell me where to find the hexdump(pkt) sourcecode?
what i want to have is the hex'ed packet, almost like str(pkt[0]) (where i can check byte by byte via str(pkt[0])[0] ), but with nothing else than hexvalues, just like displayed in hexdump(pkt).
maybe you guys could help me out with this one :)

found it, so, to answer my own question, it is located in utils.py
def hexdump(x):
x=str(x)
l = len(x)
i = 0
while i < l:
print "%04x " % i,
for j in range(16):
if i+j < l:
print "%02X" % ord(x[i+j]),
else:
print " ",
if j%16 == 7:
print "",
print " ",
print sane_color(x[i:i+16])
i += 16

Related

How do you access name of a ProtoField after declaration?

How can I access the name property of a ProtoField after I declare it?
For example, something along the lines of:
myproto = Proto("myproto", "My Proto")
myproto.fields.foo = ProtoField.int8("myproto.foo", "Foo", base.DEC)
print(myproto.fields.foo.name)
Where I get the output:
Foo
An alternate method that's a bit more terse:
local fieldString = tostring(field)
local i, j = string.find(fieldString, ": .* myproto")
print(string.sub(fieldString, i + 2, j - (1 + string.len("myproto")))
EDIT: Or an even simpler solution that works for any protocol:
local fieldString = tostring(field)
local i, j = string.find(fieldString, ": .* ")
print(string.sub(fieldString, i + 2, j - 1))
Of course the 2nd method only works as long as there are no spaces in the field name. Since that's not necessarily always going to be the case, the 1st method is more robust. Here is the 1st method wrapped up in a function that ought to be usable by any dissector:
-- The field is the field whose name you want to print.
-- The proto is the name of the relevant protocol
function printFieldName(field, protoStr)
local fieldString = tostring(field)
local i, j = string.find(fieldString, ": .* " .. protoStr)
print(string.sub(fieldString, i + 2, j - (1 + string.len(protoStr)))
end
... and here it is in use:
printFieldName(myproto.fields.foo, "myproto")
printFieldName(someproto.fields.bar, "someproto")
Ok, this is janky, and certainly not the 'right' way to do it, but it seems to work.
I discovered this after looking at the output of
print(tostring(myproto.fields.foo))
This seems to spit out the value of each of the members of ProtoField, but I couldn't figure out the correct way to access them. So, instead, I decided to parse the string. This function will return 'Foo', but could be adapted to return the other fields as well.
function getname(field)
--First, convert the field into a string
--this is going to result in a long string with
--a bunch of info we dont need
local fieldString= tostring(field)
-- fieldString looks like:
-- ProtoField(188403): Foo myproto.foo base.DEC 0000000000000000 00000000 (null)
--Split the string on '.' characters
a,b=fieldString:match"([^.]*).(.*)"
--Split the first half of the previous result (a) on ':' characters
a,b=a:match"([^.]*):(.*)"
--At this point, b will equal " Foo myproto"
--and we want to strip out that abreviation "abvr" part
--Count the number of times spaces occur in the string
local spaceCount = select(2, string.gsub(b, " ", ""))
--Declare a counter
local counter = 0
--Declare the name we are going to return
local constructedName = ''
--Step though each word in (b) separated by spaces
for word in b:gmatch("%w+") do
--If we hav reached the last space, go ahead and return
if counter == spaceCount-1 then
return constructedName
end
--Add the current word to our name
constructedName = constructedName .. word .. " "
--Increment counter
counter = counter+1
end
end

Unexpected error While adding string in print() functuon

I have a simple function fact() to print factorial of a number which is to input at runtime.
Everything works fine ata this code given below.
# Find factorial of a number...
def fact():
number = int(input('Please enter a number: '))
tmp = 1
while number > 0:
tmp *= number
number -= 1
print(tmp)
ask = input('Do you want to try again... [y/n]: ')
if ('y' or 'Y') in ask:
fact()
else:
print('Thank you for using my tool. Good bye')
fact()
But if I add some string in first print() function I get syntax error for the line "ask = input...". Here is the code below.
# Find factorial of a number...
def fact():
number = int(input('Please enter a number: '))
tmp = 1
while number > 0:
tmp *= number
number -= 1
print("Factorial of %d is %d" %(number, tmp)
ask = input('Do you want to try again... [y/n]: ')
if ('y' or 'Y') in ask:
fact()
else:
print('Thank you for using my tool. Good bye')
fact()
I have one last problem. My program asks me if I want to try again. If I type y and enter, in works as it should be. But if I type Y, it exicute else statement.
I am using python3.6.4rc1 in Debian.
this should work!
def fact():
number = int(input("Please enter a number: "))
tmp = 1
while number > 0:
tmp *= number
number -= 1
print("Factorial of %d is %d" %(number, tmp))
ask = input("Do you want to try again... [y/n]: ")
if ask in ['y','Y']:
fact()
else:
print('Thank you for using my tool. Good bye')
fact()
I had to preserve value of number variable as it will become 0 at end of loop. Otherwise my program will print Modulas of 0 is 'some_number. Now I have the correct code...
def fact():
number = int(input("Please enter a number: "))
preserve_number = number
tmp = 1
while number > 0:
tmp *= number
number -= 1
print("Factorial of %d is %d" %(preserve_number, tmp))
ask = input("Do you want to try again... [y/n]: ")
if ask in ['y','Y']:
fact()
else:
print('Thank you for using my tool. Good bye')
fact()

BBC Basic Cipher Help Needed

I am doing a school project in which I need to make a "sort of" vigenere cipher in which the user inputs both the keyword and plaintext. However the vigenere assumes a=0 whereas I am to assume a=1 and I have changed this accordingly for my program. However I am required to make my cipher work for both lower and upper case, How could I make this also work for lower case, it may be a stupid question but I'm very confused at this point and I'm new to programming, thanks.
REM Variables
plaintext$=""
PRINT "Enter the text you would like to encrypt"
INPUT plaintext$
keyword$=""
PRINT "Enter the keyword you wish to use"
INPUT keyword$
encrypted$= FNencrypt(plaintext$, keyword$)
REM PRINTING OUTPUTS
PRINT "Key = " keyword$
PRINT "Plaintext = " plaintext$
PRINT "Encrypted = " encrypted$
PRINT "Decrypted = " FNdecrypt(encrypted$, keyword$)
END
DEF FNencrypt(plain$, keyword$)
LOCAL i%, offset%, Ascii%, output$
FOR i% = 1 TO LEN(plain$)
Ascii% = ASCMID$(plain$, i%)
IF Ascii% >= 65 IF Ascii% <= 90 THEN
output$ += CHR$((66 + (Ascii% + ASCMID$(keyword$, offset%+1)) MOD 26))
ENDIF
offset% = (offset% + 1) MOD LEN(keyword$)
NEXT
= output$
DEF FNdecrypt(encrypted$, keyword$)
LOCAL i%, offset%, n%, o$
FOR i% = 1 TO LEN(encrypted$)
n% = ASCMID$(encrypted$, i%)
o$ += CHR$(64 + (n% + 26 - ASCMID$(keyword$, offset%+1)) MOD 26)
offset% = (offset% + 1) MOD LEN(keyword$)
NEXT
= output$
You can always convert from upper to lowercase and the Stringlib library contains a function for doing this.
First import stringlib at the top of your program:
import #lib$+"stringlib"
then convert strings using:
plaintext$ = fn_lower(plaintext$)

Python 3.4 help - using slicing to replace characters in a string

Say I have a string.
"poop"
I want to change "poop" to "peep".
In fact, I also want all of the o's in poop to change to e's for any word I put in.
Here's my attempt to do the above.
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
for i in range (len(y)):
if y[i] == "o":
y = y[:i] + "e"
print (y)
main()
As you can see, when you run it, it doesn't amount to what I want. Here is my expected output.
Enter a word.
>>> brother
brether
Something like this. I need to do it using slicing. I just don't know how.
Please keep your answer simple, since I'm somewhat new to Python. Thanks!
This uses slicing (but keep in mind that slicing is not the best way to do it):
def f(s):
for x in range(len(s)):
if s[x] == 'o':
s = s[:x]+'e'+s[x+1:]
return s
Strings in python are non-mutable, which means that you can't just swap out letters in a string, you would need to create a whole new string and concatenate letters on one-by-one
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
output = ''
for i in range(len(y)):
if y[i] == "o":
output = output + 'e'
else:
output = output + y[i]
print(output)
main()
I'll help you this once, but you should know that stack overflow is not a homework help site. You should be figuring these things out on your own to get the full educational experience.
EDIT
Using slicing, I suppose you could do:
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
output = '' # String variable to hold the output string. Starts empty
slice_start = 0 # Keeps track of what we have already added to the output. Starts at 0
for i in range(len(y) - 1): # Scan through all but the last character
if y[i] == "o": # If character is 'o'
output = output + y[slice_start:i] + 'e' # then add all the previous characters to the output string, and an e character to replace the o
slice_start = i + 1 # Increment the index to start the slice at to be the letter immediately after the 'o'
output = output + y[slice_start:-1] # Add the rest of the characters to output string from the last occurrence of an 'o' to the end of the string
if y[-1] == 'o': # We still haven't checked the last character, so check if its an 'o'
output = output + 'e' # If it is, add an 'e' instead to output
else:
output = output + y[-1] # Otherwise just add the character as-is
print(output)
main()
Comments should explain what is going on. I'm not sure if this is the most efficient or best way to do it (which really shouldn't matter, since slicing is a terribly inefficient way to do this anyways), just the first thing I hacked together that uses slicing.
EDIT Yeah... Ourous's solution is much more elegant
Can slicing even be used in this situation??
The only probable solution I think would work, as MirekE stated, is y.replace("o","e").

How to build a system() function call to sed with escape characters?

I can't get this to work. I want to replace all two character occurences in the first field of a csv file with the occurence and an X appended, and whitespace removed. For example SA and SA should map to SAX in the new file. Below is what I tried with sed (from help through an earlier question)
system( paste("sed ","'" ,' s/^GG/GGX/g; s/^GG\\s/GGX/g; s/^GP/GPX/g;
s/^GP\\s/GPX/g; s/^FG/FGX/g; s/^FG\\s/FGX/g; s/^SA/SAX/g; s/^SA\\s/SAX/g;
s/^TP/TPX/g; s/^TP\\s/TPX/g ',"'",' ./data/concat_csv.2 >
./data/concatenated_csv.2 ',sep=''))
I tried using the sQuote() function, but this still doesn't help. The file has problems being handled by read.csv because there are errors within some fields based on too many and not enough separators on certain lines.
I could try reading in and editing the file in pieces, but I don't know how to do that as a streaming process.
I really just want to edit the first field of the file using a system() call. The file is about 30GB.
try the following on a file like so:
echo "fi,second,third" | awk '{len = split($0,array,","); str = ""; for (i = 1; i <= len; ++i) if (i == 1) { m = split(array[i],array2,""); if (m == 2) {str = array[i]"X";} else {str = array[i]};} else str = str","array[i]; print str;}'
so you would call it from R using the following as input to the paste() call
cat fileNameToBeRead | awk '{len = split($0,array,","); str = ""; for (i = 1; i <= len; ++i) if (i == 1) { m = split(array[i],array2,""); if (m == 2) {str = array[i]"X";} else {str = array[i]};} else str = str","array[i]; print str;}' > newFile
this code won't handle your whitespace requirement though. could you provide examples to demonstrate the sort of functionality you're looking at

Resources