Debian Codegraph @

pkcs11uri.go

raw
1 /*
2 (c) Copyright IBM Corporation, 2020
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package pkcs11uri
18
19 import (
20 "errors"
21 "fmt"
22 "io/ioutil"
23 "net/url"
24 "os"
25 "path/filepath"
26 "regexp"
27 "strconv"
28 "strings"
29 )
30
31 // Pkcs11URI holds a pkcs11 URI object
32 type Pkcs11URI struct {
33 // path and query attributes may have custom attributes that either
34 // have to be in the query or in the path part, so we use two maps
35 pathAttributes map[string]string
36 queryAttributes map[string]string
37 // directories to search for pkcs11 modules
38 moduleDirectories []string
39 // file paths of allowed pkcs11 modules
40 allowedModulePaths []string
41 // whether any module is allowed to be loaded
42 allowAnyModule bool
43 // A map of environment variables needed by the pkcs11 module using this URI.
44 // This map is not needed by this implementation but is there for convenience.
45 env map[string]string
46 }
47
48 // upper character hex digits needed for pct-encoding
49 const hex = "0123456789ABCDEF"
50
51 // escapeAll pct-escapes all characters in the string
52 func escapeAll(s string) string {
53 res := make([]byte, len(s)*3)
54 j := 0
55 for i := 0; i < len(s); i++ {
56 c := s[i]
57 res[j] = '%'
58 res[j+1] = hex[c>>4]
59 res[j+2] = hex[c&0xf]
60 j += 3
61 }
62 return string(res)
63 }
64
65 // escape pct-escapes the path and query part of the pkcs11 URI following the different rules of the
66 // path and query part as decribed in RFC 7512 sec. 2.3
67 func escape(s string, isPath bool) string {
68 res := make([]byte, len(s)*3)
69 j := 0
70 for i := 0; i < len(s); i++ {
71 c := s[i]
72 // unreserved per RFC 3986 sec. 2.3
73 if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') {
74 res[j] = c
75 } else if isPath && c == '&' {
76 res[j] = c
77 } else if !isPath && (c == '/' || c == '?' || c == '|') {
78 res[j] = c
79 } else {
80 switch c {
81 case '-', '.', '_', '~': // unreserved per RFC 3986 sec. 2.3
82 res[j] = c
83 case ':', '[', ']', '@', '!', '$', '\'', '(', ')', '*', '+', ',', '=':
84 res[j] = c
85 default:
86 res[j] = '%'
87 res[j+1] = hex[c>>4]
88 res[j+2] = hex[c&0xf]
89 j += 2
90 }
91 }
92 j++
93 }
94 return string(res[:j])
95 }
96
97 // New creates a new Pkcs11URI object
98 func New() *Pkcs11URI {
99 return &Pkcs11URI{
100 pathAttributes: make(map[string]string),
101 queryAttributes: make(map[string]string),
102 env: make(map[string]string),
103 }
104 }
105
106 func (uri *Pkcs11URI) setAttribute(attrMap map[string]string, name, value string) error {
107 v, err := url.PathUnescape(value)
108 if err != nil {
109 return err
110 }
111 attrMap[name] = v
112 return nil
113 }
114
115 // GetPathAttribute returns the value of a path attribute in unescaped form or
116 // pct-encoded form
117 func (uri *Pkcs11URI) GetPathAttribute(name string, pctencode bool) (string, bool) {
118 v, ok := uri.pathAttributes[name]
119 if ok && pctencode {
120 v = escape(v, true)
121 }
122 return v, ok
123 }
124
125 // SetPathAttribute sets the value for a path attribute; this function may return an error
126 // if the given value cannot be pct-unescaped
127 func (uri *Pkcs11URI) SetPathAttribute(name, value string) error {
128 return uri.setAttribute(uri.pathAttributes, name, value)
129 }
130
131 // AddPathAttribute adds a path attribute; it returns an error if an attribute with the same
132 // name already existed or if the given value cannot be pct-unescaped
133 func (uri *Pkcs11URI) AddPathAttribute(name, value string) error {
134 if _, ok := uri.pathAttributes[name]; ok {
135 return errors.New("duplicate path attribute")
136 }
137 return uri.SetPathAttribute(name, value)
138 }
139
140 // RemovePathAttribute removes a path attribute
141 func (uri *Pkcs11URI) RemovePathAttribute(name string) {
142 delete(uri.pathAttributes, name)
143 }
144
145 // AddEnv adds an environment variable for the pkcs11 module
146 func (uri *Pkcs11URI) AddEnv(name, value string) {
147 uri.env[name] = value
148 }
149
150 // SetEnvMap sets the environment variables for the pkcs11 module
151 func (uri *Pkcs11URI) SetEnvMap(env map[string]string) {
152 uri.env = env
153 }
154
155 // GetEnvMap returns the map of environment variables
156 func (uri *Pkcs11URI) GetEnvMap() map[string]string {
157 return uri.env
158 }
159
160 // GetQueryAttribute returns the value of a query attribute in unescaped or
161 // pct-encoded form
162 func (uri *Pkcs11URI) GetQueryAttribute(name string, pctencode bool) (string, bool) {
163 v, ok := uri.queryAttributes[name]
164 if ok && pctencode {
165 v = escape(v, false)
166 }
167 return v, ok
168 }
169
170 // SetQueryAttribute sets the value for a query attribute; this function may return an error
171 // if the given value cannot pct-unescaped
172 func (uri *Pkcs11URI) SetQueryAttribute(name, value string) error {
173 return uri.setAttribute(uri.queryAttributes, name, value)
174 }
175
176 // AddQueryAttribute adds a query attribute; it returns an error if an attribute with the same
177 // name already existed or if the given value cannot be pct-unescaped
178 func (uri *Pkcs11URI) AddQueryAttribute(name, value string) error {
179 if _, ok := uri.queryAttributes[name]; ok {
180 return errors.New("duplicate query attribute")
181 }
182 return uri.SetQueryAttribute(name, value)
183 }
184
185 // RemoveQueryAttribute removes a path attribute
186 func (uri *Pkcs11URI) RemoveQueryAttribute(name string) {
187 delete(uri.queryAttributes, name)
188 }
189
190 // Validate validates a Pkcs11URI object's attributes following RFC 7512 rules and proper formatting of
191 // their values
192 func (uri *Pkcs11URI) Validate() error {
193 /* RFC 7512: 2.3 */
194 /* slot-id should be DIGIT, but we go for number */
195 if v, ok := uri.pathAttributes["slot-id"]; ok {
196 if _, err := strconv.Atoi(v); err != nil {
197 return fmt.Errorf("slot-id must be a number: %s", v)
198 }
199 }
200
201 /* library-version should 1*DIGIT [ "." 1 *DIGIT ]; allow NUMBERS for DIGIT */
202 if v, ok := uri.pathAttributes["library-version"]; ok {
203 m, err := regexp.Match("^[0-9]+(\\.[0-9]+)?$", []byte(v))
204 if err != nil || !m {
205 return fmt.Errorf("Invalid format for library-version '%s'", v)
206 }
207 }
208
209 if v, ok := uri.pathAttributes["type"]; ok {
210 m, err := regexp.Match("^(public|private|cert|secret-key}data)?$", []byte(v))
211 if err != nil || !m {
212 return fmt.Errorf("Invalid type '%s'", v)
213 }
214 }
215
216 /* RFC 7512: 2.4 */
217 _, ok1 := uri.queryAttributes["pin-source"]
218 _, ok2 := uri.queryAttributes["pin-value"]
219 if ok1 && ok2 {
220 return errors.New("URI must not contain pin-source and pin-value")
221 }
222
223 if v, ok := uri.queryAttributes["module-path"]; ok {
224 if !filepath.IsAbs(v) {
225 return fmt.Errorf("path %s of module-name attribute must be absolute", v)
226 }
227 }
228
229 return nil
230 }
231
232 // HasPIN allows the user to check whether a PIN has been provided either by the pin-value or the pin-source
233 // attributes. It should be called before GetPIN(), which may still fail getting the PIN from a file for example.
234 func (uri *Pkcs11URI) HasPIN() bool {
235 _, ok := uri.queryAttributes["pin-value"]
236 if ok {
237 return true
238 }
239 _, ok = uri.queryAttributes["pin-source"]
240 return ok
241 }
242
243 // GetPIN gets the PIN from either the pin-value or pin-source attribute; a user may want to call HasPIN()
244 // before calling this function to determine whether a PIN has been provided at all so that an error code
245 // returned by this function indicates that the PIN value could not be retrieved.
246 func (uri *Pkcs11URI) GetPIN() (string, error) {
247 if v, ok := uri.queryAttributes["pin-value"]; ok {
248 return v, nil
249 }
250 if v, ok := uri.queryAttributes["pin-source"]; ok {
251 pinuri, err := url.ParseRequestURI(v)
252 if err != nil {
253 return "", fmt.Errorf("Could not parse pin-source: %s ", err)
254 }
255 switch pinuri.Scheme {
256 case "", "file":
257 if !filepath.IsAbs(pinuri.Path) {
258 return "", fmt.Errorf("PIN URI path '%s' is not absolute", pinuri.Path)
259 }
260 pin, err := ioutil.ReadFile(pinuri.Path)
261 if err != nil {
262 return "", fmt.Errorf("Could not open PIN file: %s", err)
263 }
264 return string(pin), nil
265 default:
266 return "", fmt.Errorf("PIN URI scheme %s is not supported", pinuri.Scheme)
267 }
268 }
269 return "", fmt.Errorf("Neither pin-source nor pin-value are available")
270 }
271
272 // Parse parses a pkcs11: URI string
273 func (uri *Pkcs11URI) Parse(uristring string) error {
274 if !strings.HasPrefix(uristring, "pkcs11:") {
275 return errors.New("Malformed pkcs11 URI: missing pcks11: prefix")
276 }
277
278 parts := strings.SplitN(uristring[7:], "?", 2)
279
280 uri.pathAttributes = make(map[string]string)
281 uri.queryAttributes = make(map[string]string)
282
283 if len(parts[0]) > 0 {
284 /* parse path part */
285 for _, part := range strings.Split(parts[0], ";") {
286 p := strings.SplitN(part, "=", 2)
287 if len(p) != 2 {
288 return errors.New("Malformed pkcs11 URI: malformed path attribute")
289 }
290 if err := uri.AddPathAttribute(p[0], p[1]); err != nil {
291 return fmt.Errorf("Malformed pkcs11 URI: %s", err)
292 }
293 }
294 }
295
296 if len(parts) == 2 {
297 /* parse query part */
298 for _, part := range strings.Split(parts[1], "&") {
299 p := strings.SplitN(part, "=", 2)
300 if len(p) != 2 {
301 return errors.New("Malformed pkcs11 URI: malformed query attribute")
302 }
303 if err := uri.AddQueryAttribute(p[0], p[1]); err != nil {
304 return fmt.Errorf("Malformed pkcs11 URI: %s", err)
305 }
306 }
307 }
308 return uri.Validate()
309 }
310
311 // formatAttribute formats attributes and escapes their values as needed
312 func formatAttributes(attrMap map[string]string, ispath bool) string {
313 res := ""
314 for key, value := range attrMap {
315 switch key {
316 case "id":
317 /* id is always pct-encoded */
318 value = escapeAll(value)
319 default:
320 if ispath {
321 value = escape(value, true)
322 } else {
323 value = escape(value, false)
324 }
325 }
326 if len(res) > 0 {
327 if ispath {
328 res += ";"
329 } else {
330 res += "&"
331 }
332 }
333 res += key + "=" + value
334 }
335 return res
336 }
337
338 // Format formats a Pkcs11URI to it string representaion
339 func (uri *Pkcs11URI) Format() (string, error) {
340 if err := uri.Validate(); err != nil {
341 return "", err
342 }
343 result := "pkcs11:" + formatAttributes(uri.pathAttributes, true)
344 if len(uri.queryAttributes) > 0 {
345 result += "?" + formatAttributes(uri.queryAttributes, false)
346 }
347 return result, nil
348 }
349
350 // SetModuleDirectories sets the search directories for pkcs11 modules
351 func (uri *Pkcs11URI) SetModuleDirectories(moduleDirectories []string) {
352 uri.moduleDirectories = moduleDirectories
353 }
354
355 // GetModuleDirectories gets the search directories for pkcs11 modules
356 func (uri *Pkcs11URI) GetModuleDirectories() []string {
357 return uri.moduleDirectories
358 }
359
360 // SetAllowedModulePaths sets allowed module paths to restrict access to modules.
361 // Directory entries must end with a '/', all other ones are assumed to be file entries.
362 // Allowed modules are filtered by string matching.
363 func (uri *Pkcs11URI) SetAllowedModulePaths(allowedModulePaths []string) {
364 uri.allowedModulePaths = allowedModulePaths
365 }
366
367 // SetAllowAnyModule allows any module to be loaded; by default this is not allowed
368 func (uri *Pkcs11URI) SetAllowAnyModule(allowAnyModule bool) {
369 uri.allowAnyModule = allowAnyModule
370 }
371
372 func (uri *Pkcs11URI) isAllowedPath(path string, allowedPaths []string) bool {
373 if uri.allowAnyModule {
374 return true
375 }
376 for _, allowedPath := range allowedPaths {
377 if allowedPath == path {
378 // exact filename match
379 return true
380 }
381 if allowedPath[len(allowedPath)-1] == '/' && strings.HasPrefix(path, allowedPath) {
382 // allowedPath no subdirectory is allowed
383 idx := strings.IndexRune(path[len(allowedPath):], os.PathSeparator)
384 if idx < 0 {
385 return true
386 }
387 }
388 }
389 return false
390 }
391
392 // GetModule returns the module to use or an error in case no module could be found.
393 // First the module-path is checked for whether it holds an absolute that can be read
394 // by the current user. If this is the case the module is returned. Otherwise either the module-path
395 // is used or the user-provided module path is used to match a module containing what is set in the
396 // attribute module-name.
397 func (uri *Pkcs11URI) GetModule() (string, error) {
398 var searchdirs []string
399 v, ok := uri.queryAttributes["module-path"]
400
401 if ok {
402 info, err := os.Stat(v)
403 if err != nil {
404 return "", fmt.Errorf("module-path '%s' is not accessible", v)
405 }
406 if err == nil && info.Mode().IsRegular() {
407 // it's a file
408 if uri.isAllowedPath(v, uri.allowedModulePaths) {
409 return v, nil
410 }
411 return "", fmt.Errorf("module-path '%s' is not allowed by policy", v)
412 }
413 if !info.IsDir() {
414 return "", fmt.Errorf("module-path '%s' points to an invalid file type", v)
415 }
416 // v is a directory
417 searchdirs = []string{v}
418 } else {
419 searchdirs = uri.GetModuleDirectories()
420 }
421
422 moduleName, ok := uri.queryAttributes["module-name"]
423 if !ok {
424 return "", fmt.Errorf("module-name attribute is not set")
425 }
426 moduleName = strings.ToLower(moduleName)
427
428 for _, dir := range searchdirs {
429 files, err := ioutil.ReadDir(dir)
430 if err != nil {
431 continue
432 }
433 for _, file := range files {
434 fileLower := strings.ToLower(file.Name())
435
436 i := strings.Index(fileLower, moduleName)
437 if i < 0 {
438 continue
439 }
440 // we require that the fileLower ends with moduleName or that
441 // a suffix follows so that softhsm will not match libsofthsm2.so but only
442 // libsofthsm.so
443 if len(fileLower) == i+len(moduleName) || fileLower[i+len(moduleName)] == '.' {
444 f := filepath.Join(dir, file.Name())
445 if uri.isAllowedPath(f, uri.allowedModulePaths) {
446 return f, nil
447 }
448 return "", fmt.Errorf("module '%s' is not allowed by policy", f)
449 }
450 }
451 }
452 return "", fmt.Errorf("No module could be found")
453 }