http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/32fef61a/tools/migration/paramiko/util.py ---------------------------------------------------------------------- diff --git a/tools/migration/paramiko/util.py b/tools/migration/paramiko/util.py deleted file mode 100644 index 7cc2e25..0000000 --- a/tools/migration/paramiko/util.py +++ /dev/null @@ -1,299 +0,0 @@ -# Copyright (C) 2003-2007 Robey Pointer <[email protected]> -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Automatically generated by addcopyright.py at 04/03/2012 -# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. - -""" -Useful functions used by the rest of paramiko. -""" - -from __future__ import generators - -import array -from binascii import hexlify, unhexlify -import sys -import struct -import traceback -import threading - -from paramiko.common import * -from paramiko.config import SSHConfig - - -# Change by RogerB - python < 2.3 doesn't have enumerate so we implement it -if sys.version_info < (2,3): - class enumerate: - def __init__ (self, sequence): - self.sequence = sequence - def __iter__ (self): - count = 0 - for item in self.sequence: - yield (count, item) - count += 1 - - -def inflate_long(s, always_positive=False): - "turns a normalized byte string into a long-int (adapted from Crypto.Util.number)" - out = 0L - negative = 0 - if not always_positive and (len(s) > 0) and (ord(s[0]) >= 0x80): - negative = 1 - if len(s) % 4: - filler = '\x00' - if negative: - filler = '\xff' - s = filler * (4 - len(s) % 4) + s - for i in range(0, len(s), 4): - out = (out << 32) + struct.unpack('>I', s[i:i+4])[0] - if negative: - out -= (1L << (8 * len(s))) - return out - -def deflate_long(n, add_sign_padding=True): - "turns a long-int into a normalized byte string (adapted from Crypto.Util.number)" - # after much testing, this algorithm was deemed to be the fastest - s = '' - n = long(n) - while (n != 0) and (n != -1): - s = struct.pack('>I', n & 0xffffffffL) + s - n = n >> 32 - # strip off leading zeros, FFs - for i in enumerate(s): - if (n == 0) and (i[1] != '\000'): - break - if (n == -1) and (i[1] != '\xff'): - break - else: - # degenerate case, n was either 0 or -1 - i = (0,) - if n == 0: - s = '\000' - else: - s = '\xff' - s = s[i[0]:] - if add_sign_padding: - if (n == 0) and (ord(s[0]) >= 0x80): - s = '\x00' + s - if (n == -1) and (ord(s[0]) < 0x80): - s = '\xff' + s - return s - -def format_binary_weird(data): - out = '' - for i in enumerate(data): - out += '%02X' % ord(i[1]) - if i[0] % 2: - out += ' ' - if i[0] % 16 == 15: - out += '\n' - return out - -def format_binary(data, prefix=''): - x = 0 - out = [] - while len(data) > x + 16: - out.append(format_binary_line(data[x:x+16])) - x += 16 - if x < len(data): - out.append(format_binary_line(data[x:])) - return [prefix + x for x in out] - -def format_binary_line(data): - left = ' '.join(['%02X' % ord(c) for c in data]) - right = ''.join([('.%c..' % c)[(ord(c)+63)//95] for c in data]) - return '%-50s %s' % (left, right) - -def hexify(s): - return hexlify(s).upper() - -def unhexify(s): - return unhexlify(s) - -def safe_string(s): - out = '' - for c in s: - if (ord(c) >= 32) and (ord(c) <= 127): - out += c - else: - out += '%%%02X' % ord(c) - return out - -# ''.join([['%%%02X' % ord(c), c][(ord(c) >= 32) and (ord(c) <= 127)] for c in s]) - -def bit_length(n): - norm = deflate_long(n, 0) - hbyte = ord(norm[0]) - if hbyte == 0: - return 1 - bitlen = len(norm) * 8 - while not (hbyte & 0x80): - hbyte <<= 1 - bitlen -= 1 - return bitlen - -def tb_strings(): - return ''.join(traceback.format_exception(*sys.exc_info())).split('\n') - -def generate_key_bytes(hashclass, salt, key, nbytes): - """ - Given a password, passphrase, or other human-source key, scramble it - through a secure hash into some keyworthy bytes. This specific algorithm - is used for encrypting/decrypting private key files. - - @param hashclass: class from L{Crypto.Hash} that can be used as a secure - hashing function (like C{MD5} or C{SHA}). - @type hashclass: L{Crypto.Hash} - @param salt: data to salt the hash with. - @type salt: string - @param key: human-entered password or passphrase. - @type key: string - @param nbytes: number of bytes to generate. - @type nbytes: int - @return: key data - @rtype: string - """ - keydata = '' - digest = '' - if len(salt) > 8: - salt = salt[:8] - while nbytes > 0: - hash_obj = hashclass.new() - if len(digest) > 0: - hash_obj.update(digest) - hash_obj.update(key) - hash_obj.update(salt) - digest = hash_obj.digest() - size = min(nbytes, len(digest)) - keydata += digest[:size] - nbytes -= size - return keydata - -def load_host_keys(filename): - """ - Read a file of known SSH host keys, in the format used by openssh, and - return a compound dict of C{hostname -> keytype ->} L{PKey <paramiko.pkey.PKey>}. - The hostname may be an IP address or DNS name. The keytype will be either - C{"ssh-rsa"} or C{"ssh-dss"}. - - This type of file unfortunately doesn't exist on Windows, but on posix, - it will usually be stored in C{os.path.expanduser("~/.ssh/known_hosts")}. - - Since 1.5.3, this is just a wrapper around L{HostKeys}. - - @param filename: name of the file to read host keys from - @type filename: str - @return: dict of host keys, indexed by hostname and then keytype - @rtype: dict(hostname, dict(keytype, L{PKey <paramiko.pkey.PKey>})) - """ - from paramiko.hostkeys import HostKeys - return HostKeys(filename) - -def parse_ssh_config(file_obj): - """ - Provided only as a backward-compatible wrapper around L{SSHConfig}. - """ - config = SSHConfig() - config.parse(file_obj) - return config - -def lookup_ssh_host_config(hostname, config): - """ - Provided only as a backward-compatible wrapper around L{SSHConfig}. - """ - return config.lookup(hostname) - -def mod_inverse(x, m): - # it's crazy how small python can make this function. - u1, u2, u3 = 1, 0, m - v1, v2, v3 = 0, 1, x - - while v3 > 0: - q = u3 // v3 - u1, v1 = v1, u1 - v1 * q - u2, v2 = v2, u2 - v2 * q - u3, v3 = v3, u3 - v3 * q - if u2 < 0: - u2 += m - return u2 - -_g_thread_ids = {} -_g_thread_counter = 0 -_g_thread_lock = threading.Lock() -def get_thread_id(): - global _g_thread_ids, _g_thread_counter, _g_thread_lock - tid = id(threading.currentThread()) - try: - return _g_thread_ids[tid] - except KeyError: - _g_thread_lock.acquire() - try: - _g_thread_counter += 1 - ret = _g_thread_ids[tid] = _g_thread_counter - finally: - _g_thread_lock.release() - return ret - -def log_to_file(filename, level=DEBUG): - "send paramiko logs to a logfile, if they're not already going somewhere" - l = logging.getLogger("paramiko") - if len(l.handlers) > 0: - return - l.setLevel(level) - f = open(filename, 'w') - lh = logging.StreamHandler(f) - lh.setFormatter(logging.Formatter('%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(_threadid)-3d %(name)s: %(message)s', - '%Y%m%d-%H:%M:%S')) - l.addHandler(lh) - -# make only one filter object, so it doesn't get applied more than once -class PFilter (object): - def filter(self, record): - record._threadid = get_thread_id() - return True -_pfilter = PFilter() - -def get_logger(name): - l = logging.getLogger(name) - l.addFilter(_pfilter) - return l - - -class Counter (object): - """Stateful counter for CTR mode crypto""" - def __init__(self, nbits, initial_value=1L, overflow=0L): - self.blocksize = nbits / 8 - self.overflow = overflow - # start with value - 1 so we don't have to store intermediate values when counting - # could the iv be 0? - if initial_value == 0: - self.value = array.array('c', '\xFF' * self.blocksize) - else: - x = deflate_long(initial_value - 1, add_sign_padding=False) - self.value = array.array('c', '\x00' * (self.blocksize - len(x)) + x) - - def __call__(self): - """Increament the counter and return the new value""" - i = self.blocksize - 1 - while i > -1: - c = self.value[i] = chr((ord(self.value[i]) + 1) % 256) - if c != '\x00': - return self.value.tostring() - i -= 1 - # counter reset - x = deflate_long(self.overflow, add_sign_padding=False) - self.value = array.array('c', '\x00' * (self.blocksize - len(x)) + x) - return self.value.tostring() - - def new(cls, nbits, initial_value=1L, overflow=0L): - return cls(nbits, initial_value=initial_value, overflow=overflow) - new = classmethod(new)
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/32fef61a/tools/migration/paramiko/win_pageant.py ---------------------------------------------------------------------- diff --git a/tools/migration/paramiko/win_pageant.py b/tools/migration/paramiko/win_pageant.py deleted file mode 100644 index 2e8b51b..0000000 --- a/tools/migration/paramiko/win_pageant.py +++ /dev/null @@ -1,143 +0,0 @@ -# Copyright (C) 2005 John Arbash-Meinel <[email protected]> -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by the License. -# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Automatically generated by addcopyright.py at 04/03/2012 -# Modified up by: Todd Whiteman <[email protected]> -# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. - -""" -Functions for communicating with Pageant, the basic windows ssh agent program. -""" - -import os -import struct -import tempfile -import mmap -import array - -# ctypes is part of standard library since Python 2.5 -_has_win32all = False -_has_ctypes = False -try: - # win32gui is preferred over win32ui to avoid MFC dependencies - import win32gui - _has_win32all = True -except ImportError: - try: - import ctypes - _has_ctypes = True - except ImportError: - pass - - -_AGENT_COPYDATA_ID = 0x804e50ba -_AGENT_MAX_MSGLEN = 8192 -# Note: The WM_COPYDATA value is pulled from win32con, as a workaround -win32con_WM_COPYDATA = 74 - - -def _get_pageant_window_object(): - if _has_win32all: - try: - hwnd = win32gui.FindWindow('Pageant', 'Pageant') - return hwnd - except win32gui.error: - pass - elif _has_ctypes: - # Return 0 if there is no Pageant window. - return ctypes.windll.user32.FindWindowA('Pageant', 'Pageant') - return None - - -def can_talk_to_agent(): - """ - Check to see if there is a "Pageant" agent we can talk to. - - This checks both if we have the required libraries (win32all or ctypes) - and if there is a Pageant currently running. - """ - if (_has_win32all or _has_ctypes) and _get_pageant_window_object(): - return True - return False - - -def _query_pageant(msg): - hwnd = _get_pageant_window_object() - if not hwnd: - # Raise a failure to connect exception, pageant isn't running anymore! - return None - - # Write our pageant request string into the file (pageant will read this to determine what to do) - filename = tempfile.mktemp('.pag') - map_filename = os.path.basename(filename) - - f = open(filename, 'w+b') - f.write(msg ) - # Ensure the rest of the file is empty, otherwise pageant will read this - f.write('\0' * (_AGENT_MAX_MSGLEN - len(msg))) - # Create the shared file map that pageant will use to read from - pymap = mmap.mmap(f.fileno(), _AGENT_MAX_MSGLEN, tagname=map_filename, access=mmap.ACCESS_WRITE) - try: - # Create an array buffer containing the mapped filename - char_buffer = array.array("c", map_filename + '\0') - char_buffer_address, char_buffer_size = char_buffer.buffer_info() - # Create a string to use for the SendMessage function call - cds = struct.pack("LLP", _AGENT_COPYDATA_ID, char_buffer_size, char_buffer_address) - - if _has_win32all: - # win32gui.SendMessage should also allow the same pattern as - # ctypes, but let's keep it like this for now... - response = win32gui.SendMessage(hwnd, win32con_WM_COPYDATA, len(cds), cds) - elif _has_ctypes: - _buf = array.array('B', cds) - _addr, _size = _buf.buffer_info() - response = ctypes.windll.user32.SendMessageA(hwnd, win32con_WM_COPYDATA, _size, _addr) - else: - response = 0 - - if response > 0: - datalen = pymap.read(4) - retlen = struct.unpack('>I', datalen)[0] - return datalen + pymap.read(retlen) - return None - finally: - pymap.close() - f.close() - # Remove the file, it was temporary only - os.unlink(filename) - - -class PageantConnection (object): - """ - Mock "connection" to an agent which roughly approximates the behavior of - a unix local-domain socket (as used by Agent). Requests are sent to the - pageant daemon via special Windows magick, and responses are buffered back - for subsequent reads. - """ - - def __init__(self): - self._response = None - - def send(self, data): - self._response = _query_pageant(data) - - def recv(self, n): - if self._response is None: - return '' - ret = self._response[:n] - self._response = self._response[n:] - if self._response == '': - self._response = None - return ret - - def close(self): - pass
