aboutsummaryrefslogtreecommitdiffstats
path: root/cmd/swarm/access.go
blob: 072541b6595f8ae2c9eff53fa1fe53d8b53f6056 (plain) (blame)
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// Copyright 2018 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
package main

import (
    "crypto/rand"
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "strings"

    "github.com/ethereum/go-ethereum/cmd/utils"
    "github.com/ethereum/go-ethereum/swarm/api"
    "github.com/ethereum/go-ethereum/swarm/api/client"
    "gopkg.in/urfave/cli.v1"
)

var (
    salt          = make([]byte, 32)
    accessCommand = cli.Command{
        CustomHelpTemplate: helpTemplate,
        Name:               "access",
        Usage:              "encrypts a reference and embeds it into a root manifest",
        ArgsUsage:          "<ref>",
        Description:        "encrypts a reference and embeds it into a root manifest",
        Subcommands: []cli.Command{
            {
                CustomHelpTemplate: helpTemplate,
                Name:               "new",
                Usage:              "encrypts a reference and embeds it into a root manifest",
                ArgsUsage:          "<ref>",
                Description:        "encrypts a reference and embeds it into a root access manifest and prints the resulting manifest",
                Subcommands: []cli.Command{
                    {
                        Action:             accessNewPass,
                        CustomHelpTemplate: helpTemplate,
                        Flags: []cli.Flag{
                            utils.PasswordFileFlag,
                            SwarmDryRunFlag,
                        },
                        Name:        "pass",
                        Usage:       "encrypts a reference with a password and embeds it into a root manifest",
                        ArgsUsage:   "<ref>",
                        Description: "encrypts a reference and embeds it into a root access manifest and prints the resulting manifest",
                    },
                    {
                        Action:             accessNewPK,
                        CustomHelpTemplate: helpTemplate,
                        Flags: []cli.Flag{
                            utils.PasswordFileFlag,
                            SwarmDryRunFlag,
                            SwarmAccessGrantKeyFlag,
                        },
                        Name:        "pk",
                        Usage:       "encrypts a reference with the node's private key and a given grantee's public key and embeds it into a root manifest",
                        ArgsUsage:   "<ref>",
                        Description: "encrypts a reference and embeds it into a root access manifest and prints the resulting manifest",
                    },
                    {
                        Action:             accessNewACT,
                        CustomHelpTemplate: helpTemplate,
                        Flags: []cli.Flag{
                            SwarmAccessGrantKeysFlag,
                            SwarmDryRunFlag,
                            utils.PasswordFileFlag,
                        },
                        Name:        "act",
                        Usage:       "encrypts a reference with the node's private key and a given grantee's public key and embeds it into a root manifest",
                        ArgsUsage:   "<ref>",
                        Description: "encrypts a reference and embeds it into a root access manifest and prints the resulting manifest",
                    },
                },
            },
        },
    }
)

func init() {
    if _, err := io.ReadFull(rand.Reader, salt); err != nil {
        panic("reading from crypto/rand failed: " + err.Error())
    }
}

func accessNewPass(ctx *cli.Context) {
    args := ctx.Args()
    if len(args) != 1 {
        utils.Fatalf("Expected 1 argument - the ref")
    }

    var (
        ae        *api.AccessEntry
        accessKey []byte
        err       error
        ref       = args[0]
        password  = getPassPhrase("", 0, makePasswordList(ctx))
        dryRun    = ctx.Bool(SwarmDryRunFlag.Name)
    )
    accessKey, ae, err = api.DoPassword(ctx, password, salt)
    if err != nil {
        utils.Fatalf("error getting session key: %v", err)
    }
    m, err := api.GenerateAccessControlManifest(ctx, ref, accessKey, ae)
    if err != nil {
        utils.Fatalf("had an error generating the manifest: %v", err)
    }
    if dryRun {
        err = printManifests(m, nil)
        if err != nil {
            utils.Fatalf("had an error printing the manifests: %v", err)
        }
    } else {
        err = uploadManifests(ctx, m, nil)
        if err != nil {
            utils.Fatalf("had an error uploading the manifests: %v", err)
        }
    }
}

func accessNewPK(ctx *cli.Context) {
    args := ctx.Args()
    if len(args) != 1 {
        utils.Fatalf("Expected 1 argument - the ref")
    }

    var (
        ae               *api.AccessEntry
        sessionKey       []byte
        err              error
        ref              = args[0]
        privateKey       = getPrivKey(ctx)
        granteePublicKey = ctx.String(SwarmAccessGrantKeyFlag.Name)
        dryRun           = ctx.Bool(SwarmDryRunFlag.Name)
    )
    sessionKey, ae, err = api.DoPK(ctx, privateKey, granteePublicKey, salt)
    if err != nil {
        utils.Fatalf("error getting session key: %v", err)
    }
    m, err := api.GenerateAccessControlManifest(ctx, ref, sessionKey, ae)
    if err != nil {
        utils.Fatalf("had an error generating the manifest: %v", err)
    }
    if dryRun {
        err = printManifests(m, nil)
        if err != nil {
            utils.Fatalf("had an error printing the manifests: %v", err)
        }
    } else {
        err = uploadManifests(ctx, m, nil)
        if err != nil {
            utils.Fatalf("had an error uploading the manifests: %v", err)
        }
    }
}

func accessNewACT(ctx *cli.Context) {
    args := ctx.Args()
    if len(args) != 1 {
        utils.Fatalf("Expected 1 argument - the ref")
    }

    var (
        ae                   *api.AccessEntry
        actManifest          *api.Manifest
        accessKey            []byte
        err                  error
        ref                  = args[0]
        pkGrantees           = []string{}
        passGrantees         = []string{}
        pkGranteesFilename   = ctx.String(SwarmAccessGrantKeysFlag.Name)
        passGranteesFilename = ctx.String(utils.PasswordFileFlag.Name)
        privateKey           = getPrivKey(ctx)
        dryRun               = ctx.Bool(SwarmDryRunFlag.Name)
    )
    if pkGranteesFilename == "" && passGranteesFilename == "" {
        utils.Fatalf("you have to provide either a grantee public-keys file or an encryption passwords file (or both)")
    }

    if pkGranteesFilename != "" {
        bytes, err := ioutil.ReadFile(pkGranteesFilename)
        if err != nil {
            utils.Fatalf("had an error reading the grantee public key list")
        }
        pkGrantees = strings.Split(strings.Trim(string(bytes), "\n"), "\n")
    }

    if passGranteesFilename != "" {
        bytes, err := ioutil.ReadFile(passGranteesFilename)
        if err != nil {
            utils.Fatalf("could not read password filename: %v", err)
        }
        passGrantees = strings.Split(strings.Trim(string(bytes), "\n"), "\n")
    }
    accessKey, ae, actManifest, err = api.DoACT(ctx, privateKey, salt, pkGrantees, passGrantees)
    if err != nil {
        utils.Fatalf("error generating ACT manifest: %v", err)
    }

    if err != nil {
        utils.Fatalf("error getting session key: %v", err)
    }
    m, err := api.GenerateAccessControlManifest(ctx, ref, accessKey, ae)
    if err != nil {
        utils.Fatalf("error generating root access manifest: %v", err)
    }

    if dryRun {
        err = printManifests(m, actManifest)
        if err != nil {
            utils.Fatalf("had an error printing the manifests: %v", err)
        }
    } else {
        err = uploadManifests(ctx, m, actManifest)
        if err != nil {
            utils.Fatalf("had an error uploading the manifests: %v", err)
        }
    }
}

func printManifests(rootAccessManifest, actManifest *api.Manifest) error {
    js, err := json.Marshal(rootAccessManifest)
    if err != nil {
        return err
    }
    fmt.Println(string(js))

    if actManifest != nil {
        js, err := json.Marshal(actManifest)
        if err != nil {
            return err
        }
        fmt.Println(string(js))
    }
    return nil
}

func uploadManifests(ctx *cli.Context, rootAccessManifest, actManifest *api.Manifest) error {
    bzzapi := strings.TrimRight(ctx.GlobalString(SwarmApiFlag.Name), "/")
    client := client.NewClient(bzzapi)

    var (
        key string
        err error
    )
    if actManifest != nil {
        key, err = client.UploadManifest(actManifest, false)
        if err != nil {
            return err
        }

        rootAccessManifest.Entries[0].Access.Act = key
    }
    key, err = client.UploadManifest(rootAccessManifest, false)
    if err != nil {
        return err
    }
    fmt.Println(key)
    return nil
}

// makePasswordList reads password lines from the file specified by the global --password flag
// and also by the same subcommand --password flag.
// This function ia a fork of utils.MakePasswordList to lookup cli context for subcommand.
// Function ctx.SetGlobal is not setting the global flag value that can be accessed
// by ctx.GlobalString using the current version of cli package.
func makePasswordList(ctx *cli.Context) []string {
    path := ctx.GlobalString(utils.PasswordFileFlag.Name)
    if path == "" {
        path = ctx.String(utils.PasswordFileFlag.Name)
        if path == "" {
            return nil
        }
    }
    text, err := ioutil.ReadFile(path)
    if err != nil {
        utils.Fatalf("Failed to read password file: %v", err)
    }
    lines := strings.Split(string(text), "\n")
    // Sanitise DOS line endings.
    for i := range lines {
        lines[i] = strings.TrimRight(lines[i], "\r")
    }
    return lines
}