summaryrefslogtreecommitdiff
path: root/lib/glider/formats.py
blob: b57984838dada5a91a81cd06210468abbcd3aeb2 (plain)
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

import OpenSSL.crypto

import sexp.access
import sexp.encode
import time
import re

class UnknownMethod(Exception):
    pass

class PublicKey:
    def format(self):
        raise NotImplemented()
    def sign(self, data):
        # returns a list of method,signature tuples.
        raise NotImplemented()
    def checkSignature(self, method, data, signature):
        # returns True, False, or raises UnknownMethod.
        raise NotImplemented()
    def getKeyID(self):
        raise NotImplemented()
    def getRoles(self):
        raise NotImplemented()

class KeyDB:
    def __init__(self):
        self.keys = {}
    def addKey(self, k):
        self.keys[k.getKeyID()] = k
    def getKey(self, keyid):
        return self.keys[keyid]

def rolePathMatches(rolePath, path):
    """

    >>> rolePath.matches("a/b/c/", "a/b/c/")
    True
    >>> rolePath.matches("**/c.*", "a/b/c.txt")
    True
    """
    rolePath = re.escape(rolePath).replace(r'\*\*', r'.*')
    rolePath = rolePath.replace(r'\*', r'[^/]*')
    rolePath += "$"
    return re.match(rolePath, path) != None

def checkSignatures(signed, keyDB, role, path):
    goodSigs = []
    badSigs = []
    unknownSigs = []
    tangentialSigs = []

    for signature in sexp.access.s_children(signed, "signature"):
        attrs = signature[1]
        sig = attrs[2]
        keyid = s_child(attrs, "keyid")[1]
        try:
            key = keyDB.getKey(keyid)
        except KeyError:
            unknownSigs.append(keyid)
            continue
        method = s_child(attrs, "method")[1]
        try:
            result = key.checkSignature(method, data, sig)
        except UnknownMethod:
            continue
        if result == True:
            if role is not None:
                for r,p in key.getRoles():
                    if r == role and rolePathMatches(p, path):
                        break
                else:
                    tangentialSigs.append(sig)
                    continue

            goodSigs.append(keyid)
        else:
            badSigs.append(keyid)

def sign(signed, key):
    assert sexp.access.s_tag(signed) == 'signed'
    s = signed[1]
    keyid = key.keyID()

    oldsignatures = [ s for s in signed[2:] if s_child(s[1], "keyid") != keyid ]
    signed[2:] = oldsignatures

    for method, sig in key.sign(s):
        signed.append(['signature', [['keyid', keyid], ['method', method]]
                       sig])

def formatTime(t):
    return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(t))

def parseTime(s):
    return time.timegm(time.strptime(s, "%Y-%m-%d %H:%M:%S"))


TIME_SCHEMA = r"""/\{d}4-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/"""

ATTRS_SCHEMA = r"""(:anyof (_ *))"""

SIGNED_SCHEMA = r"""
 (=signed
   _
   (:someof
     (=signature ((:unordered
                    (=keyid _) (=method _) .ATTRS)) _)
   )
 )"""

KEYFILE_SCHEMA = r"""
 (=keylist
   (=ts .TIME)
   (=keys
     (:anyof
       (=key ((:unordered (=roles (:someof (. .))) .ATTRS)) _)
     ))
   *
 )"""

MIRRORLIST_SCHEMA = r"""
 (=mirrorlist
   (=ts .TIME)
   (=mirrors (:anyof
     (=mirror ((:unordered (=name .) (=urlbase .) (=contents (:someof .))
                           .ATTRS)))))
   *)
"""

TIMESTAMP_SCHEMA = r"""
 (=ts
   ((:unordered (=at .TIME) (=m .TIME .) (=k .TIME .)
           (:anyof (=b . . .TIME . .)) .ATTRS))
 )"""

BUNDLE_SCHEMA = r"""
 (=bundle
   (=at .TIME)
   (=os .)
   (:maybe (=arch .))
   (=packages
     (:someof
      (. . . . ((:unordered
                  (:maybe (=order . . .))
                  (:maybe (=optional))
                  (:anyof (=gloss . .))
                  (:anyof (=longgloss . .))
                  .ATTRS)))
     )
   )
   *
 )"""

PACKAGE_SCHEMA = r"""
 (=package
  ((:unordred (=name .)
              (=version .)
              (=format . (.ATTRS))
              (=path .)
              (=ts .TIME)
              (=digest .)
              (:anyof (=shortdesc . .))
              (:anyof (=longdesc . .))
              .ATTRS)))
"""