access_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. // +build !windows
  17. package main
  18. import (
  19. "bytes"
  20. "crypto/rand"
  21. "encoding/hex"
  22. "encoding/json"
  23. "io"
  24. "io/ioutil"
  25. gorand "math/rand"
  26. "net/http"
  27. "os"
  28. "path/filepath"
  29. "strings"
  30. "testing"
  31. "time"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/crypto/sha3"
  34. "github.com/ethereum/go-ethereum/log"
  35. "github.com/ethereum/go-ethereum/swarm/api"
  36. swarm "github.com/ethereum/go-ethereum/swarm/api/client"
  37. )
  38. // TestAccessPassword tests for the correct creation of an ACT manifest protected by a password.
  39. // The test creates bogus content, uploads it encrypted, then creates the wrapping manifest with the Access entry
  40. // The parties participating - node (publisher), uploads to second node then disappears. Content which was uploaded
  41. // is then fetched through 2nd node. since the tested code is not key-aware - we can just
  42. // fetch from the 2nd node using HTTP BasicAuth
  43. func TestAccessPassword(t *testing.T) {
  44. cluster := newTestCluster(t, 1)
  45. defer cluster.Shutdown()
  46. proxyNode := cluster.Nodes[0]
  47. // create a tmp file
  48. tmp, err := ioutil.TempDir("", "swarm-test")
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. defer os.RemoveAll(tmp)
  53. // write data to file
  54. data := "notsorandomdata"
  55. dataFilename := filepath.Join(tmp, "data.txt")
  56. err = ioutil.WriteFile(dataFilename, []byte(data), 0666)
  57. if err != nil {
  58. t.Fatal(err)
  59. }
  60. hashRegexp := `[a-f\d]{128}`
  61. // upload the file with 'swarm up' and expect a hash
  62. up := runSwarm(t,
  63. "--bzzapi",
  64. proxyNode.URL, //it doesn't matter through which node we upload content
  65. "up",
  66. "--encrypt",
  67. dataFilename)
  68. _, matches := up.ExpectRegexp(hashRegexp)
  69. up.ExpectExit()
  70. if len(matches) < 1 {
  71. t.Fatal("no matches found")
  72. }
  73. ref := matches[0]
  74. password := "smth"
  75. passwordFilename := filepath.Join(tmp, "password.txt")
  76. err = ioutil.WriteFile(passwordFilename, []byte(password), 0666)
  77. if err != nil {
  78. t.Fatal(err)
  79. }
  80. up = runSwarm(t,
  81. "access",
  82. "new",
  83. "pass",
  84. "--dry-run",
  85. "--password",
  86. passwordFilename,
  87. ref,
  88. )
  89. _, matches = up.ExpectRegexp(".+")
  90. up.ExpectExit()
  91. if len(matches) == 0 {
  92. t.Fatalf("stdout not matched")
  93. }
  94. var m api.Manifest
  95. err = json.Unmarshal([]byte(matches[0]), &m)
  96. if err != nil {
  97. t.Fatalf("unmarshal manifest: %v", err)
  98. }
  99. if len(m.Entries) != 1 {
  100. t.Fatalf("expected one manifest entry, got %v", len(m.Entries))
  101. }
  102. e := m.Entries[0]
  103. ct := "application/bzz-manifest+json"
  104. if e.ContentType != ct {
  105. t.Errorf("expected %q content type, got %q", ct, e.ContentType)
  106. }
  107. if e.Access == nil {
  108. t.Fatal("manifest access is nil")
  109. }
  110. a := e.Access
  111. if a.Type != "pass" {
  112. t.Errorf(`got access type %q, expected "pass"`, a.Type)
  113. }
  114. if len(a.Salt) < 32 {
  115. t.Errorf(`got salt with length %v, expected not less the 32 bytes`, len(a.Salt))
  116. }
  117. if a.KdfParams == nil {
  118. t.Fatal("manifest access kdf params is nil")
  119. }
  120. client := swarm.NewClient(cluster.Nodes[0].URL)
  121. hash, err := client.UploadManifest(&m, false)
  122. if err != nil {
  123. t.Fatal(err)
  124. }
  125. httpClient := &http.Client{}
  126. url := cluster.Nodes[0].URL + "/" + "bzz:/" + hash
  127. response, err := httpClient.Get(url)
  128. if err != nil {
  129. t.Fatal(err)
  130. }
  131. if response.StatusCode != http.StatusUnauthorized {
  132. t.Fatal("should be a 401")
  133. }
  134. authHeader := response.Header.Get("WWW-Authenticate")
  135. if authHeader == "" {
  136. t.Fatal("should be something here")
  137. }
  138. req, err := http.NewRequest(http.MethodGet, url, nil)
  139. if err != nil {
  140. t.Fatal(err)
  141. }
  142. req.SetBasicAuth("", password)
  143. response, err = http.DefaultClient.Do(req)
  144. if err != nil {
  145. t.Fatal(err)
  146. }
  147. defer response.Body.Close()
  148. if response.StatusCode != http.StatusOK {
  149. t.Errorf("expected status %v, got %v", http.StatusOK, response.StatusCode)
  150. }
  151. d, err := ioutil.ReadAll(response.Body)
  152. if err != nil {
  153. t.Fatal(err)
  154. }
  155. if string(d) != data {
  156. t.Errorf("expected decrypted data %q, got %q", data, string(d))
  157. }
  158. wrongPasswordFilename := filepath.Join(tmp, "password-wrong.txt")
  159. err = ioutil.WriteFile(wrongPasswordFilename, []byte("just wr0ng"), 0666)
  160. if err != nil {
  161. t.Fatal(err)
  162. }
  163. //download file with 'swarm down' with wrong password
  164. up = runSwarm(t,
  165. "--bzzapi",
  166. proxyNode.URL,
  167. "down",
  168. "bzz:/"+hash,
  169. tmp,
  170. "--password",
  171. wrongPasswordFilename)
  172. _, matches = up.ExpectRegexp("unauthorized")
  173. if len(matches) != 1 && matches[0] != "unauthorized" {
  174. t.Fatal(`"unauthorized" not found in output"`)
  175. }
  176. up.ExpectExit()
  177. }
  178. // TestAccessPK tests for the correct creation of an ACT manifest between two parties (publisher and grantee).
  179. // The test creates bogus content, uploads it encrypted, then creates the wrapping manifest with the Access entry
  180. // The parties participating - node (publisher), uploads to second node (which is also the grantee) then disappears.
  181. // Content which was uploaded is then fetched through the grantee's http proxy. Since the tested code is private-key aware,
  182. // the test will fail if the proxy's given private key is not granted on the ACT.
  183. func TestAccessPK(t *testing.T) {
  184. // Setup Swarm and upload a test file to it
  185. cluster := newTestCluster(t, 1)
  186. defer cluster.Shutdown()
  187. // create a tmp file
  188. tmp, err := ioutil.TempFile("", "swarm-test")
  189. if err != nil {
  190. t.Fatal(err)
  191. }
  192. defer tmp.Close()
  193. defer os.Remove(tmp.Name())
  194. // write data to file
  195. data := "notsorandomdata"
  196. _, err = io.WriteString(tmp, data)
  197. if err != nil {
  198. t.Fatal(err)
  199. }
  200. hashRegexp := `[a-f\d]{128}`
  201. // upload the file with 'swarm up' and expect a hash
  202. up := runSwarm(t,
  203. "--bzzapi",
  204. cluster.Nodes[0].URL,
  205. "up",
  206. "--encrypt",
  207. tmp.Name())
  208. _, matches := up.ExpectRegexp(hashRegexp)
  209. up.ExpectExit()
  210. if len(matches) < 1 {
  211. t.Fatal("no matches found")
  212. }
  213. ref := matches[0]
  214. pk := cluster.Nodes[0].PrivateKey
  215. granteePubKey := crypto.CompressPubkey(&pk.PublicKey)
  216. publisherDir, err := ioutil.TempDir("", "swarm-account-dir-temp")
  217. if err != nil {
  218. t.Fatal(err)
  219. }
  220. passFile, err := ioutil.TempFile("", "swarm-test")
  221. if err != nil {
  222. t.Fatal(err)
  223. }
  224. defer passFile.Close()
  225. defer os.Remove(passFile.Name())
  226. _, err = io.WriteString(passFile, testPassphrase)
  227. if err != nil {
  228. t.Fatal(err)
  229. }
  230. _, publisherAccount := getTestAccount(t, publisherDir)
  231. up = runSwarm(t,
  232. "--bzzaccount",
  233. publisherAccount.Address.String(),
  234. "--password",
  235. passFile.Name(),
  236. "--datadir",
  237. publisherDir,
  238. "--bzzapi",
  239. cluster.Nodes[0].URL,
  240. "access",
  241. "new",
  242. "pk",
  243. "--dry-run",
  244. "--grant-key",
  245. hex.EncodeToString(granteePubKey),
  246. ref,
  247. )
  248. _, matches = up.ExpectRegexp(".+")
  249. up.ExpectExit()
  250. if len(matches) == 0 {
  251. t.Fatalf("stdout not matched")
  252. }
  253. var m api.Manifest
  254. err = json.Unmarshal([]byte(matches[0]), &m)
  255. if err != nil {
  256. t.Fatalf("unmarshal manifest: %v", err)
  257. }
  258. if len(m.Entries) != 1 {
  259. t.Fatalf("expected one manifest entry, got %v", len(m.Entries))
  260. }
  261. e := m.Entries[0]
  262. ct := "application/bzz-manifest+json"
  263. if e.ContentType != ct {
  264. t.Errorf("expected %q content type, got %q", ct, e.ContentType)
  265. }
  266. if e.Access == nil {
  267. t.Fatal("manifest access is nil")
  268. }
  269. a := e.Access
  270. if a.Type != "pk" {
  271. t.Errorf(`got access type %q, expected "pk"`, a.Type)
  272. }
  273. if len(a.Salt) < 32 {
  274. t.Errorf(`got salt with length %v, expected not less the 32 bytes`, len(a.Salt))
  275. }
  276. if a.KdfParams != nil {
  277. t.Fatal("manifest access kdf params should be nil")
  278. }
  279. client := swarm.NewClient(cluster.Nodes[0].URL)
  280. hash, err := client.UploadManifest(&m, false)
  281. if err != nil {
  282. t.Fatal(err)
  283. }
  284. httpClient := &http.Client{}
  285. url := cluster.Nodes[0].URL + "/" + "bzz:/" + hash
  286. response, err := httpClient.Get(url)
  287. if err != nil {
  288. t.Fatal(err)
  289. }
  290. if response.StatusCode != http.StatusOK {
  291. t.Fatal("should be a 200")
  292. }
  293. d, err := ioutil.ReadAll(response.Body)
  294. if err != nil {
  295. t.Fatal(err)
  296. }
  297. if string(d) != data {
  298. t.Errorf("expected decrypted data %q, got %q", data, string(d))
  299. }
  300. }
  301. // TestAccessACT tests the e2e creation, uploading and downloading of an ACT type access control
  302. // the test fires up a 3 node cluster, then randomly picks 2 nodes which will be acting as grantees to the data
  303. // set. the third node should fail decoding the reference as it will not be granted access. the publisher uploads through
  304. // one of the nodes then disappears.
  305. func TestAccessACT(t *testing.T) {
  306. // Setup Swarm and upload a test file to it
  307. cluster := newTestCluster(t, 3)
  308. defer cluster.Shutdown()
  309. var uploadThroughNode = cluster.Nodes[0]
  310. client := swarm.NewClient(uploadThroughNode.URL)
  311. r1 := gorand.New(gorand.NewSource(time.Now().UnixNano()))
  312. nodeToSkip := r1.Intn(3) // a number between 0 and 2 (node indices in `cluster`)
  313. // create a tmp file
  314. tmp, err := ioutil.TempFile("", "swarm-test")
  315. if err != nil {
  316. t.Fatal(err)
  317. }
  318. defer tmp.Close()
  319. defer os.Remove(tmp.Name())
  320. // write data to file
  321. data := "notsorandomdata"
  322. _, err = io.WriteString(tmp, data)
  323. if err != nil {
  324. t.Fatal(err)
  325. }
  326. hashRegexp := `[a-f\d]{128}`
  327. // upload the file with 'swarm up' and expect a hash
  328. up := runSwarm(t,
  329. "--bzzapi",
  330. cluster.Nodes[0].URL,
  331. "up",
  332. "--encrypt",
  333. tmp.Name())
  334. _, matches := up.ExpectRegexp(hashRegexp)
  335. up.ExpectExit()
  336. if len(matches) < 1 {
  337. t.Fatal("no matches found")
  338. }
  339. ref := matches[0]
  340. grantees := []string{}
  341. for i, v := range cluster.Nodes {
  342. if i == nodeToSkip {
  343. continue
  344. }
  345. pk := v.PrivateKey
  346. granteePubKey := crypto.CompressPubkey(&pk.PublicKey)
  347. grantees = append(grantees, hex.EncodeToString(granteePubKey))
  348. }
  349. granteesPubkeyListFile, err := ioutil.TempFile("", "grantees-pubkey-list.csv")
  350. if err != nil {
  351. t.Fatal(err)
  352. }
  353. _, err = granteesPubkeyListFile.WriteString(strings.Join(grantees, "\n"))
  354. if err != nil {
  355. t.Fatal(err)
  356. }
  357. defer granteesPubkeyListFile.Close()
  358. defer os.Remove(granteesPubkeyListFile.Name())
  359. publisherDir, err := ioutil.TempDir("", "swarm-account-dir-temp")
  360. if err != nil {
  361. t.Fatal(err)
  362. }
  363. passFile, err := ioutil.TempFile("", "swarm-test")
  364. if err != nil {
  365. t.Fatal(err)
  366. }
  367. defer passFile.Close()
  368. defer os.Remove(passFile.Name())
  369. _, err = io.WriteString(passFile, testPassphrase)
  370. if err != nil {
  371. t.Fatal(err)
  372. }
  373. _, publisherAccount := getTestAccount(t, publisherDir)
  374. up = runSwarm(t,
  375. "--bzzaccount",
  376. publisherAccount.Address.String(),
  377. "--password",
  378. passFile.Name(),
  379. "--datadir",
  380. publisherDir,
  381. "--bzzapi",
  382. cluster.Nodes[0].URL,
  383. "access",
  384. "new",
  385. "act",
  386. "--grant-keys",
  387. granteesPubkeyListFile.Name(),
  388. ref,
  389. )
  390. _, matches = up.ExpectRegexp(`[a-f\d]{64}`)
  391. up.ExpectExit()
  392. if len(matches) == 0 {
  393. t.Fatalf("stdout not matched")
  394. }
  395. hash := matches[0]
  396. m, _, err := client.DownloadManifest(hash)
  397. if err != nil {
  398. t.Fatalf("unmarshal manifest: %v", err)
  399. }
  400. if len(m.Entries) != 1 {
  401. t.Fatalf("expected one manifest entry, got %v", len(m.Entries))
  402. }
  403. e := m.Entries[0]
  404. ct := "application/bzz-manifest+json"
  405. if e.ContentType != ct {
  406. t.Errorf("expected %q content type, got %q", ct, e.ContentType)
  407. }
  408. if e.Access == nil {
  409. t.Fatal("manifest access is nil")
  410. }
  411. a := e.Access
  412. if a.Type != "act" {
  413. t.Fatalf(`got access type %q, expected "act"`, a.Type)
  414. }
  415. if len(a.Salt) < 32 {
  416. t.Fatalf(`got salt with length %v, expected not less the 32 bytes`, len(a.Salt))
  417. }
  418. if a.KdfParams != nil {
  419. t.Fatal("manifest access kdf params should be nil")
  420. }
  421. httpClient := &http.Client{}
  422. // all nodes except the skipped node should be able to decrypt the content
  423. for i, node := range cluster.Nodes {
  424. log.Debug("trying to fetch from node", "node index", i)
  425. url := node.URL + "/" + "bzz:/" + hash
  426. response, err := httpClient.Get(url)
  427. if err != nil {
  428. t.Fatal(err)
  429. }
  430. log.Debug("got response from node", "response code", response.StatusCode)
  431. if i == nodeToSkip {
  432. log.Debug("reached node to skip", "status code", response.StatusCode)
  433. if response.StatusCode != http.StatusUnauthorized {
  434. t.Fatalf("should be a 401")
  435. }
  436. continue
  437. }
  438. if response.StatusCode != http.StatusOK {
  439. t.Fatal("should be a 200")
  440. }
  441. d, err := ioutil.ReadAll(response.Body)
  442. if err != nil {
  443. t.Fatal(err)
  444. }
  445. if string(d) != data {
  446. t.Errorf("expected decrypted data %q, got %q", data, string(d))
  447. }
  448. }
  449. }
  450. // TestKeypairSanity is a sanity test for the crypto scheme for ACT. it asserts the correct shared secret according to
  451. // the specs at https://github.com/ethersphere/swarm-docs/blob/eb857afda906c6e7bb90d37f3f334ccce5eef230/act.md
  452. func TestKeypairSanity(t *testing.T) {
  453. salt := make([]byte, 32)
  454. if _, err := io.ReadFull(rand.Reader, salt); err != nil {
  455. t.Fatalf("reading from crypto/rand failed: %v", err.Error())
  456. }
  457. sharedSecret := "a85586744a1ddd56a7ed9f33fa24f40dd745b3a941be296a0d60e329dbdb896d"
  458. for i, v := range []struct {
  459. publisherPriv string
  460. granteePub string
  461. }{
  462. {
  463. publisherPriv: "ec5541555f3bc6376788425e9d1a62f55a82901683fd7062c5eddcc373a73459",
  464. granteePub: "0226f213613e843a413ad35b40f193910d26eb35f00154afcde9ded57479a6224a",
  465. },
  466. {
  467. publisherPriv: "70c7a73011aa56584a0009ab874794ee7e5652fd0c6911cd02f8b6267dd82d2d",
  468. granteePub: "02e6f8d5e28faaa899744972bb847b6eb805a160494690c9ee7197ae9f619181db",
  469. },
  470. } {
  471. b, _ := hex.DecodeString(v.granteePub)
  472. granteePub, _ := crypto.DecompressPubkey(b)
  473. publisherPrivate, _ := crypto.HexToECDSA(v.publisherPriv)
  474. ssKey, err := api.NewSessionKeyPK(publisherPrivate, granteePub, salt)
  475. if err != nil {
  476. t.Fatal(err)
  477. }
  478. hasher := sha3.NewKeccak256()
  479. hasher.Write(salt)
  480. shared, err := hex.DecodeString(sharedSecret)
  481. if err != nil {
  482. t.Fatal(err)
  483. }
  484. hasher.Write(shared)
  485. sum := hasher.Sum(nil)
  486. if !bytes.Equal(ssKey, sum) {
  487. t.Fatalf("%d: got a session key mismatch", i)
  488. }
  489. }
  490. }