示例#1
0
def connect(block=False):
    global block_loop
    block_loop = block
    global current_subscribe_list
    global current_id
    times = 1
    while not microgear.accesstoken:
        get_token()
        time.sleep(times)
        times = times + 10
    microgear.mqtt_client = mqtt.Client(microgear.accesstoken["token"])
    current_id = '/&id/' + str(microgear.accesstoken["token"]) + '/#'
    current_subscribe_list.append('/&id/' +
                                  str(microgear.accesstoken["token"]) + '/#')
    endpoint = microgear.accesstoken["endpoint"].split("//")[1].split(":")
    username = microgear.gearkey + "%" + str(int(time.time()))
    password = hmac(
        microgear.accesstoken["secret"] + "&" + microgear.gearsecret,
        microgear.accesstoken["token"] + "%" + username)
    microgear.mqtt_client.username_pw_set(username, password)
    microgear.mqtt_client.connect(endpoint[0], int(endpoint[1]), 60)
    microgear.mqtt_client.on_connect = client_on_connect
    microgear.mqtt_client.on_message = client_on_message
    microgear.mqtt_client.on_publish = client_on_publish
    microgear.mqtt_client.on_subscribe = client_on_subscribe
    microgear.mqtt_client.on_disconnect = client_on_disconnect

    if (block):
        microgear.mqtt_client.loop_forever()
    else:
        microgear.mqtt_client.loop_start()
        while True:
            time.sleep(2)
            break
示例#2
0
def connect(block=False):
    global block_loop
    block_loop = block
    global current_subscribe_list
    global current_id
    times = 1
    while not microgear.accesstoken:
        get_token()
        time.sleep(times)
        times = times+10
    microgear.mqtt_client = mqtt.Client(microgear.accesstoken["token"])
    current_id = '/&id/'+str(microgear.accesstoken["token"])+'/#'
    current_subscribe_list.append('/&id/'+str(microgear.accesstoken["token"])+'/#')
    endpoint = microgear.accesstoken["endpoint"].split("//")[1].split(":")
    username = microgear.gearkey+"%"+str(int(time.time()))
    password = hmac(microgear.accesstoken["secret"]+"&"+microgear.gearsecret,microgear.accesstoken["token"]+"%"+username)
    microgear.mqtt_client.username_pw_set(username,password)
    microgear.mqtt_client.connect(endpoint[0],int(endpoint[1]), 60)
    microgear.mqtt_client.on_connect = client_on_connect
    microgear.mqtt_client.on_message = client_on_message
    microgear.mqtt_client.on_publish = client_on_publish
    microgear.mqtt_client.on_subscribe = client_on_subscribe
    microgear.mqtt_client.on_disconnect = client_on_disconnect

    if(block):
        microgear.mqtt_client.loop_forever()
    else:
        microgear.mqtt_client.loop_start()
        while True:
            time.sleep(2)
            break
示例#3
0
def server_authenticate(connection, scret_key):
    message = os.urandom(32)
    connection.send(message)
    hash = hmac(scret_key, message)
    digest = hash.digest()
    response = connection.recv(len(digest))
    return hmac.compare_digest(digest, response)
示例#4
0
 def test_invalid_len(self):
     class hmac(object):
         def new(self, *arg):
             return self
         def hexdigest(self):
             return '1234'
     serialized = serialize('123', 'secret123')
     self.assertRaises(ValueError, self._callFUT, serialized, 'secret',
                       hmac=hmac())
示例#5
0
 def test_invalid_len(self):
     class hmac(object):
         def new(self, *arg):
             return self
         def hexdigest(self):
             return '1234'
     serialized = serialize('123', 'secret123')
     self.assertRaises(ValueError, self._callFUT, serialized, 'secret',
                       hmac=hmac())
示例#6
0
    def test_invalid_len(self):
        class hmac(object):
            def new(self, *arg):
                return self

            def hexdigest(self):
                return "1234"

        serialized = serialize("123", "secret123")
        self.assertRaises(ValueError, self._callFUT, serialized, "secret", hmac=hmac())
 def _getSignature(self, secretKey, input):
     '''Unused currently.''' 
     
     if input.get('SignatureVersion', '') != '1' :
         raise SimpleDBError('400 Bad Request', getRequestId(), 'UnsupportedSignatureVersion', 'Only the newer signature version 1 is supported in SimpleDB/dev.')
     
     string = ''
     keys = sorted(input.keys())
     for key in keys:
         if key == 'Signature' : continue
         string += key+input[key]
         
     return base64.b64encode(hmac(secretKey, string, 'sha1'))
示例#8
0
def get_accesstoken(cached):
    microgear.requesttoken = cached.get("requesttoken")
    logging.debug("Already has request token.")
    logging.debug("Requesting an access token.")
    token = oauth.Token(key=microgear.requesttoken.get("token"),
                        secret=microgear.requesttoken.get("secret"))
    consumer = oauth.Consumer(key=microgear.gearkey,
                              secret=microgear.gearsecret)
    client = oauth.Client(consumer, token)
    params = {"oauth_verifier": microgear.requesttoken["verifier"]}
    headers = {}
    method = "POST"
    req = oauth.Request.from_consumer_and_token(
        consumer,
        token=token,
        http_method=method,
        http_url=microgear.gearauthaccesstokenendpoint,
        parameters=params)
    req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token)
    headers.update(req.to_header(realm="NETPIE"))
    h = httplib2.Http(
        os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), ".cache"))
    resp, content = h.request(microgear.gearauthaccesstokenendpoint,
                              method=method,
                              headers=headers)
    parsed_resp = parse_qs(content.decode(encoding='UTF-8'))
    if resp.status == 200:
        revokecode = hmac(
            parsed_resp['oauth_token_secret'][0] + "&" + microgear.gearsecret,
            parsed_resp['oauth_token'][0]).replace('/', '_')
        cached["requesttoken"] = None
        cached["accesstoken"] = {
            "token": parsed_resp['oauth_token'][0],
            "secret": parsed_resp['oauth_token_secret'][0],
            "endpoint": parsed_resp['endpoint'][0],
            "revokecode": revokecode
        }
        flag = parsed_resp.get('flag', ["P"])
        if flag[0] == "P":
            cache.set_item("microgear-" + microgear.gearkey + ".cache", cached)
        elif flag[0] == "S":
            cache.set_item("microgear-" + microgear.gearkey + ".cache", {})
        microgear.accesstoken = cached["accesstoken"]
    else:
        resettoken()
        on_error(
            "Access token is not issued, please check your consumerkey and consumersecret."
        )
        logging.error(
            "Access token is not issued, please check your consumerkey and consumersecret."
        )
示例#9
0
def get_accesstoken(cached):
    microgear.requesttoken = cached.get("requesttoken")
    logging.info("Already has request token.")
    logging.info("Requesting an access token.")
    verifier = ""
    url = ""
    path = "/oauth2/token?grant_type=authorization_code&code=" + microgear.requesttoken.get(
        "token"
    ) + "&client_id=" + microgear.gearkey + "&client_secret=" + microgear.gearsecret + "&state=mgrev:" + microgear.mgrev
    if microgear.securemode:
        url = "https://" + microgear.gearauthsite + ":" + microgear.gearapisecureport + path
    else:
        url = "http://" + microgear.gearauthsite + ":" + microgear.gearapiport + path
    response = requests.post(url)
    if response.status_code == 200:
        datajson = json.loads(response.text)
        token = datajson['access_token'].split(':')
        revokecode = hmac(token[1] + "&" + microgear.gearsecret,
                          token[0]).replace('/', '_')
        cached["requesttoken"] = None
        cached["accesstoken"] = {
            "token": token[0],
            "secret": token[1],
            "endpoint": datajson['endpoint'],
            "revokecode": revokecode
        }
        flag = datajson['flag']
        if flag == "P":
            cache.set_item("microgear-" + microgear.gearkey + ".cache", cached)
        elif flag == "S":
            cache.set_item("microgear-" + microgear.gearkey + ".cache", {})
        microgear.accesstoken = cached["accesstoken"]
    else:
        resettoken()
        on_error(
            "Access token is not issued, please check your consumerkey and consumersecret."
        )
        logging.error(
            "Access token is not issued, please check your consumerkey and consumersecret."
        )
示例#10
0
def get_accesstoken(cached):
    microgear.requesttoken = cached.get("requesttoken")
    logging.debug("Already has request token.")
    logging.debug("Requesting an access token.")
    token = oauth.Token(key=microgear.requesttoken.get("token"), secret=microgear.requesttoken.get("secret"))
    consumer = oauth.Consumer(key=microgear.gearkey, secret=microgear.gearsecret)
    client = oauth.Client(consumer, token)
    params = { "oauth_verifier": microgear.requesttoken["verifier"]}
    headers = {}
    method = "POST"
    req = oauth.Request.from_consumer_and_token(consumer, token=token, http_method=method,
            http_url=microgear.gearauthaccesstokenendpoint, parameters=params)
    req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token)
    headers.update(req.to_header(realm="NETPIE"))
    h = httplib2.Http(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),".cache"))
    resp, content = h.request(microgear.gearauthaccesstokenendpoint, method=method,
            headers=headers)
    parsed_resp = parse_qs(content.decode(encoding='UTF-8'))
    if resp.status == 200:
        revokecode = hmac(parsed_resp['oauth_token_secret'][0]+"&"+microgear.gearsecret,parsed_resp['oauth_token'][0]).replace('/','_')
        cached["requesttoken"] = None
        cached["accesstoken"] = {
            "token": parsed_resp['oauth_token'][0],
            "secret": parsed_resp['oauth_token_secret'][0],
            "endpoint": parsed_resp['endpoint'][0],
            "revokecode": revokecode
        }
        flag = parsed_resp.get('flag',["P"])
        if flag[0] == "P":
            cache.set_item("microgear-"+microgear.gearkey+".cache", cached)
        elif flag[0] == "S":
            cache.set_item("microgear-"+microgear.gearkey+".cache", {})
        microgear.accesstoken = cached["accesstoken"]
    else:
        resettoken()
        on_error("Access token is not issued, please check your consumerkey and consumersecret.")
        logging.error("Access token is not issued, please check your consumerkey and consumersecret.")
示例#11
0
    def complete_handshake(self, handshake_data):
        # The server's handshake reply is:
        # SERVER_PK   Y                       [G_LENGTH bytes]
        # AUTH        H(auth_input, t_mac)    [H_LENGTH bytes]
        Y = handshake_data[:
                           32]  # ntor data curve25519::public_key::key_size_in_bytes
        auth = handshake_data[32:]  # ntor auth is SHA1, 32 in bytes?
        assert len(auth) == 32  #

        # The client then checks Y is in G^* [see NOTE below], and computes

        # secret_input = EXP(Y,x) | EXP(B,x) | ID | B | X | Y | PROTOID

        si = curve25519_get_shared(self._x, curve25519_public_from_bytes(Y))
        si += curve25519_get_shared(self._x, self._B)
        si += self._fingerprint_bytes
        si += curve25519_to_bytes(self._B)
        si += curve25519_to_bytes(self._X)
        si += Y
        si += b'ntor-curve25519-sha256-1'

        # KEY_SEED = H(secret_input, t_key)
        # verify = H(secret_input, t_verify)
        key_seed = hmac(self.t_key, si)
        verify = hmac(self.t_verify, si)

        # auth_input = verify | ID | B | Y | X | PROTOID | "Server"
        ai = verify
        ai += self._fingerprint_bytes
        ai += curve25519_to_bytes(self._B)
        ai += Y
        ai += curve25519_to_bytes(self._X)
        ai += self.protoid
        ai += b'Server'

        # The client verifies that AUTH == H(auth_input, t_mac).
        if auth != hmac(self.t_mac, ai):
            raise NtorError('auth input does not match.')

        # Both parties check that none of the EXP() operations produced the
        # point at infinity. [NOTE: This is an adequate replacement for
        # checking Y for group membership, if the group is curve25519.]

        # Both parties now have a shared value for KEY_SEED.  They expand this
        # into the keys needed for the Tor relay protocol, using the KDF
        # described in 5.2.2 and the tag m_expand.

        # 5.2.2. KDF-RFC5869

        # For newer KDF needs, Tor uses the key derivation function HKDF from
        # RFC5869, instantiated with SHA256.  (This is due to a construction
        # from Krawczyk.)  The generated key material is:

        #     K = K_1 | K_2 | K_3 | ...

        #     Where H(x,t) is HMAC_SHA256 with value x and key t
        #       and K_1     = H(m_expand | INT8(1) , KEY_SEED )
        #       and K_(i+1) = H(K_i | m_expand | INT8(i+1) , KEY_SEED )
        #       and m_expand is an arbitrarily chosen value,
        #       and INT8(i) is a octet with the value "i".

        # In RFC5869's vocabulary, this is HKDF-SHA256 with info == m_expand,
        # salt == t_key, and IKM == secret_input.
        # WARN: length must be 92
        # 72 + byte_type rend_nonce     [20]; << ignored now
        return hkdf_sha256(key_seed, length=72, info=self.m_expand)
示例#12
0
def hash_hmac(ac_key, text):
    return str(hmac(ac_key, text, sha1).digest().encode('base64')[:-1])
示例#13
0
            if e.code == 304:
                print "X Did not get right response yet. Trying again."
                pass
            else:
                raise
        time.sleep(1)
    print "X Got Server.Message3: %s" % server_three
    
    # COMPARE KEYS
    
    print "X Generating keys"

    # This is the 'master' key. It is E = HMAC(0x00 * 32, K)
    key = j.three(server_two['payload'])
    
    aes_key  = hmac("Sync-AES_256_CBC-HMAC256\x01", key, algo="sha256")
    hmac_key = hmac(aes_key + "Sync-AES_256_CBC-HMAC256\x02", key, algo="sha256")

    # Check if the other side has the correct key. We do this by decrypting the payload (ciphertext/IV) with our calculated AES
    # key. The result should be '0123456789ABCDEF'

    check = decrypt(base64.b64decode(server_three['payload']['ciphertext']), aes_key, base64.b64decode(server_three['payload']['IV']))
    print "X Check = %s" % binascii.hexlify(check)
    
    if check != '0123456789ABCDEF':
        print "X CHECK FAIL"
        delete(url)
        sys.exit(1)
    
    # Put Client.Message3
示例#14
0
# COMPARE KEYS

print "X Generating key"
key = j.three(server_two['payload'])
print "X Generated key: %s" % key

print "X Comparing keys"
print "X   Desktop H(K) = %s" % sha256(sha256(key).digest()).hexdigest()
print "X   Mobile  H(K) = %s" % server_three['payload']

if server_three['payload'] != sha256(sha256(key).digest()).hexdigest():
    print "X KEY FAIL"
    delete(url)
    sys.exit(1)

# Put Client.Message3

iv = '0123456780abcdef'
cleartext = simplejson.dumps({ 'message': sys.argv[2] })
ciphertext = base64.b64encode(encrypt(cleartext, key, iv))
hmac_hex = binascii.hexlify(hmac(key, cleartext, algo="sha256"))
payload = {'ciphertext': ciphertext,
           'IV': base64.b64encode(iv),
           'hmac': hmac_hex}

print "X Putting Client.Message3"
client_three = { 'type': 'sender3', 'payload': payload }
client_three_etag = put(url, client_three)
print "X Put Client.Message3 (etag=%s) %s" % (client_three_etag, client_three)
示例#15
0
def client_authenticate(connection, scret_key):
    message = connection.recv(32)
    hash = hmac(scret_key, message)
    digest = hash.digest()
    connection.send(digest)
示例#16
0
    def POST(self):
        uid = web.input().login_uid
        pw = web.input().login_pw

        # DB select based on username
        # Will raise exception if not valid
        try:
            login_user = db.select('users', where = 'username = $uid',
                                   vars = locals())[0]
        except:
            # TODO return error mesage using ajax
            return render('login.html')
        
        # This will be executed if try block is executed
        # This is because except block returns value
        
        # Each user has a different salt
        # SHA256 used because it's better than default MD5
        # Rehash password and check if equal to database's
        salt = login_user['salt']
        hashed_pw = hmac(salt, pw, sha256).hexdigest()
        
        # Hashed password with user's salt matches!
        # Moves on to process the remember me toggle
        # Sets cookies accordingly
        # Redirects to /home
        if hashed_pw == login_user['pw']:

            # Exception checking using to-string conversion
            # Raises error if not remember me is not toggled
            try:
                # Remember me toggle is 'on'
                # 'on' as in string and literally on
                rmb_me = str(web.input().rmb_me)
                rmb_me = True

            # Oddly there is only 'on', no 'off'
            # So this will trigger an AttributeError (string)
            except AttributeError:
                rmb_me = False

            # Sets the cookie expiration to 3 months
            # Resets cookie expiration on every login
            if rmb_me:

                # make_cookie( uid, hashed_pw, salt )
                # cookie = uid|hashed_pw|salt
                web.setcookie('login_info',
                              make_cookie(uid, hashed_pw),
                              7776000)

                # Sets uid_login to hashed_pw for later confirmation
                memcache.set(uid + '_login', hashed_pw)
                raise web.seeother('/home')

            # Session only login, remember me is False
            else:

                web.setcookie('login_info',
                              make_cookie(uid, hashed_pw))
                # Sets uid_login to hashed_pw for later confirmation
                memcache.set(uid + '_login', hashed_pw)
                raise web.seeother('/home')

        # Input password does not match the one in database
        # Renders the html with notice
        else:
            # TODO do this rendering with Ajax request
            return render('login.html')