sso.py 7.79 KB
Newer Older
marcus-tun's avatar
marcus-tun committed
1
2
3
4
5
6
7
8
#!/usr/bin/env python 

from mod_python import apache
from mod_python import util
import httplib2
import hashlib
from base64 import b64encode, b64decode

9
from Crypto.Cipher import Blowfish
marcus-tun's avatar
marcus-tun committed
10
from Crypto.Cipher import AES
11
12
from Crypto import Random
from struct import pack
marcus-tun's avatar
marcus-tun committed
13

14
15
16
17
18
19
20
21
22
import urllib
from string import replace

def write_var (req, var, filename):
    log_path=req.document_root() + '/assertions/' + filename
    logfile=open(log_path, 'w')
    logfile.write(var)
    logfile.close

marcus-tun's avatar
marcus-tun committed
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

def handler(req):
    assertionLocation = str(req.subprocess_env['Shib-Assertion-01'])
    h1 = httplib2.HTTPSConnectionWithTimeout('saml-delegation.data.kit.edu')

    # get the path portion of the assertion link
    (i, assertionPath) = assertionLocation.split('https://saml-delegation.data.kit.edu')

    # get the assertion
    h1.request('GET', assertionPath)
    response = h1.getresponse()
    assertion = response.read()

    # remove newlines
    assertion = assertion.replace("\n", "")

    # find out at which url we were called
    (none, none, location) = req.uri.split('/')

    # sso
    if location == 'sso.py':
        req.content_type = 'text/html'
        req.write('''<!DOCTYPE html>
            <html>
            <head>
            <meta http-equiv="refresh" content="1
                  URL=https://saml-delegation.data.kit.edu/sd/ecp.py">

                  <!--   URI:     %s -->

            </head>
            <body>
            <br/>
            Save your assertion as "/tmp/samlup_uXXXX.tmp" where you replace
                  "XXXX" with your user id.<br>
            </body>
            </html>'''% req.uri)
        return apache.OK

62
    # js: sso via javascript
marcus-tun's avatar
marcus-tun committed
63
64
65
    if location == 'js.py':
        req.content_type = 'text/html'
        req.write('''<!DOCTYPE html>
66
              <meta charset="ASCII" />
marcus-tun's avatar
marcus-tun committed
67
68
            <html>
            <head>
69
            <script src="js/twofish/2-fish.js"> </script>
70
71
            <script src="js/blowfish/blowfish.js"> </script>
            <!--<script src="js/aamcrypt/aamcrypt.js"> </script>-->
72
            <script src="js/seedrandom/seedrandom.min.js"> </script>
marcus-tun's avatar
marcus-tun committed
73
74
75
76
77
78
79
80
81
            </head>
            <body>
                <script type="text/javascript">''')
        req.sendfile(req.document_root() + "/sd/js.js")
        req.write(''' </script> </body> </html> ''')
        return apache.OK

    # ecp
    if location == 'ecp.py':
82
83
84
85
        # octet stream will force saving to disk, while
        # text will allow to open with a text editor
        #req.content_type='application/octet-stream'\
        req.content_type='application/text'\
marcus-tun's avatar
marcus-tun committed
86
87
88
89
                '\nContent-Disposition: attachment; filename=samlup_uXXXX.tmp'
        req.write(assertion)
        return apache.OK

90
91
92
    ############
    #  upload  #
    ############
93
94
95
96
97
98
99
100
101
102
    if location in ( 'test.py', 'testone.py', 'testtwo.py') :
        req.content_type = 'text/plain'
        form = util.FieldStorage(req)
        b64_encrypted_assertion = form.get("encrypted_assertion", "ooops").replace(' ', '+')
        log_path=req.document_root() + '/assertions/' + location + '.txt'
        logfile=open(log_path, 'w')
        logfile.write(b64_encrypted_assertion)
        logfile.close()
        return apache.OK

103
    if location in ( 'upload.py', 'jsupload.py'):
marcus-tun's avatar
marcus-tun committed
104
105
106
107
        req.content_type = 'text/plain'
        # we expect the data via post in encrypted assertion.
        # we will return the url of where to collect the assertion
        # request.
marcus-tun's avatar
marcus-tun committed
108
109
110
111
112
113

        # This debug statement will destroy the whole processing
        #log_path=req.document_root() + '/assertions/' + 'js-log'
        #logfile=open(log_path, 'w')
        #logfile.write(req.read())
        #logfile.close()
114

115
116
117
118
        if req.method != 'POST':
            req.write("Error, i was expecting a post request")
            return apache.OK

marcus-tun's avatar
marcus-tun committed
119
        form = util.FieldStorage(req)
120
        client = form.get ("client", "oops").replace(' ', '+')
121
122
123
        if not form.has_key("encrypted_assertion"):
            req.write ("Error: did not obtain the encrypted_assertion")
            return apache.OK
124
125
126
127
128
129
        #if client == 'javascript':
        buf = form.get("encrypted_assertion", "ooops").replace(' ', '+')
        client_version = form.get ("client_verions", "oops").replace(' ', '+')
        #else:
            #buf = form.get("encrypted_assertion", "ooops")
            #client_version = form.get ("client_verions", "oops")
130
        # decode assertion
131
132
133
134
135
        if client == 'perl':
            encrypted_assertion = b64decode(buf)
        if client == 'javascript':
            encrypted_assertion = b64decode(buf+'=')

136
137
138
139
140
141
142
143
144

        # create hash
        assertion_hash = str(hashlib.md5(encrypted_assertion).hexdigest())
        assertion_path=req.document_root() + '/assertions/' + assertion_hash
        assertion_url ='https://' + req.hostname + '/assertions/' + assertion_hash

        # write to file
        try:
            file=open(assertion_path, 'w')
145
            file.write(encrypted_assertion) 
146
147
148
            file.close()
        except:
            req.write("could not save assertion")
marcus-tun's avatar
marcus-tun committed
149

150
        if location == 'jsupload.py':
151
            req.write(assertion_url);
152

153
154
155
156
157
158
159
160
161
        else:
            req.write("url=%s" % assertion_url)

        #########
        # debug #
        #########
        # decrypt assertion in case password is provided
        if form.has_key("key"):
            from binascii import hexlify, unhexlify
162
163
            log_path=req.document_root() + '/assertions/' + 'log'
            logfile=open(log_path, 'w')
164

165
166
167
168
169
170
171
            if client == 'perl':
                key = unhexlify(form.get("key", "ooops"))
                #key = form.get("key", "ooops")
                iv =  form.get("iv",  "ooops")
            if client == 'javascript':
                key = form.get("key", "ooops")
                iv =  form.get("iv",  "ooops")
172
173
            encryption_algorithm = form.get("encryption_algorithm", "ooops")

174
175
            logfile.write('iv: ' + iv + '\n')
            logfile.write('key: ' + key + '\n')
176

177
            write_var(req, encrypted_assertion, 'encrypted_assertion')
178

179
            if client == 'perl':
marcus-tun's avatar
marcus-tun committed
180
181
182
183
184
185
186
187
188
189
190
191
192
                # we need to initialise cipher twice: once to get the
                # amount of padding, and then to actually decrypt
                if encryption_algorithm == 'Blowfish':
                    cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
                    num_padding = ord(cipher.decrypt(encrypted_assertion)[-1])
                    cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
                    plaintext = cipher.decrypt(encrypted_assertion)[:(-1*num_padding)]

                if encryption_algorithm == 'AES':
                    cipher = AES.new(key, AES.MODE_CBC, iv)
                    num_padding = ord(cipher.decrypt(encrypted_assertion)[-1])
                    cipher = AES.new(key, AES.MODE_CBC, iv)
                    plaintext = cipher.decrypt(encrypted_assertion)[:(-1*num_padding)]
193
194
195
196
197
198
199
            if client == 'javascript':
                iv='asdasdff'
                num_padding = 8
                #key = 'this';
                key = base64.decode
                cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
                plaintext = cipher.decrypt(encrypted_assertion[0:5680])[:(-1*num_padding)]
200

201
            logfile.write("length: %d\n" % len(encrypted_assertion))
marcus-tun's avatar
marcus-tun committed
202

203
204
205
206

            write_var(req, plaintext, 'plaintext')

            logfile.close()
marcus-tun's avatar
marcus-tun committed
207
208
209
210
211
212
        return apache.OK

    req.content_type = 'text/plain'
    req.write("Error: Your request was not understood")
    return apache.OK
    #return apache.HTTP_BAD_REQUEST
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227


# Some leftovers:

#bs = Blowfish.block_size
#iv = '12333123'
#cipher = Blowfish.new(key, Blowfish.MODE_ECB, iv)
#cipher = new Crypt::CBC (symmetric_key, 'Twofish');
#my plaintext = cipher->decrypt(encrypted_assertion);
#print ("\n".plaintext."\n");

##plaintext = b'docendo discimus '
##plen = bs - divmod(len(plaintext),bs)[1]
##padding = [plen]*plen
##padding = pack('b'*plen, *padding)