access_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. package main
  17. import (
  18. "bytes"
  19. "crypto/rand"
  20. "encoding/hex"
  21. "encoding/json"
  22. "io"
  23. "io/ioutil"
  24. gorand "math/rand"
  25. "net/http"
  26. "os"
  27. "runtime"
  28. "strings"
  29. "testing"
  30. "time"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/crypto/ecies"
  33. "github.com/ethereum/go-ethereum/log"
  34. "github.com/ethereum/go-ethereum/swarm/api"
  35. swarmapi "github.com/ethereum/go-ethereum/swarm/api/client"
  36. "github.com/ethereum/go-ethereum/swarm/testutil"
  37. "golang.org/x/crypto/sha3"
  38. )
  39. const (
  40. hashRegexp = `[a-f\d]{128}`
  41. data = "notsorandomdata"
  42. )
  43. var DefaultCurve = crypto.S256()
  44. func TestACT(t *testing.T) {
  45. if runtime.GOOS == "windows" {
  46. t.Skip()
  47. }
  48. cluster := newTestCluster(t, clusterSize)
  49. defer cluster.Shutdown()
  50. cases := []struct {
  51. name string
  52. f func(t *testing.T, cluster *testCluster)
  53. }{
  54. {"Password", testPassword},
  55. {"PK", testPK},
  56. {"ACTWithoutBogus", testACTWithoutBogus},
  57. {"ACTWithBogus", testACTWithBogus},
  58. }
  59. for _, tc := range cases {
  60. t.Run(tc.name, func(t *testing.T) {
  61. tc.f(t, cluster)
  62. })
  63. }
  64. }
  65. // testPassword tests for the correct creation of an ACT manifest protected by a password.
  66. // The test creates bogus content, uploads it encrypted, then creates the wrapping manifest with the Access entry
  67. // The parties participating - node (publisher), uploads to second node then disappears. Content which was uploaded
  68. // is then fetched through 2nd node. since the tested code is not key-aware - we can just
  69. // fetch from the 2nd node using HTTP BasicAuth
  70. func testPassword(t *testing.T, cluster *testCluster) {
  71. dataFilename := testutil.TempFileWithContent(t, data)
  72. defer os.RemoveAll(dataFilename)
  73. // upload the file with 'swarm up' and expect a hash
  74. up := runSwarm(t,
  75. "--bzzapi",
  76. cluster.Nodes[0].URL,
  77. "up",
  78. "--encrypt",
  79. dataFilename)
  80. _, matches := up.ExpectRegexp(hashRegexp)
  81. up.ExpectExit()
  82. if len(matches) < 1 {
  83. t.Fatal("no matches found")
  84. }
  85. ref := matches[0]
  86. tmp, err := ioutil.TempDir("", "swarm-test")
  87. if err != nil {
  88. t.Fatal(err)
  89. }
  90. defer os.RemoveAll(tmp)
  91. password := "smth"
  92. passwordFilename := testutil.TempFileWithContent(t, "smth")
  93. defer os.RemoveAll(passwordFilename)
  94. up = runSwarm(t,
  95. "access",
  96. "new",
  97. "pass",
  98. "--dry-run",
  99. "--password",
  100. passwordFilename,
  101. ref,
  102. )
  103. _, matches = up.ExpectRegexp(".+")
  104. up.ExpectExit()
  105. if len(matches) == 0 {
  106. t.Fatalf("stdout not matched")
  107. }
  108. var m api.Manifest
  109. err = json.Unmarshal([]byte(matches[0]), &m)
  110. if err != nil {
  111. t.Fatalf("unmarshal manifest: %v", err)
  112. }
  113. if len(m.Entries) != 1 {
  114. t.Fatalf("expected one manifest entry, got %v", len(m.Entries))
  115. }
  116. e := m.Entries[0]
  117. ct := "application/bzz-manifest+json"
  118. if e.ContentType != ct {
  119. t.Errorf("expected %q content type, got %q", ct, e.ContentType)
  120. }
  121. if e.Access == nil {
  122. t.Fatal("manifest access is nil")
  123. }
  124. a := e.Access
  125. if a.Type != "pass" {
  126. t.Errorf(`got access type %q, expected "pass"`, a.Type)
  127. }
  128. if len(a.Salt) < 32 {
  129. t.Errorf(`got salt with length %v, expected not less the 32 bytes`, len(a.Salt))
  130. }
  131. if a.KdfParams == nil {
  132. t.Fatal("manifest access kdf params is nil")
  133. }
  134. if a.Publisher != "" {
  135. t.Fatal("should be empty")
  136. }
  137. client := swarmapi.NewClient(cluster.Nodes[0].URL)
  138. hash, err := client.UploadManifest(&m, false)
  139. if err != nil {
  140. t.Fatal(err)
  141. }
  142. url := cluster.Nodes[0].URL + "/" + "bzz:/" + hash
  143. httpClient := &http.Client{}
  144. response, err := httpClient.Get(url)
  145. if err != nil {
  146. t.Fatal(err)
  147. }
  148. if response.StatusCode != http.StatusUnauthorized {
  149. t.Fatal("should be a 401")
  150. }
  151. authHeader := response.Header.Get("WWW-Authenticate")
  152. if authHeader == "" {
  153. t.Fatal("should be something here")
  154. }
  155. req, err := http.NewRequest(http.MethodGet, url, nil)
  156. if err != nil {
  157. t.Fatal(err)
  158. }
  159. req.SetBasicAuth("", password)
  160. response, err = http.DefaultClient.Do(req)
  161. if err != nil {
  162. t.Fatal(err)
  163. }
  164. defer response.Body.Close()
  165. if response.StatusCode != http.StatusOK {
  166. t.Errorf("expected status %v, got %v", http.StatusOK, response.StatusCode)
  167. }
  168. d, err := ioutil.ReadAll(response.Body)
  169. if err != nil {
  170. t.Fatal(err)
  171. }
  172. if string(d) != data {
  173. t.Errorf("expected decrypted data %q, got %q", data, string(d))
  174. }
  175. wrongPasswordFilename := testutil.TempFileWithContent(t, "just wr0ng")
  176. defer os.RemoveAll(wrongPasswordFilename)
  177. //download file with 'swarm down' with wrong password
  178. up = runSwarm(t,
  179. "--bzzapi",
  180. cluster.Nodes[0].URL,
  181. "down",
  182. "bzz:/"+hash,
  183. tmp,
  184. "--password",
  185. wrongPasswordFilename)
  186. _, matches = up.ExpectRegexp("unauthorized")
  187. if len(matches) != 1 && matches[0] != "unauthorized" {
  188. t.Fatal(`"unauthorized" not found in output"`)
  189. }
  190. up.ExpectExit()
  191. }
  192. // testPK tests for the correct creation of an ACT manifest between two parties (publisher and grantee).
  193. // The test creates bogus content, uploads it encrypted, then creates the wrapping manifest with the Access entry
  194. // The parties participating - node (publisher), uploads to second node (which is also the grantee) then disappears.
  195. // Content which was uploaded is then fetched through the grantee's http proxy. Since the tested code is private-key aware,
  196. // the test will fail if the proxy's given private key is not granted on the ACT.
  197. func testPK(t *testing.T, cluster *testCluster) {
  198. dataFilename := testutil.TempFileWithContent(t, data)
  199. defer os.RemoveAll(dataFilename)
  200. // upload the file with 'swarm up' and expect a hash
  201. up := runSwarm(t,
  202. "--bzzapi",
  203. cluster.Nodes[0].URL,
  204. "up",
  205. "--encrypt",
  206. dataFilename)
  207. _, matches := up.ExpectRegexp(hashRegexp)
  208. up.ExpectExit()
  209. if len(matches) < 1 {
  210. t.Fatal("no matches found")
  211. }
  212. ref := matches[0]
  213. pk := cluster.Nodes[0].PrivateKey
  214. granteePubKey := crypto.CompressPubkey(&pk.PublicKey)
  215. publisherDir, err := ioutil.TempDir("", "swarm-account-dir-temp")
  216. if err != nil {
  217. t.Fatal(err)
  218. }
  219. passwordFilename := testutil.TempFileWithContent(t, testPassphrase)
  220. defer os.RemoveAll(passwordFilename)
  221. _, publisherAccount := getTestAccount(t, publisherDir)
  222. up = runSwarm(t,
  223. "--bzzaccount",
  224. publisherAccount.Address.String(),
  225. "--password",
  226. passwordFilename,
  227. "--datadir",
  228. publisherDir,
  229. "--bzzapi",
  230. cluster.Nodes[0].URL,
  231. "access",
  232. "new",
  233. "pk",
  234. "--dry-run",
  235. "--grant-key",
  236. hex.EncodeToString(granteePubKey),
  237. ref,
  238. )
  239. _, matches = up.ExpectRegexp(".+")
  240. up.ExpectExit()
  241. if len(matches) == 0 {
  242. t.Fatalf("stdout not matched")
  243. }
  244. //get the public key from the publisher directory
  245. publicKeyFromDataDir := runSwarm(t,
  246. "--bzzaccount",
  247. publisherAccount.Address.String(),
  248. "--password",
  249. passwordFilename,
  250. "--datadir",
  251. publisherDir,
  252. "print-keys",
  253. "--compressed",
  254. )
  255. _, publicKeyString := publicKeyFromDataDir.ExpectRegexp(".+")
  256. publicKeyFromDataDir.ExpectExit()
  257. pkComp := strings.Split(publicKeyString[0], "=")[1]
  258. var m api.Manifest
  259. err = json.Unmarshal([]byte(matches[0]), &m)
  260. if err != nil {
  261. t.Fatalf("unmarshal manifest: %v", err)
  262. }
  263. if len(m.Entries) != 1 {
  264. t.Fatalf("expected one manifest entry, got %v", len(m.Entries))
  265. }
  266. e := m.Entries[0]
  267. ct := "application/bzz-manifest+json"
  268. if e.ContentType != ct {
  269. t.Errorf("expected %q content type, got %q", ct, e.ContentType)
  270. }
  271. if e.Access == nil {
  272. t.Fatal("manifest access is nil")
  273. }
  274. a := e.Access
  275. if a.Type != "pk" {
  276. t.Errorf(`got access type %q, expected "pk"`, a.Type)
  277. }
  278. if len(a.Salt) < 32 {
  279. t.Errorf(`got salt with length %v, expected not less the 32 bytes`, len(a.Salt))
  280. }
  281. if a.KdfParams != nil {
  282. t.Fatal("manifest access kdf params should be nil")
  283. }
  284. if a.Publisher != pkComp {
  285. t.Fatal("publisher key did not match")
  286. }
  287. client := swarmapi.NewClient(cluster.Nodes[0].URL)
  288. hash, err := client.UploadManifest(&m, false)
  289. if err != nil {
  290. t.Fatal(err)
  291. }
  292. httpClient := &http.Client{}
  293. url := cluster.Nodes[0].URL + "/" + "bzz:/" + hash
  294. response, err := httpClient.Get(url)
  295. if err != nil {
  296. t.Fatal(err)
  297. }
  298. if response.StatusCode != http.StatusOK {
  299. t.Fatal("should be a 200")
  300. }
  301. d, err := ioutil.ReadAll(response.Body)
  302. if err != nil {
  303. t.Fatal(err)
  304. }
  305. if string(d) != data {
  306. t.Errorf("expected decrypted data %q, got %q", data, string(d))
  307. }
  308. }
  309. // testACTWithoutBogus tests the creation of the ACT manifest end-to-end, without any bogus entries (i.e. default scenario = 3 nodes 1 unauthorized)
  310. func testACTWithoutBogus(t *testing.T, cluster *testCluster) {
  311. testACT(t, cluster, 0)
  312. }
  313. // testACTWithBogus tests the creation of the ACT manifest end-to-end, with 100 bogus entries (i.e. 100 EC keys + default scenario = 3 nodes 1 unauthorized = 103 keys in the ACT manifest)
  314. func testACTWithBogus(t *testing.T, cluster *testCluster) {
  315. testACT(t, cluster, 100)
  316. }
  317. // testACT tests the e2e creation, uploading and downloading of an ACT access control with both EC keys AND password protection
  318. // the test fires up a 3 node cluster, then randomly picks 2 nodes which will be acting as grantees to the data
  319. // set and also protects the ACT with a password. the third node should fail decoding the reference as it will not be granted access.
  320. // the third node then then tries to download using a correct password (and succeeds) then uses a wrong password and fails.
  321. // the publisher uploads through one of the nodes then disappears.
  322. func testACT(t *testing.T, cluster *testCluster, bogusEntries int) {
  323. var uploadThroughNode = cluster.Nodes[0]
  324. client := swarmapi.NewClient(uploadThroughNode.URL)
  325. r1 := gorand.New(gorand.NewSource(time.Now().UnixNano()))
  326. nodeToSkip := r1.Intn(clusterSize) // a number between 0 and 2 (node indices in `cluster`)
  327. dataFilename := testutil.TempFileWithContent(t, data)
  328. defer os.RemoveAll(dataFilename)
  329. // upload the file with 'swarm up' and expect a hash
  330. up := runSwarm(t,
  331. "--bzzapi",
  332. cluster.Nodes[0].URL,
  333. "up",
  334. "--encrypt",
  335. dataFilename)
  336. _, matches := up.ExpectRegexp(hashRegexp)
  337. up.ExpectExit()
  338. if len(matches) < 1 {
  339. t.Fatal("no matches found")
  340. }
  341. ref := matches[0]
  342. var grantees []string
  343. for i, v := range cluster.Nodes {
  344. if i == nodeToSkip {
  345. continue
  346. }
  347. pk := v.PrivateKey
  348. granteePubKey := crypto.CompressPubkey(&pk.PublicKey)
  349. grantees = append(grantees, hex.EncodeToString(granteePubKey))
  350. }
  351. if bogusEntries > 0 {
  352. var bogusGrantees []string
  353. for i := 0; i < bogusEntries; i++ {
  354. prv, err := ecies.GenerateKey(rand.Reader, DefaultCurve, nil)
  355. if err != nil {
  356. t.Fatal(err)
  357. }
  358. bogusGrantees = append(bogusGrantees, hex.EncodeToString(crypto.CompressPubkey(&prv.ExportECDSA().PublicKey)))
  359. }
  360. r2 := gorand.New(gorand.NewSource(time.Now().UnixNano()))
  361. for i := 0; i < len(grantees); i++ {
  362. insertAtIdx := r2.Intn(len(bogusGrantees))
  363. bogusGrantees = append(bogusGrantees[:insertAtIdx], append([]string{grantees[i]}, bogusGrantees[insertAtIdx:]...)...)
  364. }
  365. grantees = bogusGrantees
  366. }
  367. granteesPubkeyListFile := testutil.TempFileWithContent(t, strings.Join(grantees, "\n"))
  368. defer os.RemoveAll(granteesPubkeyListFile)
  369. publisherDir, err := ioutil.TempDir("", "swarm-account-dir-temp")
  370. if err != nil {
  371. t.Fatal(err)
  372. }
  373. defer os.RemoveAll(publisherDir)
  374. passwordFilename := testutil.TempFileWithContent(t, testPassphrase)
  375. defer os.RemoveAll(passwordFilename)
  376. actPasswordFilename := testutil.TempFileWithContent(t, "smth")
  377. defer os.RemoveAll(actPasswordFilename)
  378. _, publisherAccount := getTestAccount(t, publisherDir)
  379. up = runSwarm(t,
  380. "--bzzaccount",
  381. publisherAccount.Address.String(),
  382. "--password",
  383. passwordFilename,
  384. "--datadir",
  385. publisherDir,
  386. "--bzzapi",
  387. cluster.Nodes[0].URL,
  388. "access",
  389. "new",
  390. "act",
  391. "--grant-keys",
  392. granteesPubkeyListFile,
  393. "--password",
  394. actPasswordFilename,
  395. ref,
  396. )
  397. _, matches = up.ExpectRegexp(`[a-f\d]{64}`)
  398. up.ExpectExit()
  399. if len(matches) == 0 {
  400. t.Fatalf("stdout not matched")
  401. }
  402. //get the public key from the publisher directory
  403. publicKeyFromDataDir := runSwarm(t,
  404. "--bzzaccount",
  405. publisherAccount.Address.String(),
  406. "--password",
  407. passwordFilename,
  408. "--datadir",
  409. publisherDir,
  410. "print-keys",
  411. "--compressed",
  412. )
  413. _, publicKeyString := publicKeyFromDataDir.ExpectRegexp(".+")
  414. publicKeyFromDataDir.ExpectExit()
  415. pkComp := strings.Split(publicKeyString[0], "=")[1]
  416. hash := matches[0]
  417. m, _, err := client.DownloadManifest(hash)
  418. if err != nil {
  419. t.Fatalf("unmarshal manifest: %v", err)
  420. }
  421. if len(m.Entries) != 1 {
  422. t.Fatalf("expected one manifest entry, got %v", len(m.Entries))
  423. }
  424. e := m.Entries[0]
  425. ct := "application/bzz-manifest+json"
  426. if e.ContentType != ct {
  427. t.Errorf("expected %q content type, got %q", ct, e.ContentType)
  428. }
  429. if e.Access == nil {
  430. t.Fatal("manifest access is nil")
  431. }
  432. a := e.Access
  433. if a.Type != "act" {
  434. t.Fatalf(`got access type %q, expected "act"`, a.Type)
  435. }
  436. if len(a.Salt) < 32 {
  437. t.Fatalf(`got salt with length %v, expected not less the 32 bytes`, len(a.Salt))
  438. }
  439. if a.Publisher != pkComp {
  440. t.Fatal("publisher key did not match")
  441. }
  442. httpClient := &http.Client{}
  443. // all nodes except the skipped node should be able to decrypt the content
  444. for i, node := range cluster.Nodes {
  445. log.Debug("trying to fetch from node", "node index", i)
  446. url := node.URL + "/" + "bzz:/" + hash
  447. response, err := httpClient.Get(url)
  448. if err != nil {
  449. t.Fatal(err)
  450. }
  451. log.Debug("got response from node", "response code", response.StatusCode)
  452. if i == nodeToSkip {
  453. log.Debug("reached node to skip", "status code", response.StatusCode)
  454. if response.StatusCode != http.StatusUnauthorized {
  455. t.Fatalf("should be a 401")
  456. }
  457. // try downloading using a password instead, using the unauthorized node
  458. passwordUrl := strings.Replace(url, "http://", "http://:smth@", -1)
  459. response, err = httpClient.Get(passwordUrl)
  460. if err != nil {
  461. t.Fatal(err)
  462. }
  463. if response.StatusCode != http.StatusOK {
  464. t.Fatal("should be a 200")
  465. }
  466. // now try with the wrong password, expect 401
  467. passwordUrl = strings.Replace(url, "http://", "http://:smthWrong@", -1)
  468. response, err = httpClient.Get(passwordUrl)
  469. if err != nil {
  470. t.Fatal(err)
  471. }
  472. if response.StatusCode != http.StatusUnauthorized {
  473. t.Fatal("should be a 401")
  474. }
  475. continue
  476. }
  477. if response.StatusCode != http.StatusOK {
  478. t.Fatal("should be a 200")
  479. }
  480. d, err := ioutil.ReadAll(response.Body)
  481. if err != nil {
  482. t.Fatal(err)
  483. }
  484. if string(d) != data {
  485. t.Errorf("expected decrypted data %q, got %q", data, string(d))
  486. }
  487. }
  488. }
  489. // TestKeypairSanity is a sanity test for the crypto scheme for ACT. it asserts the correct shared secret according to
  490. // the specs at https://github.com/ethersphere/swarm-docs/blob/eb857afda906c6e7bb90d37f3f334ccce5eef230/act.md
  491. func TestKeypairSanity(t *testing.T) {
  492. salt := make([]byte, 32)
  493. if _, err := io.ReadFull(rand.Reader, salt); err != nil {
  494. t.Fatalf("reading from crypto/rand failed: %v", err.Error())
  495. }
  496. sharedSecret := "a85586744a1ddd56a7ed9f33fa24f40dd745b3a941be296a0d60e329dbdb896d"
  497. for i, v := range []struct {
  498. publisherPriv string
  499. granteePub string
  500. }{
  501. {
  502. publisherPriv: "ec5541555f3bc6376788425e9d1a62f55a82901683fd7062c5eddcc373a73459",
  503. granteePub: "0226f213613e843a413ad35b40f193910d26eb35f00154afcde9ded57479a6224a",
  504. },
  505. {
  506. publisherPriv: "70c7a73011aa56584a0009ab874794ee7e5652fd0c6911cd02f8b6267dd82d2d",
  507. granteePub: "02e6f8d5e28faaa899744972bb847b6eb805a160494690c9ee7197ae9f619181db",
  508. },
  509. } {
  510. b, _ := hex.DecodeString(v.granteePub)
  511. granteePub, _ := crypto.DecompressPubkey(b)
  512. publisherPrivate, _ := crypto.HexToECDSA(v.publisherPriv)
  513. ssKey, err := api.NewSessionKeyPK(publisherPrivate, granteePub, salt)
  514. if err != nil {
  515. t.Fatal(err)
  516. }
  517. hasher := sha3.NewLegacyKeccak256()
  518. hasher.Write(salt)
  519. shared, err := hex.DecodeString(sharedSecret)
  520. if err != nil {
  521. t.Fatal(err)
  522. }
  523. hasher.Write(shared)
  524. sum := hasher.Sum(nil)
  525. if !bytes.Equal(ssKey, sum) {
  526. t.Fatalf("%d: got a session key mismatch", i)
  527. }
  528. }
  529. }