access_test.go 16 KB

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