NCClientEncryption.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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/CommonCryptor.h>
  26. #import <CommonCrypto/CommonDigest.h>
  27. #import <Security/Security.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 NSMakeError(description) [NSError errorWithDomain:@"com.nextcloud.nextcloudiOS" code:-1 userInfo:@{NSLocalizedDescriptionKey: description}];
  38. @implementation NCClientEncryption
  39. //Singleton
  40. + (id)sharedManager {
  41. static NCClientEncryption *NCClientEncryption = nil;
  42. static dispatch_once_t onceToken;
  43. dispatch_once(&onceToken, ^{
  44. NCClientEncryption = [self new];
  45. });
  46. return NCClientEncryption;
  47. }
  48. - (void)generateCertificateX509WithDirectoryUser:(NSString *)directoryUser finished:(void (^)(NSError *))finished
  49. {
  50. OPENSSL_init_ssl(0, NULL);
  51. OPENSSL_init_crypto(0, NULL);
  52. X509 *x509;
  53. x509 = X509_new();
  54. EVP_PKEY *pkey;
  55. NSError *keyError;
  56. pkey = [self generateRSAKey:&keyError];
  57. if (keyError) {
  58. finished(keyError);
  59. return;
  60. }
  61. //
  62. //NSData *data = [NSData dataWithBytes:pkey length:2048];
  63. //NSString *s = [[NSString alloc] initWithData:[NSData dataWithBytes:pkey length:2048] encoding:NSASCIIStringEncoding];
  64. X509_set_pubkey(x509, pkey);
  65. EVP_PKEY_free(pkey);
  66. // Set Serial Number
  67. ASN1_INTEGER_set(X509_get_serialNumber(x509), 123);
  68. // Set Valididity Date Range
  69. long notBefore = [[NSDate date] timeIntervalSinceDate:[NSDate date]];
  70. long notAfter = [[[NSDate date] dateByAddingTimeInterval:60*60*24*365*10] timeIntervalSinceDate:[NSDate date]]; // 10 year
  71. X509_gmtime_adj((ASN1_TIME *)X509_get0_notBefore(x509), notBefore);
  72. X509_gmtime_adj((ASN1_TIME *)X509_get0_notAfter(x509), notAfter);
  73. X509_NAME *name = X509_get_subject_name(x509);
  74. // Now to add the subject name fields to the certificate
  75. // I use a macro here to make it cleaner.
  76. #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);
  77. // The domain name or IP address that the certificate is issued for.
  78. addName("CN", "nextcloud.com");
  79. // The organizational unit for the cert. Usually this is a department.
  80. addName("OU", "Certificate Authority");
  81. // The organization of the cert.
  82. addName("O", "Nextcloud");
  83. // The city of the organization.
  84. addName("L", "Vicenza");
  85. // The state/province of the organization.
  86. addName("S", "Italy");
  87. // The country (ISO 3166) of the organization
  88. addName("C", "IT");
  89. X509_set_issuer_name(x509, name);
  90. /*
  91. for (SANObject * san in self.options.sans) {
  92. if (!san.value || san.value.length <= 0) {
  93. continue;
  94. }
  95. NSString * prefix = san.type == SANObjectTypeIP ? @"IP:" : @"DNS:";
  96. NSString * value = [NSString stringWithFormat:@"%@%@", prefix, san.value];
  97. NSLog(@"Add subjectAltName %@", value);
  98. X509_EXTENSION * extension = NULL;
  99. ASN1_STRING * asnValue = ASN1_STRING_new();
  100. ASN1_STRING_set(asnValue, (const unsigned char *)[value UTF8String], (int)value.length);
  101. X509_EXTENSION_create_by_NID(&extension, NID_subject_alt_name, 0, asnValue);
  102. X509_add_ext(x509, extension, -1);
  103. }
  104. */
  105. // Specify the encryption algorithm of the signature.
  106. // SHA256 should suit your needs.
  107. if (X509_sign(x509, pkey, EVP_sha256()) < 0) {
  108. finished([self opensslError:@"Error signing the certificate with the key"]);
  109. return;
  110. }
  111. X509_print_fp(stdout, x509);
  112. [self savePEMWithCert:x509 key:pkey directoryUser:directoryUser finished:finished];
  113. }
  114. - (EVP_PKEY *)generateRSAKey:(NSError **)error
  115. {
  116. EVP_PKEY *pkey = EVP_PKEY_new();
  117. if (!pkey) {
  118. *error = [self opensslError:@"Error creating modulus."];
  119. return NULL;
  120. }
  121. BIGNUM *bigNumber = BN_new();
  122. int exponent = RSA_F4;
  123. RSA *rsa = RSA_new();
  124. if (BN_set_word(bigNumber, exponent) < 0) {
  125. *error = [self opensslError:@"Error creating modulus."];
  126. goto cleanup;
  127. }
  128. if (RSA_generate_key_ex(rsa, 2048, bigNumber, NULL) < 0) {
  129. *error = [self opensslError:@"Error generating private key."];
  130. goto cleanup;
  131. }
  132. if (!EVP_PKEY_set1_RSA(pkey, rsa)) {
  133. *error = [self opensslError:@"Unable to generate RSA key"];
  134. goto cleanup;
  135. }
  136. cleanup:
  137. RSA_free(rsa);
  138. BN_free(bigNumber);
  139. return pkey;
  140. }
  141. - (void)savePEMWithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser finished:(void (^)(NSError *))finished
  142. {
  143. NSString *keyPath = [NSString stringWithFormat:@"%@/privatekey.pem", directoryUser];
  144. NSString *certPath = [NSString stringWithFormat:@"%@/certificate.crt", directoryUser];
  145. FILE *f = fopen([keyPath fileSystemRepresentation], "wb");
  146. // Here you write the private key (pkey) to disk. OpenSSL will encrypt the
  147. // file using the password and cipher you provide.
  148. //if (PEM_write_PrivateKey(f, pkey, EVP_des_ede3_cbc(), (unsigned char *)[password UTF8String], (int)password.length, NULL, NULL) < 0) {
  149. if (PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL) < 0) {
  150. // Error encrypting or writing to disk.
  151. finished([self opensslError:@"Error saving private key."]);
  152. fclose(f);
  153. }
  154. NSLog(@"Saved key to %@", keyPath);
  155. fclose(f);
  156. f = fopen([certPath fileSystemRepresentation], "wb");
  157. // Here you write the certificate to the disk. No encryption is needed here
  158. // since this is public facing information
  159. if (PEM_write_X509(f, x509) < 0) {
  160. // Error writing to disk.
  161. finished([self opensslError:@"Error saving cert."]);
  162. fclose(f);
  163. }
  164. NSLog(@"Saved cert to %@", certPath);
  165. fclose(f);
  166. finished(nil);
  167. }
  168. - (void)saveP12WithCert:(X509 *)x509 key:(EVP_PKEY *)pkey directoryUser:(NSString *)directoryUser finished:(void (^)(NSError *))finished
  169. {
  170. //PKCS12 * p12 = PKCS12_create([password UTF8String], NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  171. PKCS12 *p12 = PKCS12_create(NULL, NULL, pkey, x509, NULL, 0, 0, PKCS12_DEFAULT_ITER, 1, NID_key_usage);
  172. NSString *path = [NSString stringWithFormat:@"%@/certificate.p12", directoryUser];
  173. FILE *f = fopen([path fileSystemRepresentation], "wb");
  174. if (i2d_PKCS12_fp(f, p12) != 1) {
  175. finished([self opensslError:@"Error writing p12 to disk."]);
  176. fclose(f);
  177. return;
  178. }
  179. NSLog(@"Saved p12 to %@", path);
  180. fclose(f);
  181. finished(nil);
  182. }
  183. - (NSError *)opensslError:(NSString *)description
  184. {
  185. const char *file;
  186. int line;
  187. ERR_peek_last_error_line(&file, &line);
  188. NSString *errorBody = [NSString stringWithFormat:@"%@ - OpenSSL Error %s:%i", description, file, line];
  189. NSLog(@"%@", errorBody);
  190. return NSMakeError(errorBody);
  191. }
  192. - (NSString *)createSHA512:(NSString *)string
  193. {
  194. const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
  195. NSData *data = [NSData dataWithBytes:cstr length:string.length];
  196. uint8_t digest[CC_SHA512_DIGEST_LENGTH];
  197. CC_SHA512(data.bytes, (unsigned int)data.length, digest);
  198. NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
  199. for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
  200. [output appendFormat:@"%02x", digest[i]];
  201. return output;
  202. }
  203. - (void)decryptMetadata:(tableMetadata *)metadata activeUrl:(NSString *)activeUrl
  204. {
  205. NSData *keyData = [[NSData alloc] initWithBase64EncodedString:@"bGzWfQBj2lE4ZnysDWwsIg==" options:0];
  206. NSData *initVectorData = [[NSData alloc] initWithBase64EncodedString:@"rTBECYNekKF+a1HR7z32/Q==" options:0];
  207. // Encrypt
  208. //NSData *dataEncrypt = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/iosencrypted.jpg", activeUrl]];
  209. //NSData *encryptedData = cipherOperation(dataEncrypt, keyData, initVectorData, kCCEncrypt);
  210. //if (encryptedData != nil)
  211. // [encryptedData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"crypted.dms"] atomically:YES];
  212. // Decrypt
  213. //NSData *dataDecrypt = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/crypted.dms", activeUrl]];
  214. NSData *dataDecrypt = [[NSFileManager defaultManager] contentsAtPath:[NSString stringWithFormat:@"%@/%@", activeUrl, metadata.fileID]];
  215. NSData *decryptedData = cipherOperation(dataDecrypt, keyData, initVectorData, kCCDecrypt);
  216. if (decryptedData != nil)
  217. [decryptedData writeToFile:[NSString stringWithFormat:@"%@/%@", activeUrl, @"decrypted.jpg"] atomically:YES];
  218. }
  219. NSData *cipherOperation(NSData *contentData, NSData *keyData, NSData *initVectorData, CCOperation operation)
  220. {
  221. void *operationBytes = malloc(contentData.length);
  222. // setup key
  223. unsigned char cKey[kCCKeySizeAES128];
  224. bzero(cKey, sizeof(cKey));
  225. [keyData getBytes:cKey length:kCCKeySizeAES128];
  226. // setup iv
  227. char cIv[kCCBlockSizeAES128];
  228. bzero(cIv, kCCBlockSizeAES128);
  229. [initVectorData getBytes:cIv length:kCCBlockSizeAES128];
  230. // tag
  231. NSMutableData *tag = [NSMutableData dataWithLength:kCCBlockSizeAES128];
  232. size_t tagLength = kCCBlockSizeAES128;
  233. /*CCCryptorStatus cryptStatus = CCCryptorGCM(operation,
  234. kCCAlgorithmAES128,
  235. cKey,
  236. kCCKeySizeAES128,
  237. cIv,
  238. kCCBlockSizeAES128,
  239. nil,
  240. 0,
  241. contentData.bytes,
  242. contentData.length,
  243. operationBytes,
  244. tag.bytes,
  245. &tagLength);
  246. if (cryptStatus == kCCSuccess) {
  247. return [NSData dataWithBytesNoCopy:operationBytes length:contentData.length];
  248. }
  249. */
  250. free(operationBytes);
  251. return nil;
  252. }
  253. @end