~launchpad-pqm/launchpad/devel

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
# Copyright 2009 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""GPG Key Information Server Prototype.

It follows the standard URL schema for PKS/SKS systems

It implements the operations:

 - 'index' : returns key index information
 - 'get': returns an ASCII armored public key
 - 'add': adds a key to the collection (does not update the index)

It only depends on GPG for key submission; for retrieval and searching
it just looks for files in the root (eg. /var/tmp/zeca). The files
are named like this:

0x<keyid|fingerprint>.<operation>

Example:

$ gpg --list-key cprov > 0x681B6469.index

note: remove the lines containing 'sub' or 'secret' keys

$ gpg --export -a cprov > 0x681B6469.get

"""

__metaclass__ = type

__all__ = [
    'KeyServer',
    'LookUp',
    'SubmitKey',
    'Zeca',
    ]

import glob
import os
import cgi

from twisted.web.resource import Resource

from zope.component import getUtility

from canonical.launchpad.interfaces.gpghandler import (
    GPGKeyNotFoundError, IGPGHandler, MoreThanOneGPGKeyFound,
    SecretGPGKeyImportDetected)


GREETING = 'Copyright 2004-2009 Canonical Ltd.\n'


def locate_key(root, suffix):
    """Find a key file in the root with the given suffix.

    This does some globbing to possibly find a fingerprint-named key
    file when given a key ID.

    :param root: The root directory in which to look.
    :param suffix: The key ID or fingerprint, of the form
        0x<FINGERPRINT|KEYID>.<METHOD>
    :returns: An absolute path to the key file.
    """
    path = os.path.join(root, suffix)

    if not os.path.exists(path):
        # GPG might request a key ID from us, but we name the keys by
        # fingerprint. Let's glob.
        if suffix.startswith('0x'):
            suffix = suffix[2:]
        keys = glob.glob(os.path.join(root, '*'+suffix))
        if len(keys) == 1:
            path = keys[0]
        else:
            return None

    return path


class Zeca(Resource):
    def getChild(self, name, request):
        if name == '':
            return self
        return Resource.getChild(
            self, name, request)

    def render_GET(self, request):
        return GREETING


class KeyServer(Zeca):
    def render_GET(self, request):
        return 'Welcome To Fake SKS service.\n'


class LookUp(Resource):
    isLeaf = True
    permitted_actions = ['index', 'get']

    def __init__(self, root):
        Resource.__init__(self)
        self.root = root

    def render_GET(self, request):
        try:
            action = request.args['op'][0]
            keyid = request.args['search'][0]
        except KeyError:
            return 'Invalid Arguments %s' % request.args

        return self.processRequest(action, keyid)

    def processRequest(self, action, keyid):
        if (action not in self.permitted_actions) or not keyid:
            return 'Forbidden: "%s" on ID "%s"' % (action, keyid)

        page = ('<html>\n<head>\n'
                '<title>Results for Key %s</title>\n'
                '</head>\n<body>'
                '<h1>Results for Key %s</h1>\n'
                % (keyid, keyid))

        filename = '%s.%s' % (keyid, action)

        path = locate_key(self.root, filename)
        if path is not None:
            content = cgi.escape(open(path).read())
        else:
            content = 'Key Not Found'

        page += '<pre>\n%s\n</pre>\n</html>' % content

        return page


SUBMIT_KEY_PAGE = """
<html>
  <head>
    <title>Submit a key</title>
  </head>
  <body>
    <h1>Submit a key</h1>
    <p>%(banner)s</p>
    <form method="post">
      <textarea name="keytext" rows="20" cols="66"></textarea> <br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>
"""


class SubmitKey(Resource):
    isLeaf = True

    def __init__(self, root):
        Resource.__init__(self)
        self.root = root

    def render_GET(self, request):
        return SUBMIT_KEY_PAGE % {'banner': ''}

    def render_POST(self, request):
        try:
            keytext = request.args['keytext'][0]
        except KeyError:
            return 'Invalid Arguments %s' % request.args
        return self.storeKey(keytext)

    def storeKey(self, keytext):
        gpghandler = getUtility(IGPGHandler)
        try:
            key = gpghandler.importPublicKey(keytext)
        except (GPGKeyNotFoundError, SecretGPGKeyImportDetected,
                MoreThanOneGPGKeyFound), err:
            return SUBMIT_KEY_PAGE % {'banner': str(err)}

        filename = '0x%s.get' % key.fingerprint
        path = os.path.join(self.root, filename)

        fp = open(path, 'w')
        fp.write(keytext)
        fp.close()

        return SUBMIT_KEY_PAGE % {'banner': 'Key added'}