Debian Codegraph @

token/p11token/token.go

raw symbols SCIP
1 //
2 // Copyright (c) SAS Institute Inc.
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 p11token
18
19 import (
20 "context"
21 "errors"
22 "fmt"
23 "io"
24 "runtime"
25 "sync"
26
27 "github.com/miekg/pkcs11"
28
29 "github.com/sassoftware/relic/v7/config"
30 "github.com/sassoftware/relic/v7/lib/passprompt"
31 "github.com/sassoftware/relic/v7/signers/sigerrors"
32 "github.com/sassoftware/relic/v7/token"
33 )
34
35 const (
36 CKS_RO_PUBLIC_SESSION = 0
37 CKS_RO_USER_FUNCTIONS = 1
38 CKS_RW_PUBLIC_SESSION = 2
39 CKS_RW_USER_FUNCTIONS = 3
40 CKS_RW_SO_FUNCTIONS = 4
41
42 CKA_ID = pkcs11.CKA_ID
43 CKA_LABEL = pkcs11.CKA_LABEL
44 CKA_SERIAL_NUMBER = pkcs11.CKA_SERIAL_NUMBER
45
46 CKK_RSA = pkcs11.CKK_RSA
47 CKK_ECDSA = pkcs11.CKK_ECDSA
48 )
49
50 func init() {
51 token.Openers["pkcs11"] = open
52 token.Listers["pkcs11"] = List
53 }
54
55 var providerMap map[string]*pkcs11.Ctx
56 var providerMutex sync.Mutex
57
58 type Token struct {
59 config *config.Config
60 tokenConf *config.TokenConfig
61 ctx *pkcs11.Ctx
62 sh pkcs11.SessionHandle
63 mutex sync.Mutex
64 }
65
66 func List(provider string, output io.Writer) error {
67 ctx := pkcs11.New(provider)
68 if ctx == nil {
69 return errors.New("Failed to initialize pkcs11 provider")
70 }
71 defer ctx.Destroy()
72 if err := ctx.Initialize(); err != nil {
73 return err
74 }
75 slots, err := ctx.GetSlotList(false)
76 if err != nil {
77 return err
78 }
79 for _, slot := range slots {
80 info, err := ctx.GetTokenInfo(slot)
81 if rv, ok := err.(pkcs11.Error); ok && rv == pkcs11.CKR_TOKEN_NOT_PRESENT {
82 continue
83 }
84 fmt.Fprintf(output, "slot %d:\n manuf: %s\n model: %s\n label: %s\n serial: %s\n", slot, info.ManufacturerID, info.Model, info.Label, info.SerialNumber)
85 }
86 return nil
87 }
88
89 // Load a PKCS#11 provider, open a session, and login
90 func Open(config *config.Config, tokenName string, pinProvider passprompt.PasswordGetter) (*Token, error) {
91 tokenConf, err := config.GetToken(tokenName)
92 if err != nil {
93 return nil, err
94 }
95 ctx, err := openLib(tokenConf, true)
96 if err != nil {
97 return nil, err
98 }
99 tok := &Token{
100 ctx: ctx,
101 config: config,
102 tokenConf: tokenConf,
103 }
104 runtime.SetFinalizer(tok, (*Token).Close)
105 slot, err := tok.findSlot()
106 if err != nil {
107 tok.Close()
108 return nil, err
109 }
110 mode := uint(pkcs11.CKF_SERIAL_SESSION | pkcs11.CKF_RW_SESSION)
111 sh, err := tok.ctx.OpenSession(slot, mode)
112 if err != nil {
113 tok.Close()
114 return nil, err
115 }
116 tok.sh = sh
117 err = tok.autoLogIn(pinProvider)
118 if err != nil {
119 tok.Close()
120 return nil, err
121 }
122 return tok, nil
123 }
124
125 // compat shim for token.Openers
126 func open(cfg *config.Config, tokenName string, prompt passprompt.PasswordGetter) (token.Token, error) {
127 return Open(cfg, tokenName, prompt)
128 }
129
130 func openLib(tokenConf *config.TokenConfig, write bool) (*pkcs11.Ctx, error) {
131 if tokenConf.Provider == "" {
132 return nil, errors.New("Missing attribute \"provider\" in token configuration")
133 }
134 providerMutex.Lock()
135 defer providerMutex.Unlock()
136 if providerMap == nil {
137 providerMap = make(map[string]*pkcs11.Ctx)
138 }
139 ctx, ok := providerMap[tokenConf.Provider]
140 if ok {
141 return ctx, nil
142 }
143 ctx = pkcs11.New(tokenConf.Provider)
144 if ctx == nil {
145 return nil, errors.New("Failed to initialize pkcs11 provider")
146 }
147 err := ctx.Initialize()
148 if err != nil {
149 ctx.Destroy()
150 return nil, err
151 }
152 providerMap[tokenConf.Provider] = ctx
153 return ctx, nil
154 }
155
156 // Close the token session
157 func (tok *Token) Close() error {
158 tok.mutex.Lock()
159 defer tok.mutex.Unlock()
160 var err error
161 if tok.ctx != nil {
162 err = tok.ctx.CloseSession(tok.sh)
163 tok.ctx = nil
164 runtime.SetFinalizer(tok, nil)
165 }
166 return err
167 }
168
169 func (tok *Token) Config() *config.TokenConfig {
170 return tok.tokenConf
171 }
172
173 func (tok *Token) findSlot() (uint, error) {
174 tokenConf := tok.tokenConf
175 slots, err := tok.ctx.GetSlotList(false)
176 if err != nil {
177 return 0, nil
178 }
179 candidates := make([]uint, 0, len(slots))
180 for _, slot := range slots {
181 info, err := tok.ctx.GetTokenInfo(slot)
182 if err != nil {
183 if rv, ok := err.(pkcs11.Error); ok && rv == pkcs11.CKR_TOKEN_NOT_PRESENT {
184 continue
185 }
186 return 0, err
187 }
188 if tokenConf.Label != "" && tokenConf.Label != info.Label {
189 continue
190 } else if tokenConf.Serial != "" && tokenConf.Serial != info.SerialNumber {
191 continue
192 }
193 candidates = append(candidates, slot)
194 }
195 if len(candidates) == 0 {
196 return 0, errors.New("No token found with the specified attributes")
197 } else if len(candidates) != 1 {
198 return 0, errors.New("Multiple tokens matched the specified attributes")
199 } else {
200 return candidates[0], nil
201 }
202 }
203
204 // Test that the token is responding and the user is (still) logged in
205 func (tok *Token) isLoggedIn() (bool, error) {
206 tok.mutex.Lock()
207 defer tok.mutex.Unlock()
208 info, err := tok.ctx.GetSessionInfo(tok.sh)
209 if err != nil {
210 return false, err
211 }
212 return (info.State == CKS_RO_USER_FUNCTIONS || info.State == CKS_RW_USER_FUNCTIONS || info.State == CKS_RW_SO_FUNCTIONS), nil
213 }
214
215 func (tok *Token) Ping(ctx context.Context) error {
216 loggedIn, err := tok.isLoggedIn()
217 if err != nil {
218 return err
219 } else if !loggedIn {
220 return errors.New("token not logged in")
221 }
222 return nil
223 }
224
225 func (tok *Token) login(user uint, pin string) error {
226 tok.mutex.Lock()
227 defer tok.mutex.Unlock()
228 err := tok.ctx.Login(tok.sh, user, pin)
229 if err != nil {
230 if rv, ok := err.(pkcs11.Error); ok && rv == pkcs11.CKR_PIN_INCORRECT {
231 return sigerrors.PinIncorrectError{}
232 }
233 }
234 return err
235 }
236
237 func (tok *Token) autoLogIn(pinProvider passprompt.PasswordGetter) error {
238 tokenConf := tok.tokenConf
239 loggedIn, err := tok.isLoggedIn()
240 if err != nil {
241 return err
242 }
243 if loggedIn {
244 return nil
245 }
246 var user uint = pkcs11.CKU_USER
247 if tokenConf.User != nil {
248 user = *tokenConf.User
249 }
250 loginFunc := func(pin string) (bool, error) {
251 if err := tok.login(user, pin); err == nil {
252 return true, nil
253 } else if _, ok := err.(sigerrors.PinIncorrectError); ok {
254 return false, nil
255 } else {
256 return false, err
257 }
258 }
259 initialPrompt := fmt.Sprintf("PIN for token %s user %08x: ", tokenConf.Name(), user)
260 keyringUser := fmt.Sprintf("%s.%08x", tokenConf.Name(), user)
261 return token.Login(tokenConf, pinProvider, loginFunc, keyringUser, initialPrompt)
262 }
263
264 func (tok *Token) getAttribute(handle pkcs11.ObjectHandle, attr uint) []byte {
265 attrs, err := tok.ctx.GetAttributeValue(tok.sh, handle, []*pkcs11.Attribute{pkcs11.NewAttribute(attr, nil)})
266 if err != nil {
267 return nil
268 }
269 return attrs[0].Value
270 }
271
272 func (tok *Token) findObject(attrs []*pkcs11.Attribute) ([]pkcs11.ObjectHandle, error) {
273 if err := tok.ctx.FindObjectsInit(tok.sh, attrs); err != nil {
274 return nil, err
275 }
276 objects, _, err := tok.ctx.FindObjects(tok.sh, 10)
277 if err != nil {
278 _ = tok.ctx.FindObjectsFinal(tok.sh)
279 return nil, err
280 }
281 if err := tok.ctx.FindObjectsFinal(tok.sh); err != nil {
282 return nil, err
283 }
284 return objects, nil
285 }