amtmanager.js 202 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228
  1. /**
  2. * @description MeshCentral Intel AMT manager
  3. * @author Ylian Saint-Hilaire
  4. * @copyright Intel Corporation 2018-2022
  5. * @license Apache-2.0
  6. * @version v0.0.1
  7. */
  8. /*jslint node: true */
  9. /*jshint node: true */
  10. /*jshint strict:false */
  11. /*jshint -W097 */
  12. /*jshint esversion: 6 */
  13. 'use strict';
  14. module.exports.CreateAmtManager = function (parent) {
  15. var obj = {};
  16. obj.parent = parent;
  17. obj.amtDevices = {}; // Nodeid --> [ dev ]
  18. obj.activeLocalConnections = {}; // Host --> dev
  19. obj.amtAdminAccounts = {}; // DomainId -> [ { user, pass } ]
  20. obj.rootCertBase64 = obj.parent.certificates.root.cert.split('-----BEGIN CERTIFICATE-----').join('').split('-----END CERTIFICATE-----').join('').split('\r').join('').split('\n').join('')
  21. obj.rootCertCN = obj.parent.certificateOperations.forge.pki.certificateFromPem(obj.parent.certificates.root.cert).subject.getField('CN').value;
  22. // 802.1x authentication protocols
  23. const netAuthStrings = ['eap-tls', 'eap-ttls/mschapv2', 'peapv0/eap-mschapv2', 'peapv1/eap-gtc', 'eap-fast/mschapv2', 'eap-fast/gtc', 'eap-md5', 'eap-psk', 'eap-sim', 'eap-aka', 'eap-fast/tls'];
  24. // WSMAN stack
  25. const CreateWsmanComm = require('./amt/amt-wsman-comm');
  26. const WsmanStackCreateService = require('./amt/amt-wsman');
  27. const AmtStackCreateService = require('./amt/amt');
  28. const ConnectionTypeStrings = { 0: "CIRA", 1: "Relay", 2: "LMS", 3: "Local" };
  29. // Check that each domain configuration is correct because we are not going to be checking this later.
  30. if (parent.config == null) parent.config = {};
  31. if (parent.config.domains == null) parent.config.domains = {};
  32. for (var domainid in parent.config.domains) {
  33. var domain = parent.config.domains[domainid];
  34. if (typeof domain.amtmanager != 'object') { domain.amtmanager = {}; }
  35. // Load administrator accounts
  36. if (Array.isArray(domain.amtmanager.adminaccounts) == true) {
  37. for (var i = 0; i < domain.amtmanager.adminaccounts.length; i++) {
  38. var c = domain.amtmanager.adminaccounts[i], c2 = {};
  39. if (typeof c.user == 'string') { c2.user = c.user; } else { c2.user = 'admin'; }
  40. if (typeof c.pass == 'string') {
  41. c2.pass = c.pass;
  42. if (obj.amtAdminAccounts[domainid] == null) { obj.amtAdminAccounts[domainid] = []; }
  43. obj.amtAdminAccounts[domainid].push(c2);
  44. }
  45. }
  46. } else {
  47. delete domain.amtmanager.adminaccounts;
  48. }
  49. // Check environment detection
  50. if (Array.isArray(domain.amtmanager.environmentdetection) == true) {
  51. var envDetect = [];
  52. for (var i = 0; i < domain.amtmanager.environmentdetection.length; i++) {
  53. var x = domain.amtmanager.environmentdetection[i].toLowerCase();
  54. if ((typeof x == 'string') && (x != '') && (x.length < 64) && (envDetect.indexOf(x) == -1)) { envDetect.push(x); }
  55. if (envDetect.length >= 4) break; // Maximum of 4 DNS suffix
  56. }
  57. if (envDetect.length > 0) { domain.amtmanager.environmentdetection = envDetect; } else { delete domain.amtmanager.environmentdetection; }
  58. } else {
  59. delete domain.amtmanager.environmentdetection;
  60. }
  61. // Check 802.1x wired profile if present
  62. if ((domain.amtmanager['802.1x'] != null) && (typeof domain.amtmanager['802.1x'] == 'object')) {
  63. if (domain.amtmanager['802.1x'].satellitecredentials != null) {
  64. if (typeof domain.amtmanager['802.1x'].satellitecredentials != 'string') { delete domain.amtmanager['802.1x']; } else {
  65. const userSplit = domain.amtmanager['802.1x'].satellitecredentials.split('/');
  66. if (userSplit.length > 3) { delete domain.amtmanager['802.1x']; }
  67. else if (userSplit.length == 2) { domain.amtmanager['802.1x'].satellitecredentials = 'user/' + domain.id + '/' + userSplit[1]; }
  68. else if (userSplit.length == 1) { domain.amtmanager['802.1x'].satellitecredentials = 'user/' + domain.id + '/' + userSplit[0]; }
  69. }
  70. }
  71. if (typeof domain.amtmanager['802.1x'].servercertificatename != 'string') {
  72. delete domain.amtmanager['802.1x'].servercertificatenamecomparison;
  73. } else {
  74. const serverCertCompareStrings = ['', '', 'fullname', 'domainsuffix'];
  75. if (typeof domain.amtmanager['802.1x'].servercertificatenamecomparison == 'string') {
  76. domain.amtmanager['802.1x'].servercertificatenamecomparison = serverCertCompareStrings.indexOf(domain.amtmanager['802.1x'].servercertificatenamecomparison.toLowerCase());
  77. if (domain.amtmanager['802.1x'].servercertificatenamecomparison == -1) { domain.amtmanager['802.1x'].servercertificatenamecomparison = 2; } // Default to full name compare
  78. }
  79. }
  80. if (typeof domain.amtmanager['802.1x'].authenticationprotocol == 'string') {
  81. domain.amtmanager['802.1x'].authenticationprotocol = netAuthStrings.indexOf(domain.amtmanager['802.1x'].authenticationprotocol.toLowerCase());
  82. if (domain.amtmanager['802.1x'].authenticationprotocol == -1) { delete domain.amtmanager['802.1x']; }
  83. }
  84. }
  85. // Check WIFI profiles
  86. //var wifiAuthMethod = { 1: "Other", 2: "Open", 3: "Shared Key", 4: "WPA PSK", 5: "WPA 802.1x", 6: "WPA2 PSK", 7: "WPA2 802.1x", 32768: "WPA3 SAE IEEE 802.1x", 32769: "WPA3 OWE IEEE 802.1x" };
  87. //var wifiEncMethod = { 1: "Other", 2: "WEP", 3: "TKIP", 4: "CCMP", 5: "None" }
  88. if (Array.isArray(domain.amtmanager.wifiprofiles) == true) {
  89. var goodWifiProfiles = [];
  90. for (var i = 0; i < domain.amtmanager.wifiprofiles.length; i++) {
  91. var wifiProfile = domain.amtmanager.wifiprofiles[i];
  92. if ((typeof wifiProfile.ssid == 'string') && (wifiProfile.ssid != '')) {
  93. if ((wifiProfile.name == null) || (wifiProfile.name == '')) { wifiProfile.name = wifiProfile.ssid; }
  94. // Authentication
  95. if (typeof wifiProfile.authentication == 'string') { wifiProfile.authentication = wifiProfile.authentication.toLowerCase(); }
  96. if (wifiProfile.authentication == 'wpa-psk') { wifiProfile.authentication = 4; }
  97. if (wifiProfile.authentication == 'wpa2-psk') { wifiProfile.authentication = 6; }
  98. if (wifiProfile.authentication == 'wpa-8021x') { wifiProfile.authentication = 5; }
  99. if (wifiProfile.authentication == 'wpa2-802.1x') { wifiProfile.authentication = 7; }
  100. if (wifiProfile.authentication == 'wpa3-sae-802.1x') { wifiProfile.authentication = 32768; }
  101. if (wifiProfile.authentication == 'wpa3-owe-802.1x') { wifiProfile.authentication = 32769; }
  102. if (typeof wifiProfile.authentication != 'number') {
  103. if (wifiProfile['802.1x']) { wifiProfile.authentication = 7; } // Default to WPA2-802.1x
  104. else { wifiProfile.authentication = 6; } // Default to WPA2-PSK
  105. }
  106. // Encyption
  107. if (typeof wifiProfile.encryption == 'string') { wifiProfile.encryption = wifiProfile.encryption.toLowerCase(); }
  108. if ((wifiProfile.encryption == 'ccmp-aes') || (wifiProfile.encryption == 'ccmp')) { wifiProfile.encryption = 4; }
  109. if ((wifiProfile.encryption == 'tkip-rc4') || (wifiProfile.encryption == 'tkip')) { wifiProfile.encryption = 3; }
  110. if (typeof wifiProfile.encryption != 'number') { wifiProfile.encryption = 4; } // Default to CCMP-AES
  111. // Type
  112. wifiProfile.type = 3; // Infrastructure
  113. // Check authentication
  114. if ([4, 6].indexOf(wifiProfile.authentication) >= 0) {
  115. // Password authentication
  116. if ((typeof wifiProfile.password != 'string') || (wifiProfile.password.length < 8) || (wifiProfile.password.length > 63)) continue;
  117. } else if ([5, 7, 32768, 32769].indexOf(wifiProfile.authentication) >= 0) {
  118. // 802.1x authentication
  119. if ((domain.amtmanager['802.1x'] == null) || (typeof domain.amtmanager['802.1x'] != 'object')) continue;
  120. }
  121. goodWifiProfiles.push(wifiProfile);
  122. }
  123. }
  124. domain.amtmanager.wifiprofiles = goodWifiProfiles;
  125. } else {
  126. delete domain.amtmanager.wifiprofiles;
  127. }
  128. }
  129. // Check if an Intel AMT device is being managed
  130. function isAmtDeviceValid(dev) {
  131. var devices = obj.amtDevices[dev.nodeid];
  132. if (devices == null) return false;
  133. return (devices.indexOf(dev) >= 0)
  134. }
  135. // Add an Intel AMT managed device
  136. function addAmtDevice(dev) {
  137. var devices = obj.amtDevices[dev.nodeid];
  138. if (devices == null) { obj.amtDevices[dev.nodeid] = [dev]; return true; }
  139. if (devices.indexOf(dev) >= 0) return false; // This device is already in the list
  140. devices.push(dev); // Add the device to the list
  141. return true;
  142. }
  143. // Remove an Intel AMT managed device
  144. function removeAmtDevice(dev, tag) {
  145. parent.debug('amt', dev.name, "Remove device", dev.nodeid, dev.connType, tag);
  146. // Find the device in the list
  147. var devices = obj.amtDevices[dev.nodeid];
  148. if (devices == null) return false;
  149. var i = devices.indexOf(dev);
  150. if (i == -1) return false;
  151. // Remove from task limiter if needed
  152. if (dev.taskid != null) { obj.parent.taskLimiter.completed(dev.taskid); delete dev.taskLimiter; }
  153. // Clean up this device
  154. if (dev.amtstack != null) { dev.amtstack.CancelAllQueries(999); if (dev.amtstack != null) { delete dev.amtstack.dev; delete dev.amtstack; } }
  155. if (dev.polltimer != null) { clearInterval(dev.polltimer); delete dev.polltimer; }
  156. // Remove the device from the list
  157. devices.splice(i, 1);
  158. if (devices.length == 0) { delete obj.amtDevices[dev.nodeid]; } else { obj.amtDevices[dev.nodeid] = devices; }
  159. // Notify connection closure if this is a LMS connection
  160. if (dev.connType == 2) { dev.controlMsg({ action: 'close' }); }
  161. return true;
  162. }
  163. // Remove all Intel AMT devices for a given nodeid
  164. function removeDevice(nodeid) {
  165. parent.debug('amt', "Remove nodeid", nodeid);
  166. // Find the devices in the list
  167. var devices = obj.amtDevices[nodeid];
  168. if (devices == null) return false;
  169. for (var i in devices) {
  170. var dev = devices[i];
  171. // Remove from task limiter if needed
  172. if (dev.taskid != null) { obj.parent.taskLimiter.completed(dev.taskid); delete dev.taskLimiter; }
  173. // Clean up this device
  174. if (dev.amtstack != null) { dev.amtstack.wsman.comm.FailAllError = 999; delete dev.amtstack; } // Disconnect any active connections.
  175. if (dev.polltimer != null) { clearInterval(dev.polltimer); delete dev.polltimer; }
  176. // Notify connection closure if this is a LMS connection
  177. if (dev.connType == 2) { dev.controlMsg({ action: 'close' }); }
  178. }
  179. // Remove all Intel AMT management sessions for this nodeid
  180. delete obj.amtDevices[nodeid];
  181. // If a 802.1x profile is active with MeshCentral Satellite, notify Satellite of the removal
  182. if (domain.amtmanager['802.1x'] != null) {
  183. var reqId = Buffer.from(parent.crypto.randomBytes(16), 'binary').toString('base64'); // Generate a crypto-secure request id.
  184. parent.DispatchEvent([domain.amtmanager['802.1x'].satellitecredentials], obj, { action: 'satellite', subaction: '802.1x-Profile-Remove', satelliteFlags: 2, nodeid: nodeid, domain: nodeid.split('/')[1], nolog: 1, ver: dev.intelamt.ver });
  185. }
  186. return true;
  187. }
  188. // Start Intel AMT management
  189. // connType: 0 = CIRA, 1 = CIRA-Relay, 2 = CIRA-LMS, 3 = LAN
  190. obj.startAmtManagement = function (nodeid, connType, connection) {
  191. //if (connType == 3) return; // DEBUG
  192. var devices = obj.amtDevices[nodeid], dev = null;
  193. if (devices != null) { for (var i in devices) { if ((devices[i].mpsConnection == connection) || (devices[i].host == connection)) { dev = devices[i]; } } }
  194. if (dev != null) return false; // We are already managing this device on this connection
  195. dev = { nodeid: nodeid, connType: connType, domainid: nodeid.split('/')[1] };
  196. if (typeof connection == 'string') { dev.host = connection; }
  197. if (typeof connection == 'object') { dev.mpsConnection = connection; }
  198. dev.consoleMsg = function deviceConsoleMsg(msg) { parent.debug('amt', deviceConsoleMsg.dev.name, msg); if (typeof deviceConsoleMsg.conn == 'object') { deviceConsoleMsg.conn.ControlMsg({ action: 'console', msg: msg }); } }
  199. dev.consoleMsg.conn = connection;
  200. dev.consoleMsg.dev = dev;
  201. dev.controlMsg = function deviceControlMsg(msg) { if (typeof deviceControlMsg.conn == 'object') { deviceControlMsg.conn.ControlMsg(msg); } }
  202. dev.controlMsg.conn = connection;
  203. parent.debug('amt', "Start Management", nodeid, connType);
  204. addAmtDevice(dev);
  205. // Start the device manager in the task limiter so not to flood the server. Low priority task
  206. obj.parent.taskLimiter.launch(function (dev, taskid, taskLimiterQueue) {
  207. if (isAmtDeviceValid(dev)) {
  208. // Start managing this device
  209. dev.taskid = taskid;
  210. fetchIntelAmtInformation(dev);
  211. } else {
  212. // Device is not valid anymore, do nothing
  213. obj.parent.taskLimiter.completed(taskid);
  214. }
  215. }, dev, 2);
  216. }
  217. // Stop Intel AMT management
  218. obj.stopAmtManagement = function (nodeid, connType, connection) {
  219. var devices = obj.amtDevices[nodeid], dev = null;
  220. if (devices != null) { for (var i in devices) { if ((devices[i].mpsConnection == connection) || (devices[i].host == connection)) { dev = devices[i]; } } }
  221. if (dev == null) return false; // We are not managing this device on this connection
  222. parent.debug('amt', dev.name, "Stop Management", nodeid, connType);
  223. return removeAmtDevice(dev, 1);
  224. }
  225. // Get a string status of the managed devices
  226. obj.getStatusString = function () {
  227. var r = '';
  228. for (var nodeid in obj.amtDevices) {
  229. var devices = obj.amtDevices[nodeid];
  230. r += devices[0].nodeid + ', ' + devices[0].name + '\r\n';
  231. for (var i in devices) {
  232. var dev = devices[i];
  233. var items = [];
  234. if (dev.state == 1) { items.push('Connected'); } else { items.push('Trying'); }
  235. items.push(ConnectionTypeStrings[dev.connType]);
  236. if (dev.connType == 3) { items.push(dev.host); }
  237. if (dev.polltimer != null) { items.push('Polling Power'); }
  238. r += ' ' + items.join(', ') + '\r\n';
  239. }
  240. }
  241. if (r == '') { r = "No managed Intel AMT devices"; }
  242. return r;
  243. }
  244. // Receive a JSON control message from the MPS server
  245. obj.mpsControlMessage = function (nodeid, conn, connType, jsondata) {
  246. // Find the devices in the list
  247. var dev = null;
  248. var devices = obj.amtDevices[nodeid];
  249. if (devices == null) return;
  250. for (var i in devices) { if (devices[i].mpsConnection === conn) { dev = devices[i]; } }
  251. if (dev == null) return;
  252. // Process the message
  253. switch (jsondata.action) {
  254. case 'deactivate':
  255. if ((dev.connType != 2) || (dev.deactivateCcmPending != 1)) break; // Only accept MEI state on CIRA-LMS connection
  256. delete dev.deactivateCcmPending;
  257. deactivateIntelAmtCCMEx(dev, jsondata.value);
  258. break;
  259. case 'meiState':
  260. if (dev.acmactivate == 1) {
  261. // Continue ACM activation
  262. dev.consoleMsg("Got new Intel AMT MEI state. Holding 40 seconds prior to ACM activation...");
  263. delete dev.acmactivate;
  264. var continueAcmFunc = function continueAcm() { if (isAmtDeviceValid(continueAcm.dev)) { activateIntelAmtAcmEx0(continueAcm.dev); } }
  265. continueAcmFunc.dev = dev;
  266. setTimeout(continueAcmFunc, 40000);
  267. } else {
  268. if (dev.pendingUpdatedMeiState != 1) break;
  269. delete dev.pendingUpdatedMeiState;
  270. attemptInitialContact(dev);
  271. }
  272. break;
  273. case 'startTlsHostConfig':
  274. if (dev.acmTlsInfo == null) break;
  275. if ((typeof jsondata.value != 'object') || (typeof jsondata.value.status != 'number')) {
  276. removeAmtDevice(dev, 2); // Invalid startTlsHostConfig response
  277. } else {
  278. activateIntelAmtTlsAcmEx(dev, jsondata.value); // Start TLS activation.
  279. }
  280. break;
  281. case 'stopConfiguration':
  282. if (dev.acmactivate != 1) break;
  283. if (jsondata.value == 3) { delete dev.acmactivate; activateIntelAmtAcmEx0(dev); } // Intel AMT was already not in in-provisioning state, keep going right away.
  284. else if (jsondata.value == 0) {
  285. dev.consoleMsg("Cleared in-provisioning state. Holding 30 seconds prior to getting Intel AMT MEI state...");
  286. var askStateFunc = function askState() { if (isAmtDeviceValid(askState.dev)) { askState.dev.controlMsg({ action: 'mestate' }); } }
  287. askStateFunc.dev = dev;
  288. setTimeout(askStateFunc, 30000);
  289. }
  290. else { dev.consoleMsg("Unknown stopConfiguration() state of " + jsondata.value + ". Continuing with ACM activation..."); delete dev.acmactivate; activateIntelAmtAcmEx0(dev); }
  291. break;
  292. }
  293. }
  294. // Subscribe to server events
  295. parent.AddEventDispatch(['*'], obj);
  296. // Handle server events
  297. // Make sure to only manage devices with connections to this server. In a multi-server setup, we don't want multiple managers talking to the same device.
  298. obj.HandleEvent = function (source, event, ids, id) {
  299. switch (event.action) {
  300. case 'removenode': { // React to node being removed
  301. if (event.noact == 1) return; // Take no action on these events. We are likely in peering mode and need to only act when the database signals the change in state.
  302. removeDevice(event.nodeid);
  303. break;
  304. }
  305. case 'wakedevices': { // React to node wakeup command, perform Intel AMT wake if possible
  306. if (event.noact == 1) return; // Take no action on these events. We are likely in peering mode and need to only act when the database signals the change in state.
  307. if (Array.isArray(event.nodeids)) { for (var i in event.nodeids) { performPowerAction(event.nodeids[i], 2); } }
  308. break;
  309. }
  310. case 'oneclickrecovery': { // React to Intel AMT One Click Recovery command
  311. if (event.noact == 1) return; // Take no action on these events. We are likely in peering mode and need to only act when the database signals the change in state.
  312. if (Array.isArray(event.nodeids)) { for (var i in event.nodeids) { performOneClickRecoveryAction(event.nodeids[i], event.file); } }
  313. break;
  314. }
  315. case 'amtpoweraction': {
  316. if (event.noact == 1) return; // Take no action on these events. We are likely in peering mode and need to only act when the database signals the change in state.
  317. if (Array.isArray(event.nodeids)) { for (var i in event.nodeids) { performPowerAction(event.nodeids[i], event.actiontype); } }
  318. break;
  319. }
  320. case 'changenode': { // React to changes in a device
  321. var devices = obj.amtDevices[event.nodeid], rescan = false;
  322. if (devices != null) {
  323. for (var i in devices) {
  324. var dev = devices[i];
  325. dev.name = event.node.name;
  326. dev.icon = event.node.icon;
  327. dev.rname = event.node.rname;
  328. // If there are any changes, apply them.
  329. if (event.node.intelamt != null) {
  330. if (dev.intelamt == null) { dev.intelamt = {}; }
  331. if ((typeof event.node.intelamt.version == 'string') && (event.node.intelamt.version != dev.intelamt.ver)) { dev.intelamt.ver = event.node.intelamt.version; }
  332. if ((typeof event.node.intelamt.user == 'string') && (event.node.intelamt.user != dev.intelamt.user)) { dev.intelamt.user = event.node.intelamt.user; }
  333. if ((typeof event.node.intelamt.pass == 'string') && (event.node.intelamt.pass != dev.intelamt.pass)) { dev.intelamt.pass = event.node.intelamt.pass; }
  334. if ((typeof event.node.intelamt.mpspass == 'string') && (event.node.intelamt.mpspass != dev.intelamt.mpspass)) { dev.intelamt.mpspass = event.node.intelamt.mpspass; }
  335. if ((typeof event.node.intelamt.host == 'string') && (event.node.intelamt.host != dev.intelamt.host)) { dev.intelamt.host = event.node.intelamt.host; }
  336. if ((typeof event.node.intelamt.realm == 'string') && (event.node.intelamt.realm != dev.intelamt.realm)) { dev.intelamt.realm = event.node.intelamt.realm; }
  337. if ((typeof event.node.intelamt.hash == 'string') && (event.node.intelamt.hash != dev.intelamt.hash)) { dev.intelamt.hash = event.node.intelamt.hash; }
  338. if ((typeof event.node.intelamt.tls == 'number') && (event.node.intelamt.tls != dev.intelamt.tls)) { dev.intelamt.tls = event.node.intelamt.tls; }
  339. if ((typeof event.node.intelamt.state == 'number') && (event.node.intelamt.state != dev.intelamt.state)) { dev.intelamt.state = event.node.intelamt.state; }
  340. }
  341. if ((dev.connType == 3) && (dev.host != event.node.host)) {
  342. dev.host = event.node.host; // The host has changed, if we are connected to this device locally, we need to reset.
  343. removeAmtDevice(dev, 3); // We are going to wait for the AMT scanned to find this device again.
  344. rescan = true;
  345. }
  346. }
  347. } else {
  348. // If this event provides a hint that something changed with AMT and we are not managing this device, let's rescan the local network now.
  349. if (event.amtchange == 1) { rescan = true; }
  350. }
  351. // If there is a significant change to the device AMT settings and this server manages local devices, perform a re-scan of the device now.
  352. if (rescan && (parent.amtScanner != null)) { parent.amtScanner.performSpecificScan(event.node); }
  353. break;
  354. }
  355. case 'meshchange': {
  356. // TODO
  357. // TODO: If a device changes to a device group that does not have a 802.1x policy, we may need to tell MeshCentral Satellite to remove the 802.1x profile.
  358. break;
  359. }
  360. case 'satelliteResponse': {
  361. if ((typeof event.nodeid != 'string') || (typeof event.reqid != 'string') || (event.satelliteFlags != 2)) return;
  362. var devices = obj.amtDevices[event.nodeid], devFound = null;
  363. if (devices != null) { for (var i in devices) { if (devices[i].netAuthSatReqId == event.reqid) { devFound = devices[i]; } } }
  364. if (devFound == null) return; // Unable to find a device for this 802.1x profile
  365. switch (event.subaction) {
  366. case '802.1x-KeyPair-Request': {
  367. // 802.1x request for public/private key pair be generated
  368. attempt8021xKeyGeneration(devFound);
  369. break;
  370. }
  371. case '802.1x-CSR-Request': {
  372. // 802.1x request for a Certificate Signing Request
  373. attempt8021xCRSRequest(devFound, event);
  374. break;
  375. }
  376. case '802.1x-Profile-Completed': {
  377. // The 802.1x profile request is done, set it in Intel AMT.
  378. if (devFound.netAuthSatReqTimer != null) { clearTimeout(devFound.netAuthSatReqTimer); delete devFound.netAuthSatReqTimer; }
  379. if ((event.response == null) || (typeof event.response != 'object')) {
  380. // Unable to create a 802.1x profile
  381. delete devFound.netAuthSatReqId;
  382. if (isAmtDeviceValid(devFound) == false) return; // Device no longer exists, ignore this request.
  383. delete devFound.netAuthSatReqData;
  384. devFound.consoleMsg("MeshCentral Satellite could not create a 802.1x profile for this device.");
  385. devTaskCompleted(devFound);
  386. return;
  387. }
  388. if (typeof event.response.authProtocol != 'number') { delete devFound.netAuthSatReqId; break; }
  389. // We got a new 802.1x profile
  390. devFound.netAuthCredentials = event.response;
  391. perform8021xRootCertCheck(devFound);
  392. break;
  393. }
  394. }
  395. break;
  396. }
  397. }
  398. }
  399. //
  400. // Intel AMT Connection Setup
  401. //
  402. // Update information about a device
  403. function fetchIntelAmtInformation(dev) {
  404. parent.db.Get(dev.nodeid, function (err, nodes) {
  405. if ((nodes == null) || (nodes.length != 1)) { removeAmtDevice(dev, 4); return; }
  406. const node = nodes[0];
  407. if ((node.intelamt == null) || (node.meshid == null)) { removeAmtDevice(dev, 5); return; }
  408. const mesh = parent.webserver.meshes[node.meshid];
  409. if (mesh == null) { removeAmtDevice(dev, 6); return; }
  410. if (dev == null) { return; }
  411. // Fetch Intel AMT setup policy
  412. // mesh.amt.type: 0 = No Policy, 1 = Deactivate CCM, 2 = Manage in CCM, 3 = Manage in ACM
  413. // mesh.amt.cirasetup: 0 = No Change, 1 = Remove CIRA, 2 = Setup CIRA
  414. var amtPolicy = 0, ciraPolicy = 0, badPass = 0, password = null;
  415. if (mesh.amt != null) {
  416. if (mesh.amt.type) { amtPolicy = mesh.amt.type; }
  417. if (mesh.amt.type == 4) {
  418. // Fully automatic policy
  419. ciraPolicy = 2; // CIRA will be setup
  420. badPass = 1; // Automatically re-active CCM
  421. password = null; // Randomize the password.
  422. } else {
  423. if (mesh.amt.cirasetup) { ciraPolicy = mesh.amt.cirasetup; }
  424. if (mesh.amt.badpass) { badPass = mesh.amt.badpass; }
  425. if ((typeof mesh.amt.password == 'string') && (mesh.amt.password != '')) { password = mesh.amt.password; }
  426. }
  427. }
  428. if (amtPolicy == 0) { ciraPolicy = 0; } // If no policy, don't change CIRA state.
  429. if (amtPolicy == 1) { ciraPolicy = 1; } // If deactivation policy, clear CIRA.
  430. dev.policy = { amtPolicy: amtPolicy, ciraPolicy: ciraPolicy, badPass: badPass, password: password };
  431. // Setup the monitored device
  432. dev.name = node.name;
  433. dev.rname = node.rname;
  434. dev.icon = node.icon;
  435. dev.meshid = node.meshid;
  436. dev.intelamt = node.intelamt;
  437. // Check if the status of Intel AMT sent by the agents matched what we have in the database
  438. if ((dev.connType == 2) && (dev.mpsConnection != null) && (dev.mpsConnection.tag != null) && (dev.mpsConnection.tag.meiState != null)) {
  439. dev.aquired = {};
  440. if ((typeof dev.mpsConnection.tag.meiState.OsHostname == 'string') && (typeof dev.mpsConnection.tag.meiState.OsDnsSuffix == 'string')) {
  441. dev.host = dev.aquired.host = dev.mpsConnection.tag.meiState.OsHostname + '.' + dev.mpsConnection.tag.meiState.OsDnsSuffix;
  442. }
  443. if (typeof dev.mpsConnection.tag.meiState['ProvisioningState'] == 'number') {
  444. dev.intelamt.state = dev.aquired.state = dev.mpsConnection.tag.meiState['ProvisioningState'];
  445. }
  446. if ((typeof dev.mpsConnection.tag.meiState['Versions'] == 'object') && (typeof dev.mpsConnection.tag.meiState['Versions']['AMT'] == 'string')) {
  447. dev.intelamt.ver = dev.aquired.version = dev.mpsConnection.tag.meiState['Versions']['AMT'];
  448. }
  449. if (typeof dev.mpsConnection.tag.meiState['Flags'] == 'number') {
  450. const flags = dev.intelamt.flags = dev.mpsConnection.tag.meiState['Flags'];
  451. if (flags & 2) { dev.aquired.controlMode = 1; } // CCM
  452. if (flags & 4) { dev.aquired.controlMode = 2; } // ACM
  453. }
  454. UpdateDevice(dev);
  455. }
  456. // If there is no Intel AMT policy for this device, stop here.
  457. //if (amtPolicy == 0) { dev.consoleMsg("Done."); removeAmtDevice(dev, 7); return; }
  458. // Initiate the communication to Intel AMT
  459. dev.consoleMsg("Checking Intel AMT state...");
  460. attemptInitialContact(dev);
  461. });
  462. }
  463. // Attempt to perform initial contact with Intel AMT
  464. function attemptInitialContact(dev) {
  465. // If there is a WSMAN stack setup, clean it up now.
  466. if (dev.amtstack != null) {
  467. dev.amtstack.CancelAllQueries(999);
  468. delete dev.amtstack.dev;
  469. delete dev.amtstack;
  470. }
  471. delete dev.amtstack;
  472. parent.debug('amt', dev.name, "Attempt Initial Contact", ["CIRA", "CIRA-Relay", "CIRA-LMS", "Local"][dev.connType]);
  473. // Check Intel AMT policy when CIRA-LMS connection is in use.
  474. if ((dev.connType == 2) && (dev.mpsConnection != null) && (dev.mpsConnection.tag != null) && (dev.mpsConnection.tag.meiState != null)) {
  475. // Intel AMT activation policy
  476. if ((dev.policy.amtPolicy > 1) && (dev.mpsConnection.tag.meiState.ProvisioningState !== 2)) {
  477. // This Intel AMT device is not activated, we need to work on activating it.
  478. activateIntelAmt(dev);
  479. return;
  480. }
  481. // Check if we have an ACM activation policy, but the device is in CCM
  482. if (((dev.policy.amtPolicy == 3) || (dev.policy.amtPolicy == 4)) && (dev.mpsConnection.tag.meiState.ProvisioningState == 2) && ((dev.mpsConnection.tag.meiState.Flags & 2) != 0)) {
  483. // This device in is CCM, check if we can upgrade to ACM
  484. if (activateIntelAmt(dev) == false) return; // If this return true, the platform is in CCM and can't go to ACM, keep going with management.
  485. }
  486. // Intel AMT CCM deactivation policy
  487. if (dev.policy.amtPolicy == 1) {
  488. if ((dev.mpsConnection.tag.meiState.ProvisioningState == 2) && ((dev.mpsConnection.tag.meiState.Flags & 2) != 0)) {
  489. // Deactivate CCM.
  490. deactivateIntelAmtCCM(dev);
  491. return;
  492. }
  493. }
  494. }
  495. // See what username/password we need to try
  496. // We create an efficient strategy for trying different Intel AMT passwords.
  497. if (dev.acctry == null) {
  498. dev.acctry = [];
  499. // Add Intel AMT username and password provided by MeshCMD if available
  500. if ((dev.mpsConnection != null) && (dev.mpsConnection.tag != null) && (dev.mpsConnection.tag.meiState != null) && (typeof dev.mpsConnection.tag.meiState.amtuser == 'string') && (typeof dev.mpsConnection.tag.meiState.amtpass == 'string') && (dev.mpsConnection.tag.meiState.amtuser != '') && (dev.mpsConnection.tag.meiState.amtpass != '')) {
  501. dev.acctry.push([dev.mpsConnection.tag.meiState.amtuser, dev.mpsConnection.tag.meiState.amtpass]);
  502. }
  503. // Add the know Intel AMT password for this device if available
  504. if ((typeof dev.intelamt.user == 'string') && (typeof dev.intelamt.pass == 'string') && (dev.intelamt.user != '') && (dev.intelamt.pass != '')) { dev.acctry.push([dev.intelamt.user, dev.intelamt.pass]); }
  505. // Add the policy password as an alternative
  506. if ((typeof dev.policy.password == 'string') && (dev.policy.password != '')) { dev.acctry.push(['admin', dev.policy.password]); }
  507. // Add any configured admin account as alternatives
  508. if (obj.amtAdminAccounts[dev.domainid] != null) { for (var i in obj.amtAdminAccounts[dev.domainid]) { dev.acctry.push([obj.amtAdminAccounts[dev.domainid][i].user, obj.amtAdminAccounts[dev.domainid][i].pass]); } }
  509. // Add any previous passwords for the device UUID as alternative
  510. if ((parent.amtPasswords != null) && (dev.mpsConnection != null) && (dev.mpsConnection.tag != null) && (dev.mpsConnection.tag.meiState != null) && (dev.mpsConnection.tag.meiState.UUID != null) && (parent.amtPasswords[dev.mpsConnection.tag.meiState.UUID] != null)) {
  511. for (var i in parent.amtPasswords[dev.mpsConnection.tag.meiState.UUID]) {
  512. dev.acctry.push(['admin', parent.amtPasswords[dev.mpsConnection.tag.meiState.UUID][i]]);
  513. }
  514. }
  515. // Remove any duplicates user/passwords
  516. var acctry2 = [];
  517. for (var i = 0; i < dev.acctry.length; i++) {
  518. var found = false;
  519. for (var j = 0; j < acctry2.length; j++) { if ((dev.acctry[i][0] == acctry2[j][0]) && (dev.acctry[i][1] == acctry2[j][1])) { found = true; } }
  520. if (found == false) { acctry2.push(dev.acctry[i]); }
  521. }
  522. dev.acctry = acctry2;
  523. // If we have passwords to try, try the first one now.
  524. if (dev.acctry.length == 0) {
  525. dev.consoleMsg("No admin login passwords to try, stopping now.");
  526. removeAmtDevice(dev, 8);
  527. return;
  528. }
  529. }
  530. if ((dev.acctry == null) || (dev.acctry.length == 0)) { removeAmtDevice(dev, 9); return; } // No Intel AMT credentials to try
  531. var user = dev.acctry[0][0], pass = dev.acctry[0][1]; // Try the first user/pass in the list
  532. switch (dev.connType) {
  533. case 0: // CIRA
  534. // Handle the case where the Intel AMT CIRA is connected (connType 0)
  535. // In this connection type, we look at the port bindings to see if we need to do TLS or not.
  536. // Check to see if CIRA is connected on this server.
  537. var ciraconn = dev.mpsConnection;
  538. if ((ciraconn == null) || (ciraconn.tag == null) || (ciraconn.tag.boundPorts == null)) { removeAmtDevice(dev, 9); return; } // CIRA connection is not on this server, no need to deal with this device anymore.
  539. // See if we need to perform TLS or not. We prefer not to do TLS within CIRA.
  540. var dotls = -1;
  541. if (ciraconn.tag.boundPorts.indexOf('16992')) { dotls = 0; }
  542. else if (ciraconn.tag.boundPorts.indexOf('16993')) { dotls = 1; }
  543. if (dotls == -1) { removeAmtDevice(dev, 10); return; } // The Intel AMT ports are not open, not a device we can deal with.
  544. // Connect now
  545. parent.debug('amt', dev.name, 'CIRA-Connect', (dotls == 1) ? "TLS" : "NoTLS", user, pass);
  546. var comm;
  547. if (dotls == 1) {
  548. comm = CreateWsmanComm(dev.nodeid, 16993, user, pass, 1, null, ciraconn); // Perform TLS
  549. comm.xtlsFingerprint = 0; // Perform no certificate checking
  550. } else {
  551. comm = CreateWsmanComm(dev.nodeid, 16992, user, pass, 0, null, ciraconn); // No TLS
  552. }
  553. var wsstack = WsmanStackCreateService(comm);
  554. dev.amtstack = AmtStackCreateService(wsstack);
  555. dev.amtstack.dev = dev;
  556. dev.amtstack.BatchEnum(null, ['*AMT_GeneralSettings', '*IPS_HostBasedSetupService'], attemptLocalConnectResponse);
  557. break;
  558. case 1: // CIRA-Relay
  559. case 2: // CIRA-LMS
  560. // Handle the case where the Intel AMT relay or LMS is connected (connType 1 or 2)
  561. // Check to see if CIRA is connected on this server.
  562. var ciraconn = dev.mpsConnection;
  563. if ((ciraconn == null) || (ciraconn.tag == null) || (ciraconn.tag.boundPorts == null)) { removeAmtDevice(dev, 11); return; } // Relay connection not valid
  564. // Connect now
  565. var comm;
  566. if ((dev.tlsfail !== true) && (parent.config.domains[dev.domainid].amtmanager.tlsconnections !== false)) {
  567. parent.debug('amt', dev.name, (dev.connType == 1) ? 'Relay-Connect' : 'LMS-Connect', "TLS", user);
  568. comm = CreateWsmanComm(dev.nodeid, 16993, user, pass, 1, null, ciraconn); // Perform TLS
  569. comm.xtlsFingerprint = 0; // Perform no certificate checking
  570. } else {
  571. parent.debug('amt', dev.name, (dev.connType == 1) ? 'Relay-Connect' : 'LMS-Connect', "NoTLS", user);
  572. comm = CreateWsmanComm(dev.nodeid, 16992, user, pass, 0, null, ciraconn); // No TLS
  573. }
  574. var wsstack = WsmanStackCreateService(comm);
  575. dev.amtstack = AmtStackCreateService(wsstack);
  576. dev.amtstack.dev = dev;
  577. dev.amtstack.BatchEnum(null, ['*AMT_GeneralSettings', '*IPS_HostBasedSetupService'], attemptLocalConnectResponse);
  578. break;
  579. case 3: // Local LAN
  580. // Check if Intel AMT is activated. If not, stop here.
  581. if ((dev.intelamt == null) || ((dev.intelamt.state != null) && (dev.intelamt.state != 2))) { removeAmtDevice(dev, 12); return; }
  582. // Handle the case where the Intel AMT local scanner found the device (connType 3)
  583. parent.debug('amt', dev.name, "Attempt Initial Local Contact", dev.connType, dev.host);
  584. if (typeof dev.host != 'string') { removeAmtDevice(dev, 13); return; } // Local connection not valid
  585. // Since we don't allow two or more connections to the same host, check if a pending connection is active.
  586. if (obj.activeLocalConnections[dev.host] != null) {
  587. // Active connection, hold and try later.
  588. var tryAgainFunc = function tryAgainFunc() { if (obj.amtDevices[tryAgainFunc.dev.nodeid] != null) { attemptInitialContact(tryAgainFunc.dev); } }
  589. tryAgainFunc.dev = dev;
  590. setTimeout(tryAgainFunc, 5000);
  591. } else {
  592. // No active connections
  593. // Connect now
  594. var comm;
  595. if ((dev.tlsfail !== true) && (parent.config.domains[dev.domainid].amtmanager.tlsconnections !== false)) {
  596. parent.debug('amt', dev.name, 'Direct-Connect', "TLS", dev.host, user);
  597. comm = CreateWsmanComm(dev.host, 16993, user, pass, 1); // Always try with TLS first
  598. comm.xtlsFingerprint = 0; // Perform no certificate checking
  599. } else {
  600. parent.debug('amt', dev.name, 'Direct-Connect', "NoTLS", dev.host, user);
  601. comm = CreateWsmanComm(dev.host, 16992, user, pass, 0); // Try without TLS
  602. }
  603. var wsstack = WsmanStackCreateService(comm);
  604. dev.amtstack = AmtStackCreateService(wsstack);
  605. dev.amtstack.dev = dev;
  606. obj.activeLocalConnections[dev.host] = dev;
  607. dev.amtstack.BatchEnum(null, ['*AMT_GeneralSettings', '*IPS_HostBasedSetupService'], attemptLocalConnectResponse);
  608. }
  609. break;
  610. }
  611. }
  612. function attemptLocalConnectResponse(stack, name, responses, status) {
  613. const dev = stack.dev;
  614. parent.debug('amt', dev.name, "Initial Contact Response", status);
  615. // If this is a local connection device, release active connection to this host.
  616. if (dev.connType == 3) { delete obj.activeLocalConnections[dev.host]; }
  617. // Check if the device still exists
  618. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  619. // Check the response
  620. if ((status == 200) && (responses['AMT_GeneralSettings'] != null) && (responses['IPS_HostBasedSetupService'] != null) && (responses['IPS_HostBasedSetupService'].response != null) && (responses['IPS_HostBasedSetupService'].response != null) && (stack.wsman.comm.digestRealm == responses['AMT_GeneralSettings'].response.DigestRealm)) {
  621. // Everything looks good
  622. dev.consoleMsg(stack.wsman.comm.xtls ? "Intel AMT connected with TLS." : "Intel AMT connected.");
  623. dev.state = 1;
  624. if (dev.aquired == null) { dev.aquired = {}; }
  625. dev.aquired.controlMode = responses['IPS_HostBasedSetupService'].response.CurrentControlMode; // 1 = CCM, 2 = ACM
  626. if (typeof stack.wsman.comm.amtVersion == 'string') { // Set the Intel AMT version using the HTTP header if present
  627. var verSplit = stack.wsman.comm.amtVersion.split('.');
  628. if (verSplit.length >= 2) {
  629. dev.aquired.version = verSplit[0] + '.' + verSplit[1];
  630. dev.aquired.majorver = parseInt(verSplit[0]);
  631. dev.aquired.minorver = parseInt(verSplit[1]);
  632. if (verSplit.length >= 3) {
  633. dev.aquired.version = verSplit[0] + '.' + verSplit[1] + '.' + verSplit[2];
  634. dev.aquired.maintenancever = parseInt(verSplit[2]);
  635. }
  636. }
  637. }
  638. dev.aquired.realm = stack.wsman.comm.digestRealm;
  639. dev.aquired.user = dev.intelamt.user = stack.wsman.comm.user;
  640. dev.aquired.pass = dev.intelamt.pass = stack.wsman.comm.pass;
  641. dev.aquired.lastContact = Date.now();
  642. dev.aquired.warn = 0; // Clear all warnings (TODO: Check Realm and TLS cert pinning)
  643. if ((dev.connType == 1) || (dev.connType == 3)) { dev.aquired.tls = stack.wsman.comm.xtls; } // Only set the TLS state if in relay or local mode. When using CIRA, this is auto-detected.
  644. if (stack.wsman.comm.xtls == 1) { dev.aquired.hash = stack.wsman.comm.xtlsCertificate.fingerprint.split(':').join('').toLowerCase(); } else { delete dev.aquired.hash; }
  645. UpdateDevice(dev);
  646. // If this is the new first user/pass for the device UUID, update the activation log now.
  647. if ((parent.amtPasswords != null) && (dev.mpsConnection != null) && (dev.mpsConnection.tag != null) && (dev.mpsConnection.tag.meiState != null) && (dev.mpsConnection.tag.meiState.UUID != null) && (parent.amtPasswords[dev.mpsConnection.tag.meiState.UUID] != null) && (parent.amtPasswords[dev.mpsConnection.tag.meiState.UUID][0] != dev.aquired.pass)) {
  648. parent.certificateOperations.logAmtActivation(parent.config.domains[dev.domainid], { time: new Date(), action: 'amtpassword', domain: dev.domainid, amtUuid: dev.mpsConnection.tag.meiState.UUID, amtRealm: dev.aquired.realm, user: dev.aquired.user, password: dev.aquired.pass, computerName: dev.name });
  649. }
  650. // Perform Intel AMT clock sync
  651. attemptSyncClock(dev, function (dev) {
  652. // Check Intel AMT TLS state
  653. attemptTlsSync(dev, function (dev) {
  654. // If we need to switch to TLS, do it now.
  655. if (dev.switchToTls == 1) { delete dev.switchToTls; attemptInitialContact(dev); return; }
  656. // Check Intel AMT 802.1x wired state and Intel AMT WIFI state (must be done both at once).
  657. attemptWifiSync(dev, function (dev) {
  658. // Check Intel AMT root certificate state
  659. attemptRootCertSync(dev, function (dev) {
  660. // Check Intel AMT CIRA settings
  661. attemptCiraSync(dev, function (dev) {
  662. // Check Intel AMT settings
  663. attemptSettingsSync(dev, function (dev) {
  664. // Clean unused certificates
  665. attemptCleanCertsSync(dev, function (dev) {
  666. // See if we need to get hardware inventory
  667. attemptFetchHardwareInventory(dev, function (dev) {
  668. dev.consoleMsg('Done.');
  669. // Remove from task limiter if needed
  670. if (dev.taskid != null) { obj.parent.taskLimiter.completed(dev.taskid); delete dev.taskLimiter; }
  671. if (dev.connType != 2) {
  672. // Start power polling if not connected to LMS
  673. var ppfunc = function powerPoleFunction() { fetchPowerState(powerPoleFunction.dev); }
  674. ppfunc.dev = dev;
  675. if(dev.polltimer){ clearInterval(dev.polltimer); delete dev.polltimer; }
  676. dev.polltimer = new setInterval(ppfunc, 290000); // Poll for power state every 4 minutes 50 seconds.
  677. fetchPowerState(dev);
  678. } else {
  679. // For LMS connections, close now.
  680. dev.controlMsg({ action: 'close' });
  681. }
  682. });
  683. });
  684. });
  685. });
  686. });
  687. });
  688. });
  689. });
  690. } else {
  691. // We got a bad response
  692. if ((dev.conntype != 0) && (dev.tlsfail !== true) && (status == 408)) { // If not using CIRA and we get a 408 error while using TLS, try non-TLS.
  693. // TLS error on a local connection, try again without TLS
  694. dev.tlsfail = true; attemptInitialContact(dev); return;
  695. } else if (status == 401) {
  696. // Authentication error, see if we can use alternative credentials
  697. if (dev.acctry != null) {
  698. // Remove the first password from the trial list since it did not work.
  699. if (dev.acctry.length > 0) { dev.acctry.shift(); }
  700. // We have another password to try, hold 20 second and try the next user/password.
  701. if (dev.acctry.length > 0) {
  702. dev.consoleMsg("Holding 20 seconds and trying again with different credentials...");
  703. setTimeout(function () { if (isAmtDeviceValid(dev)) { attemptInitialContact(dev); } }, 20000); return;
  704. }
  705. }
  706. // If this device is in CCM mode and we have a bad password reset policy, do it now.
  707. if ((dev.connType == 2) && (dev.policy.badPass == 1) && (dev.mpsConnection != null) && (dev.mpsConnection.tag != null) && (dev.mpsConnection.tag.meiState != null) && (dev.mpsConnection.tag.meiState.Flags != null) && ((dev.mpsConnection.tag.meiState.Flags & 2) != 0)) {
  708. deactivateIntelAmtCCM(dev);
  709. return;
  710. }
  711. // We are unable to authenticate to this device
  712. dev.consoleMsg("Unable to connect.");
  713. // Set an error that we can't login to this device
  714. if (dev.aquired == null) { dev.aquired = {}; }
  715. dev.aquired.warn = 1; // Intel AMT Warning Flags: 1 = Unknown credentials, 2 = Realm Mismatch, 4 = TLS Cert Mismatch, 8 = Trying credentials
  716. UpdateDevice(dev);
  717. }
  718. //console.log(dev.nodeid, dev.name, dev.host, status, 'Bad response');
  719. removeAmtDevice(dev, 14);
  720. }
  721. }
  722. //
  723. // Intel AMT Database Update
  724. //
  725. // Change the current core information string and event it
  726. function UpdateDevice(dev) {
  727. // Check that the mesh exists
  728. const mesh = parent.webserver.meshes[dev.meshid];
  729. if (mesh == null) { removeAmtDevice(dev, 15); return false; }
  730. // Get the node and change it if needed
  731. parent.db.Get(dev.nodeid, function (err, nodes) {
  732. if ((nodes == null) || (nodes.length != 1)) return false;
  733. const device = nodes[0];
  734. var changes = [], change = 0, log = 0;
  735. var domain = parent.config.domains[device.domain];
  736. if (domain == null) return false;
  737. // Check if anything changes
  738. if (device.intelamt == null) { device.intelamt = {}; }
  739. if ((typeof dev.aquired.version == 'string') && (dev.aquired.version != device.intelamt.ver)) { change = 1; log = 1; device.intelamt.ver = dev.aquired.version; changes.push('AMT version'); }
  740. if ((typeof dev.aquired.user == 'string') && (dev.aquired.user != device.intelamt.user)) { change = 1; log = 1; device.intelamt.user = dev.aquired.user; changes.push('AMT user'); }
  741. if ((typeof dev.aquired.pass == 'string') && (dev.aquired.pass != device.intelamt.pass)) { change = 1; log = 1; device.intelamt.pass = dev.aquired.pass; changes.push('AMT pass'); }
  742. if ((typeof dev.aquired.mpspass == 'string') && (dev.aquired.mpspass != device.intelamt.mpspass)) { change = 1; log = 1; device.intelamt.mpspass = dev.aquired.mpspass; changes.push('AMT MPS pass'); }
  743. if ((typeof dev.aquired.host == 'string') && (dev.aquired.host != device.intelamt.host)) { change = 1; log = 1; device.intelamt.host = dev.aquired.host; changes.push('AMT host'); }
  744. if ((typeof dev.aquired.realm == 'string') && (dev.aquired.realm != device.intelamt.realm)) { change = 1; log = 1; device.intelamt.realm = dev.aquired.realm; changes.push('AMT realm'); }
  745. if ((typeof dev.aquired.hash == 'string') && (dev.aquired.hash != device.intelamt.hash)) { change = 1; log = 1; device.intelamt.hash = dev.aquired.hash; changes.push('AMT hash'); }
  746. if ((typeof dev.aquired.tls == 'number') && (dev.aquired.tls != device.intelamt.tls)) { change = 1; log = 1; device.intelamt.tls = dev.aquired.tls; /*changes.push('AMT TLS');*/ }
  747. if ((typeof dev.aquired.state == 'number') && (dev.aquired.state != device.intelamt.state)) { change = 1; log = 1; device.intelamt.state = dev.aquired.state; changes.push('AMT state'); }
  748. // Intel AMT Warning Flags: 1 = Unknown credentials, 2 = Realm Mismatch, 4 = TLS Cert Mismatch, 8 = Trying credentials
  749. if ((typeof dev.aquired.warn == 'number')) {
  750. if ((dev.aquired.warn == 0) && (device.intelamt.warn != null)) { delete device.intelamt.warn; change = 1; }
  751. else if ((dev.aquired.warn != 0) && (dev.aquired.warn != device.intelamt.warn)) { device.intelamt.warn = dev.aquired.warn; change = 1; }
  752. }
  753. // Update Intel AMT flags if needed
  754. // dev.aquired.controlMode // 1 = CCM, 2 = ACM
  755. // (node.intelamt.flags & 2) == CCM, (node.intelamt.flags & 4) == ACM
  756. var flags = 0;
  757. if (typeof device.intelamt.flags == 'number') { flags = device.intelamt.flags; }
  758. if (dev.aquired.controlMode == 1) { if ((flags & 4) != 0) { flags -= 4; } if ((flags & 2) == 0) { flags += 2; } } // CCM
  759. if (dev.aquired.controlMode == 2) { if ((flags & 4) == 0) { flags += 4; } if ((flags & 2) != 0) { flags -= 2; } } // ACM
  760. if (device.intelamt.flags != flags) { change = 1; log = 1; device.intelamt.flags = flags; changes.push('AMT flags'); }
  761. // If there are changes, event the new device
  762. if (change == 1) {
  763. // Save to the database
  764. parent.db.Set(device);
  765. // Event the node change
  766. var event = { etype: 'node', action: 'changenode', nodeid: device._id, domain: domain.id, node: parent.webserver.CloneSafeNode(device) };
  767. if (changes.length > 0) { event.msg = 'Changed device ' + device.name + ' from group ' + mesh.name + ': ' + changes.join(', '); }
  768. if ((log == 0) || ((obj.agentInfo) && (obj.agentInfo.capabilities) && (obj.agentInfo.capabilities & 0x20)) || (changes.length == 0)) { event.nolog = 1; } // If this is a temporary device, don't log changes
  769. if (parent.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the node. Another event will come.
  770. parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(device.meshid, [device._id]), obj, event);
  771. }
  772. });
  773. }
  774. // Change the current core information string and event it
  775. function ClearDeviceCredentials(dev) {
  776. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  777. // Check that the mesh exists
  778. const mesh = parent.webserver.meshes[dev.meshid];
  779. if (mesh == null) { removeAmtDevice(dev, 16); return; }
  780. // Get the node and change it if needed
  781. parent.db.Get(dev.nodeid, function (err, nodes) {
  782. if ((nodes == null) || (nodes.length != 1)) return;
  783. const device = nodes[0];
  784. var changes = [], change = 0, log = 0;
  785. var domain = parent.config.domains[device.domain];
  786. if (domain == null) return;
  787. // Check if anything changes
  788. if (device.intelamt == null) return;
  789. if (device.intelamt.user != null) { change = 1; log = 1; delete device.intelamt.user; changes.push('AMT user'); }
  790. if (device.intelamt.pass != null) { change = 1; log = 1; delete device.intelamt.pass; changes.push('AMT pass'); }
  791. // If there are changes, event the new device
  792. if (change == 1) {
  793. // Save to the database
  794. parent.db.Set(device);
  795. // Event the node change
  796. var event = { etype: 'node', action: 'changenode', nodeid: device._id, domain: domain.id, node: parent.webserver.CloneSafeNode(device) };
  797. if (changes.length > 0) { event.msg = 'Changed device ' + device.name + ' from group ' + mesh.name + ': ' + changes.join(', '); }
  798. if ((log == 0) || ((obj.agentInfo) && (obj.agentInfo.capabilities) && (obj.agentInfo.capabilities & 0x20)) || (changes.length == 0)) { event.nolog = 1; } // If this is a temporary device, don't log changes
  799. if (parent.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the node. Another event will come.
  800. parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(device.meshid, [device._id]), obj, event);
  801. }
  802. });
  803. }
  804. //
  805. // Intel AMT Power State
  806. //
  807. // Get the current power state of a device
  808. function fetchPowerState(dev) {
  809. if (isAmtDeviceValid(dev) == false) return;
  810. // Check if the agent is connected
  811. var constate = parent.GetConnectivityState(dev.nodeid);
  812. if ((constate == null) || (constate.connectivity & 1)) return; // If there is no connectivity or the agent is connected, skip trying to poll power state.
  813. // Fetch the power state
  814. dev.amtstack.BatchEnum(null, ['CIM_ServiceAvailableToElement'], function (stack, name, responses, status) {
  815. const dev = stack.dev;
  816. if (obj.amtDevices[dev.nodeid] == null) return; // Device no longer exists, ignore this response.
  817. if ((status != 200) || (responses['CIM_ServiceAvailableToElement'] == null) || (responses['CIM_ServiceAvailableToElement'].responses == null) || (responses['CIM_ServiceAvailableToElement'].responses.length < 1)) return; // If the polling fails, just skip it.
  818. var powerstate = responses['CIM_ServiceAvailableToElement'].responses[0].PowerState;
  819. if ((powerstate == 2) && (dev.aquired.majorver != null) && (dev.aquired.majorver > 9)) {
  820. // Device is powered on and Intel AMT 10+, poll the OS power state.
  821. dev.amtstack.Get('IPS_PowerManagementService', function (stack, name, response, status) {
  822. const dev = stack.dev;
  823. if (obj.amtDevices[dev.nodeid] == null) return; // Device no longer exists, ignore this response.
  824. if (status != 200) return;
  825. // Convert the OS power state
  826. var meshPowerState = -1;
  827. if (response.Body.OSPowerSavingState == 2) { meshPowerState = 1; } // Fully powered (S0);
  828. else if (response.Body.OSPowerSavingState == 3) { meshPowerState = 2; } // Modern standby (We are going to call this S1);
  829. // Set OS power state - connType: 0 = CIRA, 1 = CIRA-Relay, 2 = CIRA-LMS, 3 = LAN
  830. if (meshPowerState >= 0) { parent.SetConnectivityState(dev.meshid, dev.nodeid, Date.now(), (dev.connType == 3 ? 4 : 2), meshPowerState, null, { name: dev.name }); }
  831. });
  832. } else {
  833. // Convert the power state
  834. // AMT power: 1 = Other, 2 = On, 3 = Sleep-Light, 4 = Sleep-Deep, 5 = Power Cycle (Off-Soft), 6 = Off-Hard, 7 = Hibernate (Off-Soft), 8 = Off-Soft, 9 = Power Cycle (Off-Hard), 10 = Master Bus Reset, 11 = Diagnostic Interrupt (NMI), 12 = Off-Soft Graceful, 13 = Off-Hard Graceful, 14 = Master Bus Reset Graceful, 15 = Power Cycle (Off- oft Graceful), 16 = Power Cycle (Off - Hard Graceful), 17 = Diagnostic Interrupt (INIT)
  835. // Mesh power: 0 = Unknown, 1 = S0 power on, 2 = S1 Sleep, 3 = S2 Sleep, 4 = S3 Sleep, 5 = S4 Hibernate, 6 = S5 Soft-Off, 7 = Present
  836. var meshPowerState = -1, powerConversionTable = [-1, -1, 1, 2, 3, 6, 6, 5, 6];
  837. if (powerstate < powerConversionTable.length) { meshPowerState = powerConversionTable[powerstate]; } else { powerstate = 6; }
  838. // Set power state - connType: 0 = CIRA, 1 = CIRA-Relay, 2 = CIRA-LMS, 3 = LAN
  839. if (meshPowerState >= 0) { parent.SetConnectivityState(dev.meshid, dev.nodeid, Date.now(), (dev.connType == 3 ? 4 : 2), meshPowerState, null, { name: dev.name }); }
  840. }
  841. });
  842. }
  843. // Perform a power action: 2 = Power up, 5 = Power cycle, 8 = Power down, 10 = Reset, 11 = Power on to BIOS, 12 = Reset to BIOS, 13 = Power on to BIOS with SOL, 14 = Reset to BIOS with SOL, 15 = Power on to PXE, 16 = Reset to PXE
  844. function performPowerAction(nodeid, action) {
  845. console.log('performPowerAction', nodeid, action);
  846. var devices = obj.amtDevices[nodeid];
  847. if (devices == null) return;
  848. for (var i in devices) {
  849. var dev = devices[i];
  850. // If not LMS, has a AMT stack present and is in connected state, perform power operation.
  851. if ((dev.connType != 2) && (dev.state == 1) && (dev.amtstack != null)) {
  852. parent.debug('amt', dev.name, "performPowerAction", action);
  853. dev.powerAction = action;
  854. if (action <= 10) {
  855. // Action: 2 = Power up, 5 = Power cycle, 8 = Power down, 10 = Reset
  856. try { dev.amtstack.RequestPowerStateChange(action, performPowerActionResponse); } catch (ex) { }
  857. } else {
  858. // 11 = Power on to BIOS, 12 = Reset to BIOS, 13 = Power on to BIOS with SOL, 14 = Reset to BIOS with SOL, 15 = Power on to PXE, 16 = Reset to PXE
  859. dev.amtstack.BatchEnum(null, ['*AMT_BootSettingData'], performAdvancedPowerActionResponse);
  860. }
  861. }
  862. }
  863. }
  864. // Response to Intel AMT advanced power action
  865. function performAdvancedPowerActionResponse(stack, name, responses, status) {
  866. const dev = stack.dev;
  867. const action = dev.powerAction;
  868. delete dev.powerAction;
  869. if (obj.amtDevices[dev.nodeid] == null) return; // Device no longer exists, ignore this response.
  870. if (status != 200) return;
  871. if ((responses['AMT_BootSettingData'] == null) || (responses['AMT_BootSettingData'].response == null)) return;
  872. var bootSettingData = responses['AMT_BootSettingData'].response;
  873. // Clean up parameters
  874. bootSettingData['ConfigurationDataReset'] = false;
  875. delete bootSettingData['WinREBootEnabled'];
  876. delete bootSettingData['UEFILocalPBABootEnabled'];
  877. delete bootSettingData['UEFIHTTPSBootEnabled'];
  878. delete bootSettingData['SecureBootControlEnabled'];
  879. delete bootSettingData['BootguardStatus'];
  880. delete bootSettingData['OptionsCleared'];
  881. delete bootSettingData['BIOSLastStatus'];
  882. delete bootSettingData['UefiBootParametersArray'];
  883. delete bootSettingData['RPEEnabled'];
  884. delete bootSettingData['RSEPassword']
  885. // Ready boot parameters
  886. bootSettingData['BIOSSetup'] = ((action >= 11) && (action <= 14));
  887. bootSettingData['UseSOL'] = ((action >= 13) && (action <= 14));
  888. if ((action == 11) || (action == 13) || (action == 15)) { dev.powerAction = 2; } // Power on
  889. if ((action == 12) || (action == 14) || (action == 16)) { dev.powerAction = 10; } // Reset
  890. // Set boot parameters
  891. dev.amtstack.Put('AMT_BootSettingData', bootSettingData, function (stack, name, response, status, tag) {
  892. const dev = stack.dev;
  893. if ((obj.amtDevices[dev.nodeid] == null) || (status != 200)) return; // Device no longer exists or error
  894. // Set boot config
  895. dev.amtstack.SetBootConfigRole(1, function (stack, name, response, status, tag) {
  896. const dev = stack.dev;
  897. if ((obj.amtDevices[dev.nodeid] == null) || (status != 200)) return; // Device no longer exists or error
  898. // Set boot order
  899. var bootDevice = (action === 15 || action === 16) ? '<Address xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing">http://schemas.xmlsoap.org/ws/2004/08/addressing</Address><ReferenceParameters xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing"><ResourceURI xmlns="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting</ResourceURI><SelectorSet xmlns="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd"><Selector Name="InstanceID">Intel(r) AMT: Force PXE Boot</Selector></SelectorSet></ReferenceParameters>' : null;
  900. dev.amtstack.CIM_BootConfigSetting_ChangeBootOrder(bootDevice, function (stack, name, response, status) {
  901. const dev = stack.dev;
  902. if ((obj.amtDevices[dev.nodeid] == null) || (status != 200)) return; // Device no longer exists or error
  903. // Perform power action
  904. try { dev.amtstack.RequestPowerStateChange(dev.powerAction, performPowerActionResponse); } catch (ex) { }
  905. }, 0, 1);
  906. }, 0, 1);
  907. }, 0, 1);
  908. }
  909. // Response to Intel AMT power action
  910. function performPowerActionResponse(stack, name, responses, status) {
  911. const dev = stack.dev;
  912. const action = dev.powerAction;
  913. delete dev.powerAction;
  914. if (obj.amtDevices[dev.nodeid] == null) return; // Device no longer exists, ignore this response.
  915. if (status != 200) return;
  916. // If this is Intel AMT 10 or higher and we are trying to wake the device, send an OS wake.
  917. // This will wake the device from "Modern Standby".
  918. if ((action == 2) && (dev.aquired.majorver > 9)) {
  919. try { dev.amtstack.RequestOSPowerStateChange(2, function (stack, name, response, status) { }); } catch (ex) { }
  920. }
  921. }
  922. //
  923. // Intel AMT One Click Recovery
  924. //
  925. // Perform Intel AMT One Click Recovery on a device
  926. function performOneClickRecoveryAction(nodeid, file) {
  927. var devices = obj.amtDevices[nodeid];
  928. if (devices == null) return;
  929. for (var i in devices) {
  930. var dev = devices[i];
  931. // If not LMS, has a AMT stack present and is in connected state, perform operation.
  932. if ((dev.connType != 2) && (dev.state == 1) && (dev.amtstack != null)) {
  933. // Make sure the MPS server root certificate is present.
  934. // Start by looking at existing certificates.
  935. dev.ocrfile = file;
  936. dev.amtstack.BatchEnum(null, ['AMT_PublicKeyCertificate', '*AMT_BootCapabilities'], performOneClickRecoveryActionEx);
  937. }
  938. }
  939. }
  940. // Response with list of certificates in Intel AMT
  941. function performOneClickRecoveryActionEx(stack, name, responses, status) {
  942. const dev = stack.dev;
  943. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  944. if (status != 200) { dev.consoleMsg("Failed to get security information (" + status + ")."); delete dev.ocrfile; return; }
  945. // Check if this Intel AMT device supports OCR
  946. if (responses['AMT_BootCapabilities'].response['ForceUEFIHTTPSBoot'] !== true) {
  947. dev.consoleMsg("This Intel AMT device does not support UEFI HTTPS boot (" + status + ")."); delete dev.ocrfile; return;
  948. }
  949. // Organize the certificates and add the MPS root cert if missing
  950. var xxCertificates = responses['AMT_PublicKeyCertificate'].responses;
  951. for (var i in xxCertificates) {
  952. xxCertificates[i].TrustedRootCertficate = (xxCertificates[i]['TrustedRootCertficate'] == true);
  953. xxCertificates[i].X509CertificateBin = Buffer.from(xxCertificates[i]['X509Certificate'], 'base64').toString('binary');
  954. xxCertificates[i].XIssuer = parseCertName(xxCertificates[i]['Issuer']);
  955. xxCertificates[i].XSubject = parseCertName(xxCertificates[i]['Subject']);
  956. }
  957. dev.policy.certificates = xxCertificates;
  958. attemptRootCertSync(dev, performOneClickRecoveryActionEx2, true);
  959. }
  960. // MPS root certificate was added
  961. function performOneClickRecoveryActionEx2(dev) {
  962. // Ask for Boot Settings Data
  963. dev.amtstack.Get('AMT_BootSettingData', performOneClickRecoveryActionEx3, 0, 1);
  964. }
  965. // Getting Intel AMT Boot Settings Data
  966. function performOneClickRecoveryActionEx3(stack, name, response, status) {
  967. const dev = stack.dev;
  968. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  969. if (status != 200) { dev.consoleMsg("Failed to get boot settings data (" + status + ")."); delete dev.ocrfile; return; }
  970. // Generate the one-time URL.
  971. var cookie = obj.parent.encodeCookie({ a: 'f', f: dev.ocrfile }, obj.parent.loginCookieEncryptionKey)
  972. var url = 'https://' + parent.webserver.certificates.AmtMpsName + ':' + ((parent.args.mpsaliasport != null) ? parent.args.mpsaliasport : parent.args.mpsport) + '/c/' + cookie + '.efi';
  973. delete dev.ocrfile;
  974. // Generate the boot data for OCR with URL
  975. var r = response.Body;
  976. r['BIOSPause'] = false;
  977. r['BIOSSetup'] = false;
  978. r['EnforceSecureBoot'] = false;
  979. r['UefiBootParametersArray'] = Buffer.from(makeUefiBootParam(1, url) + makeUefiBootParam(20, 1, 1) + makeUefiBootParam(30, 0, 2), 'binary').toString('base64');
  980. r['UefiBootNumberOfParams'] = 3;
  981. r['BootMediaIndex'] = 0; // Do not use boot media index for One Click Recovery (OCR)
  982. // Set the boot order to null, this is needed for some Intel AMT versions that don't clear this automatically.
  983. dev.amtstack.CIM_BootConfigSetting_ChangeBootOrder(null, function (stack, name, response, status) {
  984. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  985. if (status != 200) { dev.consoleMsg("Failed to set boot order (" + status + ")."); return; }
  986. dev.amtstack.Put('AMT_BootSettingData', r, performOneClickRecoveryActionEx4, 0, 1);
  987. }, 0, 1);
  988. }
  989. // Intel AMT Put Boot Settings
  990. function performOneClickRecoveryActionEx4(stack, name, response, status) {
  991. const dev = stack.dev;
  992. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  993. if (status != 200) { dev.consoleMsg("Failed to set boot settings data (" + status + ")."); return; }
  994. dev.amtstack.SetBootConfigRole(1, function (stack, name, response, status) {
  995. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  996. if (status != 200) { dev.consoleMsg("Failed to set boot config role (" + status + ")."); return; }
  997. dev.amtstack.CIM_BootConfigSetting_ChangeBootOrder('<Address xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing">http://schemas.xmlsoap.org/ws/2004/08/addressing</Address><ReferenceParameters xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing"><ResourceURI xmlns="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting</ResourceURI><SelectorSet xmlns="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd"><Selector Name="InstanceID">Intel(r) AMT: Force OCR UEFI HTTPS Boot</Selector></SelectorSet></ReferenceParameters>', function (stack, name, response, status) {
  998. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  999. if (status != 200) { dev.consoleMsg("Failed to set boot config (" + status + ")."); return; }
  1000. dev.amtstack.RequestPowerStateChange(10, function (stack, name, response, status) { // 10 = Reset, 2 = Power Up
  1001. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1002. if (status != 200) { dev.consoleMsg("Failed to perform power action (" + status + ")."); return; }
  1003. console.log('One Click Recovery Completed.');
  1004. });
  1005. });
  1006. }, 0, 1);
  1007. }
  1008. //
  1009. // Intel AMT Clock Syncronization
  1010. //
  1011. // Attempt to sync the Intel AMT clock if needed, call func back when done.
  1012. // Care should be take not to have many pending WSMAN called when performing clock sync.
  1013. function attemptSyncClock(dev, func) {
  1014. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1015. if (dev.policy.amtPolicy == 0) { func(dev); return; } // If there is no Intel AMT policy, skip this operation.
  1016. dev.taskCount = 1;
  1017. dev.taskCompleted = func;
  1018. dev.amtstack.AMT_TimeSynchronizationService_GetLowAccuracyTimeSynch(attemptSyncClockEx);
  1019. }
  1020. // Intel AMT clock query response
  1021. function attemptSyncClockEx(stack, name, response, status) {
  1022. const dev = stack.dev;
  1023. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1024. if (status != 200) { dev.consoleMsg("Failed to get clock (" + status + ")."); removeAmtDevice(dev, 17); return; }
  1025. // Compute how much drift between Intel AMT and our clock.
  1026. var t = new Date(), now = new Date();
  1027. t.setTime(response.Body['Ta0'] * 1000);
  1028. if (Math.abs(t - now) > 10000) { // If the Intel AMT clock is more than 10 seconds off, set it.
  1029. dev.consoleMsg("Performing clock sync.");
  1030. var Tm1 = Math.round(now.getTime() / 1000);
  1031. dev.amtstack.AMT_TimeSynchronizationService_SetHighAccuracyTimeSynch(response.Body['Ta0'], Tm1, Tm1, attemptSyncClockSet);
  1032. } else {
  1033. // Clock is fine, we are done.
  1034. devTaskCompleted(dev)
  1035. }
  1036. }
  1037. // Intel AMT clock set response
  1038. function attemptSyncClockSet(stack, name, responses, status) {
  1039. const dev = stack.dev;
  1040. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1041. if (status != 200) { dev.consoleMsg("Failed to sync clock (" + status + ")."); removeAmtDevice(dev, 18); }
  1042. devTaskCompleted(dev)
  1043. }
  1044. //
  1045. // Intel AMT TLS setup
  1046. //
  1047. // Check if Intel AMT TLS state is correct
  1048. function attemptTlsSync(dev, func) {
  1049. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1050. if (dev.policy.amtPolicy == 0) { func(dev); return; } // If there is no Intel AMT policy, skip this operation.
  1051. dev.taskCount = 1;
  1052. dev.taskCompleted = func;
  1053. // TODO: We only deal with certificates starting with Intel AMT 6 and beyond
  1054. dev.amtstack.BatchEnum(null, ['AMT_PublicKeyCertificate', 'AMT_PublicPrivateKeyPair', 'AMT_TLSSettingData', 'AMT_TLSCredentialContext'], attemptTlsSyncEx);
  1055. }
  1056. // Intel AMT is not always in a good spot to generate a key pair. This will retry at 10 second interval.
  1057. function generateKeyPairWithRetry(dev, func) {
  1058. if (isAmtDeviceValid(dev) == false) return;
  1059. if (dev.keyPairAttempts == null) { dev.keyPairAttempts = 1; } else { dev.keyPairAttempts++; }
  1060. dev.amtstack.AMT_PublicKeyManagementService_GenerateKeyPair(0, 2048, function (stack, name, responses, status) {
  1061. if (isAmtDeviceValid(dev) == false) { delete dev.keyPairAttempts; return; }
  1062. if ((status == 200) || (dev.keyPairAttempts > 19)) {
  1063. delete dev.keyPairAttempts;
  1064. func(stack, name, responses, status);
  1065. } else {
  1066. if ((responses.Body != null) && (responses.Body.ReturnValue != null) && (responses.Body.ReturnValueStr != null)) {
  1067. dev.consoleMsg("Failed to generate a key pair (" + status + ", " + responses.Body.ReturnValue + ", \"" + responses.Body.ReturnValueStr + "\"), attempt " + dev.keyPairAttempts + ", trying again in 10 seconds...");
  1068. } else {
  1069. dev.consoleMsg("Failed to generate a key pair (" + status + "), attempt " + dev.keyPairAttempts + ", trying again in 10 seconds...");
  1070. }
  1071. // Wait 10 seconds before attempting again
  1072. var f = function doManage() { generateKeyPairWithRetry(doManage.dev, doManage.func); }
  1073. f.dev = dev;
  1074. f.func = func;
  1075. setTimeout(f, 10000);
  1076. }
  1077. });
  1078. }
  1079. function attemptTlsSyncEx(stack, name, responses, status) {
  1080. const dev = stack.dev;
  1081. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1082. if (status != 200) { dev.consoleMsg("Failed to get security information (" + status + ")."); removeAmtDevice(dev, 19); return; }
  1083. // Setup the certificates
  1084. dev.policy.certPrivateKeys = responses['AMT_PublicPrivateKeyPair'].responses;
  1085. dev.policy.tlsSettings = responses['AMT_TLSSettingData'].responses;
  1086. dev.policy.tlsCredentialContext = responses['AMT_TLSCredentialContext'].responses;
  1087. var xxCertificates = responses['AMT_PublicKeyCertificate'].responses;
  1088. for (var i in xxCertificates) {
  1089. xxCertificates[i].TrustedRootCertficate = (xxCertificates[i]['TrustedRootCertficate'] == true);
  1090. xxCertificates[i].X509CertificateBin = Buffer.from(xxCertificates[i]['X509Certificate'], 'base64').toString('binary');
  1091. xxCertificates[i].XIssuer = parseCertName(xxCertificates[i]['Issuer']);
  1092. xxCertificates[i].XSubject = parseCertName(xxCertificates[i]['Subject']);
  1093. }
  1094. amtcert_linkCertPrivateKey(xxCertificates, dev.policy.certPrivateKeys);
  1095. dev.policy.certificates = xxCertificates;
  1096. // Find the current TLS certificate & MeshCentral root certificate
  1097. var xxTlsCurrentCert = null;
  1098. if (dev.policy.tlsCredentialContext.length > 0) {
  1099. var certInstanceId = dev.policy.tlsCredentialContext[0]['ElementInContext']['ReferenceParameters']['SelectorSet']['Selector']['Value'];
  1100. for (var i in dev.policy.certificates) { if (dev.policy.certificates[i]['InstanceID'] == certInstanceId) { xxTlsCurrentCert = i; } }
  1101. }
  1102. // This is a managed device and TLS is not enabled, turn it on.
  1103. if (xxTlsCurrentCert == null) {
  1104. // Start by generating a key pair
  1105. generateKeyPairWithRetry(dev, function (stack, name, responses, status) {
  1106. const dev = stack.dev;
  1107. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1108. if (status != 200) { dev.consoleMsg("Failed to generate a key pair (" + status + ")."); removeAmtDevice(dev, 20); return; }
  1109. // Check that we get a key pair reference
  1110. var x = null;
  1111. try { x = responses.Body['KeyPair']['ReferenceParameters']['SelectorSet']['Selector']['Value']; } catch (ex) { }
  1112. if (x == null) { dev.consoleMsg("Unable to get key pair reference."); removeAmtDevice(dev, 21); return; }
  1113. // Get the new key pair
  1114. dev.amtstack.Enum('AMT_PublicPrivateKeyPair', function (stack, name, responses, status, tag) {
  1115. const dev = stack.dev;
  1116. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1117. if (status != 200) { dev.consoleMsg("Failed to get a key pair list (" + status + ")."); removeAmtDevice(dev, 22); return; }
  1118. // Get the new DER key
  1119. var DERKey = null;
  1120. for (var i in responses) { if (responses[i]['InstanceID'] == tag) { DERKey = responses[i]['DERKey']; } }
  1121. // Get certificate values
  1122. const commonName = 'IntelAMT-' + Buffer.from(parent.crypto.randomBytes(6), 'binary').toString('hex');
  1123. const domain = parent.config.domains[dev.domainid];
  1124. var serverName = 'MeshCentral';
  1125. if ((domain != null) && (domain.title != null)) { serverName = domain.title; }
  1126. const certattributes = { 'CN': commonName, 'O': serverName, 'ST': 'MC', 'C': 'MC' };
  1127. // See what root certificate to use to sign the TLS cert
  1128. var xxCaPrivateKey = obj.parent.certificates.root.key; // Use our own root by default
  1129. var issuerattributes = { 'CN': obj.rootCertCN };
  1130. if (domain.amtmanager.tlsrootcert2 != null) {
  1131. xxCaPrivateKey = domain.amtmanager.tlsrootcert2.key;
  1132. issuerattributes = domain.amtmanager.tlsrootcert2.attributes;
  1133. // TODO: We should change the start and end dates of our issued certificate to at least match the root.
  1134. // TODO: We could do one better and auto-renew TLS certificates as needed.
  1135. }
  1136. // Set the extended key usages
  1137. var extKeyUsage = { name: 'extKeyUsage', serverAuth: true, clientAuth: true }
  1138. // Sign the key pair using the CA certifiate
  1139. const cert = obj.amtcert_createCertificate(certattributes, xxCaPrivateKey, DERKey, issuerattributes, extKeyUsage);
  1140. if (cert == null) { dev.consoleMsg("Failed to sign the TLS certificate."); removeAmtDevice(dev, 23); return; }
  1141. // Place the resulting signed certificate back into AMT
  1142. var pem = obj.parent.certificateOperations.forge.pki.certificateToPem(cert).replace(/(\r\n|\n|\r)/gm, '');
  1143. // Set the certificate finderprint (SHA1)
  1144. var md = obj.parent.certificateOperations.forge.md.sha1.create();
  1145. md.update(obj.parent.certificateOperations.forge.asn1.toDer(obj.parent.certificateOperations.forge.pki.certificateToAsn1(cert)).getBytes());
  1146. dev.aquired.xhash = md.digest().toHex();
  1147. dev.amtstack.AMT_PublicKeyManagementService_AddCertificate(pem.substring(27, pem.length - 25), function (stack, name, responses, status) {
  1148. const dev = stack.dev;
  1149. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1150. if (status != 200) { dev.consoleMsg("Failed to add TLS certificate (" + status + ")."); removeAmtDevice(dev, 24); return; }
  1151. var certInstanceId = null;
  1152. try { certInstanceId = responses.Body['CreatedCertificate']['ReferenceParameters']['SelectorSet']['Selector']['Value']; } catch (ex) { }
  1153. if (certInstanceId == null) { dev.consoleMsg("Failed to get TLS certificate identifier."); removeAmtDevice(dev, 25); return; }
  1154. // Set the TLS certificate
  1155. if (dev.hbacmtls == 1) {
  1156. dev.setTlsSecurityPendingCalls = 2; // Set remote port only
  1157. } else {
  1158. dev.setTlsSecurityPendingCalls = 3; // Set local and remote port
  1159. }
  1160. if (dev.policy.tlsCredentialContext.length > 0) {
  1161. // Modify the current context
  1162. var newTLSCredentialContext = Clone(dev.policy.tlsCredentialContext[0]);
  1163. newTLSCredentialContext['ElementInContext']['ReferenceParameters']['SelectorSet']['Selector']['Value'] = certInstanceId;
  1164. dev.amtstack.Put('AMT_TLSCredentialContext', newTLSCredentialContext, amtSwitchToTls, 0, 1);
  1165. } else {
  1166. // Add a new security context
  1167. dev.amtstack.Create('AMT_TLSCredentialContext', {
  1168. 'ElementInContext': '<a:Address>/wsman</a:Address><a:ReferenceParameters><w:ResourceURI>' + dev.amtstack.CompleteName('AMT_PublicKeyCertificate') + '</w:ResourceURI><w:SelectorSet><w:Selector Name="InstanceID">' + certInstanceId + '</w:Selector></w:SelectorSet></a:ReferenceParameters>',
  1169. 'ElementProvidingContext': '<a:Address>/wsman</a:Address><a:ReferenceParameters><w:ResourceURI>' + dev.amtstack.CompleteName('AMT_TLSProtocolEndpointCollection') + '</w:ResourceURI><w:SelectorSet><w:Selector Name="ElementName">TLSProtocolEndpointInstances Collection</w:Selector></w:SelectorSet></a:ReferenceParameters>'
  1170. }, amtSwitchToTls);
  1171. }
  1172. // Figure out what index is local & remote
  1173. var localNdx = ((dev.policy != null) && (dev.policy.tlsSettings != null) && (dev.policy.tlsSettings[0] != null) && (dev.policy.tlsSettings[0]['InstanceID'] == 'Intel(r) AMT LMS TLS Settings')) ? 0 : 1, remoteNdx = (1 - localNdx);
  1174. // Remote TLS settings
  1175. var xxTlsSettings2 = Clone(dev.policy.tlsSettings);
  1176. xxTlsSettings2[remoteNdx]['Enabled'] = true;
  1177. xxTlsSettings2[remoteNdx]['MutualAuthentication'] = false;
  1178. xxTlsSettings2[remoteNdx]['AcceptNonSecureConnections'] = true;
  1179. delete xxTlsSettings2[remoteNdx]['TrustedCN'];
  1180. // Local TLS settings
  1181. xxTlsSettings2[localNdx]['Enabled'] = true;
  1182. delete xxTlsSettings2[localNdx]['TrustedCN'];
  1183. if (dev.hbacmtls == 1) {
  1184. // If we are doing Host-based TLS ACM activation, you need to only enable the remote port with TLS.
  1185. // If you enable on local port, the commit will succeed but be ignored.
  1186. dev.consoleMsg("Enabling TLS on remote port...");
  1187. if (remoteNdx == 0) { dev.amtstack.Put('AMT_TLSSettingData', xxTlsSettings2[0], amtSwitchToTls, 0, 1, xxTlsSettings2[0]); }
  1188. else { dev.amtstack.Put('AMT_TLSSettingData', xxTlsSettings2[1], amtSwitchToTls, 0, 1, xxTlsSettings2[1]); }
  1189. delete dev.hbacmtls; // Remove this indication
  1190. } else {
  1191. // Update TLS settings
  1192. dev.amtstack.Put('AMT_TLSSettingData', xxTlsSettings2[0], amtSwitchToTls, 0, 1, xxTlsSettings2[0]);
  1193. dev.amtstack.Put('AMT_TLSSettingData', xxTlsSettings2[1], amtSwitchToTls, 0, 1, xxTlsSettings2[1]);
  1194. }
  1195. });
  1196. }, responses.Body['KeyPair']['ReferenceParameters']['SelectorSet']['Selector']['Value']);
  1197. });
  1198. } else {
  1199. // Update device in the database
  1200. dev.intelamt.tls = dev.aquired.tls = 1;
  1201. UpdateDevice(dev);
  1202. // TLS is setup
  1203. devTaskCompleted(dev);
  1204. }
  1205. }
  1206. function amtSwitchToTls(stack, name, responses, status) {
  1207. const dev = stack.dev;
  1208. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1209. if (status != 200) { dev.consoleMsg("Failed setup TLS (" + status + ")."); removeAmtDevice(dev, 26); return; }
  1210. // Check if all the calls are done & perform a commit
  1211. if ((--dev.setTlsSecurityPendingCalls) == 0) {
  1212. dev.consoleMsg("Performing Commit...");
  1213. dev.amtstack.AMT_SetupAndConfigurationService_CommitChanges(null, function (stack, name, responses, status) {
  1214. const dev = stack.dev;
  1215. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1216. if (status != 200) { dev.consoleMsg("Failed perform commit (" + status + ")."); removeAmtDevice(dev, 27); return; }
  1217. dev.consoleMsg("Enabled TLS, holding 10 seconds...");
  1218. // Update device in the database
  1219. dev.intelamt.tls = dev.aquired.tls = 1;
  1220. dev.intelamt.hash = dev.aquired.hash = dev.aquired.xhash;
  1221. delete dev.aquired.xhash;
  1222. UpdateDevice(dev);
  1223. // Switch our communications to TLS (Restart our management of this node)
  1224. dev.switchToTls = 1;
  1225. delete dev.tlsfail;
  1226. // Wait 5 seconds before attempting to manage this device some more
  1227. var f = function doManage() { if (isAmtDeviceValid(dev)) { devTaskCompleted(doManage.dev); } }
  1228. f.dev = dev;
  1229. setTimeout(f, 10000);
  1230. });
  1231. }
  1232. }
  1233. //
  1234. // Intel AMT WIFI & Wired 802.1x
  1235. //
  1236. // Check which key pair matches the public key in the certificate
  1237. function amtcert_linkCertPrivateKey(certs, keys) {
  1238. for (var i in certs) {
  1239. var cert = certs[i];
  1240. try {
  1241. if (keys.length == 0) return;
  1242. var publicKeyPEM = forge.pki.publicKeyToPem(forge.pki.certificateFromAsn1(forge.asn1.fromDer(cert.X509Certificate)).publicKey).substring(28 + 32).replace(/(\r\n|\n|\r)/gm, "");
  1243. for (var j = 0; j < keys.length; j++) {
  1244. if (publicKeyPEM === (keys[j]['DERKey'] + '-----END PUBLIC KEY-----')) {
  1245. keys[j].XCert = cert; // Link the key pair to the certificate
  1246. cert.XPrivateKey = keys[j]; // Link the certificate to the key pair
  1247. }
  1248. }
  1249. } catch (e) { console.log(e); }
  1250. }
  1251. }
  1252. // This method will sync the WIFI profiles from the device and the server, but does not care about profile priority.
  1253. // We also sync wired 802.1x at the same time since we only allow a single 802.1x profile per device shared between wired and wireless
  1254. // We may want to work on an alternate version that does do priority if requested.
  1255. function attemptWifiSync(dev, func) {
  1256. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1257. if (dev.policy.amtPolicy == 0) { func(dev); return; } // If there is no Intel AMT policy, skip this operation.
  1258. if (dev.connType != 2) { func(dev); return; } // Only configure wireless over a CIRA-LMS link
  1259. //if (parent.config.domains[dev.domainid].amtmanager.wifiprofiles == null) { func(dev); return; } // No server WIFI profiles set, skip this.
  1260. //if ((dev.mpsConnection.tag.meiState == null) || (dev.mpsConnection.tag.meiState.net1 == null)) { func(dev); return; } // No WIFI on this device, skip this.
  1261. // Get the current list of WIFI profiles, wireless interface state and wired 802.1x profile
  1262. dev.taskCount = 1;
  1263. dev.taskCompleted = func;
  1264. const objQuery = ['CIM_WiFiEndpointSettings', '*CIM_WiFiPort', '*AMT_WiFiPortConfigurationService', 'CIM_IEEE8021xSettings', 'AMT_PublicKeyCertificate', 'AMT_PublicPrivateKeyPair'];
  1265. if (parent.config.domains[dev.domainid].amtmanager['802.1x'] != null) { objQuery.push('*AMT_8021XProfile'); }
  1266. dev.amtstack.BatchEnum(null, objQuery, function (stack, name, responses, status) {
  1267. const dev = stack.dev;
  1268. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1269. const domain = parent.config.domains[dev.domainid];
  1270. if ((responses['AMT_PublicKeyCertificate'] == null) || (responses['AMT_PublicKeyCertificate'].status != 200) || (responses['AMT_PublicPrivateKeyPair'] == null) || (responses['AMT_PublicPrivateKeyPair'].status != 200)) { devTaskCompleted(dev); return; } // We can't get the certificate list, fail and carry on.
  1271. // See if we need to perform wired or wireless 802.1x configuration
  1272. var wiredConfig = ((parent.config.domains[dev.domainid].amtmanager['802.1x'] != null) && (responses['AMT_8021XProfile'] != null) && (responses['AMT_8021XProfile'].status == 200));
  1273. const wirelessConfig = ((responses['CIM_WiFiEndpointSettings'] != null) && (responses['CIM_WiFiEndpointSettings'].status == 200) && (responses['AMT_WiFiPortConfigurationService'] != null) && (responses['AMT_WiFiPortConfigurationService'].status == 200) && (responses['CIM_WiFiPort'] != null) && (responses['CIM_WiFiPort'].status == 200) && (responses['CIM_IEEE8021xSettings'] != null) && (responses['CIM_IEEE8021xSettings'].status == 200));
  1274. if (!wiredConfig && !wirelessConfig) { devTaskCompleted(dev); return; } // We can't get wired or wireless settings, ignore and carry on.
  1275. // Sort out the certificates
  1276. var xxCertificates = responses['AMT_PublicKeyCertificate'].responses;
  1277. var xxCertPrivateKeys = responses['AMT_PublicPrivateKeyPair'].responses;
  1278. for (var i in xxCertificates) {
  1279. xxCertificates[i].TrustedRootCertficate = (xxCertificates[i]['TrustedRootCertficate'] == true);
  1280. xxCertificates[i].X509CertificateBin = Buffer.from(xxCertificates[i]['X509Certificate'], 'base64').toString('binary');
  1281. xxCertificates[i].XIssuer = parseCertName(xxCertificates[i]['Issuer']);
  1282. xxCertificates[i].XSubject = parseCertName(xxCertificates[i]['Subject']);
  1283. }
  1284. amtcert_linkCertPrivateKey(xxCertificates, xxCertPrivateKeys); // This links all certificates and private keys
  1285. // Remove any unlinked private keys
  1286. for (var i in xxCertPrivateKeys) {
  1287. if (!xxCertPrivateKeys[i].XCert) {
  1288. dev.amtstack.Delete('AMT_PublicPrivateKeyPair', { 'InstanceID': xxCertPrivateKeys[i]['InstanceID'] }, function (stack, name, response, status) {
  1289. //if (status == 200) { dev.consoleMsg("Removed unassigned private key pair."); }
  1290. });
  1291. }
  1292. }
  1293. // Check if wired 802.1x needs updating
  1294. var newNetAuthProfileRequested = false;
  1295. var srvNetAuthProfile = domain.amtmanager['802.1x'];
  1296. var devNetAuthProfile = null;
  1297. var netAuthClientCertInstanceId = null;
  1298. if (wiredConfig) {
  1299. var wiredMatch = 0;
  1300. devNetAuthProfile = responses['AMT_8021XProfile'].response;
  1301. if ((srvNetAuthProfile === false) && (devNetAuthProfile != null)) {
  1302. // Remove the 802.1x profile
  1303. wiredMatch = 1;
  1304. } else if ((srvNetAuthProfile != null) && (devNetAuthProfile == null)) {
  1305. // Device has no 802.1x, add it
  1306. wiredMatch = 2;
  1307. } else if ((typeof srvNetAuthProfile == 'object') && (devNetAuthProfile != null)) {
  1308. // Check if the existing 802.1x profile look good
  1309. if (devNetAuthProfile.AuthenticationProtocol != srvNetAuthProfile.authenticationprotocol) { wiredMatch = 2; }
  1310. if (devNetAuthProfile.ServerCertificateName != srvNetAuthProfile.servercertificatename) { wiredMatch = 2; }
  1311. if (devNetAuthProfile.ServerCertificateNameComparison != srvNetAuthProfile.servercertificatenamecomparison) { wiredMatch = 2; }
  1312. if (devNetAuthProfile.ActiveInS0 != srvNetAuthProfile.availableins0) { wiredMatch = 2; }
  1313. if (typeof srvNetAuthProfile.satellitecredentials != 'string') {
  1314. // Credentials for this profile are in the config file
  1315. if (devNetAuthProfile.RoamingIdentity != srvNetAuthProfile.roamingidentity) { wiredMatch = 2; }
  1316. if (devNetAuthProfile.Username != srvNetAuthProfile.username) { wiredMatch = 2; }
  1317. if (devNetAuthProfile.Domain != srvNetAuthProfile.domain) { wiredMatch = 2; }
  1318. }
  1319. // If the existing 802.1x profile has a certificate, remember the client certificate instance id for later checking
  1320. if (devNetAuthProfile.ClientCertificate) { netAuthClientCertInstanceId = devNetAuthProfile.ClientCertificate.ReferenceParameters.SelectorSet.Selector.Value; }
  1321. }
  1322. if (wiredMatch == 2) { newNetAuthProfileRequested = true; }
  1323. }
  1324. if (wirelessConfig) {
  1325. // If we have server WIFI profiles to sync, do this now.
  1326. if (parent.config.domains[dev.domainid].amtmanager.wifiprofiles != null) {
  1327. // The server and device WIFI profiles, find profiles to add and remove
  1328. const sevProfiles = parent.config.domains[dev.domainid].amtmanager.wifiprofiles;
  1329. const devProfiles = responses['CIM_WiFiEndpointSettings'].responses;
  1330. const netAuthProfiles = responses['CIM_IEEE8021xSettings'].responses;
  1331. var profilesToAdd = [], profilesToRemove = [];
  1332. var profilesToAdd2 = [], profilesToRemove2 = [];
  1333. // Look at the WIFI profiles in the device
  1334. for (var i in sevProfiles) {
  1335. var sevProfile = sevProfiles[i], wirelessMatch = false;
  1336. for (var j in devProfiles) {
  1337. var devProfile = devProfiles[j];
  1338. if (
  1339. (devProfile.ElementName == sevProfile.name) &&
  1340. (devProfile.SSID == sevProfile.ssid) &&
  1341. (devProfile.AuthenticationMethod == sevProfile.authentication) &&
  1342. (devProfile.EncryptionMethod == sevProfile.encryption) &&
  1343. (devProfile.BSSType == sevProfile.type)
  1344. ) {
  1345. if (([5, 7, 32768, 32769].indexOf(sevProfile.authentication)) >= 0) {
  1346. // This is a 802.1x profile, do some extra matching.
  1347. // Start by finding the 802.1x profile for this WIFI profile
  1348. var netAuthProfile = null, netAuthMatch = false;
  1349. for (var k in netAuthProfiles) { if (netAuthProfiles[k].ElementName == devProfile.ElementName) { netAuthProfile = netAuthProfiles[k]; } }
  1350. if (netAuthProfile != null) {
  1351. netAuthMatch = true;
  1352. if (srvNetAuthProfile.authenticationprotocol != netAuthProfile['AuthenticationProtocol']) { netAuthMatch = false; }
  1353. if (srvNetAuthProfile.roamingidentity != netAuthProfile['RoamingIdentity']) { netAuthMatch = false; }
  1354. if (srvNetAuthProfile.servercertificatename != netAuthProfile['ServerCertificateName']) { netAuthMatch = false; }
  1355. if (srvNetAuthProfile.servercertificatenamecomparison != netAuthProfile['ServerCertificateNameComparison']) { netAuthMatch = false; }
  1356. if (typeof srvNetAuthProfile.satellitecredentials != 'string') {
  1357. // Credentials for this profile are in the config file
  1358. if (srvNetAuthProfile.username != netAuthProfile['Username']) { netAuthMatch = false; }
  1359. if (srvNetAuthProfile.domain != netAuthProfile['Domain']) { netAuthMatch = false; }
  1360. }
  1361. }
  1362. // TODO: If the existing 802.1x profile has a certificate, remember the client certificate instance id for later checking
  1363. if (netAuthMatch == true) {
  1364. // The 802.1x profile seems to match what we want, keep it.
  1365. wirelessMatch = true;
  1366. devProfile.match = true;
  1367. }
  1368. } else {
  1369. // Not a 802.1x profile, looks fine, keep it.
  1370. wirelessMatch = true;
  1371. devProfile.match = true;
  1372. }
  1373. }
  1374. }
  1375. if (wirelessMatch == false) { profilesToAdd.push(sevProfile); } // Add non-matching profile
  1376. if ((wirelessMatch == false) || (([5, 7, 32768, 32769].indexOf(sevProfile.authentication)) >= 0)) { profilesToAdd2.push(sevProfile); } // Add non-matching profile or 802.1x profile
  1377. }
  1378. for (var j in devProfiles) {
  1379. var devProfile = devProfiles[j];
  1380. if (devProfile.InstanceID != null) {
  1381. if (devProfile.match !== true) { profilesToRemove.push(devProfile); } // Missing profile to remove
  1382. if ((devProfile.match !== true) || (([5, 7, 32768, 32769].indexOf(devProfile.AuthenticationMethod)) >= 0)) { profilesToRemove2.push(devProfile); } // Missing profile to remove or 802.1x profile
  1383. }
  1384. }
  1385. // Compute what priorities are allowed
  1386. var prioritiesInUse = [];
  1387. for (var j in devProfiles) { if (devProfiles[j].match == true) { prioritiesInUse.push(devProfiles[j].Priority); } }
  1388. // Check if any other WIFI profiles require a 802.1x request to MeshCentral Satellite
  1389. if (dev.netAuthCredentials == null) {
  1390. for (var i in profilesToAdd) { if (([5, 7, 32768, 32769].indexOf(profilesToAdd[i].authentication)) >= 0) { newNetAuthProfileRequested = true; } }
  1391. }
  1392. // If we need to request a new 802.1x profile, remove all existing 802.1x WIFI profiles and re-add later.
  1393. if (newNetAuthProfileRequested) {
  1394. profilesToAdd = profilesToAdd2; // Just use the second list we built for this purpose.
  1395. profilesToRemove = profilesToRemove2;
  1396. }
  1397. // Notify of WIFI profile changes
  1398. if ((profilesToAdd.length > 0) || (profilesToRemove.length > 0)) { dev.consoleMsg("Changing WIFI profiles, adding " + profilesToAdd.length + ", removing " + profilesToRemove.length + "."); }
  1399. // Remove any extra WIFI profiles
  1400. for (var i in profilesToRemove) {
  1401. dev.amtstack.Delete('CIM_WiFiEndpointSettings', { InstanceID: 'Intel(r) AMT:WiFi Endpoint Settings ' + profilesToRemove[i].ElementName }, function (stack, name, responses, status) { }, 0, 1);
  1402. }
  1403. }
  1404. }
  1405. // Check the 802.1x client certificate expiration time
  1406. // TODO: We are only getting the client cert from the wired 802.1x profile, need to get it for wireless too.
  1407. var netAuthClientCert = null;
  1408. if (netAuthClientCertInstanceId != null) {
  1409. netAuthClientCert = getInstance(responses['AMT_PublicKeyCertificate'].responses, netAuthClientCertInstanceId);
  1410. if (netAuthClientCert) {
  1411. var cert = null;
  1412. try { cert = obj.parent.certificateOperations.forge.pki.certificateFromAsn1(obj.parent.certificateOperations.forge.asn1.fromDer(obj.parent.certificateOperations.forge.util.decode64(netAuthClientCert.X509Certificate))); } catch (ex) { }
  1413. if (cert != null) {
  1414. const certStart = new Date(cert.validity.notBefore).getTime();
  1415. const certEnd = new Date(cert.validity.notAfter).getTime();
  1416. const certMidPoint = certStart + ((certEnd - certStart) / 2);
  1417. if (Date.now() > certMidPoint) { newNetAuthProfileRequested = true; } // Past mid-point or expired, request a new 802.1x certificate & profile
  1418. }
  1419. }
  1420. }
  1421. // Figure out if there are no changes to 802.1x wired configuration
  1422. if ((wiredMatch == 0) && (newNetAuthProfileRequested == false)) { wiredConfig = false; }
  1423. // See if we need to ask MeshCentral Satellite for a new 802.1x profile
  1424. if (newNetAuthProfileRequested && (typeof srvNetAuthProfile.satellitecredentials == 'string')) {
  1425. // Credentials for this 802.1x profile are provided using MeshCentral Satellite
  1426. // Send a message to Satellite requesting a 802.1x profile for this device
  1427. dev.consoleMsg("Requesting 802.1x credentials for " + netAuthStrings[srvNetAuthProfile.authenticationprotocol] + " from MeshCentral Satellite...");
  1428. dev.netAuthSatReqId = Buffer.from(parent.crypto.randomBytes(16), 'binary').toString('base64'); // Generate a crypto-secure request id.
  1429. dev.netAuthSatReqData = { domain: domain, wiredConfig: wiredConfig, wirelessConfig: wirelessConfig, devNetAuthProfile: devNetAuthProfile, srvNetAuthProfile: srvNetAuthProfile, profilesToAdd: profilesToAdd, prioritiesInUse: prioritiesInUse, responses: responses, xxCertificates: xxCertificates, xxCertPrivateKeys: xxCertPrivateKeys }
  1430. const request = { action: 'satellite', subaction: '802.1x-ProFile-Request', satelliteFlags: 2, nodeid: dev.nodeid, icon: dev.icon, domain: dev.nodeid.split('/')[1], nolog: 1, reqid: dev.netAuthSatReqId, authProtocol: srvNetAuthProfile.authenticationprotocol, devname: dev.name, osname: dev.rname, ver: dev.intelamt.ver };
  1431. if (netAuthClientCert != null) { request.cert = netAuthClientCert.X509Certificate; request.certid = netAuthClientCertInstanceId; }
  1432. parent.DispatchEvent([srvNetAuthProfile.satellitecredentials], obj, request);
  1433. // Set a response timeout
  1434. const netAuthTimeoutFunc = function netAuthTimeout() {
  1435. if (isAmtDeviceValid(netAuthTimeout.dev) == false) return; // Device no longer exists, ignore this request.
  1436. if (dev.netAuthSatReqId != null) {
  1437. delete netAuthTimeout.dev.netAuthSatReqId;
  1438. delete netAuthTimeout.dev.netAuthSatReqData;
  1439. netAuthTimeout.dev.consoleMsg("MeshCentral Satellite did not respond in time, 802.1x profile will not be set.");
  1440. devTaskCompleted(netAuthTimeout.dev);
  1441. }
  1442. }
  1443. netAuthTimeoutFunc.dev = dev;
  1444. dev.netAuthSatReqTimer = setTimeout(netAuthTimeoutFunc, 20000);
  1445. return;
  1446. } else {
  1447. // No need to call MeshCentral Satellite for a 802.1x profile, so configure everything now.
  1448. attempt8021xSyncEx(dev, { domain: domain, wiredConfig: wiredConfig, wirelessConfig: wirelessConfig, devNetAuthProfile: devNetAuthProfile, srvNetAuthProfile: srvNetAuthProfile, profilesToAdd: profilesToAdd, prioritiesInUse: prioritiesInUse, responses: responses, xxCertificates: xxCertificates, xxCertPrivateKeys: xxCertPrivateKeys });
  1449. }
  1450. });
  1451. }
  1452. // Check 802.1x root certificate
  1453. function perform8021xRootCertCheck(dev) {
  1454. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1455. // Check if there is a root certificate to add, if we already have it, get the instance id.
  1456. if (dev.netAuthCredentials.rootcert) {
  1457. var matchingRootCertId = null;
  1458. for (var i in dev.netAuthSatReqData.xxCertificates) {
  1459. if ((dev.netAuthSatReqData.xxCertificates[i].X509Certificate == dev.netAuthCredentials.rootcert) && (dev.netAuthSatReqData.xxCertificates[i].TrustedRootCertficate)) {
  1460. matchingRootCertId = dev.netAuthSatReqData.xxCertificates[i].InstanceID;
  1461. }
  1462. }
  1463. if (matchingRootCertId == null) {
  1464. // Root certificate not found, add it
  1465. dev.consoleMsg("Setting up new 802.1x root certificate...");
  1466. const f = function perform8021xRootCertCheckResponse(stack, name, response, status) {
  1467. if ((status != 200) || (response.Body['ReturnValue'] != 0)) {
  1468. // Failed to add the root certificate
  1469. dev.consoleMsg("Failed to sign the certificate request.");
  1470. } else {
  1471. // Root certificate added, move on to client certificate checking
  1472. perform8021xRootCertCheckResponse.dev.netAuthSatReqData.rootCertInstanceId = response.Body.CreatedCertificate.ReferenceParameters.SelectorSet.Selector.Value;
  1473. perform8021xClientCertCheck(perform8021xRootCertCheckResponse.dev);
  1474. }
  1475. }
  1476. f.dev = dev;
  1477. dev.amtstack.AMT_PublicKeyManagementService_AddTrustedRootCertificate(dev.netAuthCredentials.rootcert, f);
  1478. } else {
  1479. // Root certificate already present, move on to client certificate checking
  1480. dev.netAuthSatReqData.rootCertInstanceId = matchingRootCertId;
  1481. perform8021xClientCertCheck(dev);
  1482. }
  1483. } else {
  1484. // No root certificate to check, move on to client certificate checking
  1485. perform8021xClientCertCheck(dev);
  1486. }
  1487. }
  1488. // Check 802.1x client certificate
  1489. function perform8021xClientCertCheck(dev) {
  1490. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1491. if (dev.netAuthCredentials.certificate) {
  1492. // The new 802.1x profile includes a new certificate, add it now before adding the 802.1x profiles
  1493. // dev.netAuthCredentials.certificate must be in DER encoded format
  1494. dev.consoleMsg("Setting up new 802.1x client certificate...");
  1495. const f = function AddCertificateResponse(stack, name, response, status) {
  1496. if ((status != 200) || (response.Body['ReturnValue'] != 0)) {
  1497. AddCertificateResponse.dev.consoleMsg("Unable to set 802.1x certificate.");
  1498. } else {
  1499. // Keep the certificate reference since we need it to add 802.1x profiles
  1500. const certInstanceId = response.Body.CreatedCertificate.ReferenceParameters.SelectorSet.Selector.Value;
  1501. // Set the 802.1x wired profile in the device
  1502. AddCertificateResponse.dev.consoleMsg("Setting MeshCentral Satellite 802.1x profile...");
  1503. const netAuthSatReqData = AddCertificateResponse.dev.netAuthSatReqData;
  1504. delete dev.netAuthSatReqData;
  1505. netAuthSatReqData.certInstanceId = certInstanceId;
  1506. attempt8021xSyncEx(AddCertificateResponse.dev, netAuthSatReqData);
  1507. }
  1508. }
  1509. f.dev = dev;
  1510. dev.amtstack.AMT_PublicKeyManagementService_AddCertificate(dev.netAuthCredentials.certificate, f);
  1511. } else {
  1512. // No 802.1x certificate, set the 802.1x wired profile in the device
  1513. dev.consoleMsg("Setting MeshCentral Satellite 802.1x profile...");
  1514. const netAuthSatReqData = dev.netAuthSatReqData;
  1515. delete dev.netAuthSatReqData;
  1516. if (dev.netAuthCredentials.certid) { netAuthSatReqData.certInstanceId = dev.netAuthCredentials.certid; } // If we are reusing an existing certificate, set that now.
  1517. attempt8021xSyncEx(dev, netAuthSatReqData);
  1518. }
  1519. }
  1520. // Set the 802.1x wired profile
  1521. function attempt8021xSyncEx(dev, devNetAuthData) {
  1522. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1523. // Unpack
  1524. const domain = devNetAuthData.domain;
  1525. const devNetAuthProfile = devNetAuthData.devNetAuthProfile;
  1526. const srvNetAuthProfile = devNetAuthData.srvNetAuthProfile;
  1527. const profilesToAdd = devNetAuthData.profilesToAdd;
  1528. const responses = devNetAuthData.responses;
  1529. const wiredConfig = devNetAuthData.wiredConfig;
  1530. const wirelessConfig = devNetAuthData.wirelessConfig;
  1531. if (wiredConfig) {
  1532. var netAuthProfile = Clone(devNetAuthProfile);
  1533. netAuthProfile['Enabled'] = ((srvNetAuthProfile != null) && (typeof srvNetAuthProfile == 'object'));
  1534. if (netAuthProfile['Enabled']) {
  1535. netAuthProfile['ActiveInS0'] = (srvNetAuthProfile.availableins0 !== false);
  1536. netAuthProfile['AuthenticationProtocol'] = srvNetAuthProfile.authenticationprotocol;
  1537. if (srvNetAuthProfile.roamingidentity && (srvNetAuthProfile.roamingidentity != '')) { netAuthProfile['RoamingIdentity'] = srvNetAuthProfile.roamingidentity; } else { delete netAuthProfile['RoamingIdentity']; }
  1538. if (srvNetAuthProfile.servercertificatename && (srvNetAuthProfile.servercertificatename != '')) {
  1539. netAuthProfile['ServerCertificateName'] = srvNetAuthProfile.servercertificatename;
  1540. netAuthProfile['ServerCertificateNameComparison'] = srvNetAuthProfile.servercertificatenamecomparison;
  1541. } else {
  1542. delete netAuthProfile['ServerCertificateName'];
  1543. delete netAuthProfile['ServerCertificateNameComparison'];
  1544. }
  1545. if (srvNetAuthProfile.username && (srvNetAuthProfile.username != '')) { netAuthProfile['Username'] = srvNetAuthProfile.username; } else { delete netAuthProfile['Username']; }
  1546. if (srvNetAuthProfile.password && (srvNetAuthProfile.password != '')) { netAuthProfile['Password'] = srvNetAuthProfile.password; } else { delete netAuthProfile['Password']; }
  1547. if (srvNetAuthProfile.domain && (srvNetAuthProfile.domain != '')) { netAuthProfile['Domain'] = srvNetAuthProfile.domain; } else { delete netAuthProfile['Domain']; }
  1548. if (srvNetAuthProfile.authenticationprotocol > 3) {
  1549. netAuthProfile['ProtectedAccessCredential'] = srvNetAuthProfile.protectedaccesscredentialhex;
  1550. netAuthProfile['PACPassword'] = srvNetAuthProfile.pacpassword;
  1551. } else {
  1552. delete netAuthProfile['ProtectedAccessCredential'];
  1553. delete netAuthProfile['PACPassword'];
  1554. }
  1555. // Setup Client Certificate
  1556. if (devNetAuthData.certInstanceId) {
  1557. netAuthProfile['ClientCertificate'] = '<a:Address>/wsman</a:Address><a:ReferenceParameters><w:ResourceURI>' + dev.amtstack.CompleteName('AMT_PublicKeyCertificate') + '</w:ResourceURI><w:SelectorSet><w:Selector Name="InstanceID">' + devNetAuthData.certInstanceId + '</w:Selector></w:SelectorSet></a:ReferenceParameters>';
  1558. } else {
  1559. delete netAuthProfile['ClientCertificate'];
  1560. }
  1561. // Setup Server Certificate
  1562. if (devNetAuthData.rootCertInstanceId) {
  1563. netAuthProfile['ServerCertificateIssuer'] = '<a:Address>/wsman</a:Address><a:ReferenceParameters><w:ResourceURI>' + dev.amtstack.CompleteName('AMT_PublicKeyCertificate') + '</w:ResourceURI><w:SelectorSet><w:Selector Name="InstanceID">' + devNetAuthData.rootCertInstanceId + '</w:Selector></w:SelectorSet></a:ReferenceParameters>';
  1564. } else {
  1565. delete netAuthProfile['ServerCertificateIssuer'];
  1566. }
  1567. netAuthProfile['PxeTimeout'] = (typeof srvNetAuthProfile.pxetimeoutinseconds == 'number') ? srvNetAuthProfile.pxetimeoutinseconds : 120;
  1568. // If we have a MeshCentral Satellite profile, use that
  1569. if (dev.netAuthCredentials != null) {
  1570. const srvNetAuthProfile2 = dev.netAuthCredentials;
  1571. if (srvNetAuthProfile2.username && (srvNetAuthProfile2.username != '')) { netAuthProfile['Username'] = srvNetAuthProfile2.username; }
  1572. if (srvNetAuthProfile2.password && (srvNetAuthProfile2.password != '')) { netAuthProfile['Password'] = srvNetAuthProfile2.password; }
  1573. if (srvNetAuthProfile2.domain && (srvNetAuthProfile2.domain != '')) { netAuthProfile['Domain'] = srvNetAuthProfile2.domain; }
  1574. }
  1575. }
  1576. dev.amtstack.Put('AMT_8021XProfile', netAuthProfile, function (stack, name, responses, status) {
  1577. const dev = stack.dev;
  1578. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1579. if (status == 200) { dev.consoleMsg("802.1x wired profile set."); } else { dev.consoleMsg("Unable to set 802.1x wired profile."); }
  1580. attemptWifiSyncEx(dev, devNetAuthData);
  1581. });
  1582. } else {
  1583. // No wired interface, skip with WIFI config
  1584. attemptWifiSyncEx(dev, devNetAuthData);
  1585. }
  1586. }
  1587. function attemptWifiSyncEx(dev, devNetAuthData) {
  1588. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1589. // Unpack
  1590. const domain = devNetAuthData.domain;
  1591. const devNetAuthProfile = devNetAuthData.devNetAuthProfile;
  1592. const srvNetAuthProfile = devNetAuthData.srvNetAuthProfile;
  1593. const profilesToAdd = devNetAuthData.profilesToAdd;
  1594. const responses = devNetAuthData.responses;
  1595. const prioritiesInUse = devNetAuthData.prioritiesInUse;
  1596. const wiredConfig = devNetAuthData.wiredConfig;
  1597. const wirelessConfig = devNetAuthData.wirelessConfig;
  1598. var taskCounter = 0;
  1599. if (wirelessConfig) {
  1600. // Add missing WIFI profiles
  1601. var nextPriority = 1;
  1602. for (var i in profilesToAdd) {
  1603. while (prioritiesInUse.indexOf(nextPriority) >= 0) { nextPriority++; } // Figure out the next available priority slot.
  1604. var profileToAdd = profilesToAdd[i];
  1605. const wifiep = {
  1606. __parameterType: 'reference',
  1607. __resourceUri: 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpoint',
  1608. Name: 'WiFi Endpoint 0'
  1609. };
  1610. const wifiepsettinginput = {
  1611. __parameterType: 'instance',
  1612. __namespace: 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_WiFiEndpointSettings',
  1613. ElementName: profileToAdd.name,
  1614. InstanceID: 'Intel(r) AMT:WiFi Endpoint Settings ' + profileToAdd.name,
  1615. AuthenticationMethod: profileToAdd.authentication,
  1616. EncryptionMethod: profileToAdd.encryption,
  1617. SSID: profileToAdd.ssid,
  1618. Priority: nextPriority,
  1619. }
  1620. var netAuthProfile, netAuthSettingsClientCert, netAuthSettingsServerCaCert;
  1621. if (([4, 6].indexOf(profileToAdd.authentication)) >= 0) { wifiepsettinginput['PSKPassPhrase'] = profileToAdd.password; }
  1622. if (([5, 7, 32768, 32769].indexOf(profileToAdd.authentication)) >= 0) {
  1623. netAuthProfile = {
  1624. '__parameterType': 'instance',
  1625. '__namespace': dev.amtstack.CompleteName('CIM_IEEE8021xSettings'),
  1626. 'ElementName': '8021x-' + profileToAdd.name,
  1627. 'InstanceID': '8021x-' + profileToAdd.name,
  1628. 'ActiveInS0': (domain.amtmanager['802.1x'].availableins0 !== false),
  1629. 'AuthenticationProtocol': domain.amtmanager['802.1x'].authenticationprotocol
  1630. };
  1631. if (domain.amtmanager['802.1x'].roamingidentity) { netAuthProfile['RoamingIdentity'] = domain.amtmanager['802.1x'].roamingidentity; }
  1632. if (domain.amtmanager['802.1x'].servercertificatename) { netAuthProfile['ServerCertificateName'] = domain.amtmanager['802.1x'].servercertificatename; netAuthProfile['ServerCertificateNameComparison'] = profileToAdd['802.1x'].servercertificatenamecomparison; }
  1633. if (domain.amtmanager['802.1x'].username) { netAuthProfile['Username'] = domain.amtmanager['802.1x'].username; }
  1634. if (domain.amtmanager['802.1x'].password) { netAuthProfile['Password'] = domain.amtmanager['802.1x'].password; }
  1635. if (domain.amtmanager['802.1x'].domain) { netAuthProfile['Domain'] = domain.amtmanager['802.1x'].domain; }
  1636. if (domain.amtmanager['802.1x'].authenticationprotocol > 3) { domain.amtmanager['ProtectedAccessCredential'] = profileToAdd['802.1x'].protectedaccesscredentialhex; netAuthProfile['PACPassword'] = profileToAdd['802.1x'].pacpassword; }
  1637. // Setup Client Certificate
  1638. if (devNetAuthData.certInstanceId) {
  1639. netAuthSettingsClientCert = '<a:Address>/wsman</a:Address><a:ReferenceParameters><w:ResourceURI>' + dev.amtstack.CompleteName('AMT_PublicKeyCertificate') + '</w:ResourceURI><w:SelectorSet><w:Selector Name="InstanceID">' + devNetAuthData.certInstanceId + '</w:Selector></w:SelectorSet></a:ReferenceParameters>';
  1640. }
  1641. // Setup Server Certificate
  1642. if (devNetAuthData.rootCertInstanceId) {
  1643. netAuthSettingsServerCaCert = '<a:Address>/wsman</a:Address><a:ReferenceParameters><w:ResourceURI>' + dev.amtstack.CompleteName('AMT_PublicKeyCertificate') + '</w:ResourceURI><w:SelectorSet><w:Selector Name="InstanceID">' + devNetAuthData.rootCertInstanceId + '</w:Selector></w:SelectorSet></a:ReferenceParameters>';
  1644. }
  1645. // If we have credentials from MeshCentral Satelite, use that
  1646. if (dev.netAuthCredentials != null) {
  1647. const srvNetAuthProfile2 = dev.netAuthCredentials;
  1648. if (srvNetAuthProfile2.username && (srvNetAuthProfile2.username != '')) { netAuthProfile['Username'] = srvNetAuthProfile2.username; }
  1649. if (srvNetAuthProfile2.password && (srvNetAuthProfile2.password != '')) { netAuthProfile['Password'] = srvNetAuthProfile2.password; }
  1650. if (srvNetAuthProfile2.domain && (srvNetAuthProfile2.domain != '')) { netAuthProfile['Domain'] = srvNetAuthProfile2.domain; }
  1651. }
  1652. }
  1653. prioritiesInUse.push(nextPriority); // Occupy the priority slot and add the WIFI profile.
  1654. taskCounter++;
  1655. dev.amtstack.AMT_WiFiPortConfigurationService_AddWiFiSettings(wifiep, wifiepsettinginput, netAuthProfile, netAuthSettingsClientCert, netAuthSettingsServerCaCert, function (stack, name, response, status) {
  1656. if (status != 200) { dev.consoleMsg("Unable to set WIFI profile."); }
  1657. if (--taskCounter == 0) { attemptWifiSyncEx2(dev, devNetAuthData); } // All done, complete WIFI configuration
  1658. });
  1659. }
  1660. }
  1661. if (taskCounter == 0) { attemptWifiSyncEx2(dev, devNetAuthData); } // All done, complete WIFI configuration
  1662. }
  1663. function attemptWifiSyncEx2(dev, devNetAuthData) {
  1664. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1665. const responses = devNetAuthData.responses;
  1666. const wirelessConfig = devNetAuthData.wirelessConfig;
  1667. if (wirelessConfig) {
  1668. // Check if local WIFI profile sync is enabled, if not, enabled it.
  1669. if ((responses['AMT_WiFiPortConfigurationService'] != null) && (responses['AMT_WiFiPortConfigurationService'].response != null) && (responses['AMT_WiFiPortConfigurationService'].response['localProfileSynchronizationEnabled'] == 0)) {
  1670. responses['AMT_WiFiPortConfigurationService'].response['localProfileSynchronizationEnabled'] = 1;
  1671. dev.amtstack.Put('AMT_WiFiPortConfigurationService', responses['AMT_WiFiPortConfigurationService'].response, function (stack, name, response, status) {
  1672. if (status != 200) { dev.consoleMsg("Unable to enable local WIFI profile sync."); } else { dev.consoleMsg("Enabled local WIFI profile sync."); }
  1673. });
  1674. }
  1675. // Change the WIFI state if needed. Right now, we always enable it.
  1676. // WifiState = { 3: "Disabled", 32768: "Enabled in S0", 32769: "Enabled in S0, Sx/AC" };
  1677. var wifiState = 32769; // For now, always enable WIFI
  1678. if (responses['CIM_WiFiPort'].responses.Body.EnabledState != 32769) {
  1679. if (wifiState == 3) {
  1680. dev.amtstack.CIM_WiFiPort_RequestStateChange(wifiState, null, function (stack, name, responses, status) {
  1681. const dev = stack.dev;
  1682. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1683. if (status == 200) { dev.consoleMsg("Disabled WIFI."); }
  1684. });
  1685. } else {
  1686. dev.amtstack.CIM_WiFiPort_RequestStateChange(wifiState, null, function (stack, name, responses, status) {
  1687. const dev = stack.dev;
  1688. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1689. if (status == 200) { dev.consoleMsg("Enabled WIFI."); }
  1690. });
  1691. }
  1692. }
  1693. }
  1694. // Done
  1695. devTaskCompleted(dev);
  1696. }
  1697. // Request for a RSA key pair generation. This will be used to generate the 802.1x certificate
  1698. function attempt8021xKeyGeneration(dev) {
  1699. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1700. dev.amtstack.AMT_PublicKeyManagementService_GenerateKeyPair(0, 2048, function (stack, name, response, status) {
  1701. if ((status != 200) || (response.Body['ReturnValue'] != 0)) {
  1702. // Failed to generate a key pair
  1703. dev.consoleMsg("Failed to generate the requested RSA key pair.");
  1704. } else {
  1705. dev.amtstack.Enum('AMT_PublicPrivateKeyPair', function (stack, name, xresponse, status, keyInstanceId) {
  1706. if (status != 200) {
  1707. // Failed to get the generated key pair
  1708. dev.consoleMsg("Failed to get the generated RSA key pair.");
  1709. } else {
  1710. // We got the key pair
  1711. var DERKey = null;
  1712. for (var i in xresponse) {
  1713. if (xresponse[i]['InstanceID'] == keyInstanceId) {
  1714. // We found our matching DER key
  1715. DERKey = xresponse[i]['DERKey'];
  1716. }
  1717. }
  1718. if (DERKey == null) { dev.consoleMsg("Failed to match the generated RSA key pair."); return; }
  1719. dev.consoleMsg("Generated a RSA key pair.");
  1720. var domain = parent.config.domains[dev.domainid];
  1721. parent.DispatchEvent([domain.amtmanager['802.1x'].satellitecredentials], obj, { action: 'satellite', subaction: '802.1x-KeyPair-Response', satelliteFlags: 2, nodeid: dev.nodeid, icon: dev.icon, domain: dev.nodeid.split('/')[1], nolog: 1, reqid: dev.netAuthSatReqId, authProtocol: domain.amtmanager['802.1x'].authenticationprotocol, devname: dev.name, osname: dev.rname, DERKey: DERKey, keyInstanceId: keyInstanceId, ver: dev.intelamt.ver });
  1722. }
  1723. }, response.Body['KeyPair']['ReferenceParameters']['SelectorSet']['Selector']['Value']);
  1724. }
  1725. });
  1726. }
  1727. // 802.1x request to process a Certificate Signing Request, we ask Intel AMT to sign the request
  1728. function attempt8021xCRSRequest(dev, event) {
  1729. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1730. if ((event.response == null) || (event.response.keyInstanceId == null)) return;
  1731. var keyPair = '<a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address><a:ReferenceParameters><w:ResourceURI>http://intel.com/wbem/wscim/1/amt-schema/1/AMT_PublicPrivateKeyPair</w:ResourceURI><w:SelectorSet><w:Selector Name="InstanceID">' + event.response.keyInstanceId + '</w:Selector></w:SelectorSet></a:ReferenceParameters>'; // keyPair EPR Reference
  1732. var signingAlgorithm = 1; // 0 = SHA1-RSA, 1 = SHA256-RSA
  1733. var nullSignedCertificateRequest = event.response.csr; // DEREncodedRequest
  1734. dev.amtstack.AMT_PublicKeyManagementService_GeneratePKCS10RequestEx(keyPair, signingAlgorithm, nullSignedCertificateRequest, function (stack, name, response, status) {
  1735. if ((status != 200) || (response.Body['ReturnValue'] != 0)) {
  1736. // Failed to get the generated key pair
  1737. dev.consoleMsg("Failed to sign the certificate request.");
  1738. } else {
  1739. // We got a signed certificate request, return that to the server
  1740. dev.consoleMsg("Generated a signed certificate request.");
  1741. var domain = parent.config.domains[dev.domainid];
  1742. parent.DispatchEvent([domain.amtmanager['802.1x'].satellitecredentials], obj, { action: 'satellite', subaction: '802.1x-CSR-Response', satelliteFlags: 2, nodeid: dev.nodeid, icon: dev.icon, domain: dev.nodeid.split('/')[1], nolog: 1, reqid: dev.netAuthSatReqId, authProtocol: domain.amtmanager['802.1x'].authenticationprotocol, devname: dev.name, osname: dev.rname, signedcsr: response.Body['SignedCertificateRequest'], ver: dev.intelamt.ver });
  1743. }
  1744. });
  1745. }
  1746. //
  1747. // Intel AMT Server Root Certificate
  1748. //
  1749. // Check if Intel AMT has the server root certificate
  1750. function attemptRootCertSync(dev, func, forced) {
  1751. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1752. if (dev.policy.amtPolicy == 0) { func(dev); return; } // If there is no Intel AMT policy, skip this operation.
  1753. if (forced !== true) { if ((dev.connType != 2) || (dev.policy.ciraPolicy != 2)) { func(dev); return; } } // Server root certificate does not need to be present if CIRA is not needed and "forced" is false
  1754. if (parent.mpsserver.server == null) { func(dev); return; } // Root cert not needed if MPS is not active.
  1755. // Find the current TLS certificate & MeshCentral root certificate
  1756. var xxMeshCentralRoot = null;
  1757. if (dev.policy.tlsCredentialContext.length > 0) {
  1758. for (var i in dev.policy.certificates) { if (dev.policy.certificates[i]['X509Certificate'] == obj.rootCertBase64) { xxMeshCentralRoot = i; } }
  1759. }
  1760. // If the server root certificate is not present and we need to configure CIRA, add it
  1761. if (xxMeshCentralRoot == null) {
  1762. dev.taskCount = 1;
  1763. dev.taskCompleted = func;
  1764. dev.amtstack.AMT_PublicKeyManagementService_AddTrustedRootCertificate(obj.rootCertBase64, function (stack, name, responses, status) {
  1765. const dev = stack.dev;
  1766. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1767. if (status != 200) { dev.consoleMsg("Failed to add server root certificate (" + status + ")."); removeAmtDevice(dev, 28); return; }
  1768. dev.consoleMsg("Added server root certificate.");
  1769. devTaskCompleted(dev);
  1770. });
  1771. } else { func(dev); }
  1772. }
  1773. //
  1774. // Intel AMT CIRA Setup
  1775. //
  1776. // Check if Intel AMT has the server root certificate
  1777. // If deactivation policy is in effect, remove CIRA configuration
  1778. function attemptCiraSync(dev, func) {
  1779. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1780. if ((dev.connType != 2) || ((dev.policy.ciraPolicy != 1) && (dev.policy.ciraPolicy != 2))) { func(dev); return; } // Only setup CIRA when LMS connection is used and a CIRA policy is enabled.
  1781. // Get current CIRA settings
  1782. // TODO: We only deal with remote access starting with Intel AMT 6 and beyond
  1783. dev.taskCount = 1;
  1784. dev.taskCompleted = func;
  1785. dev.tryCount = 0;
  1786. var requests = ['*AMT_EnvironmentDetectionSettingData', 'AMT_ManagementPresenceRemoteSAP', 'AMT_RemoteAccessCredentialContext', 'AMT_RemoteAccessPolicyAppliesToMPS', 'AMT_RemoteAccessPolicyRule', '*AMT_UserInitiatedConnectionService', 'AMT_MPSUsernamePassword'];
  1787. if ((dev.aquired.majorver != null) && (dev.aquired.majorver > 11)) { requests.push('*IPS_HTTPProxyService', 'IPS_HTTPProxyAccessPoint'); }
  1788. dev.amtstack.BatchEnum(null, requests, attemptCiraSyncResponse);
  1789. }
  1790. function attemptCiraSyncResponse(stack, name, responses, status) {
  1791. const dev = stack.dev;
  1792. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1793. if ((dev.aquired.majorver != null) && (dev.aquired.majorver > 11) && (status == 400)) {
  1794. // Check if only the HTTP proxy objects failed
  1795. status = 200;
  1796. if (responses['IPS_HTTPProxyAccessPoint'].status == 400) { delete responses['IPS_HTTPProxyAccessPoint']; }
  1797. if (responses['IPS_HTTPProxyService'].status == 400) { delete responses['IPS_HTTPProxyService']; }
  1798. for (var i in responses) { if (responses[i].status != 200) { status = responses[i].status; } }
  1799. }
  1800. // If batch enumeration was not succesful, try again.
  1801. if (status != 200) {
  1802. // If we failed to get the CIRA state, try again up to 5 times.
  1803. if (dev.tryCount <= 5) {
  1804. dev.tryCount++;
  1805. var requests = ['*AMT_EnvironmentDetectionSettingData', 'AMT_ManagementPresenceRemoteSAP', 'AMT_RemoteAccessCredentialContext', 'AMT_RemoteAccessPolicyAppliesToMPS', 'AMT_RemoteAccessPolicyRule', '*AMT_UserInitiatedConnectionService', 'AMT_MPSUsernamePassword'];
  1806. if ((dev.aquired.majorver != null) && (dev.aquired.majorver > 11)) { requests.push('*IPS_HTTPProxyService', 'IPS_HTTPProxyAccessPoint'); }
  1807. dev.amtstack.BatchEnum(null, requests, attemptCiraSyncResponse);
  1808. return;
  1809. }
  1810. // We tried 5 times, give up.
  1811. dev.consoleMsg("Failed to get CIRA state (" + status + ").");
  1812. removeAmtDevice(dev, 29);
  1813. return;
  1814. }
  1815. // Check if CIRA is supported
  1816. if ((responses['AMT_UserInitiatedConnectionService'] == null) || (responses['AMT_UserInitiatedConnectionService'].response == null)) {
  1817. dev.consoleMsg("This device does not support CIRA.");
  1818. devTaskCompleted(dev);
  1819. return;
  1820. }
  1821. dev.cira = {};
  1822. dev.cira.xxRemoteAccess = responses;
  1823. dev.cira.xxEnvironementDetection = responses['AMT_EnvironmentDetectionSettingData'].response;
  1824. dev.cira.xxEnvironementDetection['DetectionStrings'] = MakeToArray(dev.cira.xxEnvironementDetection['DetectionStrings']);
  1825. dev.cira.xxCiraServers = responses['AMT_ManagementPresenceRemoteSAP'].responses;
  1826. dev.cira.xxUserInitiatedCira = responses['AMT_UserInitiatedConnectionService'].response;
  1827. dev.cira.xxRemoteAccessCredentiaLinks = responses['AMT_RemoteAccessCredentialContext'].responses;
  1828. dev.cira.xxMPSUserPass = responses['AMT_MPSUsernamePassword'].responses;
  1829. // Set CIRA initiation to BIOS & OS enabled
  1830. if (dev.cira.xxUserInitiatedCira['EnabledState'] != 32771) { // 32768: "Disabled", 32769: "BIOS enabled", 32770: "OS enable", 32771: "BIOS & OS enabled"
  1831. dev.amtstack.AMT_UserInitiatedConnectionService_RequestStateChange(32771, null, function (stack, name, responses, status) { }); // This is not a critical call.
  1832. }
  1833. // Figure out policies attached to servers. Create a policy type to server table.
  1834. dev.cira.xxPolicies = { 'User': [], 'Alert': [], 'Periodic': [] };
  1835. for (var i in responses['AMT_RemoteAccessPolicyAppliesToMPS'].responses) {
  1836. var policy = responses['AMT_RemoteAccessPolicyAppliesToMPS'].responses[i];
  1837. var server = Clone(getItem(dev.cira.xxCiraServers, 'Name', getItem(policy['ManagedElement']['ReferenceParameters']['SelectorSet']['Selector'], '@Name', 'Name')['Value']));
  1838. server.MpsType = policy['MpsType']; // MpsType was added in Intel AMT 11.6
  1839. var ptype = (getItem(policy['PolicySet']['ReferenceParameters']['SelectorSet']['Selector'], '@Name', 'PolicyRuleName')['Value']).split(' ')[0];
  1840. dev.cira.xxPolicies[ptype].push(server);
  1841. }
  1842. // Fetch the server's CIRA settings
  1843. dev.cira.mpsPresent = null;
  1844. dev.cira.mpsPolicy = false;
  1845. if ((dev.policy.ciraPolicy == 2) && (parent.mpsserver.server != null)) { // parent.mpsserver.server is not null if the MPS server is listening for TCP/TLS connections
  1846. dev.cira.meshidx = dev.meshid.split('/')[2].replace(/\@/g, 'X').replace(/\$/g, 'X').substring(0, 16);
  1847. dev.cira.mpsName = parent.webserver.certificates.AmtMpsName;
  1848. var serverNameSplit = dev.cira.mpsName.split('.');
  1849. dev.cira.mpsPort = ((parent.args.mpsaliasport != null) ? parent.args.mpsaliasport : parent.args.mpsport);
  1850. dev.cira.mpsAddressFormat = 201; // 201 = FQDN, 3 = IPv4
  1851. dev.cira.mpsPass = getRandomAmtPassword();
  1852. if ((serverNameSplit.length == 4) && (parseInt(serverNameSplit[0]) == serverNameSplit[0]) && (parseInt(serverNameSplit[1]) == serverNameSplit[1]) && (parseInt(serverNameSplit[2]) == serverNameSplit[2]) && (parseInt(serverNameSplit[3]) == serverNameSplit[3])) { dev.cira.mpsAddressFormat = 3; }
  1853. // Check if our server is already present
  1854. if ((dev.cira.xxCiraServers != null) && (dev.cira.xxCiraServers.length > 0)) {
  1855. for (var i = 0; i < dev.cira.xxCiraServers.length; i++) {
  1856. var mpsServer = dev.cira.xxCiraServers[i];
  1857. if ((mpsServer.AccessInfo == dev.cira.mpsName) && (mpsServer.Port == dev.cira.mpsPort) && (mpsServer.InfoFormat == dev.cira.mpsAddressFormat)) { dev.cira.mpsPresent = mpsServer['Name']; }
  1858. }
  1859. }
  1860. // Check if our server is already present
  1861. if ((dev.cira.xxPolicies != null) && (dev.cira.xxPolicies['Periodic'].length > 0)) {
  1862. var mpsServer = dev.cira.xxPolicies['Periodic'][0];
  1863. if ((mpsServer.AccessInfo == dev.cira.mpsName) && (mpsServer.Port == dev.cira.mpsPort) && (mpsServer.InfoFormat == dev.cira.mpsAddressFormat)) { dev.cira.mpsPolicy = true; }
  1864. }
  1865. }
  1866. // Remove all MPS policies that are not ours
  1867. if (dev.cira.xxPolicies != null) {
  1868. if ((dev.cira.xxPolicies['User'] != null) && (dev.cira.xxPolicies['User'].length > 0)) { dev.consoleMsg("Removing CIRA user trigger."); dev.amtstack.Delete('AMT_RemoteAccessPolicyRule', { 'PolicyRuleName': 'User Initiated' }, function (stack, name, responses, status) { }); }
  1869. if ((dev.cira.xxPolicies['Alert'] != null) && (dev.cira.xxPolicies['Alert'].length > 0)) { dev.consoleMsg("Removing CIRA alert trigger."); dev.amtstack.Delete('AMT_RemoteAccessPolicyRule', { 'PolicyRuleName': 'Alert' }, function (stack, name, responses, status) { }); }
  1870. if ((dev.cira.xxPolicies['Periodic'] != null) && (dev.cira.xxPolicies['Periodic'].length > 0) && (dev.cira.mpsPolicy == false)) { dev.consoleMsg("Removing CIRA periodic trigger."); dev.amtstack.Delete('AMT_RemoteAccessPolicyRule', { 'PolicyRuleName': 'Periodic' }, function (stack, name, responses, status) { }); }
  1871. }
  1872. // Remove all MPS servers that are not ours
  1873. if ((dev.cira.xxCiraServers != null) && (dev.cira.xxCiraServers.length > 0)) {
  1874. for (var i = 0; i < dev.cira.xxCiraServers.length; i++) {
  1875. var mpsServer = dev.cira.xxCiraServers[i];
  1876. if ((mpsServer.AccessInfo != dev.cira.mpsName) || (mpsServer.Port != dev.cira.mpsPort) || (mpsServer.InfoFormat != dev.cira.mpsAddressFormat)) {
  1877. dev.consoleMsg("Removing MPS server.");
  1878. dev.amtstack.Delete('AMT_ManagementPresenceRemoteSAP', { 'Name': mpsServer['Name'] }, function (stack, name, responses, status) { });
  1879. }
  1880. }
  1881. }
  1882. // If we need to setup CIRA, start by checking the MPS server
  1883. // parent.mpsserver.server is not null if the MPS server is listening for TCP/TLS connections
  1884. if ((dev.policy.ciraPolicy == 2) && (parent.mpsserver.server != null)) { addMpsServer(dev); } else { checkEnvironmentDetection(dev); }
  1885. }
  1886. function addMpsServer(dev) {
  1887. // Add the MPS server if not present
  1888. if (dev.cira.mpsPresent == null) {
  1889. dev.amtstack.AMT_RemoteAccessService_AddMpServer(dev.cira.mpsName, dev.cira.mpsAddressFormat, dev.cira.mpsPort, 2, null, dev.cira.meshidx, dev.cira.mpsPass, dev.cira.mpsName, function (stack, name, response, status) {
  1890. const dev = stack.dev;
  1891. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1892. if (status != 200) { dev.consoleMsg("Failed to create new MPS server (" + status + ")."); removeAmtDevice(dev, 31); return; }
  1893. if ((response.Body.MpServer == null) || (response.Body.MpServer.ReferenceParameters == null) || (response.Body.MpServer.ReferenceParameters.SelectorSet == null) || (response.Body.MpServer.ReferenceParameters.SelectorSet.Selector == null)) { dev.consoleMsg("Create new MPS server invalid response."); removeAmtDevice(dev, 32); return; }
  1894. dev.cira.mpsPresent = getItem(response.Body.MpServer.ReferenceParameters.SelectorSet.Selector, '@Name', 'Name').Value;
  1895. dev.consoleMsg("Created new MPS server.");
  1896. addMpsPolicy(dev);
  1897. // Update the device with the MPS password
  1898. dev.aquired.mpspass = dev.cira.mpsPass;
  1899. UpdateDevice(dev);
  1900. });
  1901. } else {
  1902. // MPS server is present, check MPS trigger policy
  1903. addMpsPolicy(dev);
  1904. }
  1905. }
  1906. function addMpsPolicy(dev) {
  1907. if (dev.cira.mpsPolicy == false) {
  1908. var cilaSupport = ((dev.aquired.majorver != null) && (dev.aquired.minorver != null)) && ((dev.aquired.majorver > 11) || ((dev.aquired.majorver == 11) && (dev.aquired.minorver >= 6)));
  1909. var trigger = 2; // 1 = Alert, 2 = Periodic
  1910. // Setup extended data
  1911. var extendedData = null;
  1912. if (trigger == 2) {
  1913. var timertype = 0; // 0 = Periodic, 1 = Time of day
  1914. var exdata = IntToStr(10); // Interval trigger, 10 seconds
  1915. extendedData = Buffer.from(IntToStr(timertype) + exdata, 'binary').toString('base64');
  1916. }
  1917. // Create the MPS server references
  1918. var server1 = '<Address xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</Address><ReferenceParameters xmlns="http://schemas.xmlsoap.org/ws/2004/08/addressing"><ResourceURI xmlns="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">http://intel.com/wbem/wscim/1/amt-schema/1/AMT_ManagementPresenceRemoteSAP</ResourceURI><SelectorSet xmlns="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd"><Selector Name="Name">' + dev.cira.mpsPresent + '</Selector></SelectorSet></ReferenceParameters>';
  1919. var server2 = null;
  1920. // Put the CIRA/CILA servers in the right bins.
  1921. var ciraServers = [], cilaServers = [];
  1922. if (server1) { ciraServers.push(server1); if (server2) { ciraServers.push(server2); } }
  1923. // Go ahead and create the new CIRA/CILA policy.
  1924. dev.amtstack.AMT_RemoteAccessService_AddRemoteAccessPolicyRule(trigger, 0, extendedData, ciraServers, cilaServers, function (stack, name, responses, status) {
  1925. const dev = stack.dev;
  1926. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1927. if (status != 200) { dev.consoleMsg("Failed to create new MPS policy (" + status + ")."); removeAmtDevice(dev, 33); return; }
  1928. dev.consoleMsg("Created new MPS policy.");
  1929. checkEnvironmentDetection(dev);
  1930. });
  1931. } else {
  1932. checkEnvironmentDetection(dev);
  1933. }
  1934. }
  1935. function checkEnvironmentDetection(dev) {
  1936. var changes = false;
  1937. var editEnvironmentDetectionTmp = [];
  1938. var currentEnvDetect = dev.cira.xxEnvironementDetection['DetectionStrings'];
  1939. if (currentEnvDetect == null) { currentEnvDetect = []; }
  1940. if ((dev.policy.ciraPolicy == 2) && (parent.mpsserver.server != null)) { // ciraPolicy: 0 = Do Nothing, 1 = Clear, 2 = Set
  1941. const newEnvDetect = parent.config.domains[dev.domainid].amtmanager.environmentdetection;
  1942. if (newEnvDetect == null) {
  1943. // If no environment detection is specified in the config.json, check that we have a random environment detection
  1944. if (currentEnvDetect.length == 0) { editEnvironmentDetectionTmp = [ Buffer.from(parent.crypto.randomBytes(6), 'binary').toString('hex') ]; changes = true; }
  1945. } else {
  1946. // Check that we have exactly the correct environement detection suffixes
  1947. var mismatch = false;
  1948. if (currentEnvDetect.length != newEnvDetect.length) {
  1949. mismatch = true;
  1950. } else {
  1951. // Check if everything matches
  1952. for (var i in currentEnvDetect) { if (newEnvDetect.indexOf(currentEnvDetect[i]) == -1) { mismatch = true; } }
  1953. for (var i in newEnvDetect) { if (currentEnvDetect.indexOf(newEnvDetect[i]) == -1) { mismatch = true; } }
  1954. }
  1955. // If not, we need to set the new ones
  1956. if (mismatch == true) { editEnvironmentDetectionTmp = newEnvDetect; changes = true; }
  1957. }
  1958. } else if ((dev.policy.ciraPolicy == 1) || (parent.mpsserver.server == null)) {
  1959. // Check environment detection is clear
  1960. if (currentEnvDetect.length != 0) { editEnvironmentDetectionTmp = []; changes = true; }
  1961. }
  1962. // If we need to change the environment detection on the remote device, do it now.
  1963. if (changes == true) {
  1964. var t = Clone(dev.cira.xxEnvironementDetection);
  1965. t['DetectionStrings'] = editEnvironmentDetectionTmp;
  1966. dev.cira.envclear = (editEnvironmentDetectionTmp.length == 0);
  1967. dev.amtstack.Put('AMT_EnvironmentDetectionSettingData', t, function (stack, name, responses, status) {
  1968. const dev = stack.dev;
  1969. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1970. if (status != 200) { dev.consoleMsg("Failed to set environement detection (" + status + ")."); removeAmtDevice(dev, 34); return; }
  1971. if (dev.cira.envclear) { dev.consoleMsg("Environment detection cleared."); } else { dev.consoleMsg("Environment detection set."); }
  1972. devTaskCompleted(dev);
  1973. }, 0, 1);
  1974. } else {
  1975. devTaskCompleted(dev);
  1976. }
  1977. }
  1978. //
  1979. // Intel AMT Settings
  1980. //
  1981. function attemptSettingsSync(dev, func) {
  1982. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1983. if (dev.policy.amtPolicy == 0) { func(dev); return; } // If there is no Intel AMT policy, skip this operation.
  1984. dev.taskCount = 1;
  1985. dev.taskCompleted = func;
  1986. // Query the things we are going to be checking
  1987. var query = ['*AMT_GeneralSettings', '*AMT_RedirectionService'];
  1988. if ((dev.aquired.majorver != null) && (dev.aquired.majorver > 5)) { query.push('*CIM_KVMRedirectionSAP', '*IPS_OptInService'); }
  1989. dev.amtstack.BatchEnum('', query, attemptSettingsSyncResponse);
  1990. }
  1991. function attemptSettingsSyncResponse(stack, name, responses, status) {
  1992. const dev = stack.dev;
  1993. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  1994. if (status != 200) { devTaskCompleted(dev); return; }
  1995. // If this device does not have KVM, ignore the response. This can happen for Intel Standard Manageability (Intel(R) SM).
  1996. if ((responses['CIM_KVMRedirectionSAP'] == null) || (responses['CIM_KVMRedirectionSAP'].status == 400)) { responses['CIM_KVMRedirectionSAP'] = null; }
  1997. // Set user consent requirement to match device group user consent
  1998. const mesh = parent.webserver.meshes[dev.meshid];
  1999. if (mesh == null) { removeAmtDevice(dev, 35); return; }
  2000. const userConsentRequirement = ((typeof mesh.consent == 'number') && ((mesh.consent & 8) != 0)) ? 1 : 0; // Enable user consent for KVM if device group desktop "Prompt for user consent" is enabled.
  2001. // Check user consent requirements
  2002. if ((responses['IPS_OptInService'] != null) && (responses['IPS_OptInService'].response['OptInRequired'] != userConsentRequirement)) {
  2003. responses['IPS_OptInService'].response['OptInRequired'] = userConsentRequirement; // 0 = Not Required, 1 = Required for KVM only, 0xFFFFFFFF = Always Required
  2004. dev.amtstack.Put('IPS_OptInService', responses['IPS_OptInService'].response, function (stack, name, responses, status) {
  2005. const dev = stack.dev;
  2006. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2007. if (status == 200) {
  2008. if (userConsentRequirement == 0) {
  2009. dev.consoleMsg("Cleared user consent requirements.");
  2010. } else if (userConsentRequirement == 1) {
  2011. dev.consoleMsg("Enabled KVM user consent requirement.");
  2012. } else if (userConsentRequirement == 0xFFFFFFFF) {
  2013. dev.consoleMsg("Enabled all user consent requirement.");
  2014. }
  2015. }
  2016. }, 0, 1);
  2017. }
  2018. // Enable SOL & IDER
  2019. if ((responses['AMT_RedirectionService'].response['EnabledState'] != 32771) || (responses['AMT_RedirectionService'].response['ListenerEnabled'] == false)) {
  2020. dev.redirObj = responses['AMT_RedirectionService'].response;
  2021. dev.redirObj['ListenerEnabled'] = true;
  2022. dev.redirObj['EnabledState'] = 32771;
  2023. dev.taskCount++;
  2024. dev.amtstack.AMT_RedirectionService_RequestStateChange(32771,
  2025. function (stack, name, response, status) {
  2026. const dev = stack.dev;
  2027. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2028. dev.amtstack.Put('AMT_RedirectionService', dev.redirObj, function (stack, name, response, status) {
  2029. const dev = stack.dev;
  2030. delete dev.redirObj;
  2031. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2032. if (status == 200) { dev.consoleMsg("Enabled redirection features."); }
  2033. devTaskCompleted(dev);
  2034. }, 0, 1);
  2035. }
  2036. );
  2037. }
  2038. // Check KVM state
  2039. if ((dev.aquired.majorver != null) && (dev.aquired.majorver > 5) && (responses['CIM_KVMRedirectionSAP'] != null)) {
  2040. const kvm = ((responses['CIM_KVMRedirectionSAP'].response['EnabledState'] == 2) || (responses['CIM_KVMRedirectionSAP'].response['EnabledState'] == 6));
  2041. if (kvm == false) {
  2042. // Enable KVM
  2043. dev.taskCount++;
  2044. dev.amtstack.CIM_KVMRedirectionSAP_RequestStateChange(2, 0,
  2045. function (stack, name, response, status) {
  2046. const dev = stack.dev;
  2047. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2048. if (status == 200) { dev.consoleMsg("Enabled KVM."); }
  2049. devTaskCompleted(dev);
  2050. }
  2051. );
  2052. }
  2053. }
  2054. // Check device name and domain name
  2055. if ((dev.connType == 2) && (dev.mpsConnection != null) && (dev.mpsConnection.tag != null) && (dev.mpsConnection.tag.meiState != null) && (typeof dev.mpsConnection.tag.meiState.OsHostname == 'string') && (typeof dev.mpsConnection.tag.meiState.OsDnsSuffix == 'string')) {
  2056. const generalSettings = responses['AMT_GeneralSettings'].response;
  2057. if ((generalSettings['HostName'] != dev.mpsConnection.tag.meiState.OsHostname) || (generalSettings['DomainName'] != dev.mpsConnection.tag.meiState.OsDnsSuffix)) {
  2058. // Change the computer and domain name
  2059. generalSettings['HostName'] = dev.mpsConnection.tag.meiState.OsHostname;
  2060. generalSettings['DomainName'] = dev.mpsConnection.tag.meiState.OsDnsSuffix;
  2061. dev.taskCount++;
  2062. dev.xname = dev.mpsConnection.tag.meiState.OsHostname + '.' + dev.mpsConnection.tag.meiState.OsDnsSuffix;
  2063. dev.amtstack.Put('AMT_GeneralSettings', generalSettings, function () {
  2064. const dev = stack.dev;
  2065. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2066. if (status == 200) { dev.consoleMsg("Changed device name: " + dev.xname); }
  2067. delete dev.xname;
  2068. devTaskCompleted(dev);
  2069. }, 0, 1);
  2070. }
  2071. }
  2072. // Done
  2073. devTaskCompleted(dev);
  2074. }
  2075. //
  2076. // Intel AMT Certificate cleanup
  2077. //
  2078. // Remove any unused, non-trusted certificates
  2079. function attemptCleanCertsSync(dev, func) {
  2080. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2081. dev.amtstack.BatchEnum(null, ['AMT_PublicKeyCertificate', 'AMT_PublicPrivateKeyPair'], function (stack, name, responses, status) {
  2082. const dev = stack.dev;
  2083. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2084. const domain = parent.config.domains[dev.domainid];
  2085. if ((responses['AMT_PublicKeyCertificate'].status != 200) || (responses['AMT_PublicKeyCertificate'].status != 200)) { func(dev); return; } // We can't get the certificate list, fail and carry on.
  2086. // Sort out the certificates
  2087. var xxCertificates = responses['AMT_PublicKeyCertificate'].responses;
  2088. var xxCertPrivateKeys = responses['AMT_PublicPrivateKeyPair'].responses;
  2089. for (var i in xxCertificates) {
  2090. xxCertificates[i].TrustedRootCertficate = (xxCertificates[i]['TrustedRootCertficate'] == true);
  2091. xxCertificates[i].X509CertificateBin = Buffer.from(xxCertificates[i]['X509Certificate'], 'base64').toString('binary');
  2092. xxCertificates[i].XIssuer = parseCertName(xxCertificates[i]['Issuer']);
  2093. xxCertificates[i].XSubject = parseCertName(xxCertificates[i]['Subject']);
  2094. }
  2095. amtcert_linkCertPrivateKey(xxCertificates, xxCertPrivateKeys); // This links all certificates and private keys
  2096. dev.certDeleteTasks = 0;
  2097. // Remove any unlinked private keys
  2098. for (var i in xxCertPrivateKeys) {
  2099. if (!xxCertPrivateKeys[i].XCert) {
  2100. dev.certDeleteTasks++;
  2101. dev.amtstack.Delete('AMT_PublicPrivateKeyPair', { 'InstanceID': xxCertPrivateKeys[i]['InstanceID'] }, function (stack, name, response, status) {
  2102. //if (status == 200) { dev.consoleMsg("Removed unassigned private key pair."); }
  2103. if (--dev.certDeleteTasks == 0) { delete dev.certDeleteTasks; func(dev); }
  2104. });
  2105. }
  2106. }
  2107. // Try to remove all untrusted certificates
  2108. for (var i in xxCertificates) {
  2109. if (xxCertificates[i].TrustedRootCertficate == false) {
  2110. var privateKeyInstanceId = null;
  2111. if (xxCertificates[i].XPrivateKey) { privateKeyInstanceId = { 'InstanceID': xxCertificates[i].XPrivateKey['InstanceID'] }; }
  2112. dev.certDeleteTasks++;
  2113. dev.amtstack.Delete('AMT_PublicKeyCertificate', { 'InstanceID': xxCertificates[i]['InstanceID'] }, function (stack, name, response, status, tag) {
  2114. if ((status == 200) && (tag != null)) {
  2115. // If there is a private key, delete it.
  2116. dev.amtstack.Delete('AMT_PublicPrivateKeyPair', tag, function () {
  2117. if (--dev.certDeleteTasks == 0) { delete dev.certDeleteTasks; func(dev); }
  2118. }, 0, 1);
  2119. } else {
  2120. if (--dev.certDeleteTasks == 0) { delete dev.certDeleteTasks; func(dev); }
  2121. }
  2122. }, privateKeyInstanceId);
  2123. }
  2124. }
  2125. });
  2126. }
  2127. //
  2128. // Intel AMT Hardware Inventory and Networking
  2129. //
  2130. function attemptFetchHardwareInventory(dev, func) {
  2131. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2132. const mesh = parent.webserver.meshes[dev.meshid];
  2133. if (mesh == null) { removeAmtDevice(dev, 35); return; }
  2134. if (mesh.mtype == 1) { // If this is a Intel AMT only device group, pull the hardware inventory and network information for this device
  2135. dev.consoleMsg("Fetching hardware inventory.");
  2136. dev.taskCount = 2;
  2137. dev.taskCompleted = func;
  2138. dev.amtstack.BatchEnum('', ['*CIM_ComputerSystemPackage', 'CIM_SystemPackaging', '*CIM_Chassis', 'CIM_Chip', '*CIM_Card', '*CIM_BIOSElement', 'CIM_Processor', 'CIM_PhysicalMemory', 'CIM_MediaAccessDevice', 'CIM_PhysicalPackage'], attemptFetchHardwareInventoryResponse);
  2139. dev.amtstack.BatchEnum('', ['AMT_EthernetPortSettings'], attemptFetchNetworkResponse);
  2140. } else {
  2141. if (func) { func(dev); }
  2142. }
  2143. }
  2144. function attemptFetchNetworkResponse(stack, name, responses, status) {
  2145. const dev = stack.dev;
  2146. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2147. if (status != 200) { devTaskCompleted(dev); return; }
  2148. //console.log(JSON.stringify(responses, null, 2));
  2149. if ((responses['AMT_EthernetPortSettings'] == null) || (responses['AMT_EthernetPortSettings'].responses == null)) { devTaskCompleted(dev); return; }
  2150. // Find the wired and wireless interfaces
  2151. var wired = null, wireless = null;
  2152. for (var i in responses['AMT_EthernetPortSettings'].responses) {
  2153. var netif = responses['AMT_EthernetPortSettings'].responses[i];
  2154. if ((netif.MACAddress != null) && (netif.MACAddress != '00-00-00-00-00-00')) {
  2155. if (netif.WLANLinkProtectionLevel != null) { wireless = netif; } else { wired = netif; }
  2156. }
  2157. }
  2158. if ((wired == null) && (wireless == null)) { devTaskCompleted(dev); return; }
  2159. // Sent by the agent to update agent network interface information
  2160. var net = { netif2: {} };
  2161. if (wired != null) {
  2162. var x = {};
  2163. x.family = 'IPv4';
  2164. x.type = 'ethernet';
  2165. x.address = wired.IPAddress;
  2166. x.netmask = wired.SubnetMask;
  2167. x.mac = wired.MACAddress.split('-').join(':').toUpperCase();
  2168. x.gateway = wired.DefaultGateway;
  2169. net.netif2['Ethernet'] = [x];
  2170. }
  2171. if (wireless != null) {
  2172. var x = {};
  2173. x.family = 'IPv4';
  2174. x.type = 'wireless';
  2175. x.address = wireless.IPAddress;
  2176. x.netmask = wireless.SubnetMask;
  2177. x.mac = wireless.MACAddress.split('-').join(':').toUpperCase();
  2178. x.gateway = wireless.DefaultGateway;
  2179. net.netif2['Wireless'] = [x];
  2180. }
  2181. net.updateTime = Date.now();
  2182. net._id = 'if' + dev.nodeid;
  2183. net.type = 'ifinfo';
  2184. parent.db.Set(net);
  2185. // Event the node interface information change
  2186. parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(dev.meshid, [dev.nodeid]), obj, { action: 'ifchange', nodeid: dev.nodeid, domain: dev.nodeid.split('/')[1], nolog: 1 });
  2187. devTaskCompleted(dev);
  2188. }
  2189. /*
  2190. // http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_2.7.1.pdf
  2191. const DMTFCPUStatus = ["Unknown", "Enabled", "Disabled by User", "Disabled By BIOS (POST Error)", "Idle", "Other"];
  2192. const DMTFMemType = ["Unknown", "Other", "DRAM", "Synchronous DRAM", "Cache DRAM", "EDO", "EDRAM", "VRAM", "SRAM", "RAM", "ROM", "Flash", "EEPROM", "FEPROM", "EPROM", "CDRAM", "3DRAM", "SDRAM", "SGRAM", "RDRAM", "DDR", "DDR-2", "BRAM", "FB-DIMM", "DDR3", "FBD2", "DDR4", "LPDDR", "LPDDR2", "LPDDR3", "LPDDR4"];
  2193. const DMTFMemFormFactor = ['', "Other", "Unknown", "SIMM", "SIP", "Chip", "DIP", "ZIP", "Proprietary Card", "DIMM", "TSOP", "Row of chips", "RIMM", "SODIMM", "SRIMM", "FB-DIM"];
  2194. const DMTFProcFamilly = { // Page 46 of DMTF document
  2195. 191: "Intel&reg; Core&trade; 2 Duo Processor",
  2196. 192: "Intel&reg; Core&trade; 2 Solo processor",
  2197. 193: "Intel&reg; Core&trade; 2 Extreme processor",
  2198. 194: "Intel&reg; Core&trade; 2 Quad processor",
  2199. 195: "Intel&reg; Core&trade; 2 Extreme mobile processor",
  2200. 196: "Intel&reg; Core&trade; 2 Duo mobile processor",
  2201. 197: "Intel&reg; Core&trade; 2 Solo mobile processor",
  2202. 198: "Intel&reg; Core&trade; i7 processor",
  2203. 199: "Dual-Core Intel&reg; Celeron&reg; processor"
  2204. };
  2205. */
  2206. function attemptFetchHardwareInventoryResponse(stack, name, responses, status) {
  2207. const dev = stack.dev;
  2208. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2209. if (status != 200) { devTaskCompleted(dev); return; }
  2210. // Extract basic data
  2211. var hw = {}
  2212. hw.PlatformGUID = responses['CIM_ComputerSystemPackage'].response.PlatformGUID;
  2213. hw.Chassis = responses['CIM_Chassis'].response;
  2214. hw.Chips = responses['CIM_Chip'].responses;
  2215. hw.Card = responses['CIM_Card'].response;
  2216. hw.Bios = responses['CIM_BIOSElement'].response;
  2217. hw.Processors = responses['CIM_Processor'].responses;
  2218. hw.PhysicalMemory = responses['CIM_PhysicalMemory'].responses;
  2219. hw.MediaAccessDevice = responses['CIM_MediaAccessDevice'].responses;
  2220. hw.PhysicalPackage = responses['CIM_PhysicalPackage'].responses;
  2221. // Convert the hardware data into the same structure as we get from Windows
  2222. var hw2 = { hardware: { windows: {}, identifiers: {} } };
  2223. hw2.hardware.identifiers.product_uuid = guidToStr(hw.PlatformGUID);
  2224. if ((hw.PhysicalMemory != null) && (hw.PhysicalMemory.length > 0)) {
  2225. var memory = [];
  2226. for (var i in hw.PhysicalMemory) {
  2227. var m2 = {}, m = hw.PhysicalMemory[i];
  2228. m2.BankLabel = m.BankLabel;
  2229. m2.Capacity = m.Capacity;
  2230. if (typeof m.PartNumber == 'string') { m2.PartNumber = m.PartNumber.trim(); }
  2231. if (typeof m.PartNumber == 'number') { m2.PartNumber = m.PartNumber; }
  2232. if (typeof m.SerialNumber == 'string') { m2.SerialNumber = m.SerialNumber.trim(); }
  2233. if (typeof m.SerialNumber == 'number') { m2.SerialNumber = m.SerialNumber; }
  2234. if (typeof m.Manufacturer == 'string') { m2.Manufacturer = m.Manufacturer.trim(); }
  2235. if (typeof m.Manufacturer == 'number') { m2.Manufacturer = m.Manufacturer; }
  2236. memory.push(m2);
  2237. }
  2238. hw2.hardware.windows.memory = memory;
  2239. }
  2240. if ((hw.MediaAccessDevice != null) && (hw.MediaAccessDevice.length > 0)) {
  2241. var drives = [];
  2242. for (var i in hw.MediaAccessDevice) {
  2243. var m2 = {}, m = hw.MediaAccessDevice[i];
  2244. m2.Caption = m.DeviceID;
  2245. if (m.MaxMediaSize) { m2.Size = (m.MaxMediaSize * 1000); }
  2246. drives.push(m2);
  2247. }
  2248. hw2.hardware.identifiers.storage_devices = drives;
  2249. }
  2250. if (hw.Bios != null) {
  2251. if (typeof hw.Bios.Manufacturer == 'string') { hw2.hardware.identifiers.bios_vendor = hw.Bios.Manufacturer.trim(); }
  2252. if (typeof hw.Bios.Manufacturer == 'number') { hw2.hardware.identifiers.bios_vendor = hw.Bios.Manufacturer; }
  2253. hw2.hardware.identifiers.bios_version = hw.Bios.Version;
  2254. if (hw.Bios.ReleaseDate && hw.Bios.ReleaseDate.Datetime) { hw2.hardware.identifiers.bios_date = hw.Bios.ReleaseDate.Datetime; }
  2255. }
  2256. if (hw.PhysicalPackage != null) {
  2257. if (typeof hw.Card.Model == 'string') { hw2.hardware.identifiers.board_name = hw.Card.Model.trim(); }
  2258. if (typeof hw.Card.Model == 'number') { hw2.hardware.identifiers.board_name = hw.Card.Model; }
  2259. if (typeof hw.Card.Manufacturer == 'string') { hw2.hardware.identifiers.board_vendor = hw.Card.Manufacturer.trim(); }
  2260. if (typeof hw.Card.Manufacturer == 'number') { hw2.hardware.identifiers.board_vendor = hw.Card.Manufacturer; }
  2261. if (typeof hw.Card.Version == 'string') { hw2.hardware.identifiers.board_version = hw.Card.Version.trim(); }
  2262. if (typeof hw.Card.Version == 'number') { hw2.hardware.identifiers.board_version = hw.Card.Version; }
  2263. if (typeof hw.Card.SerialNumber == 'string') { hw2.hardware.identifiers.board_serial = hw.Card.SerialNumber.trim(); }
  2264. if (typeof hw.Card.SerialNumber == 'number') { hw2.hardware.identifiers.board_serial = hw.Card.SerialNumber; }
  2265. }
  2266. if ((hw.Chips != null) && (hw.Chips.length > 0)) {
  2267. for (var i in hw.Chips) {
  2268. if ((hw.Chips[i].ElementName == 'Managed System Processor Chip') && (hw.Chips[i].Version)) {
  2269. hw2.hardware.identifiers.cpu_name = hw.Chips[i].Version;
  2270. }
  2271. }
  2272. }
  2273. // Compute the hash of the document
  2274. hw2.hash = parent.crypto.createHash('sha384').update(JSON.stringify(hw2)).digest().toString('hex');
  2275. // Fetch system information
  2276. parent.db.GetHash('si' + dev.nodeid, function (err, results) {
  2277. var sysinfohash = null;
  2278. if ((results != null) && (results.length == 1)) { sysinfohash = results[0].hash; }
  2279. if (sysinfohash != hw2.hash) {
  2280. // Hardware information has changed, update the database
  2281. hw2._id = 'si' + dev.nodeid;
  2282. hw2.domain = dev.nodeid.split('/')[1];
  2283. hw2.time = Date.now();
  2284. hw2.type = 'sysinfo';
  2285. parent.db.Set(hw2);
  2286. // Event the new sysinfo hash, this will notify everyone that the sysinfo document was changed
  2287. var event = { etype: 'node', action: 'sysinfohash', nodeid: dev.nodeid, domain: hw2.domain, hash: hw2.hash, nolog: 1 };
  2288. parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(dev.meshid, [dev.nodeid]), obj, event);
  2289. }
  2290. });
  2291. devTaskCompleted(dev);
  2292. }
  2293. //
  2294. // Intel AMT Activation
  2295. //
  2296. function activateIntelAmt(dev) {
  2297. // Find the Intel AMT policy
  2298. const mesh = parent.webserver.meshes[dev.meshid];
  2299. if (mesh == null) { dev.consoleMsg("Unable to find device group (" + dev.meshid + ")."); removeAmtDevice(dev, 36); return false; }
  2300. var amtPolicy = 0; // 0 = Do nothing, 1 = Deactivate CCM, 2 = CCM, 3 = ACM
  2301. var ccmPolicy = 0; // Only used when in ACM policy: 0 = Do nothing, 1 = Deactivate CCM, 2 = CCM is ACM fails
  2302. if (mesh.amt != null) { if (typeof mesh.amt.type == 'number') { amtPolicy = mesh.amt.type; } if (typeof mesh.amt.ccm == 'number') { ccmPolicy = mesh.amt.ccm; } }
  2303. if ((typeof dev.mpsConnection.tag.meiState.OsAdmin != 'object') || (typeof dev.mpsConnection.tag.meiState.OsAdmin.user != 'string') || (typeof dev.mpsConnection.tag.meiState.OsAdmin.pass != 'string')) { amtPolicy = 0; }
  2304. if (amtPolicy == 0) { removeAmtDevice(dev, 37); return false; } // Do nothing, we should not have gotten this CIRA-LMS connection.
  2305. if (amtPolicy == 2) { activateIntelAmtCcm(dev, mesh.amt.password); } // Activate to CCM policy
  2306. if ((amtPolicy == 3) || (amtPolicy == 4)) { // Activate to ACM policy
  2307. var acminfo = checkAcmActivation(dev);
  2308. if ((acminfo == null) || (acminfo.err != null)) {
  2309. // No opportunity to activate to ACM, check if we are in CCM
  2310. if ((dev.mpsConnection.tag.meiState.Flags & 2) != 0) {
  2311. if ((amtPolicy == 3) && (ccmPolicy == 1)) { deactivateIntelAmtCCM(dev); } // If we are in ACM policy and CCM is not allowed, deactivate it now.
  2312. else { return true; } // We are in CCM, keep going
  2313. } else {
  2314. // We are not in CCM, go to CCM now
  2315. if ((amtPolicy == 4) || ((amtPolicy == 3) && (ccmPolicy == 2))) { activateIntelAmtCcm(dev, mesh.amt.password); } // If we are in full automatic or ACM with CCM allowed, setup CCM.
  2316. else {
  2317. // Unable to find an activation match.
  2318. if (acminfo == null) { dev.consoleMsg("No opportunity for ACM activation."); } else { dev.consoleMsg("No opportunity for ACM activation: " + acminfo.err); }
  2319. removeAmtDevice(dev, 38);
  2320. return false; // We are not in CCM and policy restricts use of CCM, so exit now.
  2321. }
  2322. }
  2323. } else {
  2324. // Found a certificate to activate to ACM.
  2325. if ((dev.mpsConnection.tag.meiState.Flags & 2) != 0) {
  2326. // We are in CCM, deactivate CCM first.
  2327. deactivateIntelAmtCCM(dev);
  2328. } else {
  2329. // We are not activated now, go to ACM directly.
  2330. // Check if we are allowed to perform TLS ACM activation
  2331. var TlsAcmActivation = false;
  2332. var domain = parent.config.domains[dev.domainid];
  2333. if (domain && domain.amtmanager && (domain.amtmanager.tlsacmactivation == true)) { TlsAcmActivation = true; }
  2334. // Check Intel AMT version
  2335. if (typeof dev.intelamt.ver == 'string') {
  2336. var verSplit = dev.intelamt.ver.split('.');
  2337. if (verSplit.length >= 2) {
  2338. dev.aquired.majorver = parseInt(verSplit[0]);
  2339. dev.aquired.minorver = parseInt(verSplit[1]);
  2340. if (verSplit.length >= 3) { dev.aquired.maintenancever = parseInt(verSplit[2]); }
  2341. }
  2342. }
  2343. // If this is Intel AMT 14 or better and allowed, we are going to attempt a host-based end-to-end TLS activation.
  2344. if (TlsAcmActivation && (dev.aquired.majorver >= 14)) {
  2345. // Perform host-based TLS ACM activation
  2346. activateIntelAmtTlsAcm(dev, mesh.amt.password, acminfo);
  2347. } else {
  2348. // Perform host-based ACM activation
  2349. activateIntelAmtAcm(dev, mesh.amt.password, acminfo);
  2350. }
  2351. }
  2352. }
  2353. }
  2354. return false;
  2355. }
  2356. function activateIntelAmtCcm(dev, password) {
  2357. // Generate a random Intel AMT password if needed
  2358. if ((password == null) || (password == '')) { password = getRandomAmtPassword(); }
  2359. dev.temp = { pass: password };
  2360. // Setup the WSMAN stack, no TLS
  2361. var comm = CreateWsmanComm(dev.nodeid, 16992, dev.mpsConnection.tag.meiState.OsAdmin.user, dev.mpsConnection.tag.meiState.OsAdmin.pass, 0, null, dev.mpsConnection); // No TLS
  2362. var wsstack = WsmanStackCreateService(comm);
  2363. dev.amtstack = AmtStackCreateService(wsstack);
  2364. dev.amtstack.dev = dev;
  2365. dev.amtstack.BatchEnum(null, ['*AMT_GeneralSettings', '*IPS_HostBasedSetupService'], activateIntelAmtCcmEx1);
  2366. }
  2367. function activateIntelAmtCcmEx1(stack, name, responses, status) {
  2368. const dev = stack.dev;
  2369. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2370. if (status != 200) { dev.consoleMsg("Failed to get Intel AMT state."); removeAmtDevice(dev, 39); return; }
  2371. if (responses['IPS_HostBasedSetupService'].response['AllowedControlModes'].length != 2) { dev.consoleMsg("Client control mode activation not allowed."); removeAmtDevice(dev, 40); return; }
  2372. // Log the activation request, logging is a required step for activation.
  2373. var domain = parent.config.domains[dev.domainid];
  2374. if (domain == null) { dev.consoleMsg("Invalid domain."); removeAmtDevice(dev, 41); return; }
  2375. if (parent.certificateOperations.logAmtActivation(domain, { time: new Date(), action: 'ccmactivate', domain: dev.domainid, amtUuid: dev.mpsConnection.tag.meiState.UUID, amtRealm: responses['AMT_GeneralSettings'].response['DigestRealm'], user: 'admin', password: dev.temp.pass, ipport: dev.mpsConnection.remoteAddr + ':' + dev.mpsConnection.remotePort, nodeid: dev.nodeid, meshid: dev.meshid, computerName: dev.name }) == false) {
  2376. dev.consoleMsg("Unable to log operation."); removeAmtDevice(dev, 42); return;
  2377. }
  2378. // Perform CCM activation
  2379. dev.amtstack.IPS_HostBasedSetupService_Setup(2, hex_md5('admin:' + responses['AMT_GeneralSettings'].response['DigestRealm'] + ':' + dev.temp.pass).substring(0, 32), null, null, null, null, activateIntelAmtCcmEx2);
  2380. }
  2381. function activateIntelAmtCcmEx2(stack, name, responses, status) {
  2382. const dev = stack.dev;
  2383. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2384. if (status != 200) { dev.consoleMsg("Failed to activate Intel AMT to CCM."); removeAmtDevice(dev, 43); return; }
  2385. // Update the device
  2386. dev.aquired = {};
  2387. dev.aquired.controlMode = 1; // 1 = CCM, 2 = ACM
  2388. if (typeof dev.amtstack.wsman.comm.amtVersion == 'string') {
  2389. var verSplit = dev.amtstack.wsman.comm.amtVersion.split('.');
  2390. if (verSplit.length >= 2) {
  2391. dev.aquired.version = verSplit[0] + '.' + verSplit[1];
  2392. dev.aquired.majorver = parseInt(verSplit[0]);
  2393. dev.aquired.minorver = parseInt(verSplit[1]);
  2394. if (verSplit.length >= 3) {
  2395. dev.aquired.version = verSplit[0] + '.' + verSplit[1] + '.' + verSplit[2];
  2396. dev.aquired.maintenancever = parseInt(verSplit[2]);
  2397. }
  2398. }
  2399. }
  2400. if ((typeof dev.mpsConnection.tag.meiState.OsHostname == 'string') && (typeof dev.mpsConnection.tag.meiState.OsDnsSuffix == 'string')) {
  2401. dev.aquired.host = dev.mpsConnection.tag.meiState.OsHostname + '.' + dev.mpsConnection.tag.meiState.OsDnsSuffix;
  2402. }
  2403. dev.aquired.realm = dev.amtstack.wsman.comm.digestRealm;
  2404. dev.intelamt.user = dev.aquired.user = 'admin';
  2405. dev.intelamt.pass = dev.aquired.pass = dev.temp.pass;
  2406. dev.intelamt.tls = dev.aquired.tls = 0;
  2407. dev.aquired.lastContact = Date.now();
  2408. dev.aquired.state = 2; // Activated
  2409. dev.aquired.warn = 0; // Clear all warnings
  2410. delete dev.acctry;
  2411. delete dev.temp;
  2412. UpdateDevice(dev);
  2413. // Success, switch to managing this device
  2414. obj.parent.mpsserver.SendJsonControl(dev.mpsConnection, { action: 'mestate' }); // Request an MEI state refresh
  2415. dev.consoleMsg("Succesfully activated in CCM mode, holding 10 seconds...");
  2416. // Wait 10 seconds before attempting to manage this device in CCM
  2417. var f = function doManage() { if (isAmtDeviceValid(dev)) { attemptInitialContact(doManage.dev); } }
  2418. f.dev = dev;
  2419. setTimeout(f, 10000);
  2420. }
  2421. // Check if this device has any way to be activated in ACM using our server certificates.
  2422. function checkAcmActivation(dev) {
  2423. var domain = parent.config.domains[dev.domainid];
  2424. if ((domain == null) || (domain.amtacmactivation == null) || (domain.amtacmactivation.certs == null) || (domain.amtacmactivation.certs.length == 0)) return { err: "Server does not have any ACM activation certificates." };
  2425. const activationCerts = domain.amtacmactivation.certs;
  2426. if ((dev.mpsConnection.tag.meiState == null) || (dev.mpsConnection.tag.meiState.Hashes == null) || (dev.mpsConnection.tag.meiState.Hashes.length == 0)) return { err: "Intel AMT did not report any trusted hashes." };
  2427. const deviceHashes = dev.mpsConnection.tag.meiState.Hashes;
  2428. // Get the trusted FQDN of the device
  2429. var trustedFqdn = null;
  2430. if (dev.mpsConnection.tag.meiState.OsDnsSuffix != null) { trustedFqdn = dev.mpsConnection.tag.meiState.OsDnsSuffix; }
  2431. if (dev.mpsConnection.tag.meiState.DnsSuffix != null) { trustedFqdn = dev.mpsConnection.tag.meiState.DnsSuffix; }
  2432. if (trustedFqdn == null) return { err: "No trusted DNS suffix reported" };
  2433. // Find a matching certificate
  2434. var gotSuffixMatch = false;
  2435. var devValidHash = false;
  2436. for (var i in activationCerts) {
  2437. var cert = activationCerts[i];
  2438. var certDnsMatch = checkAcmActivationCertName(cert.cn, trustedFqdn);
  2439. if (certDnsMatch == true) { gotSuffixMatch = true; }
  2440. if ((cert.cn == '*') || certDnsMatch) {
  2441. for (var j in deviceHashes) {
  2442. var hashInfo = deviceHashes[j];
  2443. if ((hashInfo != null) && (hashInfo.isActive == 1)) {
  2444. devValidHash = true;
  2445. if ((hashInfo.hashAlgorithmStr == 'SHA256') && (hashInfo.certificateHash.toLowerCase() == cert.sha256)) { return { cert: cert, fqdn: trustedFqdn, hash: cert.sha256 }; } // Found a match
  2446. else if ((hashInfo.hashAlgorithmStr == 'SHA1') && (hashInfo.certificateHash.toLowerCase() == cert.sha1)) { return { cert: cert, fqdn: trustedFqdn, hash: cert.sha1 }; } // Found a match
  2447. }
  2448. }
  2449. }
  2450. }
  2451. if (!devValidHash) { return { err: "Intel AMT has no trusted root hashes for \"" + trustedFqdn + "\"." }; } // Found no trusted root hashes
  2452. if (gotSuffixMatch) { return { err: "Certificate root hash matching failed for \"" + trustedFqdn + "\"." }; } // Found a DNS suffix match, but root hash failed to match.
  2453. return { err: "No matching ACM activation certificate for \"" + trustedFqdn + "\"." }; // Did not find a match
  2454. }
  2455. // Return true if the trusted FQDN matched the certificate common name
  2456. function checkAcmActivationCertName(commonName, trustedFqdn) {
  2457. commonName = commonName.toLowerCase();
  2458. trustedFqdn = trustedFqdn.toLowerCase();
  2459. if (commonName.startsWith('*.') && (commonName.length > 2)) { commonName = commonName.substring(2); }
  2460. return ((commonName == trustedFqdn) || (trustedFqdn.endsWith('.' + commonName)));
  2461. }
  2462. // Attempt Intel AMT TLS ACM activation
  2463. function activateIntelAmtTlsAcm(dev, password, acminfo) {
  2464. // Check if MeshAgent/MeshCMD can support the startConfigurationhostB() call.
  2465. if ((dev.mpsConnection != null) && (dev.mpsConnection.tag != null) && (dev.mpsConnection.tag.meiState != null) && (typeof dev.mpsConnection.tag.meiState['core-ver'] == 'number') && (dev.mpsConnection.tag.meiState['core-ver'] > 0)) {
  2466. // Generate a random Intel AMT password if needed
  2467. if ((password == null) || (password == '')) { password = getRandomAmtPassword(); }
  2468. dev.temp = { pass: password, acminfo: acminfo };
  2469. // Get our ACM activation certificate chain
  2470. var acmTlsInfo = parent.certificateOperations.getAcmCertChain(parent.config.domains[dev.domainid], dev.temp.acminfo.fqdn, dev.temp.acminfo.hash);
  2471. if (acmTlsInfo.error == 1) { dev.consoleMsg(acmTlsInfo.errorText); removeAmtDevice(dev, 44); return; }
  2472. dev.acmTlsInfo = acmTlsInfo;
  2473. // Send the MEI command to enable TLS connections
  2474. dev.consoleMsg("Performing TLS ACM activation...");
  2475. dev.controlMsg({ action: 'startTlsHostConfig', hash: acmTlsInfo.hash256, hostVpn: false, dnsSuffixList: null }); // TODO: Use SHA384 is possible.
  2476. } else {
  2477. // MeshCore or MeshCMD is to old
  2478. dev.consoleMsg("This software is to old to support ACM activation, pleasse update and try again.");
  2479. removeAmtDevice(dev);
  2480. }
  2481. }
  2482. // Attempt Intel AMT TLS ACM activation after startConfiguration() is called on remote device
  2483. function activateIntelAmtTlsAcmEx(dev, startConfigData) {
  2484. if ((startConfigData == null) || (startConfigData.status != 0) || (typeof startConfigData.hash != 'string')) {
  2485. // Unable to call startTlsHostConfig on remote host.
  2486. dev.consoleMsg("Failed to startConfigurationHBased(), status = " + startConfigData.status);
  2487. removeAmtDevice(dev);
  2488. } else {
  2489. // Setup the WSMAN stack, no TLS
  2490. dev.consoleMsg("Attempting TLS connection...");
  2491. var comm = CreateWsmanComm(dev.nodeid, 16993, 'admin', '', 1, { cert: dev.acmTlsInfo.certs.join(''), key: dev.acmTlsInfo.signkey }, dev.mpsConnection); // TLS with client certificate chain and key.
  2492. comm.xtlsFingerprint = startConfigData.hash.toLowerCase(); // Intel AMT leaf TLS cert need to match this hash (SHA256 or SHA384)
  2493. var wsstack = WsmanStackCreateService(comm);
  2494. dev.amtstack = AmtStackCreateService(wsstack);
  2495. dev.amtstack.dev = dev;
  2496. dev.amtstack.BatchEnum(null, ['*AMT_GeneralSettings', 'CIM_SoftwareIdentity', '*AMT_SetupAndConfigurationService'], activateIntelAmtTlsAcmEx1);
  2497. }
  2498. }
  2499. function activateIntelAmtTlsAcmEx1(stack, name, responses, status) {
  2500. const dev = stack.dev;
  2501. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2502. // Check if we succesfully connected
  2503. if (status != 200) {
  2504. dev.consoleMsg("Failed to perform ACM TLS connection, status " + status + ".");
  2505. //activateIntelAmtAcm(dev); // It's possible to fallback to legacy WSMAN ACM activation here if we needed to..
  2506. removeAmtDevice(dev);
  2507. return;
  2508. }
  2509. // Fetch the Intel AMT version from WSMAN
  2510. if ((responses != null) && (responses['CIM_SoftwareIdentity'] != null) && (responses['CIM_SoftwareIdentity'].responses != null)) {
  2511. var amtlogicalelements = [];
  2512. amtlogicalelements = responses['CIM_SoftwareIdentity'].responses;
  2513. if (responses['AMT_SetupAndConfigurationService'] != null && responses['AMT_SetupAndConfigurationService'].response != null) {
  2514. amtlogicalelements.push(responses['AMT_SetupAndConfigurationService'].response);
  2515. }
  2516. if (amtlogicalelements.length > 0) {
  2517. var vs = getInstance(amtlogicalelements, 'AMT')['VersionString'];
  2518. if (vs != null) {
  2519. dev.aquired.version = vs;
  2520. version = dev.aquired.version.split('.')
  2521. dev.aquired.versionmajor = parseInt(version[0]);
  2522. dev.aquired.versionminor = parseInt(version[1]);
  2523. if (version.length > 2) { dev.aquired.versionmaintenance = parseInt(version[2]); }
  2524. }
  2525. }
  2526. }
  2527. // Fetch the Intel AMT version from HTTP stack
  2528. if ((dev.amtversionstr == null) && (stack.wsman.comm.amtVersion != null)) {
  2529. var s = stack.wsman.comm.amtVersion.split('.');
  2530. if (s.length >= 2) {
  2531. dev.aquired.version = s[0] + '.' + s[1] + '.';
  2532. dev.aquired.versionmajor = parseInt(s[0]);
  2533. dev.aquired.versionminor = parseInt(s[1]);
  2534. if (s.length >= 3) {
  2535. dev.aquired.version = s[0] + '.' + s[1] + '.' + s[2];
  2536. dev.aquired.versionmaintenance = parseInt(s[2]);
  2537. }
  2538. }
  2539. }
  2540. // If we can't get the Intel AMT version, stop here.
  2541. if (dev.aquired.version == null) { dev.consoleMsg('Could not get Intel AMT version.'); removeAmtDevice(dev); return; } // Could not get Intel AMT version, disconnect();
  2542. // Get the digest realm
  2543. if (responses['AMT_GeneralSettings'] && responses['AMT_GeneralSettings'].response && (typeof responses['AMT_GeneralSettings'].response['DigestRealm'] == 'string')) {
  2544. // Set the realm in the stack since we are not doing HTTP digest and this will be checked later by different code.
  2545. dev.aquired.realm = dev.amtstack.wsman.comm.digestRealm = responses['AMT_GeneralSettings'].response['DigestRealm'];
  2546. } else {
  2547. dev.consoleMsg('Could not get Intel AMT digest realm.'); removeAmtDevice(dev); return;
  2548. }
  2549. // Looks like we are doing well.
  2550. dev.consoleMsg('Succesful TLS connection, Intel AMT v' + dev.aquired.version);
  2551. // Log this activation event
  2552. var event = { etype: 'node', action: 'amtactivate', nodeid: dev.nodeid, domain: dev.domainid, msgid: 111, msgArgs: [dev.temp.acminfo.fqdn], msg: 'Device requested Intel(R) AMT ACM TLS activation, FQDN: ' + dev.temp.acminfo.fqdn };
  2553. if (parent.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the node. Another event will come.
  2554. parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(dev.meshid, [dev.nodeid]), obj, event);
  2555. // Log the activation request, logging is a required step for activation.
  2556. var domain = parent.config.domains[dev.domainid];
  2557. if (domain == null) { dev.consoleMsg("Invalid domain."); removeAmtDevice(dev, 41); return; }
  2558. if (parent.certificateOperations.logAmtActivation(domain, { time: new Date(), action: 'acmactivate-tls', domain: dev.domainid, amtUuid: dev.mpsConnection.tag.meiState.UUID, amtRealm: dev.aquired.realm, user: 'admin', password: dev.temp.pass, ipport: dev.mpsConnection.remoteAddr + ':' + dev.mpsConnection.remotePort, nodeid: dev.nodeid, meshid: dev.meshid, computerName: dev.name }) == false) {
  2559. dev.consoleMsg("Unable to log operation."); removeAmtDevice(dev, 42); return;
  2560. }
  2561. // See what admin password to use
  2562. dev.aquired.user = 'admin';
  2563. dev.aquired.pass = dev.temp.password;
  2564. // Set the account password
  2565. if (typeof dev.temp.mebxpass == 'string') {
  2566. // Set the new MEBx password
  2567. dev.consoleMsg('Setting MEBx password...');
  2568. dev.amtstack.AMT_SetupAndConfigurationService_SetMEBxPassword(dev.temp.mebxpass, activateIntelAmtTlsAcmEx2);
  2569. } else {
  2570. // Set the admin password
  2571. dev.consoleMsg('Setting admin password...');
  2572. dev.amtstack.AMT_AuthorizationService_SetAdminAclEntryEx(dev.aquired.user, hex_md5(dev.aquired.user + ':' + dev.aquired.realm + ':' + dev.aquired.pass), activateIntelAmtTlsAcmEx3);
  2573. }
  2574. }
  2575. // Response from setting MEBx password
  2576. function activateIntelAmtTlsAcmEx2(stack, name, responses, status) {
  2577. const dev = stack.dev;
  2578. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2579. if (status != 200) { dev.consoleMsg('Failed to set MEBx password, status=' + status + '.'); destroyDevice(dev); return; }
  2580. dev.consoleMsg('MEBx password set. Setting admin password...');
  2581. // Set the admin password
  2582. dev.amtstack.AMT_AuthorizationService_SetAdminAclEntryEx(dev.aquired.user, hex_md5(dev.aquired.user + ':' + dev.aquired.realm + ':' + dev.aquired.pass), activateIntelAmtTlsAcmEx3);
  2583. }
  2584. // Response from setting admin password
  2585. function activateIntelAmtTlsAcmEx3(stack, name, responses, status) {
  2586. const dev = stack.dev;
  2587. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2588. if (status != 200) { dev.consoleMsg('Failed to set admin password, status=' + status + '.'); removeAmtDevice(dev); return; }
  2589. dev.consoleMsg('Admin password set.');
  2590. // Switch the state of Intel AMT.
  2591. if ((dev.mpsConnection != null) && (dev.mpsConnection.tag != null) && (dev.mpsConnection.tag.meiState != null)) { dev.mpsConnection.tag.meiState.ProvisioningState = 2; }
  2592. dev.aquired.controlMode = 2; // 1 = CCM, 2 = ACM
  2593. dev.aquired.state = 2; // Activated
  2594. dev.hbacmtls = 1; // Indicate that we are doing a Host
  2595. // Proceed to going the normal Intel AMT sync. This will trigger a commit when the TLS cert is setup.
  2596. dev.amtstack.BatchEnum(null, ['*AMT_GeneralSettings', '*IPS_HostBasedSetupService'], attemptLocalConnectResponse);
  2597. }
  2598. // Attempt Intel AMT ACM activation
  2599. function activateIntelAmtAcm(dev, password, acminfo) {
  2600. // Check if MeshAgent/MeshCMD can support the stopConfiguration() call.
  2601. if ((dev.mpsConnection != null) && (dev.mpsConnection.tag != null) && (dev.mpsConnection.tag.meiState != null) && (typeof dev.mpsConnection.tag.meiState['core-ver'] == 'number') && (dev.mpsConnection.tag.meiState['core-ver'] > 0)) {
  2602. // Generate a random Intel AMT password if needed
  2603. if (acminfo != null) {
  2604. if ((password == null) || (password == '')) { password = getRandomAmtPassword(); }
  2605. dev.temp = { pass: password, acminfo: acminfo };
  2606. }
  2607. dev.acmactivate = 1;
  2608. // Send the MEI command to stop configuration.
  2609. // If Intel AMT is "in-provisioning" mode, the WSMAN ACM activation will not work, so we need to do this first.
  2610. dev.consoleMsg("Getting ready for ACM activation...");
  2611. dev.controlMsg({ action: 'stopConfiguration' });
  2612. } else {
  2613. // MeshCore or MeshCMD is to old
  2614. dev.consoleMsg("This software is to old to support ACM activation, pleasse update and try again.");
  2615. removeAmtDevice(dev);
  2616. }
  2617. }
  2618. function activateIntelAmtAcmEx0(dev) {
  2619. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2620. // Setup the WSMAN stack, no TLS
  2621. var comm = CreateWsmanComm(dev.nodeid, 16992, dev.mpsConnection.tag.meiState.OsAdmin.user, dev.mpsConnection.tag.meiState.OsAdmin.pass, 0, null, dev.mpsConnection); // No TLS
  2622. var wsstack = WsmanStackCreateService(comm);
  2623. dev.amtstack = AmtStackCreateService(wsstack);
  2624. dev.amtstack.dev = dev;
  2625. dev.amtstack.BatchEnum(null, ['*AMT_GeneralSettings', '*IPS_HostBasedSetupService'], activateIntelAmtAcmEx1);
  2626. }
  2627. function activateIntelAmtAcmEx1(stack, name, responses, status) {
  2628. const dev = stack.dev;
  2629. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2630. if (status != 200) { dev.consoleMsg("Failed to get Intel AMT state."); removeAmtDevice(dev, 46); return; }
  2631. // Sign the Intel AMT ACM activation request
  2632. var info = { nonce: responses['IPS_HostBasedSetupService'].response['ConfigurationNonce'], realm: responses['AMT_GeneralSettings'].response['DigestRealm'], fqdn: dev.temp.acminfo.fqdn, hash: dev.temp.acminfo.hash, uuid: dev.mpsConnection.tag.meiState.UUID };
  2633. var acmdata = parent.certificateOperations.signAcmRequest(parent.config.domains[dev.domainid], info, 'admin', dev.temp.pass, dev.mpsConnection.remoteAddr + ':' + dev.mpsConnection.remotePort, dev.nodeid, dev.meshid, dev.name, 0);
  2634. if (acmdata == null) { dev.consoleMsg("Failed to sign ACM nonce."); removeAmtDevice(dev, 47); return; }
  2635. if (acmdata.error != null) { dev.consoleMsg(acmdata.errorText); removeAmtDevice(dev, 48); return; }
  2636. // Log this activation event
  2637. var event = { etype: 'node', action: 'amtactivate', nodeid: dev.nodeid, domain: dev.domainid, msgid: 58, msgArgs: [ dev.temp.acminfo.fqdn ], msg: 'Device requested Intel(R) AMT ACM activation, FQDN: ' + dev.temp.acminfo.fqdn };
  2638. if (parent.db.changeStream) { event.noact = 1; } // If DB change stream is active, don't use this event to change the node. Another event will come.
  2639. parent.DispatchEvent(parent.webserver.CreateMeshDispatchTargets(dev.meshid, [dev.nodeid]), obj, event);
  2640. // Start the activation process
  2641. dev.temp.acmdata = acmdata;
  2642. dev.temp.acmdata.index = 0;
  2643. dev.consoleMsg("Performing ACM activation...");
  2644. activateIntelAmtAcmEx2(dev);
  2645. }
  2646. // Recursive function to inject the provisioning certificates into AMT in the proper order and completes ACM activation
  2647. function activateIntelAmtAcmEx2(dev) {
  2648. var acmdata = dev.temp.acmdata;
  2649. var leaf = (acmdata.index == 0), root = (acmdata.index == (acmdata.certs.length - 1));
  2650. if ((acmdata.index < acmdata.certs.length) && (acmdata.certs[acmdata.index] != null)) {
  2651. dev.amtstack.IPS_HostBasedSetupService_AddNextCertInChain(acmdata.certs[acmdata.index], leaf, root,
  2652. function (stack, name, responses, status) {
  2653. const dev = stack.dev;
  2654. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2655. if (status != 200) { dev.consoleMsg("Failed to set ACM certificate chain (" + status + ")."); removeAmtDevice(dev, 49); return; }
  2656. if (responses['Body']['ReturnValue'] != 0) { dev.consoleMsg("Failed to set ACM certificate chain (ERR/" + responses['Body']['ReturnValue'] + ")."); removeAmtDevice(dev, 50); return; }
  2657. // Move to the next activation operation
  2658. dev.temp.acmdata.index++;
  2659. activateIntelAmtAcmEx2(dev);
  2660. }
  2661. );
  2662. } else {
  2663. dev.amtstack.IPS_HostBasedSetupService_AdminSetup(2, acmdata.password, acmdata.nonce, 2, acmdata.signature,
  2664. function (stack, name, responses, status) {
  2665. const dev = stack.dev;
  2666. if (isAmtDeviceValid(dev) == false) return; // Device no longer exists, ignore this request.
  2667. if (status != 200) { dev.consoleMsg("Failed to complete ACM activation (" + status + ")."); removeAmtDevice(dev, 51); return; }
  2668. if (responses['Body']['ReturnValue'] != 0) { dev.consoleMsg("Failed to complete ACM activation (ERR/" + responses['Body']['ReturnValue'] + ")."); removeAmtDevice(dev, 52); return; }
  2669. // Success, switch to managing this device
  2670. obj.parent.mpsserver.SendJsonControl(dev.mpsConnection, { action: 'mestate' }); // Request an MEI state refresh
  2671. dev.consoleMsg("Succesfully activated in ACM mode, holding 10 seconds...");
  2672. // Update the device
  2673. dev.aquired = {};
  2674. dev.aquired.controlMode = 2; // 1 = CCM, 2 = ACM
  2675. if (typeof dev.amtstack.wsman.comm.amtVersion == 'string') {
  2676. var verSplit = dev.amtstack.wsman.comm.amtVersion.split('.');
  2677. if (verSplit.length >= 3) { dev.aquired.version = verSplit[0] + '.' + verSplit[1] + '.' + verSplit[2]; dev.aquired.majorver = parseInt(verSplit[0]); dev.aquired.minorver = parseInt(verSplit[1]); }
  2678. }
  2679. if ((typeof dev.mpsConnection.tag.meiState.OsHostname == 'string') && (typeof dev.mpsConnection.tag.meiState.OsDnsSuffix == 'string')) {
  2680. dev.aquired.host = dev.mpsConnection.tag.meiState.OsHostname + '.' + dev.mpsConnection.tag.meiState.OsDnsSuffix;
  2681. }
  2682. dev.aquired.realm = dev.amtstack.wsman.comm.digestRealm;
  2683. dev.intelamt.user = dev.aquired.user = 'admin';
  2684. dev.intelamt.pass = dev.aquired.pass = dev.temp.pass;
  2685. dev.intelamt.tls = dev.aquired.tls = 0;
  2686. dev.aquired.lastContact = Date.now();
  2687. dev.aquired.state = 2; // Activated
  2688. delete dev.acctry;
  2689. delete dev.temp;
  2690. UpdateDevice(dev);
  2691. // Wait 10 seconds before attempting to manage this device in ACM
  2692. var f = function doManage() { if (isAmtDeviceValid(dev)) { attemptInitialContact(doManage.dev); } }
  2693. f.dev = dev;
  2694. setTimeout(f, 10000);
  2695. }
  2696. );
  2697. }
  2698. }
  2699. //
  2700. // Intel AMT CCM deactivation
  2701. //
  2702. function deactivateIntelAmtCCM(dev) {
  2703. dev.consoleMsg("Deactivating CCM...");
  2704. dev.deactivateCcmPending = 1;
  2705. dev.controlMsg({ action: 'deactivate' });
  2706. }
  2707. // This is called after the deactivation call
  2708. function deactivateIntelAmtCCMEx(dev, state) {
  2709. if (state != 0) {
  2710. dev.consoleMsg("Failed to deactivate Intel AMT CCM.");
  2711. removeAmtDevice(dev, 53);
  2712. } else {
  2713. // Update the device
  2714. dev.aquired = {};
  2715. dev.aquired.controlMode = 0; // 1 = CCM, 2 = ACM
  2716. dev.aquired.state = 0; // Not activated
  2717. delete dev.acctry;
  2718. delete dev.amtstack;
  2719. UpdateDevice(dev);
  2720. if (dev.policy.amtPolicy == 1) { // Deactivation policy, we are done.
  2721. dev.consoleMsg("Deactivation successful.");
  2722. dev.consoleMsg("Done.");
  2723. removeAmtDevice(dev, 54);
  2724. } else {
  2725. // Wait 20 seconds before attempting any operation on this device
  2726. dev.consoleMsg("Deactivation successful, holding for 1 minute...");
  2727. var f = function askMeiState() {
  2728. askMeiState.dev.pendingUpdatedMeiState = 1;
  2729. askMeiState.dev.controlMsg({ action: 'mestate' });
  2730. }
  2731. f.dev = dev;
  2732. setTimeout(f, 60000);
  2733. }
  2734. }
  2735. }
  2736. //
  2737. // General Methods
  2738. //
  2739. // Called this when a task is completed, when all tasks are completed the call back function will be called.
  2740. function devTaskCompleted(dev) {
  2741. dev.taskCount--;
  2742. if (dev.taskCount == 0) { var f = dev.taskCompleted; delete dev.taskCount; delete dev.taskCompleted; if (f != null) { f(dev); } }
  2743. }
  2744. function guidToStr(g) { return g.substring(6, 8) + g.substring(4, 6) + g.substring(2, 4) + g.substring(0, 2) + '-' + g.substring(10, 12) + g.substring(8, 10) + '-' + g.substring(14, 16) + g.substring(12, 14) + '-' + g.substring(16, 20) + '-' + g.substring(20); }
  2745. // Base64 to string conversion utility functions
  2746. function atob(x) { return Buffer.from(x, 'base64').toString('binary'); }
  2747. function btoa(x) { return Buffer.from(x, 'binary').toString('base64'); }
  2748. // Check which key pair matches the public key in the certificate
  2749. function amtcert_linkCertPrivateKey(certs, keys) {
  2750. if ((keys == null) || (keys.length == 0)) return;
  2751. for (var i in certs) {
  2752. var cert = certs[i];
  2753. try {
  2754. var publicKeyPEM = obj.parent.certificateOperations.forge.pki.publicKeyToPem(obj.parent.certificateOperations.forge.pki.certificateFromAsn1(obj.parent.certificateOperations.forge.asn1.fromDer(cert.X509CertificateBin)).publicKey).substring(28 + 32).replace(/(\r\n|\n|\r)/gm, "");
  2755. publicKeyPEM = publicKeyPEM.substring(0, publicKeyPEM.length - 24); // Remove the PEM footer
  2756. for (var j = 0; j < keys.length; j++) {
  2757. if ((publicKeyPEM === (keys[j]['DERKey'])) || (publicKeyPEM == btoa(atob(keys[j]['DERKey']).substring(24)))) { // Match directly or, new version of Intel AMT put the key type OID in the private key, skip that and match.
  2758. keys[j].XCert = cert; // Link the key pair to the certificate
  2759. cert.XPrivateKey = keys[j]; // Link the certificate to the key pair
  2760. }
  2761. }
  2762. } catch (ex) { console.log(ex); }
  2763. }
  2764. }
  2765. // Generate a random Intel AMT password
  2766. function checkAmtPassword(p) { return (p.length > 7) && (/\d/.test(p)) && (/[a-z]/.test(p)) && (/[A-Z]/.test(p)) && (/\W/.test(p)); }
  2767. function getRandomAmtPassword() { var p; do { p = Buffer.from(parent.crypto.randomBytes(9), 'binary').toString('base64').split('/').join('@'); } while (checkAmtPassword(p) == false); return p; }
  2768. function getRandomPassword() { return Buffer.from(parent.crypto.randomBytes(9), 'binary').toString('base64').split('/').join('@'); }
  2769. function getRandomLowerCase(len) { var r = '', random = parent.crypto.randomBytes(len); for (var i = 0; i < len; i++) { r += String.fromCharCode(97 + (random[i] % 26)); } return r; }
  2770. function getInstance(x, y) { for (var i in x) { if (x[i]['InstanceID'] == y) return x[i]; } return null; }
  2771. function hex_md5(str) { return parent.crypto.createHash('md5').update(str).digest('hex'); }
  2772. function Clone(v) { return JSON.parse(JSON.stringify(v)); }
  2773. function MakeToArray(v) { if (!v || v == null || typeof v == 'object') return v; return [v]; }
  2774. function getItem(x, y, z) { for (var i in x) { if (x[i][y] == z) return x[i]; } return null; }
  2775. function IntToStr(v) { return String.fromCharCode((v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF); }
  2776. // Returns a UEFI boot parameter in binary
  2777. function makeUefiBootParam(type, data, len) {
  2778. if (typeof data == 'number') { if (len == 1) { data = String.fromCharCode(data & 0xFF); } if (len == 2) { data = parent.common.ShortToStrX(data); } if (len == 4) { data = parent.common.IntToStrX(data); } }
  2779. return parent.common.ShortToStrX(0x8086) + parent.common.ShortToStrX(type) + parent.common.IntToStrX(data.length) + data;
  2780. }
  2781. function parseCertName(x) {
  2782. var j, r = {}, xx = x.split(',');
  2783. for (var i in xx) { j = xx[i].indexOf('='); r[xx[i].substring(0, j)] = xx[i].substring(j + 1); }
  2784. return r;
  2785. }
  2786. /*
  2787. function amtcert_signWithCaKey(DERKey, caPrivateKey, certAttributes, issuerAttributes, extKeyUsage) {
  2788. return obj.amtcert_createCertificate(certAttributes, caPrivateKey, DERKey, issuerAttributes, extKeyUsage);
  2789. }
  2790. */
  2791. // --- Extended Key Usage OID's ---
  2792. // 1.3.6.1.5.5.7.3.1 = TLS Server certificate
  2793. // 1.3.6.1.5.5.7.3.2 = TLS Client certificate
  2794. // 2.16.840.1.113741.1.2.1 = Intel AMT Remote Console
  2795. // 2.16.840.1.113741.1.2.2 = Intel AMT Local Console
  2796. // 2.16.840.1.113741.1.2.3 = Intel AMT Client Setup Certificate (Zero-Touch)
  2797. // Generate a certificate with a set of attributes signed by a rootCert. If the rootCert is obmitted, the generated certificate is self-signed.
  2798. obj.amtcert_createCertificate = function(certAttributes, caPrivateKey, DERKey, issuerAttributes, extKeyUsage) {
  2799. // Generate a keypair and create an X.509v3 certificate
  2800. var keys, cert = obj.parent.certificateOperations.forge.pki.createCertificate();
  2801. cert.publicKey = obj.parent.certificateOperations.forge.pki.publicKeyFromPem('-----BEGIN PUBLIC KEY-----' + DERKey + '-----END PUBLIC KEY-----');
  2802. cert.serialNumber = '' + Math.floor((Math.random() * 100000) + 1);
  2803. cert.validity.notBefore = new Date(2018, 0, 1);
  2804. //cert.validity.notBefore.setFullYear(cert.validity.notBefore.getFullYear() - 1); // Create a certificate that is valid one year before, to make sure out-of-sync clocks don't reject this cert.
  2805. cert.validity.notAfter = new Date(2049, 11, 31);
  2806. //cert.validity.notAfter.setFullYear(cert.validity.notAfter.getFullYear() + 20);
  2807. var attrs = [];
  2808. if (certAttributes['CN']) attrs.push({ name: 'commonName', value: certAttributes['CN'] });
  2809. if (certAttributes['C']) attrs.push({ name: 'countryName', value: certAttributes['C'] });
  2810. if (certAttributes['ST']) attrs.push({ shortName: 'ST', value: certAttributes['ST'] });
  2811. if (certAttributes['O']) attrs.push({ name: 'organizationName', value: certAttributes['O'] });
  2812. cert.setSubject(attrs);
  2813. // Use root attributes
  2814. var rootattrs = [];
  2815. if (issuerAttributes['CN']) rootattrs.push({ name: 'commonName', value: issuerAttributes['CN'] });
  2816. if (issuerAttributes['C']) rootattrs.push({ name: 'countryName', value: issuerAttributes['C'] });
  2817. if (issuerAttributes['ST']) rootattrs.push({ shortName: 'ST', value: issuerAttributes['ST'] });
  2818. if (issuerAttributes['O']) rootattrs.push({ name: 'organizationName', value: issuerAttributes['O'] });
  2819. cert.setIssuer(rootattrs);
  2820. if (extKeyUsage == null) { extKeyUsage = { name: 'extKeyUsage', serverAuth: true, } } else { extKeyUsage.name = 'extKeyUsage'; }
  2821. /*
  2822. {
  2823. name: 'extKeyUsage',
  2824. serverAuth: true,
  2825. clientAuth: true,
  2826. codeSigning: true,
  2827. emailProtection: true,
  2828. timeStamping: true,
  2829. '2.16.840.1.113741.1.2.1': true
  2830. }
  2831. */
  2832. // Create a leaf certificate
  2833. cert.setExtensions([{
  2834. name: 'basicConstraints'
  2835. }, {
  2836. name: 'keyUsage',
  2837. keyCertSign: true,
  2838. digitalSignature: true,
  2839. nonRepudiation: true,
  2840. keyEncipherment: true,
  2841. dataEncipherment: true
  2842. }, extKeyUsage, {
  2843. name: 'nsCertType',
  2844. client: true,
  2845. server: true,
  2846. email: true,
  2847. objsign: true,
  2848. }, {
  2849. name: 'subjectKeyIdentifier'
  2850. }]);
  2851. // Self-sign certificate
  2852. var privatekey = obj.parent.certificateOperations.forge.pki.privateKeyFromPem(caPrivateKey);
  2853. cert.sign(privatekey, obj.parent.certificateOperations.forge.md.sha256.create());
  2854. return cert;
  2855. }
  2856. return obj;
  2857. };