act.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. package api
  2. import (
  3. "context"
  4. "crypto/ecdsa"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "strings"
  12. "time"
  13. "github.com/ethereum/go-ethereum/common"
  14. "github.com/ethereum/go-ethereum/crypto"
  15. "github.com/ethereum/go-ethereum/crypto/ecies"
  16. "github.com/ethereum/go-ethereum/swarm/log"
  17. "github.com/ethereum/go-ethereum/swarm/sctx"
  18. "github.com/ethereum/go-ethereum/swarm/storage"
  19. "golang.org/x/crypto/scrypt"
  20. "golang.org/x/crypto/sha3"
  21. cli "gopkg.in/urfave/cli.v1"
  22. )
  23. var (
  24. ErrDecrypt = errors.New("cant decrypt - forbidden")
  25. ErrUnknownAccessType = errors.New("unknown access type (or not implemented)")
  26. ErrDecryptDomainForbidden = errors.New("decryption request domain forbidden - can only decrypt on localhost")
  27. AllowedDecryptDomains = []string{
  28. "localhost",
  29. "127.0.0.1",
  30. }
  31. )
  32. const EmptyCredentials = ""
  33. type AccessEntry struct {
  34. Type AccessType
  35. Publisher string
  36. Salt []byte
  37. Act string
  38. KdfParams *KdfParams
  39. }
  40. type DecryptFunc func(*ManifestEntry) error
  41. func (a *AccessEntry) MarshalJSON() (out []byte, err error) {
  42. return json.Marshal(struct {
  43. Type AccessType `json:"type,omitempty"`
  44. Publisher string `json:"publisher,omitempty"`
  45. Salt string `json:"salt,omitempty"`
  46. Act string `json:"act,omitempty"`
  47. KdfParams *KdfParams `json:"kdf_params,omitempty"`
  48. }{
  49. Type: a.Type,
  50. Publisher: a.Publisher,
  51. Salt: hex.EncodeToString(a.Salt),
  52. Act: a.Act,
  53. KdfParams: a.KdfParams,
  54. })
  55. }
  56. func (a *AccessEntry) UnmarshalJSON(value []byte) error {
  57. v := struct {
  58. Type AccessType `json:"type,omitempty"`
  59. Publisher string `json:"publisher,omitempty"`
  60. Salt string `json:"salt,omitempty"`
  61. Act string `json:"act,omitempty"`
  62. KdfParams *KdfParams `json:"kdf_params,omitempty"`
  63. }{}
  64. err := json.Unmarshal(value, &v)
  65. if err != nil {
  66. return err
  67. }
  68. a.Act = v.Act
  69. a.KdfParams = v.KdfParams
  70. a.Publisher = v.Publisher
  71. a.Salt, err = hex.DecodeString(v.Salt)
  72. if err != nil {
  73. return err
  74. }
  75. if len(a.Salt) != 32 {
  76. return errors.New("salt should be 32 bytes long")
  77. }
  78. a.Type = v.Type
  79. return nil
  80. }
  81. type KdfParams struct {
  82. N int `json:"n"`
  83. P int `json:"p"`
  84. R int `json:"r"`
  85. }
  86. type AccessType string
  87. const AccessTypePass = AccessType("pass")
  88. const AccessTypePK = AccessType("pk")
  89. const AccessTypeACT = AccessType("act")
  90. // NewAccessEntryPassword creates a manifest AccessEntry in order to create an ACT protected by a password
  91. func NewAccessEntryPassword(salt []byte, kdfParams *KdfParams) (*AccessEntry, error) {
  92. if len(salt) != 32 {
  93. return nil, fmt.Errorf("salt should be 32 bytes long")
  94. }
  95. return &AccessEntry{
  96. Type: AccessTypePass,
  97. Salt: salt,
  98. KdfParams: kdfParams,
  99. }, nil
  100. }
  101. // NewAccessEntryPK creates a manifest AccessEntry in order to create an ACT protected by a pair of Elliptic Curve keys
  102. func NewAccessEntryPK(publisher string, salt []byte) (*AccessEntry, error) {
  103. if len(publisher) != 66 {
  104. return nil, fmt.Errorf("publisher should be 66 characters long, got %d", len(publisher))
  105. }
  106. if len(salt) != 32 {
  107. return nil, fmt.Errorf("salt should be 32 bytes long")
  108. }
  109. return &AccessEntry{
  110. Type: AccessTypePK,
  111. Publisher: publisher,
  112. Salt: salt,
  113. }, nil
  114. }
  115. // NewAccessEntryACT creates a manifest AccessEntry in order to create an ACT protected by a combination of EC keys and passwords
  116. func NewAccessEntryACT(publisher string, salt []byte, act string) (*AccessEntry, error) {
  117. if len(salt) != 32 {
  118. return nil, fmt.Errorf("salt should be 32 bytes long")
  119. }
  120. if len(publisher) != 66 {
  121. return nil, fmt.Errorf("publisher should be 66 characters long")
  122. }
  123. return &AccessEntry{
  124. Type: AccessTypeACT,
  125. Publisher: publisher,
  126. Salt: salt,
  127. Act: act,
  128. KdfParams: DefaultKdfParams,
  129. }, nil
  130. }
  131. // NOOPDecrypt is a generic decrypt function that is passed into the API in places where real ACT decryption capabilities are
  132. // either unwanted, or alternatively, cannot be implemented in the immediate scope
  133. func NOOPDecrypt(*ManifestEntry) error {
  134. return nil
  135. }
  136. var DefaultKdfParams = NewKdfParams(262144, 1, 8)
  137. // NewKdfParams returns a KdfParams struct with the given scrypt params
  138. func NewKdfParams(n, p, r int) *KdfParams {
  139. return &KdfParams{
  140. N: n,
  141. P: p,
  142. R: r,
  143. }
  144. }
  145. // NewSessionKeyPassword creates a session key based on a shared secret (password) and the given salt
  146. // and kdf parameters in the access entry
  147. func NewSessionKeyPassword(password string, accessEntry *AccessEntry) ([]byte, error) {
  148. if accessEntry.Type != AccessTypePass && accessEntry.Type != AccessTypeACT {
  149. return nil, errors.New("incorrect access entry type")
  150. }
  151. return sessionKeyPassword(password, accessEntry.Salt, accessEntry.KdfParams)
  152. }
  153. func sessionKeyPassword(password string, salt []byte, kdfParams *KdfParams) ([]byte, error) {
  154. return scrypt.Key(
  155. []byte(password),
  156. salt,
  157. kdfParams.N,
  158. kdfParams.R,
  159. kdfParams.P,
  160. 32,
  161. )
  162. }
  163. // NewSessionKeyPK creates a new ACT Session Key using an ECDH shared secret for the given key pair and the given salt value
  164. func NewSessionKeyPK(private *ecdsa.PrivateKey, public *ecdsa.PublicKey, salt []byte) ([]byte, error) {
  165. granteePubEcies := ecies.ImportECDSAPublic(public)
  166. privateKey := ecies.ImportECDSA(private)
  167. bytes, err := privateKey.GenerateShared(granteePubEcies, 16, 16)
  168. if err != nil {
  169. return nil, err
  170. }
  171. bytes = append(salt, bytes...)
  172. sessionKey := crypto.Keccak256(bytes)
  173. return sessionKey, nil
  174. }
  175. func (a *API) doDecrypt(ctx context.Context, credentials string, pk *ecdsa.PrivateKey) DecryptFunc {
  176. return func(m *ManifestEntry) error {
  177. if m.Access == nil {
  178. return nil
  179. }
  180. allowed := false
  181. requestDomain := sctx.GetHost(ctx)
  182. for _, v := range AllowedDecryptDomains {
  183. if strings.Contains(requestDomain, v) {
  184. allowed = true
  185. }
  186. }
  187. if !allowed {
  188. return ErrDecryptDomainForbidden
  189. }
  190. switch m.Access.Type {
  191. case "pass":
  192. if credentials != "" {
  193. key, err := NewSessionKeyPassword(credentials, m.Access)
  194. if err != nil {
  195. return err
  196. }
  197. ref, err := hex.DecodeString(m.Hash)
  198. if err != nil {
  199. return err
  200. }
  201. enc := NewRefEncryption(len(ref) - 8)
  202. decodedRef, err := enc.Decrypt(ref, key)
  203. if err != nil {
  204. return ErrDecrypt
  205. }
  206. m.Hash = hex.EncodeToString(decodedRef)
  207. m.Access = nil
  208. return nil
  209. }
  210. return ErrDecrypt
  211. case "pk":
  212. publisherBytes, err := hex.DecodeString(m.Access.Publisher)
  213. if err != nil {
  214. return ErrDecrypt
  215. }
  216. publisher, err := crypto.DecompressPubkey(publisherBytes)
  217. if err != nil {
  218. return ErrDecrypt
  219. }
  220. key, err := NewSessionKeyPK(pk, publisher, m.Access.Salt)
  221. if err != nil {
  222. return ErrDecrypt
  223. }
  224. ref, err := hex.DecodeString(m.Hash)
  225. if err != nil {
  226. return err
  227. }
  228. enc := NewRefEncryption(len(ref) - 8)
  229. decodedRef, err := enc.Decrypt(ref, key)
  230. if err != nil {
  231. return ErrDecrypt
  232. }
  233. m.Hash = hex.EncodeToString(decodedRef)
  234. m.Access = nil
  235. return nil
  236. case "act":
  237. var (
  238. sessionKey []byte
  239. err error
  240. )
  241. publisherBytes, err := hex.DecodeString(m.Access.Publisher)
  242. if err != nil {
  243. return ErrDecrypt
  244. }
  245. publisher, err := crypto.DecompressPubkey(publisherBytes)
  246. if err != nil {
  247. return ErrDecrypt
  248. }
  249. sessionKey, err = NewSessionKeyPK(pk, publisher, m.Access.Salt)
  250. if err != nil {
  251. return ErrDecrypt
  252. }
  253. found, ciphertext, decryptionKey, err := a.getACTDecryptionKey(ctx, storage.Address(common.Hex2Bytes(m.Access.Act)), sessionKey)
  254. if err != nil {
  255. return err
  256. }
  257. if !found {
  258. // try to fall back to password
  259. if credentials != "" {
  260. sessionKey, err = NewSessionKeyPassword(credentials, m.Access)
  261. if err != nil {
  262. return err
  263. }
  264. found, ciphertext, decryptionKey, err = a.getACTDecryptionKey(ctx, storage.Address(common.Hex2Bytes(m.Access.Act)), sessionKey)
  265. if err != nil {
  266. return err
  267. }
  268. if !found {
  269. return ErrDecrypt
  270. }
  271. } else {
  272. return ErrDecrypt
  273. }
  274. }
  275. enc := NewRefEncryption(len(ciphertext) - 8)
  276. decodedRef, err := enc.Decrypt(ciphertext, decryptionKey)
  277. if err != nil {
  278. return ErrDecrypt
  279. }
  280. ref, err := hex.DecodeString(m.Hash)
  281. if err != nil {
  282. return err
  283. }
  284. enc = NewRefEncryption(len(ref) - 8)
  285. decodedMainRef, err := enc.Decrypt(ref, decodedRef)
  286. if err != nil {
  287. return ErrDecrypt
  288. }
  289. m.Hash = hex.EncodeToString(decodedMainRef)
  290. m.Access = nil
  291. return nil
  292. }
  293. return ErrUnknownAccessType
  294. }
  295. }
  296. func (a *API) getACTDecryptionKey(ctx context.Context, actManifestAddress storage.Address, sessionKey []byte) (found bool, ciphertext, decryptionKey []byte, err error) {
  297. hasher := sha3.NewLegacyKeccak256()
  298. hasher.Write(append(sessionKey, 0))
  299. lookupKey := hasher.Sum(nil)
  300. hasher.Reset()
  301. hasher.Write(append(sessionKey, 1))
  302. accessKeyDecryptionKey := hasher.Sum(nil)
  303. hasher.Reset()
  304. lk := hex.EncodeToString(lookupKey)
  305. list, err := a.GetManifestList(ctx, NOOPDecrypt, actManifestAddress, lk)
  306. if err != nil {
  307. return false, nil, nil, err
  308. }
  309. for _, v := range list.Entries {
  310. if v.Path == lk {
  311. cipherTextBytes, err := hex.DecodeString(v.Hash)
  312. if err != nil {
  313. return false, nil, nil, err
  314. }
  315. return true, cipherTextBytes, accessKeyDecryptionKey, nil
  316. }
  317. }
  318. return false, nil, nil, nil
  319. }
  320. func GenerateAccessControlManifest(ctx *cli.Context, ref string, accessKey []byte, ae *AccessEntry) (*Manifest, error) {
  321. refBytes, err := hex.DecodeString(ref)
  322. if err != nil {
  323. return nil, err
  324. }
  325. // encrypt ref with accessKey
  326. enc := NewRefEncryption(len(refBytes))
  327. encrypted, err := enc.Encrypt(refBytes, accessKey)
  328. if err != nil {
  329. return nil, err
  330. }
  331. m := &Manifest{
  332. Entries: []ManifestEntry{
  333. {
  334. Hash: hex.EncodeToString(encrypted),
  335. ContentType: ManifestType,
  336. ModTime: time.Now(),
  337. Access: ae,
  338. },
  339. },
  340. }
  341. return m, nil
  342. }
  343. // DoPK is a helper function to the CLI API that handles the entire business logic for
  344. // creating a session key and access entry given the cli context, ec keys and salt
  345. func DoPK(ctx *cli.Context, privateKey *ecdsa.PrivateKey, granteePublicKey string, salt []byte) (sessionKey []byte, ae *AccessEntry, err error) {
  346. if granteePublicKey == "" {
  347. return nil, nil, errors.New("need a grantee Public Key")
  348. }
  349. b, err := hex.DecodeString(granteePublicKey)
  350. if err != nil {
  351. log.Error("error decoding grantee public key", "err", err)
  352. return nil, nil, err
  353. }
  354. granteePub, err := crypto.DecompressPubkey(b)
  355. if err != nil {
  356. log.Error("error decompressing grantee public key", "err", err)
  357. return nil, nil, err
  358. }
  359. sessionKey, err = NewSessionKeyPK(privateKey, granteePub, salt)
  360. if err != nil {
  361. log.Error("error getting session key", "err", err)
  362. return nil, nil, err
  363. }
  364. ae, err = NewAccessEntryPK(hex.EncodeToString(crypto.CompressPubkey(&privateKey.PublicKey)), salt)
  365. if err != nil {
  366. log.Error("error generating access entry", "err", err)
  367. return nil, nil, err
  368. }
  369. return sessionKey, ae, nil
  370. }
  371. // DoACT is a helper function to the CLI API that handles the entire business logic for
  372. // creating a access key, access entry and ACT manifest (including uploading it) given the cli context, ec keys, password grantees and salt
  373. func DoACT(ctx *cli.Context, privateKey *ecdsa.PrivateKey, salt []byte, grantees []string, encryptPasswords []string) (accessKey []byte, ae *AccessEntry, actManifest *Manifest, err error) {
  374. if len(grantees) == 0 && len(encryptPasswords) == 0 {
  375. return nil, nil, nil, errors.New("did not get any grantee public keys or any encryption passwords")
  376. }
  377. publisherPub := hex.EncodeToString(crypto.CompressPubkey(&privateKey.PublicKey))
  378. grantees = append(grantees, publisherPub)
  379. accessKey = make([]byte, 32)
  380. if _, err := io.ReadFull(rand.Reader, salt); err != nil {
  381. panic("reading from crypto/rand failed: " + err.Error())
  382. }
  383. if _, err := io.ReadFull(rand.Reader, accessKey); err != nil {
  384. panic("reading from crypto/rand failed: " + err.Error())
  385. }
  386. lookupPathEncryptedAccessKeyMap := make(map[string]string)
  387. i := 0
  388. for _, v := range grantees {
  389. i++
  390. if v == "" {
  391. return nil, nil, nil, errors.New("need a grantee Public Key")
  392. }
  393. b, err := hex.DecodeString(v)
  394. if err != nil {
  395. log.Error("error decoding grantee public key", "err", err)
  396. return nil, nil, nil, err
  397. }
  398. granteePub, err := crypto.DecompressPubkey(b)
  399. if err != nil {
  400. log.Error("error decompressing grantee public key", "err", err)
  401. return nil, nil, nil, err
  402. }
  403. sessionKey, err := NewSessionKeyPK(privateKey, granteePub, salt)
  404. if err != nil {
  405. return nil, nil, nil, err
  406. }
  407. hasher := sha3.NewLegacyKeccak256()
  408. hasher.Write(append(sessionKey, 0))
  409. lookupKey := hasher.Sum(nil)
  410. hasher.Reset()
  411. hasher.Write(append(sessionKey, 1))
  412. accessKeyEncryptionKey := hasher.Sum(nil)
  413. enc := NewRefEncryption(len(accessKey))
  414. encryptedAccessKey, err := enc.Encrypt(accessKey, accessKeyEncryptionKey)
  415. if err != nil {
  416. return nil, nil, nil, err
  417. }
  418. lookupPathEncryptedAccessKeyMap[hex.EncodeToString(lookupKey)] = hex.EncodeToString(encryptedAccessKey)
  419. }
  420. for _, pass := range encryptPasswords {
  421. sessionKey, err := sessionKeyPassword(pass, salt, DefaultKdfParams)
  422. if err != nil {
  423. return nil, nil, nil, err
  424. }
  425. hasher := sha3.NewLegacyKeccak256()
  426. hasher.Write(append(sessionKey, 0))
  427. lookupKey := hasher.Sum(nil)
  428. hasher.Reset()
  429. hasher.Write(append(sessionKey, 1))
  430. accessKeyEncryptionKey := hasher.Sum(nil)
  431. enc := NewRefEncryption(len(accessKey))
  432. encryptedAccessKey, err := enc.Encrypt(accessKey, accessKeyEncryptionKey)
  433. if err != nil {
  434. return nil, nil, nil, err
  435. }
  436. lookupPathEncryptedAccessKeyMap[hex.EncodeToString(lookupKey)] = hex.EncodeToString(encryptedAccessKey)
  437. }
  438. m := &Manifest{
  439. Entries: []ManifestEntry{},
  440. }
  441. for k, v := range lookupPathEncryptedAccessKeyMap {
  442. m.Entries = append(m.Entries, ManifestEntry{
  443. Path: k,
  444. Hash: v,
  445. ContentType: "text/plain",
  446. })
  447. }
  448. ae, err = NewAccessEntryACT(hex.EncodeToString(crypto.CompressPubkey(&privateKey.PublicKey)), salt, "")
  449. if err != nil {
  450. return nil, nil, nil, err
  451. }
  452. return accessKey, ae, m, nil
  453. }
  454. // DoPassword is a helper function to the CLI API that handles the entire business logic for
  455. // creating a session key and an access entry given the cli context, password and salt.
  456. // By default - DefaultKdfParams are used as the scrypt params
  457. func DoPassword(ctx *cli.Context, password string, salt []byte) (sessionKey []byte, ae *AccessEntry, err error) {
  458. ae, err = NewAccessEntryPassword(salt, DefaultKdfParams)
  459. if err != nil {
  460. return nil, nil, err
  461. }
  462. sessionKey, err = NewSessionKeyPassword(password, ae)
  463. if err != nil {
  464. return nil, nil, err
  465. }
  466. return sessionKey, ae, nil
  467. }