client.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. package main
  2. /*
  3. #cgo CFLAGS: -O2
  4. #cgo LDFLAGS: -lcrypto -lm
  5. #include "../c/dpf.h"
  6. #include "../c/okvClient.h"
  7. #include "../c/dpf.c"
  8. #include "../c/okvClient.c"
  9. */
  10. import "C"
  11. //sssssssssss
  12. import (
  13. lib "2PPS/lib"
  14. "bytes"
  15. "crypto/rand"
  16. "crypto/sha256"
  17. "crypto/tls"
  18. "encoding/json"
  19. "fmt"
  20. "math/big"
  21. "net"
  22. "sync"
  23. "time"
  24. "unsafe"
  25. "golang.org/x/crypto/nacl/box"
  26. )
  27. type tweet struct {
  28. Topics []string
  29. Text string
  30. }
  31. const leader string = "127.0.0.1:4441"
  32. //needs to be changed at leader/follower/client at the same time
  33. const neededSubscriptions = 1
  34. const numClients = 2
  35. var topicList []string
  36. var archiveTopicList []string
  37. //todo! expand this for multiple clients
  38. var archiveInterests = make([]int, 1)
  39. var sharedSecret [numClients][2][32]byte = createSharedSecret()
  40. var wantsArchive = make([]byte, 1)
  41. var dataLen int = 32
  42. var numThreads int = 12
  43. var numRows int = 2
  44. var leaderPublicKey *[32]byte
  45. var followerPublicKey *[32]byte
  46. var clientPrivateKey *[32]byte
  47. var clientPublicKey *[32]byte
  48. func main() {
  49. //creates test tweets
  50. tweets := make([][]byte, numClients)
  51. for i := range tweets {
  52. tweets[i] = make([]byte, dataLen)
  53. }
  54. for i := 0; i < numClients; i++ {
  55. var tweet []byte
  56. if i == 0 {
  57. topics := []byte("house; mouse")
  58. text := []byte("I am a house in a mouse;")
  59. tweet = append(tweet, topics...)
  60. tweet = append(tweet, text...)
  61. }
  62. length := len(tweet)
  63. for i := length; i < dataLen; i++ {
  64. tweet = append(tweet, []byte(";")[0])
  65. }
  66. tweets[i] = tweet
  67. }
  68. wg := &sync.WaitGroup{}
  69. for i := 0; i < numClients; i++ {
  70. wg.Add(1)
  71. go client(tweets[i], i)
  72. }
  73. wg.Wait()
  74. }
  75. func client(tweet []byte, clientNumber int) {
  76. /*
  77. if len(os.Args) != 4 {
  78. fmt.Println("try again with: numThreads, dataLength, numRows")
  79. return
  80. }
  81. //input when executing is follower amount
  82. serverAmount, _ = strconv.Atoi(os.Args[1])
  83. serverAmount++
  84. dataLen, _ = strconv.Atoi(os.Args[2])
  85. numThreads, _ = strconv.Atoi(os.Args[3])
  86. dbSize, _ = strconv.Atoi(os.Args[4])
  87. */
  88. generatedPublicKey, generatedPrivateKey, err := box.GenerateKey(rand.Reader)
  89. if err != nil {
  90. panic(err)
  91. }
  92. clientPrivateKey = generatedPrivateKey
  93. clientPublicKey = generatedPublicKey
  94. C.initializeCipher()
  95. //initializes the connection to the leader
  96. conf := &tls.Config{
  97. InsecureSkipVerify: true,
  98. }
  99. leaderConn, err := tls.Dial("tcp", leader, conf)
  100. if err != nil {
  101. panic(err)
  102. }
  103. leaderConn.SetDeadline(time.Time{})
  104. //receives topics first so client can participate asap
  105. receiveTopicLists(leaderConn)
  106. //gets the public keys of both servers
  107. var tmpLeaderPubKey [32]byte
  108. _, err = leaderConn.Read(tmpLeaderPubKey[:])
  109. if err != nil {
  110. panic(err)
  111. }
  112. leaderPublicKey = &tmpLeaderPubKey
  113. var tmpFollowerPubKey [32]byte
  114. _, err = leaderConn.Read(tmpFollowerPubKey[:])
  115. if err != nil {
  116. panic(err)
  117. }
  118. followerPublicKey = &tmpFollowerPubKey
  119. //sends own public key
  120. _, err = leaderConn.Write(clientPublicKey[:])
  121. if err != nil {
  122. panic(err)
  123. }
  124. //setup ends above
  125. //while client is active he is always connected and has to participate
  126. for {
  127. //gets current phase
  128. phase := make([]byte, 1)
  129. _, err = leaderConn.Read(phase)
  130. if err != nil {
  131. panic(err)
  132. }
  133. fmt.Println("Phase: ", phase[0])
  134. if phase[0] == 1 {
  135. //todo! put into tweet creation
  136. roundAsBytes := make([]byte, 4)
  137. _, err = leaderConn.Read(roundAsBytes)
  138. if err != nil {
  139. panic(err)
  140. }
  141. //prep the query
  142. dataSize := len(tweet)
  143. querySize := make([]byte, 4)
  144. cQuerySize := C.int(byteToInt(querySize))
  145. var dpfQueryA *C.uchar
  146. var dpfQueryB *C.uchar
  147. //change to clientNumber
  148. C.prepQuery(C.int(0), C.int(numRows), (*C.uchar)(&tweet[0]), C.int(dataSize), &cQuerySize, &dpfQueryA, &dpfQueryB)
  149. intQuerySize := int(cQuerySize) //byteToInt(querySize)
  150. //write the query
  151. queryAPlaintext := C.GoBytes(unsafe.Pointer(dpfQueryA), C.int(intQuerySize))
  152. //encrypts queryA and appends it to message
  153. var nonce [24]byte
  154. //fill nonce with randomness
  155. _, err = rand.Read(nonce[:])
  156. if err != nil {
  157. panic("couldn't get randomness for nonce!")
  158. }
  159. dpfQueryAEncrypted := box.Seal(nonce[:], queryAPlaintext, &nonce, leaderPublicKey, clientPrivateKey)
  160. //encrypts queryB and appends it to message
  161. queryBPlaintext := C.GoBytes(unsafe.Pointer(dpfQueryB), C.int(intQuerySize))
  162. //fill nonce with randomness
  163. _, err = rand.Read(nonce[:])
  164. if err != nil {
  165. panic("couldn't get randomness for nonce!")
  166. }
  167. dpfQueryBEncrypted := box.Seal(nonce[:], queryBPlaintext, &nonce, followerPublicKey, clientPrivateKey)
  168. //writes the dpfQuery to the leader
  169. dpfLengthBytes := intToByte(len(dpfQueryAEncrypted))
  170. _, err = leaderConn.Write(dpfLengthBytes)
  171. if err != nil {
  172. panic(err)
  173. }
  174. _, err = leaderConn.Write(dpfQueryAEncrypted)
  175. if err != nil {
  176. panic(err)
  177. }
  178. _, err = leaderConn.Write(dpfQueryBEncrypted)
  179. if err != nil {
  180. panic(err)
  181. }
  182. //auditing starts here
  183. //read seed from leader(in preparation for auditing)
  184. seed := make([]byte, 16)
  185. _, err = leaderConn.Read(seed)
  186. if err != nil {
  187. panic(err)
  188. }
  189. //prepare message for auditor, box it, and send to server A
  190. //prepare the auditor message
  191. outputsA := (*C.uchar)(C.malloc(C.ulong(160)))
  192. outputsB := (*C.uchar)(C.malloc(C.ulong(160)))
  193. C.prepAudit((*C.uchar)(&seed[0]), outputsA, outputsB, dpfQueryA, dpfQueryB)
  194. auditPlaintextLeader := C.GoBytes(unsafe.Pointer(outputsA), C.int(160))
  195. auditPlaintextFollower := C.GoBytes(unsafe.Pointer(outputsB), C.int(160))
  196. //encrypt messages for auditing
  197. //fill nonce with randomness
  198. _, err = rand.Read(nonce[:])
  199. if err != nil {
  200. panic("couldn't get randomness for nonce!")
  201. }
  202. auditCiphertextLeader := box.Seal(nonce[:], auditPlaintextLeader, &nonce, leaderPublicKey, clientPrivateKey)
  203. //fill nonce with randomness
  204. _, err = rand.Read(nonce[:])
  205. if err != nil {
  206. panic("couldn't get randomness for nonce!")
  207. }
  208. auditCiphertextFollower := box.Seal(nonce[:], auditPlaintextFollower, &nonce, followerPublicKey, clientPrivateKey)
  209. //send boxed audits to leader
  210. auditLengthBytes := intToByte(len(auditCiphertextLeader))
  211. _, err = leaderConn.Write(auditLengthBytes)
  212. if err != nil {
  213. panic(err)
  214. }
  215. _, err = leaderConn.Write(auditCiphertextLeader)
  216. if err != nil {
  217. panic(err)
  218. }
  219. _, err = leaderConn.Write(auditCiphertextFollower)
  220. if err != nil {
  221. panic(err)
  222. }
  223. C.free(unsafe.Pointer(outputsA))
  224. C.free(unsafe.Pointer(outputsB))
  225. C.free(unsafe.Pointer(dpfQueryA))
  226. C.free(unsafe.Pointer(dpfQueryB))
  227. } else if phase[0] == 3 {
  228. /*
  229. possible Values
  230. 0 : new client
  231. leader expects sharedSecrets, expects pirQuery
  232. 1 : update needed
  233. leader sends topicList, performs local update of sharedSecret, expects pirQuery
  234. 2 : no update needed
  235. nothing
  236. */
  237. subPhase := make([]byte, 1)
  238. _, err := leaderConn.Read(subPhase)
  239. if err != nil {
  240. panic(err)
  241. }
  242. var encryptedQueryLeader, encryptedQueryFollower []byte
  243. //first time participating
  244. if subPhase[0] == 0 {
  245. receiveTopicLists(leaderConn)
  246. encryptedQueryLeader, encryptedQueryFollower = createPIRQuery(int(subPhase[0]), clientNumber)
  247. sendQuerys(encryptedQueryLeader, encryptedQueryFollower, leaderConn, false)
  248. }
  249. //updates the topic list and what client is interested in
  250. if subPhase[0] == 1 {
  251. receiveTopicLists(leaderConn)
  252. //updates local secret
  253. for index := 0; index < 2; index++ {
  254. sharedSecret[clientNumber][index] = sha256.Sum256(sharedSecret[clientNumber][index][:])
  255. }
  256. encryptedQueryLeader, encryptedQueryFollower = createPIRQuery(int(subPhase[0]), clientNumber)
  257. sendQuerys(encryptedQueryLeader, encryptedQueryFollower, leaderConn, false)
  258. }
  259. receiveTweets(sharedSecret[clientNumber], leaderConn, clientNumber, false)
  260. if len(archiveTopicList) > 0 {
  261. wantsArchive[0] = 0 //archive test
  262. } else {
  263. wantsArchive[0] = 0
  264. }
  265. _, err = leaderConn.Write(wantsArchive)
  266. if err != nil {
  267. panic(err)
  268. }
  269. if wantsArchive[0] == 1 && len(archiveTopicList) > 0 {
  270. encryptedQueryLeader, encryptedQueryFollower = createPIRQuery(-1, clientNumber)
  271. sendQuerys(encryptedQueryLeader, encryptedQueryFollower, leaderConn, true)
  272. receiveTweets(sharedSecret[clientNumber], leaderConn, clientNumber, true)
  273. }
  274. } else {
  275. panic("somethin went wrong")
  276. }
  277. }
  278. }
  279. //creates and sends the pirQuerys for each server
  280. func createPIRQuery(subPhase int, clientNumber int) ([]byte, []byte) {
  281. //later this will be taken from gui, this is only for testing
  282. topicsOfInterest := make([]int, 1)
  283. topicsOfInterest[0] = 1
  284. archiveInterests[0] = 1
  285. tmptopicsOfInterest := make([]int, len(topicsOfInterest))
  286. copy(tmptopicsOfInterest, topicsOfInterest)
  287. tmpNeededSubscriptions := neededSubscriptions
  288. tmpTopicList := make([]string, len(topicList))
  289. copy(tmpTopicList, topicList)
  290. if wantsArchive[0] == 1 && subPhase == -1 {
  291. tmpNeededSubscriptions = len(archiveInterests)
  292. copy(tmptopicsOfInterest, archiveInterests) //archiveInterests from gui
  293. copy(tmpTopicList, archiveTopicList)
  294. }
  295. topicsOfInterestAsBytes := make([][]byte, tmpNeededSubscriptions)
  296. for i := range topicsOfInterestAsBytes {
  297. topicsOfInterestAsBytes[i] = make([]byte, len(tmpTopicList))
  298. }
  299. //creates fake topicsOfInterest if client is boooring
  300. if len(tmptopicsOfInterest) < tmpNeededSubscriptions && subPhase != -1 {
  301. //this should be done when client is idling
  302. tmptopicsOfInterest = addFakeInterests(tmptopicsOfInterest)
  303. }
  304. for topic, position := range tmptopicsOfInterest {
  305. topicsOfInterestAsBytes[topic][position-1] = 1
  306. }
  307. //this for N servers for one topic
  308. /* interested in topic 3, 6 servers
  309. this needs to be repeated for every topic client is interested in
  310. wanted
  311. [0, 0, 1]
  312. random creation of 1 pirQuery
  313. [0, 1, 0]
  314. manual creation of 1 pirQuery
  315. [0, 1, 1]
  316. xor result
  317. [0, 0, 1]
  318. */
  319. //pirQuery [serverAmount][topicsofinterest][topicAmount]byte
  320. pirQuerys := make([][][]byte, 2)
  321. for i := range pirQuerys {
  322. pirQuerys[i] = make([][]byte, len(tmptopicsOfInterest))
  323. for j := range pirQuerys[i] {
  324. pirQuerys[i][j] = make([]byte, len(tmpTopicList))
  325. }
  326. }
  327. //for leader
  328. //pirQuery will be filled with random bits
  329. for topic := range tmptopicsOfInterest {
  330. for index := range tmpTopicList {
  331. bit, err := rand.Int(rand.Reader, big.NewInt(2))
  332. if err != nil {
  333. panic(err)
  334. }
  335. pirQuerys[0][topic][index] = byte(bit.Int64())
  336. }
  337. }
  338. //creating last manually with result and wanted
  339. //if position random result correct -> 0, not correct -> 1
  340. for topic := range tmptopicsOfInterest {
  341. for index := range tmpTopicList {
  342. if pirQuerys[0][topic][index] == topicsOfInterestAsBytes[topic][index] {
  343. pirQuerys[1][topic][index] = 0
  344. } else {
  345. pirQuerys[1][topic][index] = 1
  346. }
  347. }
  348. }
  349. //flattens the querys to be able to send them more efficently
  350. messagesFlattened := make([][]byte, 2)
  351. //adds the sharedSecret to the first pirQuery when first time participating
  352. if subPhase == 0 {
  353. for server := 0; server < 2; server++ {
  354. messagesFlattened[server] = append(messagesFlattened[server], sharedSecret[clientNumber][server][:]...)
  355. }
  356. }
  357. for server := 0; server < 2; server++ {
  358. for topic := range pirQuerys[server] {
  359. messagesFlattened[server] = append(messagesFlattened[server], pirQuerys[server][topic][:]...)
  360. }
  361. }
  362. var nonce [24]byte
  363. _, err := rand.Read(nonce[:])
  364. if err != nil {
  365. panic("couldn't get randomness for nonce!")
  366. }
  367. encryptedQueryLeader := box.Seal(nonce[:], messagesFlattened[0], &nonce, leaderPublicKey, clientPrivateKey)
  368. _, err = rand.Read(nonce[:])
  369. if err != nil {
  370. panic("couldn't get randomness for nonce!")
  371. }
  372. encryptedQueryFollower := box.Seal(nonce[:], messagesFlattened[1], &nonce, followerPublicKey, clientPrivateKey)
  373. return encryptedQueryLeader, encryptedQueryFollower
  374. }
  375. func sendQuerys(encryptedQueryLeader, encryptedQueryFollower []byte, leaderConn net.Conn, getArchive bool) {
  376. encryptedLength := len(encryptedQueryLeader)
  377. //sends the pirQuerysLength to the leader
  378. _, err := leaderConn.Write(intToByte(encryptedLength))
  379. if err != nil {
  380. panic(err)
  381. }
  382. //sends the pirQuerys to the leader
  383. _, err = leaderConn.Write(encryptedQueryLeader)
  384. if err != nil {
  385. panic(err)
  386. }
  387. _, err = leaderConn.Write(encryptedQueryFollower)
  388. if err != nil {
  389. panic(err)
  390. }
  391. if getArchive {
  392. leaderConn.Write(intToByte(len(archiveInterests)))
  393. if err != nil {
  394. panic(err)
  395. }
  396. }
  397. }
  398. func receiveTweets(sharedSecret [2][32]byte, leaderConn net.Conn, clientNumber int, getArchive bool) {
  399. tmpNeededSubscriptions := neededSubscriptions
  400. if getArchive {
  401. tmpNeededSubscriptions = len(archiveInterests)
  402. }
  403. for i := 0; i < tmpNeededSubscriptions; i++ {
  404. //client receives tweets
  405. tweetsLengthBytes := make([]byte, 4)
  406. _, err := leaderConn.Read(tweetsLengthBytes)
  407. if err != nil {
  408. panic(err)
  409. }
  410. tweetsLength := byteToInt(tweetsLengthBytes)
  411. tweets := make([]byte, tweetsLength)
  412. _, err = leaderConn.Read(tweets)
  413. if err != nil {
  414. panic(err)
  415. }
  416. //expand sharedSecret so it is of right length
  417. expandBy := len(tweets) / 32
  418. expandedSharedSecrets := make([][]byte, 2)
  419. for i := 0; i < 2; i++ {
  420. for j := 0; j < expandBy; j++ {
  421. expandedSharedSecrets[i] = append(expandedSharedSecrets[i], sharedSecret[i][:]...)
  422. }
  423. //fmt.Println(expandedSharedSecrets[i])
  424. }
  425. //xors the received messge into the message to display
  426. for i := 0; i < 2; i++ {
  427. lib.Xor(expandedSharedSecrets[i][:], tweets)
  428. }
  429. //tweets can be displayed
  430. fmt.Println("final result: ", string(tweets))
  431. }
  432. }
  433. //creates a shared secret for each server
  434. func createSharedSecret() [numClients][2][32]byte {
  435. var tmpSharedSecret [numClients][2][32]byte
  436. for i := 0; i < numClients; i++ {
  437. for j := 0; j < 2; j++ {
  438. _, err := rand.Read(tmpSharedSecret[i][j][:])
  439. if err != nil {
  440. panic("couldn't get randomness for sharedSecret!")
  441. }
  442. }
  443. }
  444. return tmpSharedSecret
  445. }
  446. //generates a topicOfInterest Array with random values
  447. //todo! fix
  448. func addFakeInterests(topicsOfInterest []int) []int {
  449. length := neededSubscriptions
  450. fakeTopicsOfInterest := make([]int, length)
  451. //fills the array with unique random ascending values in range with len(topicList)
  452. for index := 0; index < length; index++ {
  453. min := (index * (len(topicList) / length)) + 1
  454. max := ((index + 1) * (len(topicList) / length))
  455. //fmt.Println("max", max, "list", len(topicList))
  456. if max == len(topicList)-1 {
  457. max++
  458. }
  459. //fmt.Println("i", index, min, max, len(topicList))
  460. bigNumber, err := rand.Int(rand.Reader, big.NewInt(int64(max-min+1)))
  461. if err != nil {
  462. panic(err)
  463. }
  464. var number int = int(bigNumber.Int64()) + min
  465. fakeTopicsOfInterest[index] = number
  466. }
  467. //adds unique and new random numbers to topicOfInterests until length is satisfied
  468. for _, number := range fakeTopicsOfInterest {
  469. if !inList(number, topicsOfInterest) {
  470. topicsOfInterest = append(topicsOfInterest, number)
  471. }
  472. if len(topicsOfInterest) == length {
  473. break
  474. }
  475. }
  476. return topicsOfInterest
  477. }
  478. func inList(number int, list []int) bool {
  479. for _, element := range list {
  480. if element == number {
  481. return true
  482. }
  483. }
  484. return false
  485. }
  486. func receiveTopicLists(leaderConn net.Conn) {
  487. for i := 0; i < 2; i++ {
  488. topicListLength := make([]byte, 4)
  489. _, err := leaderConn.Read(topicListLength)
  490. if err != nil {
  491. panic(err)
  492. }
  493. recTopicList := make([]byte, byteToInt(topicListLength))
  494. _, err = leaderConn.Read(recTopicList[:])
  495. if err != nil {
  496. panic(err)
  497. }
  498. var tmpTopicList []string
  499. arrayReader := bytes.NewReader(recTopicList[:])
  500. json.NewDecoder(arrayReader).Decode(&tmpTopicList)
  501. if i == 0 {
  502. topicList = tmpTopicList
  503. } else {
  504. archiveTopicList = tmpTopicList
  505. }
  506. }
  507. }
  508. func intToByte(myInt int) (retBytes []byte) {
  509. retBytes = make([]byte, 4)
  510. retBytes[3] = byte((myInt >> 24) & 0xff)
  511. retBytes[2] = byte((myInt >> 16) & 0xff)
  512. retBytes[1] = byte((myInt >> 8) & 0xff)
  513. retBytes[0] = byte(myInt & 0xff)
  514. return
  515. }
  516. func byteToInt(myBytes []byte) (x int) {
  517. x = int(myBytes[3])<<24 + int(myBytes[2])<<16 + int(myBytes[1])<<8 + int(myBytes[0])
  518. return
  519. }