| 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 scdtoken |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "crypto" |
| 22 | "crypto/ecdsa" |
| 23 | "crypto/rand" |
| 24 | "crypto/rsa" |
| 25 | "crypto/x509" |
| 26 | "errors" |
| 27 | "fmt" |
| 28 | "io" |
| 29 | "os" |
| 30 | "strings" |
| 31 | "sync" |
| 32 | |
| 33 | "github.com/sassoftware/relic/v7/config" |
| 34 | "github.com/sassoftware/relic/v7/lib/assuan" |
| 35 | "github.com/sassoftware/relic/v7/lib/passprompt" |
| 36 | "github.com/sassoftware/relic/v7/lib/x509tools" |
| 37 | "github.com/sassoftware/relic/v7/signers/sigerrors" |
| 38 | "github.com/sassoftware/relic/v7/token" |
| 39 | ) |
| 40 | |
| 41 | const tokenType = "scdtoken" |
| 42 | |
| 43 | func init() { |
| 44 | token.Openers[tokenType] = Open |
| 45 | token.Listers[tokenType] = List |
| 46 | } |
| 47 | |
| 48 | var defaultScdSockets = []string{ |
| 49 | "/run/user/$UID/gnupg/S.scdaemon", |
| 50 | "/var/run/user/$UID/gnupg/S.scdaemon", |
| 51 | "$HOME/.gnupg/S.scdaemon", |
| 52 | } |
| 53 | |
| 54 | type scdToken struct { |
| 55 | config *config.Config |
| 56 | tokenConf *config.TokenConfig |
| 57 | sock *assuan.ScdConn |
| 58 | serial, pin string |
| 59 | keyInfos []*assuan.ScdKey |
| 60 | mu sync.Mutex |
| 61 | } |
| 62 | |
| 63 | type scdKey struct { |
| 64 | token *scdToken |
| 65 | keyConf *config.KeyConfig |
| 66 | key *assuan.ScdKey |
| 67 | publicKey crypto.PublicKey |
| 68 | } |
| 69 | |
| 70 | func findSock() string { |
| 71 | uid := fmt.Sprintf("%d", os.Getuid()) |
| 72 | for _, fp := range defaultScdSockets { |
| 73 | fp = strings.ReplaceAll(fp, "$UID", uid) |
| 74 | fp = os.ExpandEnv(fp) |
| 75 | _, err := os.Stat(fp) |
| 76 | if err == nil { |
| 77 | return fp |
| 78 | } |
| 79 | } |
| 80 | return "" |
| 81 | } |
| 82 | |
| 83 | func List(sockPath string, output io.Writer) error { |
| 84 | if sockPath == "" { |
| 85 | sockPath = findSock() |
| 86 | } |
| 87 | if sockPath == "" { |
| 88 | return errors.New("scdaemon not found; provide an explicit path to the scdaemon socket") |
| 89 | } |
| 90 | sock, err := assuan.DialScd(sockPath) |
| 91 | if err != nil { |
| 92 | return err |
| 93 | } |
| 94 | defer sock.Close() |
| 95 | keyInfos, err := sock.Learn() |
| 96 | if err != nil { |
| 97 | return err |
| 98 | } |
| 99 | if len(keyInfos) == 0 { |
| 100 | fmt.Fprintln(output, "token is empty or missing") |
| 101 | } else { |
| 102 | fmt.Fprintf(output, "serial: %s\n", keyInfos[0].Serial) |
| 103 | } |
| 104 | return nil |
| 105 | } |
| 106 | |
| 107 | func Open(conf *config.Config, tokenName string, prompt passprompt.PasswordGetter) (token.Token, error) { |
| 108 | tconf, err := conf.GetToken(tokenName) |
| 109 | if err != nil { |
| 110 | return nil, err |
| 111 | } |
| 112 | sockPath := tconf.Provider |
| 113 | if sockPath == "" { |
| 114 | sockPath = findSock() |
| 115 | } |
| 116 | if sockPath == "" { |
| 117 | return nil, fmt.Errorf("scdaemon not found; set tokens.%s.provider to the path to the scdaemon socket", tokenName) |
| 118 | } |
| 119 | sock, err := assuan.DialScd(sockPath) |
| 120 | if err != nil { |
| 121 | return nil, err |
| 122 | } |
| 123 | tok := &scdToken{ |
| 124 | config: conf, |
| 125 | tokenConf: tconf, |
| 126 | sock: sock, |
| 127 | } |
| 128 | if err := tok.login(prompt); err != nil { |
| 129 | sock.Close() |
| 130 | return nil, err |
| 131 | } |
| 132 | return tok, nil |
| 133 | } |
| 134 | |
| 135 | func (tok *scdToken) login(prompt passprompt.PasswordGetter) error { |
| 136 | tconf := tok.tokenConf |
| 137 | keyInfos, err := tok.sock.Learn() |
| 138 | if err != nil { |
| 139 | return err |
| 140 | } |
| 141 | tok.keyInfos = keyInfos |
| 142 | tok.serial = keyInfos[0].Serial |
| 143 | if tconf.Serial != "" && tconf.Serial != tok.serial { |
| 144 | return fmt.Errorf("scdaemon token %s has serial %s but configuration specifies %s", tconf.Name(), tok.serial, tconf.Serial) |
| 145 | } |
| 146 | loginFunc := func(pin string) (bool, error) { |
| 147 | if err := tok.sock.CheckPin(pin); err == nil { |
| 148 | tok.pin = pin |
| 149 | return true, nil |
| 150 | } else if _, ok := err.(sigerrors.PinIncorrectError); ok { |
| 151 | return false, nil |
| 152 | } else { |
| 153 | return false, err |
| 154 | } |
| 155 | } |
| 156 | initialPrompt := fmt.Sprintf("PIN for token %s (serial %s): ", tconf.Name(), tok.serial) |
| 157 | keyringUser := tok.serial |
| 158 | return token.Login(tconf, prompt, loginFunc, keyringUser, initialPrompt) |
| 159 | } |
| 160 | |
| 161 | func (tok *scdToken) Ping(ctx context.Context) error { |
| 162 | tok.mu.Lock() |
| 163 | defer tok.mu.Unlock() |
| 164 | // TODO |
| 165 | return nil |
| 166 | } |
| 167 | |
| 168 | func (tok *scdToken) Close() error { |
| 169 | tok.mu.Lock() |
| 170 | defer tok.mu.Unlock() |
| 171 | if tok.sock != nil { |
| 172 | tok.sock.Close() |
| 173 | tok.sock = nil |
| 174 | } |
| 175 | return nil |
| 176 | } |
| 177 | |
| 178 | func (tok *scdToken) Config() *config.TokenConfig { |
| 179 | return tok.tokenConf |
| 180 | } |
| 181 | |
| 182 | func (tok *scdToken) ListKeys(opts token.ListOptions) error { |
| 183 | tok.mu.Lock() |
| 184 | defer tok.mu.Unlock() |
| 185 | fmt.Fprintf(opts.Output, "serial: %#v\n", tok.serial) |
| 186 | for i, key := range tok.keyInfos { |
| 187 | if opts.ID != "" && opts.ID != key.KeyId { |
| 188 | continue |
| 189 | } |
| 190 | fmt.Fprintf(opts.Output, "key %d:\n id: %s\n fingerprint: %s\n keygrip: %s\n", i+1, key.KeyId, key.Fingerprint, key.KeyGrip) |
| 191 | if opts.Values { |
| 192 | pub, err := key.Public() |
| 193 | if err != nil { |
| 194 | fmt.Fprintln(opts.Output, " error reading key:", err) |
| 195 | continue |
| 196 | } |
| 197 | switch k := pub.(type) { |
| 198 | case *rsa.PublicKey: |
| 199 | fmt.Fprintf(opts.Output, " n: 0x%x\n e: %d\n", k.N, k.E) |
| 200 | case *ecdsa.PublicKey: |
| 201 | curve, err := x509tools.CurveByCurve(k.Curve) |
| 202 | if err == nil { |
| 203 | fmt.Fprintf(opts.Output, " bits: %d\n", curve.Bits) |
| 204 | } |
| 205 | fmt.Fprintf(opts.Output, " x: %x\n y: %x\n", k.X, k.Y) |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | return nil |
| 210 | } |
| 211 | |
| 212 | func (tok *scdToken) GetKey(ctx context.Context, keyName string) (token.Key, error) { |
| 213 | tok.mu.Lock() |
| 214 | defer tok.mu.Unlock() |
| 215 | keyConf, err := tok.config.GetKey(keyName) |
| 216 | if err != nil { |
| 217 | return nil, err |
| 218 | } |
| 219 | var key *assuan.ScdKey |
| 220 | for _, kc := range tok.keyInfos { |
| 221 | if keyConf.ID != "" && keyConf.ID != kc.KeyId { |
| 222 | continue |
| 223 | } |
| 224 | key = kc |
| 225 | break |
| 226 | } |
| 227 | if key.KeyId == "" { |
| 228 | return nil, fmt.Errorf("key %s not found in token %s", keyName, tok.tokenConf.Name()) |
| 229 | } |
| 230 | pubkey, err := key.Public() |
| 231 | if err != nil { |
| 232 | return nil, err |
| 233 | } |
| 234 | return &scdKey{ |
| 235 | token: tok, |
| 236 | keyConf: keyConf, |
| 237 | key: key, |
| 238 | publicKey: pubkey, |
| 239 | }, nil |
| 240 | } |
| 241 | |
| 242 | func (key *scdKey) Public() crypto.PublicKey { |
| 243 | return key.publicKey |
| 244 | } |
| 245 | |
| 246 | func (key *scdKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) { |
| 247 | key.token.mu.Lock() |
| 248 | defer key.token.mu.Unlock() |
| 249 | return key.key.Sign(digest, opts, key.token.pin) |
| 250 | } |
| 251 | |
| 252 | func (key *scdKey) SignContext(ctx context.Context, digest []byte, opts crypto.SignerOpts) ([]byte, error) { |
| 253 | return key.Sign(rand.Reader, digest, opts) |
| 254 | } |
| 255 | |
| 256 | func (key *scdKey) Config() *config.KeyConfig { |
| 257 | return key.keyConf |
| 258 | } |
| 259 | |
| 260 | func (key *scdKey) Certificate() []byte { |
| 261 | return nil |
| 262 | } |
| 263 | |
| 264 | func (key *scdKey) GetID() []byte { |
| 265 | return []byte(key.token.serial) |
| 266 | } |
| 267 | |
| 268 | func (tok *scdToken) Import(keyName string, privKey crypto.PrivateKey) (token.Key, error) { |
| 269 | return nil, token.NotImplementedError{Op: "import-key", Type: tokenType} |
| 270 | } |
| 271 | |
| 272 | func (tok *scdToken) ImportCertificate(cert *x509.Certificate, labelBase string) error { |
| 273 | return token.NotImplementedError{Op: "import-certificate", Type: tokenType} |
| 274 | } |
| 275 | |
| 276 | func (tok *scdToken) Generate(keyName string, keyType token.KeyType, bits uint) (token.Key, error) { |
| 277 | // TODO - probably useful |
| 278 | return nil, token.NotImplementedError{Op: "generate-key", Type: tokenType} |
| 279 | } |
| 280 | |
| 281 | func (key *scdKey) ImportCertificate(cert *x509.Certificate) error { |
| 282 | return token.NotImplementedError{Op: "import-certificate", Type: tokenType} |
| 283 | } |