desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Add authority records >>> q = DNSRecord.question("abc.com") >>> a = q.reply() >>> a.add_answer(*RR.fromZone("abc.com 60 A 1.2.3.4")) >>> a.add_auth(*RR.fromZone("abc.com 3600 NS nsa.abc.com")) >>> print(a) ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ... ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 0 ;; QUESTION SECTION: ;abc.com. IN A ;; ANSWER SECTION: abc.com. 60 IN A 1.2.3.4 ;; AUTHORITY SECTION: abc.com. 3600 IN NS nsa.abc.com.'
def add_auth(self, *auth):
self.auth.extend(auth) self.set_header_qa()
'Add additional records >>> q = DNSRecord.question("abc.com") >>> a = q.reply() >>> a.add_answer(*RR.fromZone("abc.com 60 CNAME x.abc.com")) >>> a.add_ar(*RR.fromZone("x.abc.com 3600 A 1.2.3.4")) >>> print(a) ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ... ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; QUESTION SECTION: ;abc.com. IN A ;; ANSWER SECTION: abc.com. 60 IN CNAME x.abc.com. ;; ADDITIONAL SECTION: x.abc.com. 3600 IN A 1.2.3.4'
def add_ar(self, *ar):
self.ar.extend(ar) self.set_header_qa()
'Reset header q/a/auth/ar counts to match numver of records (normally done transparently)'
def set_header_qa(self):
self.header.q = len(self.questions) self.header.a = len(self.rr) self.header.auth = len(self.auth) self.header.ar = len(self.ar)
'Pack record into binary packet (recursively packs each section into buffer) >>> q = DNSRecord.question("abc.com") >>> q.header.id = 1234 >>> a = q.replyZone("abc.com A 1.2.3.4") >>> a.header.aa = 0 >>> pkt = a.pack() >>> print(DNSRecord.parse(pkt)) ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 1234 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;abc.com. IN A ;; ANSWER SECTION: abc.com. 0 IN A 1.2.3.4'
def pack(self):
self.set_header_qa() buffer = DNSBuffer() self.header.pack(buffer) for q in self.questions: q.pack(buffer) for rr in self.rr: rr.pack(buffer) for auth in self.auth: auth.pack(buffer) for ar in self.ar: ar.pack(buffer) return buffer.data
'Return truncated copy of DNSRecord (with TC flag set) (removes all Questions & RRs and just returns header) >>> q = DNSRecord.question("abc.com") >>> a = q.reply() >>> a.add_answer(*RR.fromZone(\'abc.com IN TXT %s\' % (\'x\' * 255))) >>> a.add_answer(*RR.fromZone(\'abc.com IN TXT %s\' % (\'x\' * 255))) >>> a.add_answer(*RR.fromZone(\'abc.com IN TXT %s\' % (\'x\' * 255))) >>> len(a.pack()) 829 >>> t = a.truncate() >>> print(t) ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ... ;; flags: qr aa tc rd ra; QUERY: 0, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0'
def truncate(self):
return DNSRecord(DNSHeader(id=self.header.id, bitmap=self.header.bitmap, tc=1))
'Send packet to nameserver and return response'
def send(self, dest, port=53, tcp=False, timeout=None, ipv6=False):
data = self.pack() if ipv6: inet = socket.AF_INET6 else: inet = socket.AF_INET if tcp: if (len(data) > 65535): raise ValueError(('Packet length too long: %d' % len(data))) data = (struct.pack('!H', len(data)) + data) sock = socket.socket(inet, socket.SOCK_STREAM) if (timeout is not None): sock.settimeout(timeout) sock.connect((dest, port)) sock.sendall(data) response = sock.recv(8192) length = struct.unpack('!H', bytes(response[:2]))[0] while ((len(response) - 2) < length): response += sock.recv(8192) sock.close() response = response[2:] else: sock = socket.socket(inet, socket.SOCK_DGRAM) if (timeout is not None): sock.settimeout(timeout) sock.sendto(self.pack(), (dest, port)) (response, server) = sock.recvfrom(8192) sock.close() return response
'Formatted \'repr\'-style representation of record (optionally with prefix and/or sorted RRs)'
def format(self, prefix='', sort=False):
s = (sorted if sort else (lambda x: x)) sections = [repr(self.header)] sections.extend(s([repr(q) for q in self.questions])) sections.extend(s([repr(rr) for rr in self.rr])) sections.extend(s([repr(rr) for rr in self.auth])) sections.extend(s([repr(rr) for rr in self.ar])) return (prefix + ('\n' + prefix).join(sections))
'Formatted \'DiG\' (zone) style output (with optional prefix)'
def toZone(self, prefix=''):
z = self.header.toZone().split('\n') if self.questions: z.append(';; QUESTION SECTION:') [z.extend(q.toZone().split('\n')) for q in self.questions] if self.rr: z.append(';; ANSWER SECTION:') [z.extend(rr.toZone().split('\n')) for rr in self.rr] if self.auth: z.append(';; AUTHORITY SECTION:') [z.extend(rr.toZone().split('\n')) for rr in self.auth] if self.ar: z.append(';; ADDITIONAL SECTION:') [z.extend(rr.toZone().split('\n')) for rr in self.ar] return (prefix + ('\n' + prefix).join(z))
'Just return RDATA'
def short(self):
return '\n'.join([rr.rdata.toZone() for rr in self.rr])
'Test for equality by diffing records'
def __eq__(self, other):
if (type(other) != type(self)): return False else: return (self.diff(other) == [])
'Diff records - recursively diff sections (sorting RRs)'
def diff(self, other):
err = [] if (self.header != other.header): err.append((self.header, other.header)) for section in ('questions', 'rr', 'auth', 'ar'): if (section == 'questions'): k = (lambda x: tuple(map(str, (x.qname, x.qtype)))) else: k = (lambda x: tuple(map(str, (x.rname, x.rtype, x.rdata)))) a = dict([(k(rr), rr) for rr in getattr(self, section)]) b = dict([(k(rr), rr) for rr in getattr(other, section)]) sa = set(a) sb = set(b) for e in sorted(sa.intersection(sb)): if (a[e] != b[e]): err.append((a[e], b[e])) for e in sorted(sa.difference(sb)): err.append((a[e], None)) for e in sorted(sb.difference(sa)): err.append((None, b[e])) return err
'Implements parse interface'
@classmethod def parse(cls, buffer):
try: (id, bitmap, q, a, auth, ar) = buffer.unpack('!HHHHHH') return cls(id, bitmap, q, a, auth, ar) except (BufferError, BimapError) as e: raise DNSError(('Error unpacking DNSHeader [offset=%d]: %s' % (buffer.offset, e)))
'Parse RR data from zone file and return list of RRs'
@classmethod def fromZone(cls, zone, origin='', ttl=0):
return list(ZoneParser(zone, origin=origin, ttl=ttl))
'Unpack from buffer'
@classmethod def parse(cls, buffer, length):
try: data = buffer.get(length) return cls(data) except (BufferError, BimapError) as e: raise DNSError(('Error unpacking RD [offset=%d]: %s' % (buffer.offset, e)))
'Create new record from zone format data RD is a list of strings parsed from DiG output'
@classmethod def fromZone(cls, rd, origin=None):
return cls(binascii.unhexlify(rd[(-1)].encode('ascii')))
'Pack record into buffer'
def pack(self, buffer):
buffer.append(self.data)
'Default \'repr\' format should be equivalent to RD zone format'
def __repr__(self):
return binascii.hexlify(self.data).decode()
'address/port - upstream server ttl - default ttl for intercept records intercept - list of wildcard RRs to respond to (zone format) skip - list of wildcard labels to skip nxdomain - list of wildcard labels to retudn NXDOMAIN timeout - timeout for upstream server'
def __init__(self, address, port, ttl, intercept, skip, nxdomain, timeout=0):
self.address = address self.port = port self.ttl = parse_time(ttl) self.skip = skip self.nxdomain = nxdomain self.timeout = timeout self.zone = [] for i in intercept: if (i == '-'): i = sys.stdin.read() for rr in RR.fromZone(i, ttl=self.ttl): self.zone.append((rr.rname, QTYPE[rr.rtype], rr))
'If \'length\' is specified the buffer is created with an initial size'
def __init__(self, length=None):
if length: self.__bytes = array.array('B', ('\x00' * length)) else: self.__bytes = array.array('B')
'Sets the value of the packet buffer from the string \'data\''
def set_bytes_from_string(self, data):
self.__bytes = array.array('B', data)
'Returns the packet buffer as a string object'
def get_buffer_as_string(self):
return self.__bytes.tostring()
'Returns the packet buffer as an array'
def get_bytes(self):
return self.__bytes
'Set the packet buffer from an array'
def set_bytes(self, bytes):
self.__bytes = array.array('B', bytes.tolist())
'Set byte at \'index\' to \'value\''
def set_byte(self, index, value):
index = self.__validate_index(index, 1) self.__bytes[index] = value
'Return byte at \'index\''
def get_byte(self, index):
index = self.__validate_index(index, 1) return self.__bytes[index]
'Set 2-byte word at \'index\' to \'value\'. See struct module\'s documentation to understand the meaning of \'order\'.'
def set_word(self, index, value, order='!'):
index = self.__validate_index(index, 2) ary = array.array('B', struct.pack((order + 'H'), value)) if ((-2) == index): self.__bytes[index:] = ary else: self.__bytes[index:(index + 2)] = ary
'Return 2-byte word at \'index\'. See struct module\'s documentation to understand the meaning of \'order\'.'
def get_word(self, index, order='!'):
index = self.__validate_index(index, 2) if ((-2) == index): bytes = self.__bytes[index:] else: bytes = self.__bytes[index:(index + 2)] (value,) = struct.unpack((order + 'H'), bytes.tostring()) return value
'Set 4-byte \'value\' at \'index\'. See struct module\'s documentation to understand the meaning of \'order\'.'
def set_long(self, index, value, order='!'):
index = self.__validate_index(index, 4) ary = array.array('B', struct.pack((order + 'L'), value)) if ((-4) == index): self.__bytes[index:] = ary else: self.__bytes[index:(index + 4)] = ary
'Return 4-byte value at \'index\'. See struct module\'s documentation to understand the meaning of \'order\'.'
def get_long(self, index, order='!'):
index = self.__validate_index(index, 4) if ((-4) == index): bytes = self.__bytes[index:] else: bytes = self.__bytes[index:(index + 4)] (value,) = struct.unpack((order + 'L'), bytes.tostring()) return value
'Set 8-byte \'value\' at \'index\'. See struct module\'s documentation to understand the meaning of \'order\'.'
def set_long_long(self, index, value, order='!'):
index = self.__validate_index(index, 8) ary = array.array('B', struct.pack((order + 'Q'), value)) if ((-8) == index): self.__bytes[index:] = ary else: self.__bytes[index:(index + 8)] = ary
'Return 8-byte value at \'index\'. See struct module\'s documentation to understand the meaning of \'order\'.'
def get_long_long(self, index, order='!'):
index = self.__validate_index(index, 8) if ((-8) == index): bytes = self.__bytes[index:] else: bytes = self.__bytes[index:(index + 8)] (value,) = struct.unpack((order + 'Q'), bytes.tostring()) return value
'Return 4-byte value at \'index\' as an IP string'
def get_ip_address(self, index):
index = self.__validate_index(index, 4) if ((-4) == index): bytes = self.__bytes[index:] else: bytes = self.__bytes[index:(index + 4)] return socket.inet_ntoa(bytes.tostring())
'Set 4-byte value at \'index\' from \'ip_string\''
def set_ip_address(self, index, ip_string):
index = self.__validate_index(index, 4) raw = socket.inet_aton(ip_string) (b1, b2, b3, b4) = struct.unpack('BBBB', raw) self.set_byte(index, b1) self.set_byte((index + 1), b2) self.set_byte((index + 2), b3) self.set_byte((index + 3), b4)
'Set 16-bit checksum at \'index\' by calculating checksum of \'data\''
def set_checksum_from_data(self, index, data):
self.set_word(index, self.compute_checksum(data))
'Return the one\'s complement of the one\'s complement sum of all the 16-bit words in \'anArray\''
def compute_checksum(self, anArray):
nleft = len(anArray) sum = 0 pos = 0 while (nleft > 1): sum = ((anArray[pos] * 256) + (anArray[(pos + 1)] + sum)) pos = (pos + 2) nleft = (nleft - 2) if (nleft == 1): sum = (sum + (anArray[pos] * 256)) return self.normalize_checksum(sum)
'This method performs two tasks: to allocate enough space to fit the elements at positions index through index+size, and to adjust negative indexes to their absolute equivalent.'
def __validate_index(self, index, size):
orig_index = index curlen = len(self.__bytes) if (index < 0): index = (curlen + index) diff = ((index + size) - curlen) if (diff > 0): self.__bytes.fromstring(('\x00' * diff)) if (orig_index < 0): orig_index -= diff return orig_index
'Set \'aHeader\' as the child of this protocol layer'
def contains(self, aHeader):
self.__child = aHeader aHeader.set_parent(self)
'Set the header \'my_parent\' as the parent of this protocol layer'
def set_parent(self, my_parent):
self.__parent = my_parent
'Return the child of this protocol layer'
def child(self):
return self.__child
'Return the parent of this protocol layer'
def parent(self):
return self.__parent
'Break the hierarchy parent/child child/parent'
def unlink_child(self):
if self.__child: self.__child.set_parent(None) self.__child = None
'Return frame header size'
def get_header_size(self):
return self.__HEADER_SIZE
'Return frame tail size'
def get_tail_size(self):
return self.__TAIL_SIZE
'Return frame body size'
def get_body_size(self):
self.__update_body_from_child() return self.__BODY_SIZE
'Return frame total size'
def get_size(self):
return ((self.get_header_size() + self.get_body_size()) + self.get_tail_size())
'Load the packet body from string. WARNING: Using this function will break the hierarchy of preceding protocol layer'
def load_body(self, aBuffer):
self.unlink_child() self.__BODY_SIZE = len(aBuffer) self.__body.set_bytes_from_string(aBuffer)
'Load the whole packet from a stringWARNING: Using this function will break the hierarchy of preceding protocol layer'
def load_packet(self, aBuffer):
self.unlink_child() self.__extract_header(aBuffer) self.__extract_body(aBuffer) self.__extract_tail(aBuffer)
'Returns all data from children of this header as string'
def get_data_as_string(self):
if self.child(): return self.child().get_packet() else: return None
'Returns the raw representation of this packet and its children as a string. The output from this method is a packet ready to be transmitted over the wire.'
def get_packet(self):
self.calculate_checksum() data = self.get_data_as_string() if data: return (self.get_buffer_as_string() + data) else: return self.get_buffer_as_string()
'Return the size of this header and all of it\'s children'
def get_size(self):
tmp_value = self.get_header_size() if self.child(): tmp_value = (tmp_value + self.child().get_size()) return tmp_value
'Calculate and set the checksum for this header'
def calculate_checksum(self):
pass
'Pseudo headers can be used to limit over what content will the checksums be calculated.'
def get_pseudo_header(self):
return array.array('B')
'Properly set the state of this instance to reflect that of the raw packet passed as argument.'
def load_header(self, aBuffer):
self.set_bytes_from_string(aBuffer) hdr_len = self.get_header_size() if (len(aBuffer) < hdr_len): diff = (hdr_len - len(aBuffer)) for i in range(0, diff): aBuffer += '\x00' self.set_bytes_from_string(aBuffer[:hdr_len])
'Return the size of this header, that is, not counting neither the size of the children nor of the parents.'
def get_header_size(self):
raise RuntimeError(('Method %s.get_header_size must be overridden.' % self.__class__))
'Returns Tag Protocol Identifier'
def get_tpid(self):
return self.get_word(0)
'Sets Tag Protocol Identifier'
def set_tpid(self, value):
return self.set_word(0, value)
'Returns Priority Code Point'
def get_pcp(self):
return ((self.get_byte(2) & 224) >> 5)
'Sets Priority Code Point'
def set_pcp(self, value):
orig_value = self.get_byte(2) self.set_byte(2, ((orig_value & 31) | ((value & 7) << 5)))
'Returns Drop Eligible Indicator'
def get_dei(self):
return ((self.get_byte(2) & 16) >> 4)
'Sets Drop Eligible Indicator'
def set_dei(self, value):
orig_value = self.get_byte(2) self.set_byte(2, ((orig_value | 16) if value else (orig_value & 239)))
'Returns VLAN Identifier'
def get_vid(self):
return (self.get_word(2) & 4095)
'Sets VLAN Identifier'
def set_vid(self, value):
orig_value = self.get_word(2) self.set_word(2, ((orig_value & 61440) | (value & 4095)))
'Set ethernet data type field to \'aValue\''
def set_ether_type(self, aValue):
self.set_word((12 + (4 * self.tag_cnt)), aValue)
'Return ethernet data type field'
def get_ether_type(self):
return self.get_word((12 + (4 * self.tag_cnt)))
'Returns an EthernetTag initialized from index-th VLAN tag. The tags are numbered from 0 to self.tag_cnt-1 as they appear in the frame. It is possible to use negative indexes as well.'
def get_tag(self, index):
index = self.__validate_tag_index(index) return EthernetTag(self.get_long((12 + (4 * index))))
'Sets the index-th VLAN tag to contents of an EthernetTag object. The tags are numbered from 0 to self.tag_cnt-1 as they appear in the frame. It is possible to use negative indexes as well.'
def set_tag(self, index, tag):
index = self.__validate_tag_index(index) pos = (12 + (4 * index)) for (i, val) in enumerate(tag.get_bytes()): self.set_byte((pos + i), val)
'Inserts contents of an EthernetTag object before the index-th VLAN tag. Index defaults to 0 (the top of the stack).'
def push_tag(self, tag, index=0):
if (index < 0): index += self.tag_cnt pos = (12 + (4 * max(0, min(index, self.tag_cnt)))) data = self.get_bytes() data[pos:pos] = tag.get_bytes() self.set_bytes(data) self.tag_cnt += 1
'Removes the index-th VLAN tag and returns it as an EthernetTag object. Index defaults to 0 (the top of the stack).'
def pop_tag(self, index=0):
index = self.__validate_tag_index(index) pos = (12 + (4 * index)) tag = self.get_long(pos) data = self.get_bytes() del data[pos:(pos + 4)] self.set_bytes(data) self.tag_cnt -= 1 return EthernetTag(tag)
'Return size of Ethernet header'
def get_header_size(self):
return (14 + (4 * self.tag_cnt))
'Return 48 bit destination ethernet address as a 6 byte array'
def get_ether_dhost(self):
return self.get_bytes()[0:6]
'Set destination ethernet address from 6 byte array \'aValue\''
def set_ether_dhost(self, aValue):
for i in range(0, 6): self.set_byte(i, aValue[i])
'Return 48 bit source ethernet address as a 6 byte array'
def get_ether_shost(self):
return self.get_bytes()[6:12]
'Set source ethernet address from 6 byte array \'aValue\''
def set_ether_shost(self, aValue):
for i in range(0, 6): self.set_byte((i + 6), aValue[i])
'Adjusts negative indices to their absolute equivalents. Raises IndexError when out of range <0, self.tag_cnt-1>.'
def __validate_tag_index(self, index):
if (index < 0): index += self.tag_cnt if ((index < 0) or (index >= self.tag_cnt)): raise IndexError('Tag index out of range') return index
'Sets the packet type field to type'
def set_type(self, type):
self.set_word(0, type)
'Returns the packet type field'
def get_type(self):
return self.get_word(0)
'Sets the ARPHDR value for the link layer device type'
def set_arphdr(self, value):
self.set_word(2, type)
'Returns the ARPHDR value for the link layer device type'
def get_arphdr(self):
return self.get_word(2)
'Sets the length of the sender\'s address field to len'
def set_addr_len(self, len):
self.set_word(4, len)
'Returns the length of the sender\'s address field'
def get_addr_len(self):
return self.get_word(4)
'Sets the sender\'s address field to addr. Addr must be at most 8-byte long.'
def set_addr(self, addr):
if (len(addr) < 8): addr += ('\x00' * (8 - len(addr))) self.get_bytes()[6:14] = addr
'Returns the sender\'s address field'
def get_addr(self):
return self.get_bytes()[6:14].tostring()
'Set ethernet data type field to \'aValue\''
def set_ether_type(self, aValue):
self.set_word(14, aValue)
'Return ethernet data type field'
def get_ether_type(self):
return self.get_word(14)
'Return size of packet header'
def get_header_size(self):
return 16
'Returns entire packet including child data as a string. This is the function used to extract the final packet'
def get_packet(self):
if len(self.__option_list): self.set_th_off((self.get_header_size() / 4)) self.calculate_checksum() bytes = (self.get_bytes() + self.get_padded_options()) data = self.get_data_as_string() if data: return (bytes.tostring() + data) else: return bytes.tostring()
'Return an array containing all options padded to a 4 byte boundry'
def get_padded_options(self):
op_buf = array.array('B') for op in self.__option_list: op_buf += op.get_bytes() num_pad = ((4 - (len(op_buf) % 4)) % 4) if num_pad: op_buf.fromstring(('\x00' * num_pad)) return op_buf
'size: number of bytes in the field'
def __init__(self, size):
self.size = size
'Perform protocol negotiation :param string preferredDialect: the dialect desired to talk with the target server. If None is specified the highest one available will be used :param string flags1: the SMB FLAGS capabilities :param string flags2: the SMB FLAGS2 capabilities :param string negoData: data to be sent as part of the nego handshake :return: True, raises a Session Error if error.'
def negotiateSession(self, preferredDialect=None, flags1=(smb.SMB.FLAGS1_PATHCASELESS | smb.SMB.FLAGS1_CANONICALIZED_PATHS), flags2=((smb.SMB.FLAGS2_EXTENDED_SECURITY | smb.SMB.FLAGS2_NT_STATUS) | smb.SMB.FLAGS2_LONG_NAMES), negoData='\x02NT LM 0.12\x00\x02SMB 2.002\x00\x02SMB 2.???\x00'):
if ((self._sess_port == nmb.SMB_SESSION_PORT) and (self._remoteName == '*SMBSERVER')): self._remoteName = self._remoteHost elif ((self._sess_port == nmb.NETBIOS_SESSION_PORT) and (self._remoteName == '*SMBSERVER')): nb = nmb.NetBIOS() try: res = nb.getnetbiosname(self._remoteHost) except: pass else: self._remoteName = res hostType = nmb.TYPE_SERVER if (preferredDialect is None): packet = self._negotiateSession(self._myName, self._remoteName, self._remoteHost, self._sess_port, self._timeout, True, flags1=flags1, flags2=flags2, data=negoData) if (packet[0] == '\xfe'): self._SMBConnection = smb3.SMB3(self._remoteName, self._remoteHost, self._myName, hostType, self._sess_port, self._timeout, session=self._nmbSession, negSessionResponse=SMB2Packet(packet)) else: self._SMBConnection = smb.SMB(self._remoteName, self._remoteHost, self._myName, hostType, self._sess_port, self._timeout, session=self._nmbSession, negPacket=packet) elif (preferredDialect == smb.SMB_DIALECT): self._SMBConnection = smb.SMB(self._remoteName, self._remoteHost, self._myName, hostType, self._sess_port, self._timeout) elif (preferredDialect in [SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30]): self._SMBConnection = smb3.SMB3(self._remoteName, self._remoteHost, self._myName, hostType, self._sess_port, self._timeout, preferredDialect=preferredDialect) else: LOG.critical('Unknown dialect ', preferredDialect) raise if isinstance(self._SMBConnection, smb.SMB): self._SMBConnection.set_flags(flags1=flags1, flags2=flags2) return True
'returns the SMB/SMB3 instance being used. Useful for calling low level methods'
def getSMBServer(self):
return self._SMBConnection
'logins into the target system :param string user: username :param string password: password for the user :param string domain: domain where the account is valid for :param string lmhash: LMHASH used to authenticate using hashes (password is not used) :param string nthash: NTHASH used to authenticate using hashes (password is not used) :param bool ntlmFallback: If True it will try NTLMv1 authentication if NTLMv2 fails. Only available for SMBv1 :return: None, raises a Session Error if error.'
def login(self, user, password, domain='', lmhash='', nthash='', ntlmFallback=True):
self._ntlmFallback = ntlmFallback try: if (self.getDialect() == smb.SMB_DIALECT): return self._SMBConnection.login(user, password, domain, lmhash, nthash, ntlmFallback) else: return self._SMBConnection.login(user, password, domain, lmhash, nthash) except (smb.SessionError, smb3.SessionError) as e: raise SessionError(e.get_error_code())
'logins into the target system explicitly using Kerberos. Hashes are used if RC4_HMAC is supported. :param string user: username :param string password: password for the user :param string domain: domain where the account is valid for (required) :param string lmhash: LMHASH used to authenticate using hashes (password is not used) :param string nthash: NTHASH used to authenticate using hashes (password is not used) :param string aesKey: aes256-cts-hmac-sha1-96 or aes128-cts-hmac-sha1-96 used for Kerberos authentication :param string kdcHost: hostname or IP Address for the KDC. If None, the domain will be used (it needs to resolve tho) :param struct TGT: If there\'s a TGT available, send the structure here and it will be used :param struct TGS: same for TGS. See smb3.py for the format :param bool useCache: whether or not we should use the ccache for credentials lookup. If TGT or TGS are specified this is False :return: None, raises a Session Error if error.'
def kerberosLogin(self, user, password, domain='', lmhash='', nthash='', aesKey='', kdcHost=None, TGT=None, TGS=None, useCache=True):
import os from impacket.krb5.ccache import CCache from impacket.krb5.kerberosv5 import KerberosError from impacket.krb5 import constants from impacket.ntlm import compute_lmhash, compute_nthash self._kdcHost = kdcHost self._useCache = useCache if ((TGT is not None) or (TGS is not None)): useCache = False if (useCache is True): try: ccache = CCache.loadFile(os.getenv('KRB5CCNAME')) except: pass else: LOG.debug(('Using Kerberos Cache: %s' % os.getenv('KRB5CCNAME'))) if (domain == ''): domain = ccache.principal.realm['data'] LOG.debug(('Domain retrieved from CCache: %s' % domain)) principal = ('cifs/%s@%s' % (self.getRemoteName().upper(), domain.upper())) creds = ccache.getCredential(principal) if (creds is None): principal = ('krbtgt/%s@%s' % (domain.upper(), domain.upper())) creds = ccache.getCredential(principal) if (creds is not None): TGT = creds.toTGT() LOG.debug('Using TGT from cache') else: LOG.debug('No valid credentials found in cache. ') else: TGS = creds.toTGS(principal) LOG.debug('Using TGS from cache') if ((user == '') and (creds is not None)): user = creds['client'].prettyPrint().split('@')[0] LOG.debug(('Username retrieved from CCache: %s' % user)) elif ((user == '') and (len(ccache.principal.components) > 0)): user = ccache.principal.components[0]['data'] LOG.debug(('Username retrieved from CCache: %s' % user)) while True: try: if (self.getDialect() == smb.SMB_DIALECT): return self._SMBConnection.kerberos_login(user, password, domain, lmhash, nthash, aesKey, kdcHost, TGT, TGS) return self._SMBConnection.kerberosLogin(user, password, domain, lmhash, nthash, aesKey, kdcHost, TGT, TGS) except (smb.SessionError, smb3.SessionError) as e: raise SessionError(e.get_error_code()) except KerberosError as e: if (e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value): if ((lmhash is '') and (nthash is '') and ((aesKey is '') or (aesKey is None)) and (TGT is None) and (TGS is None)): from impacket.ntlm import compute_lmhash, compute_nthash lmhash = compute_lmhash(password) nthash = compute_nthash(password) else: raise e else: raise e
'get a list of available shares at the connected target :return: a list containing dict entries for each share, raises exception if error'
def listShares(self):
from impacket.dcerpc.v5 import transport, srvs rpctransport = transport.SMBTransport(self.getRemoteName(), self.getRemoteHost(), filename='\\srvsvc', smb_connection=self) dce = rpctransport.get_dce_rpc() dce.connect() dce.bind(srvs.MSRPC_UUID_SRVS) resp = srvs.hNetrShareEnum(dce, 1) return resp['InfoStruct']['ShareInfo']['Level1']['Buffer']
'list the files/directories under shareName/path :param string shareName: a valid name for the share where the files/directories are going to be searched :param string path: a base path relative to shareName :password string: the password for the share :return: a list containing smb.SharedFile items, raises a SessionError exception if error.'
def listPath(self, shareName, path, password=None):
try: return self._SMBConnection.list_path(shareName, path, password) except (smb.SessionError, smb3.SessionError) as e: raise SessionError(e.get_error_code())
'creates a remote file :param HANDLE treeId: a valid handle for the share where the file is to be created :param string pathName: the path name of the file to create :return: a valid file descriptor, if not raises a SessionError exception.'
def createFile(self, treeId, pathName, desiredAccess=GENERIC_ALL, shareMode=((FILE_SHARE_READ | FILE_SHARE_WRITE) | FILE_SHARE_DELETE), creationOption=FILE_NON_DIRECTORY_FILE, creationDisposition=FILE_OVERWRITE_IF, fileAttributes=FILE_ATTRIBUTE_NORMAL, impersonationLevel=SMB2_IL_IMPERSONATION, securityFlags=0, oplockLevel=SMB2_OPLOCK_LEVEL_NONE, createContexts=None):
if (self.getDialect() == smb.SMB_DIALECT): (_, flags2) = self._SMBConnection.get_flags() pathName = pathName.replace('/', '\\') pathName = (pathName.encode('utf-16le') if (flags2 & smb.SMB.FLAGS2_UNICODE) else pathName) ntCreate = smb.SMBCommand(smb.SMB.SMB_COM_NT_CREATE_ANDX) ntCreate['Parameters'] = smb.SMBNtCreateAndX_Parameters() ntCreate['Data'] = smb.SMBNtCreateAndX_Data(flags=flags2) ntCreate['Parameters']['FileNameLength'] = len(pathName) ntCreate['Parameters']['AccessMask'] = desiredAccess ntCreate['Parameters']['FileAttributes'] = fileAttributes ntCreate['Parameters']['ShareAccess'] = shareMode ntCreate['Parameters']['Disposition'] = creationDisposition ntCreate['Parameters']['CreateOptions'] = creationOption ntCreate['Parameters']['Impersonation'] = impersonationLevel ntCreate['Parameters']['SecurityFlags'] = securityFlags ntCreate['Parameters']['CreateFlags'] = 22 ntCreate['Data']['FileName'] = pathName if (flags2 & smb.SMB.FLAGS2_UNICODE): ntCreate['Data']['Pad'] = 0 if (createContexts is not None): LOG.error('CreateContexts not supported in SMB1') try: return self._SMBConnection.nt_create_andx(treeId, pathName, cmd=ntCreate) except (smb.SessionError, smb3.SessionError) as e: raise SessionError(e.get_error_code()) else: try: return self._SMBConnection.create(treeId, pathName, desiredAccess, shareMode, creationOption, creationDisposition, fileAttributes, impersonationLevel, securityFlags, oplockLevel, createContexts) except (smb.SessionError, smb3.SessionError) as e: raise SessionError(e.get_error_code())
'opens a remote file :param HANDLE treeId: a valid handle for the share where the file is to be opened :param string pathName: the path name to open :return: a valid file descriptor, if not raises a SessionError exception.'
def openFile(self, treeId, pathName, desiredAccess=(FILE_READ_DATA | FILE_WRITE_DATA), shareMode=FILE_SHARE_READ, creationOption=FILE_NON_DIRECTORY_FILE, creationDisposition=FILE_OPEN, fileAttributes=FILE_ATTRIBUTE_NORMAL, impersonationLevel=SMB2_IL_IMPERSONATION, securityFlags=0, oplockLevel=SMB2_OPLOCK_LEVEL_NONE, createContexts=None):
if (self.getDialect() == smb.SMB_DIALECT): (_, flags2) = self._SMBConnection.get_flags() pathName = pathName.replace('/', '\\') pathName = (pathName.encode('utf-16le') if (flags2 & smb.SMB.FLAGS2_UNICODE) else pathName) ntCreate = smb.SMBCommand(smb.SMB.SMB_COM_NT_CREATE_ANDX) ntCreate['Parameters'] = smb.SMBNtCreateAndX_Parameters() ntCreate['Data'] = smb.SMBNtCreateAndX_Data(flags=flags2) ntCreate['Parameters']['FileNameLength'] = len(pathName) ntCreate['Parameters']['AccessMask'] = desiredAccess ntCreate['Parameters']['FileAttributes'] = fileAttributes ntCreate['Parameters']['ShareAccess'] = shareMode ntCreate['Parameters']['Disposition'] = creationDisposition ntCreate['Parameters']['CreateOptions'] = creationOption ntCreate['Parameters']['Impersonation'] = impersonationLevel ntCreate['Parameters']['SecurityFlags'] = securityFlags ntCreate['Parameters']['CreateFlags'] = 22 ntCreate['Data']['FileName'] = pathName if (flags2 & smb.SMB.FLAGS2_UNICODE): ntCreate['Data']['Pad'] = 0 if (createContexts is not None): LOG.error('CreateContexts not supported in SMB1') try: return self._SMBConnection.nt_create_andx(treeId, pathName, cmd=ntCreate) except (smb.SessionError, smb3.SessionError) as e: raise SessionError(e.get_error_code()) else: try: return self._SMBConnection.create(treeId, pathName, desiredAccess, shareMode, creationOption, creationDisposition, fileAttributes, impersonationLevel, securityFlags, oplockLevel, createContexts) except (smb.SessionError, smb3.SessionError) as e: raise SessionError(e.get_error_code())
'writes data to a file :param HANDLE treeId: a valid handle for the share where the file is to be written :param HANDLE fileId: a valid handle for the file :param string data: buffer with the data to write :param integer offset: offset where to start writing the data :return: amount of bytes written, if not raises a SessionError exception.'
def writeFile(self, treeId, fileId, data, offset=0):
try: return self._SMBConnection.writeFile(treeId, fileId, data, offset) except (smb.SessionError, smb3.SessionError) as e: raise SessionError(e.get_error_code())
'reads data from a file :param HANDLE treeId: a valid handle for the share where the file is to be read :param HANDLE fileId: a valid handle for the file to be read :param integer offset: offset where to start reading the data :param integer bytesToRead: amount of bytes to attempt reading. If None, it will attempt to read Dialect[\'MaxBufferSize\'] bytes. :param boolean singleCall: If True it won\'t attempt to read all bytesToRead. It will only make a single read call :return: the data read, if not raises a SessionError exception. Length of data read is not always bytesToRead'
def readFile(self, treeId, fileId, offset=0, bytesToRead=None, singleCall=True):
finished = False data = '' maxReadSize = self._SMBConnection.getIOCapabilities()['MaxReadSize'] remainingBytesToRead = bytesToRead while (not finished): if (remainingBytesToRead > maxReadSize): toRead = maxReadSize else: toRead = remainingBytesToRead try: bytesRead = self._SMBConnection.read_andx(treeId, fileId, offset, toRead) except (smb.SessionError, smb3.SessionError) as e: if (e.get_error_code() == nt_errors.STATUS_END_OF_FILE): toRead = '' break else: raise SessionError(e.get_error_code()) data += bytesRead if (len(data) >= bytesToRead): finished = True elif (len(bytesRead) == 0): finished = True elif (singleCall is True): finished = True else: offset += len(bytesRead) remainingBytesToRead -= len(bytesRead) return data
'closes a file handle :param HANDLE treeId: a valid handle for the share where the file is to be opened :param HANDLE fileId: a valid handle for the file/directory to be closed :return: None, raises a SessionError exception if error.'
def closeFile(self, treeId, fileId):
try: return self._SMBConnection.close(treeId, fileId) except (smb.SessionError, smb3.SessionError) as e: raise SessionError(e.get_error_code())
'removes a file :param string shareName: a valid name for the share where the file is to be deleted :param string pathName: the path name to remove :return: None, raises a SessionError exception if error.'
def deleteFile(self, shareName, pathName):
try: return self._SMBConnection.remove(shareName, pathName) except (smb.SessionError, smb3.SessionError) as e: raise SessionError(e.get_error_code())