Example #1
0
def crypt(SHELL, brutelen=7, alphanum=False):
    nums = '0123456789'
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    if alphanum:
	keyspace = nums + alpha + alpha.upper()
    else:
	keyspace = nums
    BLOCK_SIZE = 16
    BRUTE_LENGTH = brutelen
    PADDING = '\x00'
    pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
    EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
    #DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
    decoded = ''
    secret = Random.new().read(BLOCK_SIZE-BRUTE_LENGTH)
    secret += ''.join(random.choice(keyspace) for i in range(BRUTE_LENGTH))
    #print secret
    IV = Random.new().read(16)
    checkstring = ''.join(random.choice(nums+alpha) for i in range(BLOCK_SIZE))
    cipher = AES.new(secret)
    encoded = EncodeAES(cipher, SHELL) 
    control = cipher.encrypt(checkstring)
    encoded += secret[:-BRUTE_LENGTH] + control + checkstring
    encoded = base64.b64encode(encoded)
    return encoded
Example #2
0
    def __init__(self):
        super(Xeger, self).__init__()
        self._cache = dict()
        self._categories = {
            "category_digit": lambda: self._alphabets['digits'],
            "category_not_digit": lambda: self._alphabets['nondigits'],
            "category_space": lambda: self._alphabets['whitespace'],
            "category_not_space": lambda: self._alphabets['nonwhitespace'],
            "category_word": lambda: self._alphabets['word'],
            "category_not_word": lambda: self._alphabets['nonword'],
                  }

        self._cases = {"literal": lambda x: unichr(x),
             "not_literal": lambda x: choice(
                                string.printable.replace(unichr(x), '')),
             "at": lambda x: '',
             "in": lambda x: self._handle_in(x),
             "any": lambda x: self.printable(1),
             "range": lambda x: [unichr(i) for i in xrange(x[0], x[1]+1)],
             "category": lambda x: self._categories[x](),
             'branch': lambda x: ''.join(self._handle_state(i) for
                                                            i in choice(x[1])),
             "subpattern": lambda x: self._handle_group(x),
             "assert": lambda x: ''.join(self._handle_state(i) for i in x[1]),
             "assert_not": lambda x: '',
             "groupref": lambda x: self._cache[x],
             'max_repeat': lambda x: self._handle_repeat(*x),
             'negate': lambda x: [False],
             }
Example #3
0
def generate_request(**request_parameters):
    '''Generate a token provisioning request.'''
    default_model = 'MacBookPro%d,%d' % (random.randint(1, 12), random.randint(1, 4))
    default_request_parameters = {
        'timestamp':int(time.time()),
        'token_model':'VSST',
        'otp_algorithm':'HMAC-SHA1-TRUNC-6DIGITS',
        'shared_secret_delivery_method':'HTTPS',
        'manufacturer':'Apple Inc.',
        'serial':''.join(random.choice(string.digits + string.ascii_uppercase) for x in range(12)),
        'model':default_model,
        'app_handle':'iMac010200',
        'client_id_type':'BOARDID',
        'client_id':'Mac-' + ''.join(random.choice('0123456789ABCDEF') for x in range(16)),
        'dist_channel':'Symantec',
        'platform':'iMac',
        'os':default_model,
    }

    default_request_parameters.update(request_parameters)
    request_parameters = default_request_parameters

    data_before_hmac = u'%(timestamp)d%(timestamp)d%(client_id_type)s%(client_id)s%(dist_channel)s' % request_parameters
    request_parameters['data'] = base64.b64encode(
        hmac.new(
            HMAC_KEY,
            data_before_hmac.encode('utf-8'),
            hashlib.sha256
            ).digest()
        ).decode('utf-8')

    return REQUEST_TEMPLATE % request_parameters
Example #4
0
def generate_password(length=16, symbolgroups=DEFAULT_PASSWORD_SYMBOLS):
    """Generate a random password from the supplied symbol groups.

    At least one symbol from each group will be included. Unpredictable
    results if length is less than the number of symbol groups.

    Believed to be reasonably secure (with a reasonable password length!)

    """
    # NOTE(jerdfelt): Some password policies require at least one character
    # from each group of symbols, so start off with one random character
    # from each symbol group
    password = [random.choice(s) for s in symbolgroups]
    # If length < len(symbolgroups), the leading characters will only
    # be from the first length groups. Try our best to not be predictable
    # by shuffling and then truncating.
    random.shuffle(password)
    password = password[:length]
    length -= len(password)

    # then fill with random characters from all symbol groups
    symbols = ''.join(symbolgroups)
    password.extend([random.choice(symbols) for _i in range(length)])

    # finally shuffle to ensure first x characters aren't from a
    # predictable group
    random.shuffle(password)

    return ''.join(password)
Example #5
0
 def _handle_in(self, value):
     candidates = list(chain(*(self._handle_state(i) for
                                                  i in value)))
     if candidates[0] is False:
         candidates = set(string.printable).difference(candidates[1:])
         return choice(list(candidates))
     else:
         return choice(candidates)
Example #6
0
def random_plugin_gus():
    length = 10

    if TESTING:
        global global_debug_counter
        global_debug_counter += 1
        string_value = str(global_debug_counter)
        return u'p_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value
    else:
        return u'p_'+(''.join(random.choice('0123456789') for x in range(length)))
Example #7
0
def random_submission_gus(testingmode=False):
    """
    this need to be not guessable because this secret auth the WB
    during the submission procedure.
    """
    length = 50

    if testingmode:
        return u's_'+(''.join(random.choice('A') for x in range(length)))
    else:
        return u's_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
Example #8
0
def generate_password(range=None, size=16):
    if not range:
        range = string.digits + string.ascii_letters + string.digits
    a = []
    while len(a) < size - 4:
        a.append(random.choice(range))
    while len(a) < size - 2:
        a.append(random.choice(r"+=-@#~,.[]()!%^*$"))
    random.shuffle(a)
    return random.choice(string.ascii_letters) + \
           ''.join(a) + \
           random.choice(string.ascii_letters)
Example #9
0
def random_tip_gus():
    """
    need to be NOT guessable
    """
    length = 50

    if TESTING:
        global global_debug_counter
        global_debug_counter += 1
        string_value = str(global_debug_counter)
        return u't_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value
    else:
        return u't_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
Example #10
0
def random_submission_gus():
    """
    this need to be not guessable because this secret auth the WB
    during the submission procedure.
    """
    length = 50

    if TESTING:
        global global_debug_counter
        global_debug_counter += 1
        string_value = str(global_debug_counter)
        return u's_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value
    else:
        return u's_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
Example #11
0
def random_file_gus():
    """
    need to be random
    XXX file is now starting with f_ and is supposed to be random
    """
    length = 30

    if TESTING:
        global global_debug_counter
        global_debug_counter += 1
        string_value = str(global_debug_counter)
        return u'f_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value
    else:
        return u'f_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
Example #12
0
def random_receiver_gus():
    """
    maybe guessable, because is an information available to the whistleblower, and
    then every time is used as input, need to be checked in coherence, in the context.
    anyway we made it not guessable, just to avoid enumeration.
    """
    length = 20

    if TESTING:
        global global_debug_counter
        global_debug_counter += 1
        string_value = str(global_debug_counter)
        return u'r_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value
    else:
        return u'r_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
Example #13
0
def random_context_gus():
    """
    need to be random (because not all context maybe reachable directly from the
    home page, or not all context need to be disclosed publicly), but need to be
    short, just for do not create a loooong URL
    """
    length = 20

    if TESTING:
        global global_debug_counter
        global_debug_counter += 1
        string_value = str(global_debug_counter)
        return u'c_'+(''.join(random.choice('0') for x in range(length - len(string_value))))+string_value
    else:
        return u'c_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
Example #14
0
 def reset(self):
     self.surface.fill(backgroundcolor)
     self.point = 0
     self.level = 1
     self.count = 0
     self.time = 500
     self.board_show = {i : [SingleBlock(self.surface, BLACK, WHITE) for j in range(NROWS)] for i in range(NCOLS)}
     self.board = {i: [0 for j in range(NROWS + 1)] for i in range(-1, NCOLS + 1)}
     self.board[-1] = [1 for j in range(NROWS + 1)]
     self.board[NCOLS] = [1 for j in range(NROWS + 1)]
     for i in range(-1, NCOLS + 1):
         self.board[i][NROWS] = 1
     self.block = Block(self.board, self.board_show, random.choice(Blocks))
     self.block_next = random.choice(Blocks)
     self.draw()
Example #15
0
 def generate_random_password(self, size=10 ):
     """
     Generates random password of given size
     it ensures -
     1 uppercase
     1 lowercase
     1 digit
     1 punc
     """
     P = [random.choice(s) for s in self.must_set]
     P.extend([random.choice(self.All) 
               for n in range(size-len(self.must_set))])
     n = random.randint(0, MAX_INT) 
     password = self.decode2string(n, P)
     return password
Example #16
0
    def get_db_prep_value(self, value, connection=None, prepared=False):
        if value is None:
            return None

        value = smart_bytes(value)

        if not self._is_encrypted(value):
            padding = self._get_padding(value)
            if padding > 0:
                value += smart_bytes("\0" + ''.join([
                    random.choice(string.printable)
                    for index in range(padding-1)
                ]))
            if self.block_type:
                self.cipher = self.cipher_object.new(
                    self.secret_key,
                    getattr(self.cipher_object, self.block_type),
                    self.iv)
                value = smart_bytes(self.prefix) + binascii.b2a_hex(
                    smart_bytes(self.iv) + self.cipher.encrypt(smart_bytes(value))
                )
            else:
                value = smart_bytes(self.prefix) + binascii.b2a_hex(
                    self.cipher.encrypt(smart_bytes(value))
                )
        return value
Example #17
0
def random_file_gus():
    """
    need to be random
    XXX file is now starting with f_ and is supposed to be random
    """
    length = 30
    return u'f_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
Example #18
0
def random_folder_gus():
    """
    need to be random
    XXX this has been changed to starting d_ for directory.
    """
    length = 20
    return u'd_'+(''.join(random.choice(string.ascii_letters) for x in range(length)))
Example #19
0
    def ranpassgen(self, passlen, lower, upper, spec, dig):

        """ Constructs a random password using the provided parameters.

        :param passlen: the length of the password to be generated
        :param lower: use lower case characters in the password
        :param upper: use upper case characters in the password
        :param spec: use special characters in the password
        :param dig: use digits in the password
        :return: Returns randomly generated password
        """
        char_set = []

        if lower is True:
            char_set.append(self.ascii_lower)

        if upper is True:
            char_set.append(self.ascii_upper)

        if spec is True:
            char_set.append(self.special)

        if dig is True:
            char_set.append(self.digits)

        characters = "".join(char_set[:4])
        password = "".join(random.choice(characters) for i in range(int(passlen)))

        return password
Example #20
0
    def get_db_prep_value(self, value, connection=None, prepared=False):
        if value is None:
            return None

        value = smart_str(value)

        if not self._is_encrypted(value):
            padding = self._get_padding(value)
            if padding > 0:
                value += "\0" + ''.join([
                    random.choice(string.printable)
                    for index in range(padding-1)
                ])
            if self.block_type:
                self.cipher = self.cipher_object.new(
                    self.secret_key,
                    getattr(self.cipher_object, self.block_type),
                    self.iv)
                if PYTHON3 is True:
                    value = self.prefix + binascii.b2a_hex(
                        self.iv + self.cipher.encrypt(value)).decode('utf-8')
                else:
                    value = self.prefix + binascii.b2a_hex(
                        self.iv + self.cipher.encrypt(value))
            else:
                if PYTHON3 is True:
                    print('>>>', value, '-->', len(value)/16)
                    value = self.prefix + binascii.b2a_hex(
                        self.cipher.encrypt(value)).decode('utf-8')
                else:
                    value = self.prefix + binascii.b2a_hex(
                        self.cipher.encrypt(value))
        return value
def pad_message(message):
    """
    Adds padding to the front of the message. Padding is generated by random
    selections from RANDOM_SAMPLE using Crypto.Random.random.choice(). A new
    message is returned in the following format:

                            "{padding}`{message}"

    padding is added to the front to obscure common output from the command
    line i.e. windows sends the stdin to the stdout, beginning with the
    working directory.
    """

    # determine the pad_length based on the key BLOCK_SIZE
    if len(message) < BLOCK_SIZE:
        pad_length = (BLOCK_SIZE - len(message))
    elif len(message) > BLOCK_SIZE:
        pad_length = (len(message) % BLOCK_SIZE)
    else:
        pad_length = BLOCK_SIZE

    if pad_length < 16:
        pad_length += BLOCK_SIZE

    # reduce by one for the delimiter that is added between message and padding
    pad_length -= 1
    padding = ""

    while len(padding) < pad_length:
        padding += random.choice(RANDOM_SAMPLE)

    return"{}`{}".format(padding, message)
Example #22
0
def random_str(length=8):
    '''生成可打印的 [0-9a-zA-Z] 随机字符串.'''
    seeds = string.letters + string.digits
    random_str = ''
    for x in xrange(length):
        random_str += random.choice(seeds)
    return random_str
Example #23
0
    def generate_expiring_request(lifetime, plaintext):
        """
        Generate the parameters needed for an expiring email request with the given payload.
        Payload should be comma-delimited, and the consumer should expect to find and verify
        a timestamp and nonce appended to the given plaintext.
        """

        # Add nonce
        rng = Random.new()
        nonce = ''.join(choice(string.ascii_uppercase + string.digits) for _ in range(256))

        expiry = str(time.time() + lifetime)

        plaintext = (plaintext + "," + expiry + "," + nonce).encode('utf-8')

        # Pad the plaintext to the next full block with commas, because I can't be arsed to
        # write an actually clever parser.
        bs = Blowfish.block_size
        paddinglen = bs - (len(plaintext) % bs)
        plaintext += b',' * paddinglen

        # Generate random IV of size one block.
        iv = rng.read(bs)
        cipher = Blowfish.new(VERIFICATION_SECRET_KEY, Blowfish.MODE_CBC, iv)
        ciphertext = cipher.encrypt(plaintext)

        # Generate the verification hash.
        verification = hashlib.sha256()
        verification.update(plaintext + VERIFICATION_HASH_SECRET.encode('utf-8'))
        verify_hex = verification.hexdigest()

        return base64.urlsafe_b64encode(iv), base64.urlsafe_b64encode(ciphertext), verify_hex
Example #24
0
    def post_request(self, method, filename, request_params={}):
        """
        Generate an API POST request string for an image upload search.

        The POST request string can be sent as is to issue the POST
        request to the API server.

        - `method`, API method being called.
        - `filename`, the filename of the image that is being searched for.
        - `request_params`, the list of search parameters.

        Returns:

        - `request_url`, the URL to send the search to.
        - `boundary`, the boundary to be used in the POST request.
        """
        if filename is None or not len(str(filename).strip()):
            raise APIRequestError("Must specify an image to search for.")

        # Have to generate a boundary, nonce, and date to use in generating a POST
        # request signature
        boundary = ''.join(
            random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
        nonce = self._generate_nonce()
        date = int(time.time())

        api_signature = self._generate_post_hmac_signature(
            "search", boundary, nonce, date, filename,
            request_params=request_params)

        return self._request_url(method, nonce, date, api_signature, request_params), boundary
Example #25
0
def generate_unused_dbkey():
    """
    Returns a id matching /[A-Z]{2}[1-9][0-9]{3}/
    for example WL2007
    """
    # Two upper case letters
    new_key = "".join(random.choice(settings.CHARS) for x in range(2))
    # Four digit number, not starting with zero
    new_key += str(random.choice(settings.NUMBERS[1:10]))
    new_key += "".join(random.choice(settings.NUMBERS) for x in range(3))
    try:
        Profile.objects.get(uid = new_key)
        # If we get to here, the key already exists. generate another one..
        return generate_unused_dbkey()
    except ObjectDoesNotExist:
        return new_key
Example #26
0
def generate_token(length=32):
    """
    Generates a random token containing a-z A-Z 0-9 of size `length`
    Crypto.Random may be a bad choice, consider switching to os.urandom:
    http://stackoverflow.com/a/20469525/263132
    """
    return ''.join(chr(random.choice(_POOL)) for _ in range(length))
 def generate_random_password(self, length = 8):
     #concatination of all chosen sets (uppercase, lowercase, etc.)
     password_set = self.UPPERCASE_LETTERS + self.LOWERCASE_LETTERS + self.DIGITS + self.PUNCTUATION
     password = ''
     for i in xrange(length):
         password += random.choice(password_set)
     return password
Example #28
0
    def prepare_request(self,url,token=None,secret='',additional_params={},method='GET'):
        encode=lambda t:urlquote(str(t),'')
        urlquh=lambda t:urlquote(str(t),'~')

        params={'oauth_consumer_key':self.consumer_key,
                'oauth_signature_method':'HMAC-SHA1',
                'oauth_timestamp':str(int(time())),
                'oauth_nonce':''.join(list(choice(seqstr) for i in xrange(64))),
                'oauth_version':'1.0'}

        if token:
            params['oauth_token']=token
        elif self.callback_url:
            params['oauth_callback']=self.callback_url

        params.update(additional_params)
        for k,v in params.iteritems():
            if isinstance(v,unicode):
                params[k]=v.encode('utf8')

        params_str='&'.join([encode(k)+'='+urlquh(v) for k,v in sorted(params.iteritems())])
        params['oauth_signature']=hmac('&'.join([self.consumer_secret,secret]),
                                       '&'.join([method,encode(url),urlquh(params_str)]),
                                       sha1).digest().encode('base64').strip()
        return '&'.join([urlquote_plus(str(k),'~')+'='+urlquote_plus(str(v),'~') for k,v in sorted(params.iteritems())])
Example #29
0
def login(request, *args, **kwargs):
    response = authlogin(request, *args, **kwargs)
    if request.user.is_authenticated():
        lst = [random.choice(string.ascii_letters + string.digits) for n in xrange(30)]
        key = "".join(lst)
        request.user.db.magic_cookie = key
    return response
Example #30
0
def generate_password(keyfile, args):
    characters = args.get('characters', keyfile.characters)
    length = int(args.get('length', keyfile.length))
    password = ''
    while len(password) < length:
        password += random.choice(characters)
    return password