forked from jsxc/xmpp-cloud-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
external_cloud.py
executable file
·218 lines (165 loc) · 5.46 KB
/
external_cloud.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env python
import logging
import argparse
import urllib
import requests
import hmac
import hashlib
import sys
from struct import *
from time import time
import hmac, hashlib
from base64 import b64decode
from string import maketrans
DEFAULT_LOG_DIR = '/var/log/ejabberd'
URL = ''
SECRET = ''
usersafe_encoding = maketrans('-$%', 'OIl')
def send_request(data):
payload = urllib.urlencode(data)
signature = hmac.new(SECRET, msg=payload, digestmod=hashlib.sha1).hexdigest();
headers = {
'X-JSXC-SIGNATURE': 'sha1=' + signature,
'content-type': 'application/x-www-form-urlencoded'
}
try:
r = requests.post(URL, data = payload, headers = headers, allow_redirects = False)
except requests.exceptions.HTTPError as err:
logging.warn(err)
return False
except requests.exceptions.RequestException as err:
logging.warn('An error occured during the request')
return False
if r.status_code != requests.codes.ok:
return False
json = r.json();
return json;
def verify_token(username, server, password):
try:
token = b64decode(password.translate(usersafe_encoding) + "=======")
except:
logging.debug('Could not decode token')
return False
jid = username + '@' + server
if len(token) != 23:
logging.debug('Token is too short')
return False
(version, mac, header) = unpack("> B 16s 6s", token)
if version != 0:
logging.debug('Wrong token version')
return False;
(secretID, expiry) = unpack("> H I", header)
if expiry < time():
logging.debug('Token is expired')
return False
challenge = pack("> B 6s %ds" % len(jid), version, header, jid)
response = hmac.new(SECRET, challenge, hashlib.sha256).digest()
return hmac.compare_digest(mac, response[:16])
def verify_cloud(username, server, password):
response = send_request({
'operation':'auth',
'username':username,
'password':password
});
if not response:
return False
if response['result'] == 'success':
return True
return False
def is_user_cloud(username, server):
response = send_request({
'operation':'isuser',
'username':username
});
if not response:
return False
if response['result'] == 'success' and response['data']['isUser']:
return True
return False
def from_server(type):
if type == 'ejabberd':
return from_ejabberd();
elif type == 'prosody':
return from_prosody();
def to_server(type, bool):
if type == 'ejabberd':
return to_ejabberd(bool);
elif type == 'prosody':
return to_prosody(bool);
def from_prosody():
line = sys.stdin.readline().rstrip("\n")
return line.split(':')
def to_prosody(bool):
answer = '0'
if bool:
answer = '1'
sys.stdout.write(answer+"\n")
sys.stdout.flush()
def from_ejabberd():
input_length = sys.stdin.read(2)
(size,) = unpack('>h', input_length)
return sys.stdin.read(size).split(':')
def to_ejabberd(bool):
answer = 0
if bool:
answer = 1
token = pack('>hh', 2, answer)
sys.stdout.write(token)
sys.stdout.flush()
def auth(username, server, password):
if verify_token(username, server, password):
logging.info('Token is valid')
return True
if verify_cloud(username, server, password):
logging.info('Cloud says this password is valid')
return True
return False
def is_user(username, server):
if is_user_cloud(username, server):
logging.info('Cloud says this user exists')
return True
return False
def getArgs():
# build command line argument parser
desc = 'XMPP server authentication script'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-t', '--type',
required=True,
choices=['prosody', 'ejabberd'],
help='XMPP server')
parser.add_argument('-u', '--url',
required=True,
help='base URL')
parser.add_argument('-s', '--secret',
required=True,
help='secure api token')
parser.add_argument('-l', '--log',
default=DEFAULT_LOG_DIR,
help='log directory (default: %(default)s)')
parser.add_argument('-d', '--debug',
action='store_const', const=True,
help='toggle debug mode')
args = vars(parser.parse_args())
return args['type'], args['url'], args['secret'], args['debug'], args['log']
if __name__ == '__main__':
TYPE, URL, SECRET, DEBUG, LOG = getArgs()
LOGFILE = LOG + '/extauth.log'
LEVEL = logging.DEBUG if DEBUG else logging.INFO
# redirect stderr
ERRFILE = LOG + '/extauth.err'
sys.stderr = open(ERRFILE, 'a+')
logging.basicConfig(filename=LOGFILE,level=LEVEL,format='%(asctime)s %(levelname)s: %(message)s')
logging.info('Start external auth script for %s with endpoint: %s', TYPE, URL)
logging.info('Log location: %s', LOG)
logging.info('Log level: %s', 'DEBUG' if DEBUG else 'INFO')
while True:
data = from_server(TYPE)
logging.info('Receive operation ' + data[0]);
success = False
if data[0] == "auth" and len(data) == 4:
success = auth(data[1], data[2], data[3])
if data[0] == "isuser" and len(data) == 3:
success = is_user(data[1], data[2])
to_server(TYPE, success)
logging.info('Shutting down...');
# vim: tabstop=8 softtabstop=0 expandtab shiftwidth=4 smarttab