NCClientEncryption.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. //
  2. // NCClientEncryption.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 "NCClientEncryption.h"
  24. #import "NCBridgeSwift.h"
  25. #import <CommonCrypto/CommonDigest.h>
  26. #import <openssl/x509.h>
  27. #import <openssl/bio.h>
  28. #import <openssl/err.h>
  29. #import <openssl/pem.h>
  30. #import <openssl/rsa.h>
  31. #import <openssl/pkcs12.h>
  32. #import <openssl/ssl.h>
  33. #import <openssl/err.h>
  34. #import <openssl/bn.h>
  35. #define NSMakeError(description) [NSError errorWithDomain:@"com.nextcloud.nextcloudiOS" code:-1 userInfo:@{NSLocalizedDescriptionKey: description}];
  36. #define AES_KEY_LENGTH 16
  37. #define AES_IVEC_LENGTH 16
  38. //#define AES_KEY_LENGTH_BITS 128
  39. //#define AES_GCM_TAG_LENGTH 16
  40. @implementation NCClientEncryption
  41. //Singleton
  42. + (id)sharedManager {
  43. static NCClientEncryption *NCClientEncryption = nil;
  44. static dispatch_once_t onceToken;
  45. dispatch_once(&onceToken, ^{
  46. NCClientEncryption = [self new];
  47. });
  48. return NCClientEncryption;
  49. }
  50. - (void)generateCertificateX509WithDirectoryUser:(NSString *)directoryUser userID:(NSString *)userID finished:(void (^)(NSError *))finished
  51. {
  52. OPENSSL_init_ssl(0, NULL);
  53. OPENSSL_init_crypto(0, NULL);
  54. X509 *x509;
  55. x509 = X509_new();
  56. EVP_PKEY *pkey;
  57. NSError *keyError;
  58. pkey = [self generateRSAKey:&keyError];
  59. if (keyError) {
  60. finished(keyError);
  61. return;
  62. }
  63. //
  64. //NSData *data = [NSData dataWithBytes:pkey length:2048];
  65. //NSString *s = [[NSString alloc] initWithData:[NSData dataWithBytes:pkey length:2048] encoding:NSASCIIStringEncoding];
  66. X509_set_pubkey(x509, pkey);
  67. EVP_PKEY_free(pkey);
  68. // Set Serial Number
  69. ASN1_INTEGER_set(X509_get_serialNumber(x509), 123);
  70. // Set Valididity Date Range
  71. long notBefore = [[NSDate date] timeIntervalSinceDate:[NSDate date]];
  72. long notAfter = [[[NSDate date] dateByAddingTimeInterval:60*60*24*365*10] timeIntervalSinceDate:[NSDate date]]; // 10 year
  73. X509_gmtime_adj((ASN1_TIME *)X509_get0_notBefore(x509), notBefore);
  74. X509_gmtime_adj((ASN1_TIME *)X509_get0_notAfter(x509), notAfter);
  75. X509_NAME *name = X509_get_subject_name(x509);
  76. // Now to add the subject name fields to the certificate
  77. // I use a macro here to make it cleaner.
  78. #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);
  79. const unsigned char *cUserID = (const unsigned char *) [userID cStringUsingEncoding:NSUTF8StringEncoding];
  80. // CN = UserID.
  81. addName("CN", cUserID);
  82. // The organizational unit for the cert. Usually this is a department.
  83. addName("OU", "Certificate Authority");
  84. // The organization of the cert.
  85. addName("O", "Nextcloud");
  86. // The city of the organization.
  87. addName("L", "Vicenza");
  88. // The state/province of the organization.
  89. addName("S", "Italy");
  90. // The country (ISO 3166) of the organization
  91. addName("C", "IT");
  92. X509_set_issuer_name(x509, name);
  93. /*
  94. for (SANObject * san in self.options.sans) {
  95. if (!san.value || san.value.length <= 0) {
  96. continue;
  97. }
  98. NSString * prefix = san.type == SANObjectTypeIP ? @"IP:" : @"DNS:";
  99. NSString * value = [NSString stringWithFormat:@"%@%@", prefix, san.value];
  100. NSLog(@"Add subjectAltName %@", value);
  101. X509_EXTENSION * extension = NULL;
  102. ASN1_STRING * asnValue = ASN1_STRING_new();
  103. ASN1_STRING_set(asnValue, (const unsigned char *)[value UTF8String], (int)value.length);
  104. X509_EXTENSION_create_by_NID(&extension, NID_subject_alt_name, 0, asnValue);
  105. X509_add_ext(x509, extension, -1);
  106. }
  107. */
  108. // Specify the encryption algorithm of the signature.
  109. // SHA256 should suit your needs.
  110. if (X509_sign(x509, pkey, EVP_sha256()) < 0) {
  111. finished([self opensslError:@"Error signing the certificate with the key"]);
  112. return;
  113. }
  114. X509_print_fp(stdout, x509);
  115. [self savePEMWithCert:x509 key:pkey directoryUser:directoryUser finished:finished];
  116. }
  117. - (EVP_PKEY *)generateRSAKey:(NSError **)error
  118. {
  119. EVP_PKEY *pkey = EVP_PKEY_new();
  120. if (!pkey) {
  121. *error = [self opensslError:@"Error creating modulus."];
  122. return NULL;
  123. }
  124. BIGNUM *bigNumber = BN_new();
  125. int exponent = RSA_F4;
  126. RSA *rsa = RSA_new();
  127. if (BN_set_word(bigNumber, exponent) < 0) {
  128. *error = [self opensslError:@"Error creating modulus."];
  129. goto cleanup;
  130. }
  131. if (RSA_generate_key_ex(rsa, 2048, bigNumber, NULL) < 0) {
  132. *error = [self opensslError:@"Error generating private key."];
  133. goto cleanup;
  134. }
  135. if (!EVP_PKEY_set1_RSA(pkey, rsa)) {
  136. *error = [self opensslError:@"Unable to generate RSA key"];
  137. goto cleanup;
  138. }
  139. cleanup:
  140. RSA_free(rsa);
  141. BN_free(bigNumber);
  142. return pkey;
  143. }
  144. - (void)savePEMWithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser finished:(void (^)(NSError *))finished
  145. {
  146. NSString *keyPath = [NSString stringWithFormat:@"%@/privatekey.pem", directoryUser];
  147. NSString *certPath = [NSString stringWithFormat:@"%@/certificate.crt", directoryUser];
  148. FILE *f = fopen([keyPath fileSystemRepresentation], "wb");
  149. // Here you write the private key (pkey) to disk. OpenSSL will encrypt the
  150. // file using the password and cipher you provide.
  151. //if (PEM_write_PrivateKey(f, pkey, EVP_des_ede3_cbc(), (unsigned char *)[password UTF8String], (int)password.length, NULL, NULL) < 0) {
  152. if (PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL) < 0) {
  153. // Error encrypting or writing to disk.
  154. finished([self opensslError:@"Error saving private key."]);
  155. fclose(f);
  156. }
  157. NSLog(@"Saved key to %@", keyPath);
  158. fclose(f);
  159. f = fopen([certPath fileSystemRepresentation], "wb");
  160. // Here you write the certificate to the disk. No encryption is needed here
  161. // since this is public facing information
  162. if (PEM_write_X509(f, x509) < 0) {
  163. // Error writing to disk.
  164. finished([self opensslError:@"Error saving cert."]);
  165. fclose(f);
  166. }
  167. NSLog(@"Saved cert to %@", certPath);
  168. fclose(f);
  169. finished(nil);
  170. }
  171. - (void)saveP12WithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser finished:(void (^)(NSError *))finished
  172. {
  173. //PKCS12 * p12 = PKCS12_create([password UTF8String], NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  174. PKCS12 *p12 = PKCS12_create(NULL, NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  175. NSString *path = [NSString stringWithFormat:@"%@/certificate.p12", directoryUser];
  176. FILE *f = fopen([path fileSystemRepresentation], "wb");
  177. if (i2d_PKCS12_fp(f, p12) != 1) {
  178. finished([self opensslError:@"Error writing p12 to disk."]);
  179. fclose(f);
  180. return;
  181. }
  182. NSLog(@"Saved p12 to %@", path);
  183. fclose(f);
  184. finished(nil);
  185. }
  186. - (NSError *)opensslError:(NSString *)description
  187. {
  188. const char *file;
  189. int line;
  190. ERR_peek_last_error_line(&file, &line);
  191. NSString *errorBody = [NSString stringWithFormat:@"%@ - OpenSSL Error %s:%i", description, file, line];
  192. NSLog(@"%@", errorBody);
  193. return NSMakeError(errorBody);
  194. }
  195. - (NSString *)createSHA512:(NSString *)string
  196. {
  197. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  198. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  199. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  200. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  201. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  202. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  203. [output appendFormat:@"%02x", digest[i]];
  204. return output;
  205. }
  206. - (void)encryptMetadata:(tableMetadata *)metadata activeUrl:(NSString *)activeUrl
  207. {
  208. NSMutableData *cipherData;
  209. NSData *plainData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", activeUrl, metadata.fileID]];
  210. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"bGzWfQBj2lE4ZnysDWwsIg==" options:0];
  211. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:@"rTBECYNekKF+a1HR7z32/Q==" options:0];
  212. [self aes256gcmEncrypt:plainData cipherData:&cipherData keyData:keyData initVectorData:initVectorData];
  213. if (cipherData != nil)
  214. [cipherData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"encrypted.dms"] atomically:YES];
  215. }
  216. - (void)decryptMetadata:(tableMetadata *)metadata activeUrl:(NSString *)activeUrl
  217. {
  218. NSMutableData *plainData;
  219. NSData *cipherData = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", activeUrl, metadata.fileID]];
  220. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"bGzWfQBj2lE4ZnysDWwsIg==" options:0];
  221. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:@"rTBECYNekKF+a1HR7z32/Q==" options:0];
  222. [self aes256gcmDecrypt:cipherData plainData:&plainData keyData:keyData initVectorData:initVectorData];
  223. if (plainData != nil)
  224. [plainData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"decrypted.jpg"] atomically:YES];
  225. }
  226. // encrypt plain data
  227. - (BOOL)aes256gcmEncrypt:(NSData*)plainData cipherData:(NSMutableData**)cipherData keyData:(NSData *)keyData initVectorData:(NSData *)initVectorData
  228. {
  229. int status = 0;
  230. *cipherData = [NSMutableData dataWithLength:[plainData length]];
  231. if (! *cipherData)
  232. return NO;
  233. // set up to Encrypt AES 128 GCM
  234. int numberOfBytes = 0;
  235. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  236. EVP_EncryptInit_ex (ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  237. // set up key
  238. unsigned char cKey[AES_KEY_LENGTH];
  239. bzero(cKey, sizeof(cKey));
  240. [keyData getBytes:cKey length:AES_KEY_LENGTH];
  241. // set up ivec
  242. unsigned char cIv[AES_IVEC_LENGTH];
  243. bzero(cIv, AES_IVEC_LENGTH);
  244. [initVectorData getBytes:cIv length:AES_IVEC_LENGTH];
  245. // set the key and ivec
  246. EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, AES_IVEC_LENGTH, NULL);
  247. EVP_EncryptInit_ex (ctx, NULL, NULL, cKey, cIv);
  248. // add optional AAD (Additional Auth Data)
  249. //if (aad)
  250. // status = EVP_EncryptUpdate( ctx, NULL, &numberOfBytes, [aad bytes], (int)[aad length]);
  251. unsigned char * ctBytes = [*cipherData mutableBytes];
  252. EVP_EncryptUpdate (ctx, ctBytes, &numberOfBytes, [plainData bytes], (int)[plainData length]);
  253. status = EVP_EncryptFinal_ex (ctx, ctBytes+numberOfBytes, &numberOfBytes);
  254. //if (status && tag) {
  255. // status = EVP_CIPHER_CTX_ctrl (ctx, EVP_CTRL_GCM_GET_TAG, AES_GCM_TAG_LENGTH, tag);
  256. //}
  257. EVP_CIPHER_CTX_free(ctx);
  258. return (status != 0); // OpenSSL uses 1 for success
  259. }
  260. // decrypt cipher data
  261. - (BOOL)aes256gcmDecrypt:(NSData*)cipherData plainData:(NSMutableData**)plainData keyData:(NSData *)keyData initVectorData:(NSData *)initVectorData
  262. {
  263. int status = 0;
  264. *plainData = [NSMutableData dataWithLength:[cipherData length]];
  265. if (! *plainData)
  266. return NO;
  267. // set up to Decrypt AES 128 GCM
  268. int numberOfBytes = 0;
  269. EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
  270. EVP_DecryptInit_ex (ctx, EVP_aes_128_gcm(), NULL, NULL, NULL);
  271. // set up key
  272. unsigned char cKey[AES_KEY_LENGTH];
  273. bzero(cKey, sizeof(cKey));
  274. [keyData getBytes:cKey length:AES_KEY_LENGTH];
  275. // set up ivec
  276. unsigned char cIv[AES_IVEC_LENGTH];
  277. bzero(cIv, AES_IVEC_LENGTH);
  278. [initVectorData getBytes:cIv length:AES_IVEC_LENGTH];
  279. // set the key and ivec
  280. EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, AES_IVEC_LENGTH, NULL);
  281. status = EVP_DecryptInit_ex (ctx, NULL, NULL, cKey, cIv);
  282. // Set expected tag value. A restriction in OpenSSL 1.0.1c and earlier requires the tag before any AAD or ciphertext
  283. //if (status && tag)
  284. // EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, AES_GCM_TAG_LENGTH, tag);
  285. // add optional AAD (Additional Auth Data)
  286. //if (aad)
  287. // EVP_DecryptUpdate(ctx, NULL, &numberOfBytes, [aad bytes], (int)[aad length]);
  288. status = EVP_DecryptUpdate (ctx, [*plainData mutableBytes], &numberOfBytes, [cipherData bytes], (int)[cipherData length]);
  289. if (! status) {
  290. NSLog(@"aes256gcmDecrypt: EVP_DecryptUpdate failed");
  291. return NO;
  292. }
  293. EVP_DecryptFinal_ex (ctx, NULL, &numberOfBytes);
  294. EVP_CIPHER_CTX_free(ctx);
  295. return (status != 0); // OpenSSL uses 1 for success
  296. }
  297. @end