NCClientEncryption.m 14 KB

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