follower.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. package main
  2. //#cgo CFLAGS: -fopenmp -O2
  3. //#cgo LDFLAGS: -lcrypto -lm -fopenmp
  4. //#include "../c/dpf.h"
  5. //#include "../c/okv.h"
  6. //#include "../c/dpf.c"
  7. //#include "../c/okv.c"
  8. import "C"
  9. //sssssssssssssssss
  10. import (
  11. "2PPS/lib"
  12. "crypto/rand"
  13. "crypto/rsa"
  14. "crypto/sha256"
  15. "crypto/tls"
  16. "crypto/x509"
  17. "crypto/x509/pkix"
  18. "encoding/pem"
  19. "fmt"
  20. "math/big"
  21. "net"
  22. "strconv"
  23. "sync"
  24. "time"
  25. "unsafe"
  26. "golang.org/x/crypto/nacl/box"
  27. )
  28. //this stores all neccessary information for each client
  29. type clientKeys struct {
  30. SharedSecret [32]byte
  31. PirQuery [][]byte
  32. }
  33. //uses clients publicKey as key
  34. var clientData = make(map[[32]byte]clientKeys)
  35. var topicList []byte
  36. var topicAmount int
  37. var followerPrivateKey *[32]byte
  38. var followerPublicKey *[32]byte
  39. var leaderPublicKey *[32]byte
  40. //needs to be changed at leader/follower/client at the same time
  41. const neededSubscriptions = 1
  42. const dataLength = 64
  43. const numThreads = 12
  44. var dbWriteSize int = 4
  45. var maxTimePerRound time.Duration = 5 * time.Second
  46. var round int = 1
  47. var startTime time.Time
  48. func main() {
  49. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  50. if err != nil {
  51. panic(err)
  52. }
  53. followerPrivateKey = generatedPrivateKey
  54. followerPublicKey = generatedPublicKey
  55. C.initializeServer(C.int(numThreads))
  56. followerConnectionPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  57. if err != nil {
  58. panic(err)
  59. }
  60. // Generate a pem block with the private key
  61. keyPem := pem.EncodeToMemory(&pem.Block{
  62. Type: "RSA PRIVATE KEY",
  63. Bytes: x509.MarshalPKCS1PrivateKey(followerConnectionPrivateKey),
  64. })
  65. tml := x509.Certificate{
  66. // you can add any attr that you need
  67. NotBefore: time.Now(),
  68. NotAfter: time.Now().AddDate(5, 0, 0),
  69. // you have to generate a different serial number each execution
  70. SerialNumber: big.NewInt(123123),
  71. Subject: pkix.Name{
  72. CommonName: "New Name",
  73. Organization: []string{"New Org."},
  74. },
  75. BasicConstraintsValid: true,
  76. }
  77. cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &followerConnectionPrivateKey.PublicKey, followerConnectionPrivateKey)
  78. if err != nil {
  79. panic(err)
  80. }
  81. // Generate a pem block with the certificate
  82. certPem := pem.EncodeToMemory(&pem.Block{
  83. Type: "CERTIFICATE",
  84. Bytes: cert,
  85. })
  86. tlsCert, err := tls.X509KeyPair(certPem, keyPem)
  87. if err != nil {
  88. panic(err)
  89. }
  90. config := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
  91. fmt.Println("start leader")
  92. //listens for leader
  93. lnLeader, err := tls.Listen("tcp", ":4442", config)
  94. if err != nil {
  95. panic(err)
  96. }
  97. defer lnLeader.Close()
  98. leaderConnection, err := lnLeader.Accept()
  99. if err != nil {
  100. panic(err)
  101. }
  102. //send publicKey to leader
  103. writeToConn(leaderConnection, followerPublicKey[:])
  104. //receives leader PublicKey
  105. var tmpLeaderPubKey [32]byte
  106. _, err = leaderConnection.Read(tmpLeaderPubKey[:])
  107. if err != nil {
  108. panic(err)
  109. }
  110. leaderPublicKey = &tmpLeaderPubKey
  111. //setup ends here
  112. //locks access to DB
  113. m := &sync.RWMutex{}
  114. wg := &sync.WaitGroup{}
  115. for {
  116. //phase1
  117. fmt.Println("phase1")
  118. //create write db for this round
  119. for i := 0; i < dbWriteSize; i++ {
  120. C.createDb(C.int(0), C.int(dataLength))
  121. }
  122. //receives the virtualAddresses
  123. virtualAddresses := make([]int, dbWriteSize+1)
  124. for i := 0; i <= dbWriteSize; i++ {
  125. virtualAddress := readFromConn(leaderConnection, 4)
  126. virtualAddresses[i] = byteToInt(virtualAddress)
  127. }
  128. for i := 0; i < numThreads; i++ {
  129. wg.Add(1)
  130. leaderConnection, err := lnLeader.Accept()
  131. if err != nil {
  132. panic(err)
  133. }
  134. leaderConnection.SetDeadline(time.Time{})
  135. startTime = time.Now()
  136. go phase1(i, leaderConnection, m, wg, virtualAddresses)
  137. }
  138. wg.Wait()
  139. //phase2
  140. fmt.Println("phase2")
  141. leaderConnection, err := lnLeader.Accept()
  142. if err != nil {
  143. panic(err)
  144. }
  145. leaderConnection.SetDeadline(time.Time{})
  146. phase2(leaderConnection)
  147. //phase3
  148. fmt.Println("phase3")
  149. if round == 1 {
  150. //addTestTweets()
  151. }
  152. //no tweets -> continue to phase 1 and mb get tweets
  153. topicList, topicAmount = lib.GetTopicList(0)
  154. if len(topicList) == 0 {
  155. continue
  156. }
  157. for i := 0; i < numThreads; i++ {
  158. wg.Add(1)
  159. leaderConnection, err := lnLeader.Accept()
  160. if err != nil {
  161. panic(err)
  162. }
  163. leaderConnection.SetDeadline(time.Time{})
  164. startTime = time.Now()
  165. go phase3(leaderConnection, wg, m)
  166. }
  167. wg.Wait()
  168. lib.CleanUpdbR(round)
  169. round++
  170. }
  171. }
  172. func phase1(id int, leaderWorkerConnection net.Conn, m *sync.RWMutex, wg *sync.WaitGroup, virtualAddresses []int) {
  173. gotClient := make([]byte, 1)
  174. for {
  175. gotClient = readFromConn(leaderWorkerConnection, 1)
  176. //this worker is done
  177. if gotClient[0] == 0 {
  178. wg.Done()
  179. return
  180. }
  181. //setup the worker-specific db
  182. dbSize := int(C.dbSize)
  183. db := make([][]byte, dbSize)
  184. for i := 0; i < dbSize; i++ {
  185. db[i] = make([]byte, int(C.db[i].dataSize))
  186. }
  187. //gets clients publicKey
  188. var clientPublicKey *[32]byte
  189. var tmpClientPublicKey [32]byte
  190. _, err := leaderWorkerConnection.Read(tmpClientPublicKey[:])
  191. if err != nil {
  192. panic(err)
  193. }
  194. clientPublicKey = &tmpClientPublicKey
  195. m.RLock()
  196. clientKeys := clientData[tmpClientPublicKey]
  197. m.RUnlock()
  198. clientKeys, pirQuery := handlePirQuery(clientKeys, leaderWorkerConnection, 0, tmpClientPublicKey, true)
  199. getSendVirtualAddress(pirQuery[0], virtualAddresses, clientKeys.SharedSecret, leaderWorkerConnection)
  200. m.Lock()
  201. clientData[*clientPublicKey] = clientKeys
  202. m.Unlock()
  203. //gets dpfQuery from leader
  204. dpfLengthBytes := readFromConn(leaderWorkerConnection, 4)
  205. dpfLength := byteToInt(dpfLengthBytes)
  206. dpfQueryBEncrypted := make([]byte, dpfLength)
  207. dpfQueryBEncrypted = readFromConn(leaderWorkerConnection, dpfLength)
  208. //decrypt dpfQueryB for sorting into db
  209. var decryptNonce [24]byte
  210. copy(decryptNonce[:], dpfQueryBEncrypted[:24])
  211. dpfQueryB, ok := box.Open(nil, dpfQueryBEncrypted[24:], &decryptNonce, clientPublicKey, followerPrivateKey)
  212. if !ok {
  213. panic("dpfQueryB decryption not ok")
  214. }
  215. ds := int(C.db[0].dataSize)
  216. dataShareFollower := make([]byte, ds)
  217. pos := C.getUint128_t(C.int(virtualAddresses[dbWriteSize]))
  218. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryB[0]), pos, C.int(ds), (*C.uchar)(&dataShareFollower[0]))
  219. dataShareLeader := make([]byte, ds)
  220. writeToConn(leaderWorkerConnection, dataShareFollower)
  221. dataShareLeader = readFromConn(leaderWorkerConnection, ds)
  222. auditXOR := make([]byte, ds)
  223. passedAudit := true
  224. for i := 0; i < ds; i++ {
  225. auditXOR[i] = dataShareLeader[i] ^ dataShareFollower[i]
  226. //client tried to write to a position that is not a virtuallAddress
  227. if auditXOR[i] != 0 {
  228. passedAudit = false
  229. }
  230. }
  231. if passedAudit {
  232. //run dpf, xor into local db
  233. for i := 0; i < dbSize; i++ {
  234. ds := int(C.db[i].dataSize)
  235. dataShare := make([]byte, ds)
  236. pos := C.getUint128_t(C.int(virtualAddresses[i]))
  237. C.evalDPF(C.ctx[id], (*C.uchar)(&dpfQueryB[0]), pos, C.int(ds), (*C.uchar)(&dataShare[0]))
  238. for j := 0; j < ds; j++ {
  239. db[i][j] = db[i][j] ^ dataShare[j]
  240. }
  241. }
  242. //xor the worker's DB into the main DB
  243. for i := 0; i < dbSize; i++ {
  244. m.Lock()
  245. C.xorIn(C.int(i), (*C.uchar)(&db[i][0]))
  246. m.Unlock()
  247. }
  248. }
  249. }
  250. }
  251. func phase2(leaderWorkerConnection net.Conn) {
  252. //gets current seed
  253. seedFollower := make([]byte, 16)
  254. C.readSeed((*C.uchar)(&seedFollower[0]))
  255. //get data
  256. dbSize := int(C.dbSize)
  257. tmpdbFollower := make([][]byte, dbSize)
  258. for i := range tmpdbFollower {
  259. tmpdbFollower[i] = make([]byte, dataLength)
  260. }
  261. for i := 0; i < dbSize; i++ {
  262. C.readData(C.int(i), (*C.uchar)(&tmpdbFollower[i][0]))
  263. }
  264. //receive seed from leader
  265. seedLeader := readFromConn(leaderWorkerConnection, 16)
  266. //receive data from leader
  267. tmpdbLeader := make([][]byte, dbSize)
  268. for i := range tmpdbLeader {
  269. tmpdbLeader[i] = make([]byte, dataLength)
  270. }
  271. for i := 0; i < dbSize; i++ {
  272. tmpdbLeader[i] = readFromConn(leaderWorkerConnection, dataLength)
  273. }
  274. //writes seed to leader
  275. writeToConn(leaderWorkerConnection, seedFollower)
  276. //write data to leader
  277. for i := 0; i < dbSize; i++ {
  278. writeToConn(leaderWorkerConnection, tmpdbFollower[i])
  279. }
  280. //put together the db
  281. tmpdb := make([][]byte, dbSize)
  282. for i := range tmpdb {
  283. tmpdb[i] = make([]byte, dataLength)
  284. }
  285. //get own Ciphers
  286. ciphersFollowers := make([]*C.uchar, dbSize)
  287. for i := 0; i < dbSize; i++ {
  288. ciphersFollowers[i] = (*C.uchar)(C.malloc(16))
  289. }
  290. for i := 0; i < dbSize; i++ {
  291. C.getCipher(0, C.int(i), ciphersFollowers[i])
  292. }
  293. //receive ciphers from leader
  294. ciphersLeader := make([]byte, dbSize*16)
  295. for i := 0; i < dbSize; i++ {
  296. _, err := leaderWorkerConnection.Read(ciphersLeader[i*16:])
  297. if err != nil {
  298. panic(err)
  299. }
  300. }
  301. //send own Ciphers to leader
  302. for i := 0; i < dbSize; i++ {
  303. writeToConn(leaderWorkerConnection, C.GoBytes(unsafe.Pointer(ciphersFollowers[i]), 16))
  304. }
  305. //put in ciphers from leader
  306. for i := 0; i < dbSize; i++ {
  307. C.putCipher(0, C.int(i), (*C.uchar)(&ciphersLeader[i*16]))
  308. }
  309. for i := 0; i < dbSize; i++ {
  310. C.decryptRow(C.int(i), (*C.uchar)(&tmpdb[i][0]), (*C.uchar)(&tmpdbLeader[i][0]), (*C.uchar)(&tmpdbFollower[i][0]), (*C.uchar)(&seedLeader[0]), (*C.uchar)(&seedFollower[0]))
  311. }
  312. var tweets []lib.Tweet
  313. for i := 0; i < dbSize; i++ {
  314. //discard cover message
  315. if tmpdb[i][0] == 0 {
  316. continue
  317. } else {
  318. //reconstruct tweet
  319. var position int = 0
  320. var topics []string
  321. var topic string
  322. var text string
  323. for _, letter := range tmpdb[i] {
  324. if string(letter) == ";" {
  325. if topic != "" {
  326. topics = append(topics, topic)
  327. topic = ""
  328. }
  329. position++
  330. } else {
  331. if position == 0 {
  332. if string(letter) == "," {
  333. topics = append(topics, topic)
  334. topic = ""
  335. } else {
  336. topic = topic + string(letter)
  337. }
  338. } else if position == 1 {
  339. text = text + string(letter)
  340. }
  341. }
  342. }
  343. tweet := lib.Tweet{"", -1, topics, text, round}
  344. tweets = append(tweets, tweet)
  345. }
  346. }
  347. //fmt.Println("tweets recovered: ", tweets)
  348. //sort into read db
  349. lib.NewEntries(tweets, 0)
  350. //reset write db after the tweets were moved to read db
  351. C.resetDb()
  352. //gets current dbWriteSize from leader
  353. dbWriteSizeBytes := readFromConn(leaderWorkerConnection, 4)
  354. dbWriteSize = byteToInt(dbWriteSizeBytes)
  355. }
  356. func addTestTweets() {
  357. //creates test tweets
  358. tweets := make([]lib.Tweet, 5)
  359. for i := range tweets {
  360. j := i
  361. if i == 1 {
  362. j = 0
  363. }
  364. text := "Text " + strconv.Itoa(i)
  365. var topics []string
  366. topics = append(topics, "Topic "+strconv.Itoa(j))
  367. tweets[i] = lib.Tweet{"", -1, topics, text, i}
  368. }
  369. lib.NewEntries(tweets, 0)
  370. }
  371. func phase3(leaderWorkerConnection net.Conn, wg *sync.WaitGroup, m *sync.RWMutex) {
  372. gotClient := make([]byte, 1)
  373. for {
  374. gotClient = readFromConn(leaderWorkerConnection, 1)
  375. //this worker is done
  376. if gotClient[0] == 0 {
  377. wg.Done()
  378. return
  379. }
  380. subPhase := readFromConn(leaderWorkerConnection, 1)
  381. var clientPublicKey [32]byte
  382. _, err := leaderWorkerConnection.Read(clientPublicKey[:])
  383. if err != nil {
  384. panic(err)
  385. }
  386. //gets the client data
  387. m.RLock()
  388. clientKeys := clientData[clientPublicKey]
  389. m.RUnlock()
  390. if subPhase[0] == 0 || subPhase[0] == 1 {
  391. clientKeys, _ = handlePirQuery(clientKeys, leaderWorkerConnection, int(subPhase[0]), clientPublicKey, false)
  392. }
  393. getSendTweets(clientKeys, nil, leaderWorkerConnection)
  394. wantsArchive := readFromConn(leaderWorkerConnection, 1)
  395. if wantsArchive[0] == 1 {
  396. _, archiveQuerys := handlePirQuery(clientKeys, leaderWorkerConnection, -1, clientPublicKey, false)
  397. getSendTweets(clientKeys, archiveQuerys, leaderWorkerConnection)
  398. }
  399. //saves clientKeys
  400. m.Lock()
  401. clientData[clientPublicKey] = clientKeys
  402. m.Unlock()
  403. }
  404. }
  405. func getSendTweets(clientKeys clientKeys, archiveQuerys [][]byte, leaderWorkerConnection net.Conn) {
  406. tmpNeededSubscriptions := neededSubscriptions
  407. if archiveQuerys != nil {
  408. tmpNeededSubscriptions = len(archiveQuerys)
  409. }
  410. for i := 0; i < tmpNeededSubscriptions; i++ {
  411. //gets all requested tweets
  412. var tweets []byte
  413. if archiveQuerys == nil {
  414. tweets = lib.GetTweets(clientKeys.PirQuery[i], dataLength, 0)
  415. } else {
  416. tweets = lib.GetTweets(archiveQuerys[i], dataLength, 1)
  417. }
  418. //expand sharedSecret so it is of right length
  419. expandBy := len(tweets) / 32
  420. var expandedSharedSecret []byte
  421. for i := 0; i < expandBy; i++ {
  422. expandedSharedSecret = append(expandedSharedSecret, clientKeys.SharedSecret[:]...)
  423. }
  424. //Xor's sharedSecret with all tweets
  425. lib.Xor(expandedSharedSecret[:], tweets)
  426. lib.Xor(tweets, expandedSharedSecret[:])
  427. //sends tweets to leader
  428. tweetsLengthBytes := intToByte(len(tweets))
  429. writeToConn(leaderWorkerConnection, tweetsLengthBytes)
  430. writeToConn(leaderWorkerConnection, tweets)
  431. }
  432. }
  433. func handlePirQuery(clientKeys clientKeys, leaderWorkerConnection net.Conn, subPhase int, clientPublicKey [32]byte, doAuditing bool) (clientKeys, [][]byte) {
  434. archiveNeededSubscriptions := make([]byte, 4)
  435. if subPhase == -1 {
  436. archiveNeededSubscriptions = readFromConn(leaderWorkerConnection, 4)
  437. }
  438. //gets the msg length
  439. msgLengthBytes := readFromConn(leaderWorkerConnection, 4)
  440. msgLength := byteToInt(msgLengthBytes)
  441. //gets the message
  442. message := readFromConn(leaderWorkerConnection, msgLength)
  443. var decryptNonce [24]byte
  444. copy(decryptNonce[:], message[:24])
  445. decrypted, ok := box.Open(nil, message[24:], &decryptNonce, &clientPublicKey, followerPrivateKey)
  446. if !ok {
  447. panic("pirQuery decryption not ok")
  448. }
  449. //gets sharedSecret
  450. if subPhase == 0 {
  451. //bs!
  452. var newSharedSecret [32]byte
  453. for index := 0; index < 32; index++ {
  454. newSharedSecret[index] = decrypted[index]
  455. }
  456. clientKeys.SharedSecret = newSharedSecret
  457. decrypted = decrypted[32:]
  458. if doAuditing {
  459. result := make([][]byte, 1)
  460. result[0] = decrypted
  461. return clientKeys, result
  462. }
  463. //follower updates sharedSecret
  464. } else if subPhase == 1 {
  465. sharedSecret := clientKeys.SharedSecret
  466. sharedSecret = sha256.Sum256(sharedSecret[:])
  467. clientKeys.SharedSecret = sharedSecret
  468. }
  469. //follower expects pirQuery
  470. //transforms byteArray to ints of wanted topics
  471. tmpNeededSubscriptions := neededSubscriptions
  472. tmpTopicAmount := topicAmount
  473. if subPhase == -1 {
  474. tmpNeededSubscriptions = byteToInt(archiveNeededSubscriptions)
  475. _, tmpTopicAmount = lib.GetTopicList(1)
  476. }
  477. pirQueryFlattened := decrypted
  478. pirQuerys := make([][]byte, tmpNeededSubscriptions)
  479. for i := range pirQuerys {
  480. pirQuerys[i] = make([]byte, tmpTopicAmount)
  481. }
  482. for i := 0; i < tmpNeededSubscriptions; i++ {
  483. pirQuerys[i] = pirQueryFlattened[i*tmpTopicAmount : (i+1)*tmpTopicAmount]
  484. }
  485. //sets the pirQuery for the client in case whe are not archiving
  486. if subPhase != -1 {
  487. clientKeys.PirQuery = pirQuerys
  488. }
  489. return clientKeys, pirQuerys
  490. }
  491. func getSendVirtualAddress(pirQuery []byte, virtualAddresses []int, sharedSecret [32]byte, leaderWorkerConnection net.Conn) {
  492. //xores all requested addresses into virtuallAddress
  493. virtualAddress := make([]byte, 4)
  494. for index, num := range pirQuery {
  495. if num == 1 {
  496. currentAddress := intToByte(virtualAddresses[index])
  497. for i := 0; i < 4; i++ {
  498. virtualAddress[i] = virtualAddress[i] ^ currentAddress[i]
  499. }
  500. }
  501. }
  502. //xores the sharedSecret
  503. for i := 0; i < 4; i++ {
  504. virtualAddress[i] = virtualAddress[i] ^ sharedSecret[i]
  505. }
  506. writeToConn(leaderWorkerConnection, virtualAddress)
  507. }
  508. //sends the array to the connection
  509. func writeToConn(connection net.Conn, array []byte) {
  510. _, err := connection.Write(array)
  511. if err != nil {
  512. panic(err)
  513. }
  514. }
  515. //reads an array which is returned and of size "size" from the connection
  516. func readFromConn(connection net.Conn, size int) []byte {
  517. array := make([]byte, size)
  518. _, err := connection.Read(array)
  519. if err != nil {
  520. panic(err)
  521. }
  522. return array
  523. }
  524. func transformBytesToStringArray(topicsAsBytes []byte) []string {
  525. var topics []string
  526. var topic string
  527. var position int = 0
  528. for _, letter := range topicsAsBytes {
  529. if string(letter) == "," {
  530. topics[position] = topic
  531. topic = ""
  532. position++
  533. } else {
  534. topic = topic + string(letter)
  535. }
  536. }
  537. return topics
  538. }
  539. func byteToInt(myBytes []byte) (x int) {
  540. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  541. return
  542. }
  543. func intToByte(myInt int) (retBytes []byte) {
  544. retBytes = make([]byte, 4)
  545. retBytes[3] = byte((myInt >> 24) & 0xff)
  546. retBytes[2] = byte((myInt >> 16) & 0xff)
  547. retBytes[1] = byte((myInt >> 8) & 0xff)
  548. retBytes[0] = byte(myInt & 0xff)
  549. return
  550. }