Commit 6ed107c8 authored by Matthew Pounsett's avatar Matthew Pounsett

fixing line-endings to be unix

parent 73d9e61e
############################################################################ ############################################################################
# Copyright (C) 2016 Internet Systems Consortium, Inc. ("ISC") # Copyright (C) 2016 Internet Systems Consortium, Inc. ("ISC")
# #
# Permission to use, copy, modify, and/or distribute this software for any # Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above # purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies. # copyright notice and this permission notice appear in all copies.
# #
# THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE. # PERFORMANCE OF THIS SOFTWARE.
############################################################################ ############################################################################
# rndc.py # rndc.py
# This module implements the RNDC control protocol. # This module implements the RNDC control protocol.
############################################################################ ############################################################################
from collections import OrderedDict from collections import OrderedDict
from exceptions import TypeError from exceptions import TypeError
import time import time
import struct import struct
import hashlib import hashlib
import hmac import hmac
import base64 import base64
import random import random
import socket import socket
class rndc(object): class rndc(object):
"""RNDC protocol client library""" """RNDC protocol client library"""
__algos = {'md5': 157, __algos = {'md5': 157,
'sha1': 161, 'sha1': 161,
'sha224': 162, 'sha224': 162,
'sha256': 163, 'sha256': 163,
'sha384': 164, 'sha384': 164,
'sha512': 165} 'sha512': 165}
def __init__(self, host, algo, secret): def __init__(self, host, algo, secret):
"""Creates a persistent connection to RNDC and logs in """Creates a persistent connection to RNDC and logs in
host - (ip, port) tuple host - (ip, port) tuple
algo - HMAC algorithm, one of md5, sha1, sha224, sha256, sha384, sha512 algo - HMAC algorithm, one of md5, sha1, sha224, sha256, sha384, sha512
secret - HMAC secret, base64 encoded""" secret - HMAC secret, base64 encoded"""
self.host = host self.host = host
self.algo = algo self.algo = algo
self.hlalgo = getattr(hashlib, algo) self.hlalgo = getattr(hashlib, algo)
self.secret = base64.b64decode(secret) self.secret = base64.b64decode(secret)
self.ser = random.randint(0, 1 << 24) self.ser = random.randint(0, 1 << 24)
self.nonce = None self.nonce = None
self.__connect_login() self.__connect_login()
def call(self, cmd): def call(self, cmd):
"""Call a RNDC command, all parsing is done on the server side """Call a RNDC command, all parsing is done on the server side
cmd - a complete string with a command (eg 'reload zone example.com') cmd - a complete string with a command (eg 'reload zone example.com')
""" """
return dict(self.__command(type=cmd)['_data']) return dict(self.__command(type=cmd)['_data'])
def __serialize_dict(self, data, ignore_auth=False): def __serialize_dict(self, data, ignore_auth=False):
rv = '' rv = ''
for k, v in data.iteritems(): for k, v in data.iteritems():
if ignore_auth and k == '_auth': if ignore_auth and k == '_auth':
continue continue
rv += chr(len(k)) rv += chr(len(k))
rv += k rv += k
if type(v) == str: if type(v) == str:
rv += struct.pack('>BI', 1, len(v)) + v rv += struct.pack('>BI', 1, len(v)) + v
elif type(v) == OrderedDict: elif type(v) == OrderedDict:
sd = self.__serialize_dict(v) sd = self.__serialize_dict(v)
rv += struct.pack('>BI', 2, len(sd)) + sd rv += struct.pack('>BI', 2, len(sd)) + sd
else: else:
raise NotImplementedError('Cannot serialize element of type %s' raise NotImplementedError('Cannot serialize element of type %s'
% type(v)) % type(v))
return rv return rv
def __prep_message(self, *args, **kwargs): def __prep_message(self, *args, **kwargs):
self.ser += 1 self.ser += 1
now = int(time.time()) now = int(time.time())
data = OrderedDict(*args, **kwargs) data = OrderedDict(*args, **kwargs)
d = OrderedDict() d = OrderedDict()
d['_auth'] = OrderedDict() d['_auth'] = OrderedDict()
d['_ctrl'] = OrderedDict() d['_ctrl'] = OrderedDict()
d['_ctrl']['_ser'] = str(self.ser) d['_ctrl']['_ser'] = str(self.ser)
d['_ctrl']['_tim'] = str(now) d['_ctrl']['_tim'] = str(now)
d['_ctrl']['_exp'] = str(now+60) d['_ctrl']['_exp'] = str(now+60)
if self.nonce is not None: if self.nonce is not None:
d['_ctrl']['_nonce'] = self.nonce d['_ctrl']['_nonce'] = self.nonce
d['_data'] = data d['_data'] = data
msg = self.__serialize_dict(d, ignore_auth=True) msg = self.__serialize_dict(d, ignore_auth=True)
hash = hmac.new(self.secret, msg, self.hlalgo).digest() hash = hmac.new(self.secret, msg, self.hlalgo).digest()
bhash = base64.b64encode(hash) bhash = base64.b64encode(hash)
if self.algo == 'md5': if self.algo == 'md5':
d['_auth']['hmd5'] = struct.pack('22s', bhash) d['_auth']['hmd5'] = struct.pack('22s', bhash)
else: else:
d['_auth']['hsha'] = struct.pack('B88s', d['_auth']['hsha'] = struct.pack('B88s',
self.__algos[self.algo], bhash) self.__algos[self.algo], bhash)
msg = self.__serialize_dict(d) msg = self.__serialize_dict(d)
msg = struct.pack('>II', len(msg) + 4, 1) + msg msg = struct.pack('>II', len(msg) + 4, 1) + msg
return msg return msg
def __verify_msg(self, msg): def __verify_msg(self, msg):
if self.nonce is not None and msg['_ctrl']['_nonce'] != self.nonce: if self.nonce is not None and msg['_ctrl']['_nonce'] != self.nonce:
return False return False
bhash = msg['_auth']['hmd5' if self.algo == 'md5' else 'hsha'] bhash = msg['_auth']['hmd5' if self.algo == 'md5' else 'hsha']
bhash += '=' * (4 - (len(bhash) % 4)) bhash += '=' * (4 - (len(bhash) % 4))
remote_hash = base64.b64decode(bhash) remote_hash = base64.b64decode(bhash)
my_msg = self.__serialize_dict(msg, ignore_auth=True) my_msg = self.__serialize_dict(msg, ignore_auth=True)
my_hash = hmac.new(self.secret, my_msg, self.hlalgo).digest() my_hash = hmac.new(self.secret, my_msg, self.hlalgo).digest()
return (my_hash == remote_hash) return (my_hash == remote_hash)
def __command(self, *args, **kwargs): def __command(self, *args, **kwargs):
msg = self.__prep_message(*args, **kwargs) msg = self.__prep_message(*args, **kwargs)
sent = self.socket.send(msg) sent = self.socket.send(msg)
if sent != len(msg): if sent != len(msg):
raise IOError("Cannot send the message") raise IOError("Cannot send the message")
header = self.socket.recv(8) header = self.socket.recv(8)
if len(header) != 8: if len(header) != 8:
# What should we throw here? Bad auth can cause this... # What should we throw here? Bad auth can cause this...
raise IOError("Can't read response header") raise IOError("Can't read response header")
length, version = struct.unpack('>II', header) length, version = struct.unpack('>II', header)
if version != 1: if version != 1:
raise NotImplementedError('Wrong message version %d' % version) raise NotImplementedError('Wrong message version %d' % version)
# it includes the header # it includes the header
length -= 4 length -= 4
data = self.socket.recv(length, socket.MSG_WAITALL) data = self.socket.recv(length, socket.MSG_WAITALL)
if len(data) != length: if len(data) != length:
raise IOError("Can't read response data") raise IOError("Can't read response data")
msg = self.__parse_message(data) msg = self.__parse_message(data)
if not self.__verify_msg(msg): if not self.__verify_msg(msg):
raise IOError("Authentication failure") raise IOError("Authentication failure")
return msg return msg
def __connect_login(self): def __connect_login(self):
self.socket = socket.create_connection(self.host) self.socket = socket.create_connection(self.host)
self.nonce = None self.nonce = None
msg = self.__command(type='null') msg = self.__command(type='null')
self.nonce = msg['_ctrl']['_nonce'] self.nonce = msg['_ctrl']['_nonce']
def __parse_element(self, input): def __parse_element(self, input):
pos = 0 pos = 0
labellen = ord(input[pos]) labellen = ord(input[pos])
pos += 1 pos += 1
label = input[pos:pos+labellen] label = input[pos:pos+labellen]
pos += labellen pos += labellen
type = ord(input[pos]) type = ord(input[pos])
pos += 1 pos += 1
datalen = struct.unpack('>I', input[pos:pos+4])[0] datalen = struct.unpack('>I', input[pos:pos+4])[0]
pos += 4 pos += 4
data = input[pos:pos+datalen] data = input[pos:pos+datalen]
pos += datalen pos += datalen
rest = input[pos:] rest = input[pos:]
if type == 1: # raw binary value if type == 1: # raw binary value
return label, data, rest return label, data, rest
elif type == 2: # dictionary elif type == 2: # dictionary
d = OrderedDict() d = OrderedDict()
while len(data) > 0: while len(data) > 0:
ilabel, value, data = self.__parse_element(data) ilabel, value, data = self.__parse_element(data)
d[ilabel] = value d[ilabel] = value
return label, d, rest return label, d, rest
# TODO type 3 - list # TODO type 3 - list
else: else:
raise NotImplementedError('Unknown element type %d' % type) raise NotImplementedError('Unknown element type %d' % type)
def __parse_message(self, input): def __parse_message(self, input):
rv = OrderedDict() rv = OrderedDict()
hdata = None hdata = None
while len(input) > 0: while len(input) > 0:
label, value, input = self.__parse_element(input) label, value, input = self.__parse_element(input)
rv[label] = value rv[label] = value
return rv return rv
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment