NCEndToEndEncryption.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. //
  2. // NCEndToEndEncryption.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 19/09/17.
  6. // Copyright © 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "NCEndToEndEncryption.h"
  24. #import "NCBridgeSwift.h"
  25. #import "CCUtility.h"
  26. #import <CommonCrypto/CommonDigest.h>
  27. #import <CommonCrypto/CommonKeyDerivation.h>
  28. #import <openssl/x509.h>
  29. #import <openssl/bio.h>
  30. #import <openssl/err.h>
  31. #import <openssl/pem.h>
  32. #import <openssl/rsa.h>
  33. #import <openssl/pkcs12.h>
  34. #import <openssl/ssl.h>
  35. #import <openssl/err.h>
  36. #import <openssl/bn.h>
  37. #define addName(field, value) X509_NAME_add_entry_by_txt(name, field, MBSTRING_ASC, (unsigned char *)value, -1, -1, 0); NSLog(@"%s: %s", field, value);
  38. #define AES_KEY_LENGTH 16
  39. #define AES_IVEC_LENGTH 16
  40. #define AES_GCM_TAG_LENGTH 16
  41. #define IV_DELIMITER_ENCODED @"fA==" // "|" base64 encoded
  42. #define PBKDF2_INTERACTION_COUNT 1024
  43. #define PBKDF2_KEY_LENGTH 256
  44. #define PBKDF2_SALT @"$4$YmBjm3hk$Qb74D5IUYwghUmzsMqeNFx5z0/8$"
  45. #define fileNameCertificate @"e2e_cert.pem"
  46. #define fileNameCSR @"e2e_csr.pem"
  47. #define fileNamePrivateKey @"e2e_privateKey.pem"
  48. @implementation NCEndToEndEncryption
  49. //Singleton
  50. + (id)sharedManager {
  51. static NCEndToEndEncryption *NCEndToEndEncryption = nil;
  52. static dispatch_once_t onceToken;
  53. dispatch_once(&onceToken, ^{
  54. NCEndToEndEncryption = [self new];
  55. });
  56. return NCEndToEndEncryption;
  57. }
  58. #
  59. #pragma mark - Generate Certificate X509 - CSR - Private Key
  60. #
  61. - (BOOL)generateCertificateX509WithUserID:(NSString *)userID directoryUser:(NSString *)directoryUser
  62. {
  63. OPENSSL_init_ssl(0, NULL);
  64. OPENSSL_init_crypto(0, NULL);
  65. X509 *x509;
  66. x509 = X509_new();
  67. EVP_PKEY *pkey;
  68. NSError *keyError;
  69. pkey = [self generateRSAKey:&keyError];
  70. if (keyError) {
  71. return NO;
  72. }
  73. X509_set_pubkey(x509, pkey);
  74. EVP_PKEY_free(pkey);
  75. // Set Serial Number
  76. ASN1_INTEGER_set(X509_get_serialNumber(x509), 123);
  77. // Set Valididity Date Range
  78. long notBefore = [[NSDate date] timeIntervalSinceDate:[NSDate date]];
  79. long notAfter = [[[NSDate date] dateByAddingTimeInterval:60*60*24*365*10] timeIntervalSinceDate:[NSDate date]]; // 10 year
  80. X509_gmtime_adj((ASN1_TIME *)X509_get0_notBefore(x509), notBefore);
  81. X509_gmtime_adj((ASN1_TIME *)X509_get0_notAfter(x509), notAfter);
  82. X509_NAME *name = X509_get_subject_name(x509);
  83. // Now to add the subject name fields to the certificate
  84. // I use a macro here to make it cleaner.
  85. const unsigned char *cUserID = (const unsigned char *) [userID cStringUsingEncoding:NSUTF8StringEncoding];
  86. // Common Name = UserID.
  87. addName("CN", cUserID);
  88. // The organizational unit for the cert. Usually this is a department.
  89. addName("OU", "Certificate Authority");
  90. // The organization of the cert.
  91. addName("O", "Nextcloud");
  92. // The city of the organization.
  93. addName("L", "Vicenza");
  94. // The state/province of the organization.
  95. addName("S", "Italy");
  96. // The country (ISO 3166) of the organization
  97. addName("C", "IT");
  98. X509_set_issuer_name(x509, name);
  99. /*
  100. for (SANObject * san in self.options.sans) {
  101. if (!san.value || san.value.length <= 0) {
  102. continue;
  103. }
  104. NSString * prefix = san.type == SANObjectTypeIP ? @"IP:" : @"DNS:";
  105. NSString * value = [NSString stringWithFormat:@"%@%@", prefix, san.value];
  106. NSLog(@"Add subjectAltName %@", value);
  107. X509_EXTENSION * extension = NULL;
  108. ASN1_STRING * asnValue = ASN1_STRING_new();
  109. ASN1_STRING_set(asnValue, (const unsigned char *)[value UTF8String], (int)value.length);
  110. X509_EXTENSION_create_by_NID(&extension, NID_subject_alt_name, 0, asnValue);
  111. X509_add_ext(x509, extension, -1);
  112. }
  113. */
  114. // Specify the encryption algorithm of the signature.
  115. // SHA256 should suit your needs.
  116. if (X509_sign(x509, pkey, EVP_sha256()) < 0) {
  117. return NO;
  118. }
  119. X509_print_fp(stdout, x509);
  120. [self savePEMWithCert:x509 key:pkey directoryUser:directoryUser];
  121. return YES;
  122. }
  123. - (EVP_PKEY *)generateRSAKey:(NSError **)error
  124. {
  125. EVP_PKEY *pkey = EVP_PKEY_new();
  126. if (!pkey) {
  127. return NULL;
  128. }
  129. BIGNUM *bigNumber = BN_new();
  130. int exponent = RSA_F4;
  131. RSA *rsa = RSA_new();
  132. if (BN_set_word(bigNumber, exponent) < 0) {
  133. goto cleanup;
  134. }
  135. if (RSA_generate_key_ex(rsa, 2048, bigNumber, NULL) < 0) {
  136. goto cleanup;
  137. }
  138. if (!EVP_PKEY_set1_RSA(pkey, rsa)) {
  139. goto cleanup;
  140. }
  141. cleanup:
  142. RSA_free(rsa);
  143. BN_free(bigNumber);
  144. return pkey;
  145. }
  146. - (BOOL)savePEMWithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser
  147. {
  148. NSString *certificatePath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCertificate];
  149. NSString *privatekeyPath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePrivateKey];
  150. NSString *csrPath = [NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCSR];
  151. // Here you write the private key (pkey) to disk. OpenSSL will encrypt the
  152. // file using the password and cipher you provide.
  153. //if (PEM_write_PrivateKey(f, pkey, EVP_des_ede3_cbc(), (unsigned char *)[password UTF8String], (int)password.length, NULL, NULL) < 0) {
  154. FILE *f = fopen([privatekeyPath fileSystemRepresentation], "wb");
  155. if (PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL) < 0) {
  156. // Error encrypting or writing to disk.
  157. fclose(f);
  158. return NO;
  159. }
  160. NSLog(@"Saved key to %@", privatekeyPath);
  161. fclose(f);
  162. // Here you write the certificate to the disk. No encryption is needed here since this is public facing information
  163. f = fopen([certificatePath fileSystemRepresentation], "wb");
  164. if (PEM_write_X509(f, x509) < 0) {
  165. // Error writing to disk.
  166. fclose(f);
  167. return NO;
  168. }
  169. NSLog(@"Saved cert to %@", certificatePath);
  170. fclose(f);
  171. // CSR Request sha256
  172. f = fopen([csrPath fileSystemRepresentation], "wb");
  173. X509_REQ *certreq = X509_to_X509_REQ(x509, pkey, EVP_sha256());
  174. if (PEM_write_X509_REQ(f, certreq) < 0) {
  175. // Error writing to disk.
  176. fclose(f);
  177. return NO;
  178. }
  179. NSLog(@"Saved csr to %@", csrPath);
  180. fclose(f);
  181. return YES;
  182. }
  183. /*
  184. - (BOOL)saveP12WithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser finished:(void (^)(NSError *))finished
  185. {
  186. //PKCS12 * p12 = PKCS12_create([password UTF8String], NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  187. PKCS12 *p12 = PKCS12_create(NULL, NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  188. NSString *path = [NSString stringWithFormat:@"%@/certificate.p12", directoryUser];
  189. FILE *f = fopen([path fileSystemRepresentation], "wb");
  190. if (i2d_PKCS12_fp(f, p12) != 1) {
  191. fclose(f);
  192. return NO;
  193. }
  194. NSLog(@"Saved p12 to %@", path);
  195. fclose(f);
  196. return YES;
  197. }
  198. */
  199. - (NSString *)createEndToEndPublicKey:(NSString *)userID directoryUser:(NSString *)directoryUser
  200. {
  201. NSString *csr;
  202. NSError *error;
  203. BOOL result = [self generateCertificateX509WithUserID:userID directoryUser:directoryUser];
  204. if (result) {
  205. csr = [NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", directoryUser, fileNameCSR] encoding:NSUTF8StringEncoding error:&error];
  206. if (error)
  207. return nil;
  208. } else {
  209. return nil;
  210. }
  211. // return URLEncode
  212. return [CCUtility URLEncodeStringFromString:csr];
  213. }
  214. - (NSString *)createEndToEndPrivateKey:(NSString *)directoryUser mnemonic:(NSString *)mnemonic
  215. {
  216. NSMutableData *privateKeyCipherData;
  217. NSString *privateKeyCipher;
  218. NSMutableData *keyData = [NSMutableData dataWithLength:PBKDF2_KEY_LENGTH];
  219. NSData *saltData = [PBKDF2_SALT dataUsingEncoding:NSUTF8StringEncoding];
  220. CCKeyDerivationPBKDF(kCCPBKDF2, mnemonic.UTF8String, mnemonic.length, saltData.bytes, saltData.length, kCCPRFHmacAlgSHA1, PBKDF2_INTERACTION_COUNT, keyData.mutableBytes, keyData.length);
  221. NSData *initVectorData = [self generateIV:AES_IVEC_LENGTH];
  222. NSData *privateKeyData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileNamePrivateKey]];
  223. BOOL result = [self aes256gcmEncrypt:privateKeyData cipherData:&privateKeyCipherData keyData:keyData initVectorData:initVectorData tagData:nil];
  224. if (result && privateKeyCipherData) {
  225. privateKeyCipher = [privateKeyCipherData base64EncodedStringWithOptions:0];
  226. NSString *initVector= [initVectorData base64EncodedStringWithOptions:0];
  227. privateKeyCipher = [NSString stringWithFormat:@"%@%@%@", privateKeyCipher, IV_DELIMITER_ENCODED, initVector];
  228. } else {
  229. return nil;
  230. }
  231. // return URLEncode
  232. return [CCUtility URLEncodeStringFromString:privateKeyCipher];
  233. }
  234. #
  235. #pragma mark - Encrypt/Decrypt AES/GCM/NoPadding as cipher (128 bit key size)
  236. #
  237. - (void)encryptMetadata:(tableMetadata *)metadata activeUrl:(NSString *)activeUrl
  238. {
  239. NSMutableData *cipherData;
  240. NSData *tagData;
  241. NSString* authenticationTag;
  242. NSData *plainData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", activeUrl, metadata.fileID]];
  243. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"WANM0gRv+DhaexIsI0T3Lg==" options:0];
  244. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:@"gKm3n+mJzeY26q4OfuZEqg==" options:0];
  245. BOOL result = [self aes256gcmEncrypt:plainData cipherData:&cipherData keyData:keyData initVectorData:initVectorData tagData:&tagData];
  246. if (cipherData != nil && result) {
  247. [cipherData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"encrypted.dms"] atomically:YES];
  248. authenticationTag = [tagData base64EncodedStringWithOptions:0];
  249. }
  250. }
  251. - (void)decryptMetadata:(tableMetadata *)metadata activeUrl:(NSString *)activeUrl
  252. {
  253. NSMutableData *plainData;
  254. NSData *cipherData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", activeUrl, metadata.fileID]];
  255. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"WANM0gRv+DhaexIsI0T3Lg==" options:0];
  256. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:@"gKm3n+mJzeY26q4OfuZEqg==" options:0];
  257. NSString *tag = @"PboI9tqHHX3QeAA22PIu4w==";
  258. BOOL result = [self aes256gcmDecrypt:cipherData plainData:&plainData keyData:keyData initVectorData:initVectorData tag:tag];
  259. if (plainData != nil && result) {
  260. [plainData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"decrypted"] atomically:YES];
  261. }
  262. }
  263. // encrypt plain data
  264. - (BOOL)aes256gcmEncrypt:(NSData*)plainData cipherData:(NSMutableData **)cipherData keyData:(NSData *)keyData initVectorData:(NSData *)initVectorData tagData:(NSData **)tagData
  265. {
  266. int status = 0;
  267. *cipherData = [NSMutableData dataWithLength:[plainData length]];
  268. // set up key
  269. unsigned char cKey[AES_KEY_LENGTH];
  270. bzero(cKey, sizeof(cKey));
  271. [keyData getBytes:cKey length:AES_KEY_LENGTH];
  272. // set up ivec
  273. unsigned char cIv[AES_IVEC_LENGTH];
  274. bzero(cIv, AES_IVEC_LENGTH);
  275. [initVectorData getBytes:cIv length:AES_IVEC_LENGTH];
  276. // set up to Encrypt AES 128 GCM
  277. int numberOfBytes = 0;
  278. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  279. EVP_EncryptInit_ex (ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  280. // set the key and ivec
  281. EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, AES_IVEC_LENGTH, NULL);
  282. EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIv);
  283. unsigned char * ctBytes = [*cipherData mutableBytes];
  284. EVP_EncryptUpdate (ctx, ctBytes, &numberOfBytes, [plainData bytes], (int)[plainData length]);
  285. status = EVP_EncryptFinal_ex (ctx, ctBytes+numberOfBytes, &numberOfBytes);
  286. if (status && tagData) {
  287. unsigned char cTag[AES_GCM_TAG_LENGTH];
  288. bzero(cTag, AES_GCM_TAG_LENGTH);
  289. status = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_GET_TAG, AES_GCM_TAG_LENGTH, cTag);
  290. *tagData = [NSData dataWithBytes:cTag length:AES_GCM_TAG_LENGTH];
  291. }
  292. EVP_CIPHER_CTX_free(ctx);
  293. return (status != 0); // OpenSSL uses 1 for success
  294. }
  295. // decrypt cipher data
  296. - (BOOL)aes256gcmDecrypt:(NSData *)cipherData plainData:(NSMutableData **)plainData keyData:(NSData *)keyData initVectorData:(NSData *)initVectorData tag:(NSString *)tag
  297. {
  298. int status = 0;
  299. int numberOfBytes = 0;
  300. *plainData = [NSMutableData dataWithLength:[cipherData length]];
  301. // set up key
  302. unsigned char cKey[AES_KEY_LENGTH];
  303. bzero(cKey, sizeof(cKey));
  304. [keyData getBytes:cKey length:AES_KEY_LENGTH];
  305. // set up ivec
  306. unsigned char cIv[AES_IVEC_LENGTH];
  307. bzero(cIv, AES_IVEC_LENGTH);
  308. [initVectorData getBytes:cIv length:AES_IVEC_LENGTH];
  309. // set up tag
  310. //unsigned char cTag[AES_GCM_TAG_LENGTH];
  311. //bzero(cTag, AES_GCM_TAG_LENGTH);
  312. //[tagData getBytes:cTag length:AES_GCM_TAG_LENGTH];
  313. /* verify tag */
  314. NSData *authenticationTagData = [cipherData subdataWithRange:NSMakeRange([cipherData length] - AES_GCM_TAG_LENGTH, AES_GCM_TAG_LENGTH)];
  315. NSString *authenticationTag = [authenticationTagData base64EncodedStringWithOptions:0];
  316. if (![authenticationTag isEqualToString:tag])
  317. return NO;
  318. /* Create and initialise the context */
  319. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  320. /* Initialise the decryption operation. */
  321. status = EVP_DecryptInit_ex (ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  322. if (! status)
  323. return NO;
  324. /* Set IV length. Not necessary if this is 12 bytes (96 bits) */
  325. status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, AES_IVEC_LENGTH, NULL);
  326. if (! status)
  327. return NO;
  328. /* Initialise key and IV */
  329. status = EVP_DecryptInit_ex (ctx, NULL, NULL, cKey, cIv);
  330. if (! status)
  331. return NO;
  332. /* Provide the message to be decrypted, and obtain the plaintext output. */
  333. unsigned char * ctBytes = [*plainData mutableBytes];
  334. status = EVP_DecryptUpdate (ctx, ctBytes, &numberOfBytes, [cipherData bytes], (int)[cipherData length]);
  335. if (! status)
  336. return NO;
  337. /* Set expected tag value. Works in OpenSSL 1.0.1d and later */
  338. //status = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, AES_GCM_TAG_LENGTH, cTag);
  339. //if (!status)
  340. // return NO;
  341. /* Finalise the decryption. A positive return value indicates success, anything else is a failure - the plaintext is n trustworthy. */
  342. //status = EVP_EncryptFinal_ex (ctx, ctBytes+numberOfBytes, &numberOfBytes);
  343. //if (!status)
  344. // return NO;
  345. // Without test Final
  346. EVP_DecryptFinal_ex (ctx, NULL, &numberOfBytes);
  347. EVP_CIPHER_CTX_free(ctx);
  348. return status; // OpenSSL uses 1 for success
  349. }
  350. #
  351. #pragma mark - Utility
  352. #
  353. - (NSString *)createSHA512:(NSString *)string
  354. {
  355. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  356. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  357. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  358. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  359. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  360. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  361. [output appendFormat:@"%02x", digest[i]];
  362. return output;
  363. }
  364. - (NSData *)generateIV:(int)ivLength
  365. {
  366. NSMutableData *ivData = [NSMutableData dataWithLength:ivLength];
  367. (void)SecRandomCopyBytes(kSecRandomDefault, ivLength, ivData.mutableBytes);
  368. return ivData;
  369. }
  370. @end