VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/UnattendedScript.cpp@ 102395

Last change on this file since 102395 was 102360, checked in by vboxsync, 16 months ago

IPRT/crypto: Removed RTCrShaCryptGenerateSaltWeak() again, as this didn't work on Windows. Now we're using so #ifdef ugliness in UnattendedScript to get a reproducible salt for the testcases. bugref:10551

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 41.2 KB
Line 
1/* $Id: UnattendedScript.cpp 102360 2023-11-28 12:47:27Z vboxsync $ */
2/** @file
3 * Classes for reading/parsing/saving scripts for unattended installation.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_MAIN_UNATTENDED
33#include "LoggingNew.h"
34#include "VirtualBoxBase.h"
35#include "AutoCaller.h"
36#include <VBox/com/ErrorInfo.h>
37
38#include "UnattendedScript.h"
39#include "UnattendedImpl.h"
40
41#include <iprt/err.h>
42#include <iprt/md5.h>
43#include <iprt/sha.h>
44
45#include <iprt/ctype.h>
46#include <iprt/file.h>
47#include <iprt/rand.h> /* For RTCrShaCrypt salt generation. */
48#include <iprt/vfs.h>
49#include <iprt/getopt.h>
50#include <iprt/path.h>
51
52#include <iprt/crypto/shacrypt.h>
53
54using namespace std;
55
56#ifdef VBOX_WITH_UNATTENDED
57
58
59/*********************************************************************************************************************************
60* Defined Constants And Macros *
61*********************************************************************************************************************************/
62static const char g_szPrefix[] = "@@VBOX_";
63static const char g_szPrefixInsert[] = "@@VBOX_INSERT";
64static const char g_szPrefixInsertXxx[] = "@@VBOX_INSERT_";
65static const char g_szPrefixInsertExpr[] = "@@VBOX_INSERT[";
66static const char g_szPrefixCond[] = "@@VBOX_COND";
67static const char g_szPrefixCondXxx[] = "@@VBOX_COND_";
68static const char g_szPrefixCondExpr[] = "@@VBOX_COND[";
69static const char g_szPrefixCondElse[] = "@@VBOX_COND_ELSE@@";
70static const char g_szPrefixCondEnd[] = "@@VBOX_COND_END@@";
71static const char g_szPrefixSplitter[] = "@@VBOX_SPLITTER";
72
73
74/*********************************************************************************************************************************
75* UnattendedScriptTemplate Implementation *
76*********************************************************************************************************************************/
77
78UnattendedScriptTemplate::UnattendedScriptTemplate(Unattended *pUnattended, const char *pszDefaultTemplateFilename,
79 const char *pszDefaultFilename)
80 : BaseTextScript(pUnattended, pszDefaultTemplateFilename, pszDefaultFilename), mpUnattended(pUnattended)
81{
82}
83
84HRESULT UnattendedScriptTemplate::saveToString(Utf8Str &rStrDst)
85{
86 RTEXPREVAL hEvaluator = NIL_RTEXPREVAL;
87 int vrc = RTExprEvalCreate(&hEvaluator, 0, "unattended", this, UnattendedScriptTemplate::queryVariableForExpr);
88 AssertRCReturn(vrc, mpSetError->setErrorVrc(vrc));
89
90 struct
91 {
92 bool fSavedOutputting;
93 } aConds[8];
94 unsigned cConds = 0;
95 bool fOutputting = true;
96 HRESULT hrc = E_FAIL;
97 size_t offTemplate = 0;
98 size_t cchTemplate = mStrScriptFullContent.length();
99 rStrDst.setNull();
100 for (;;)
101 {
102 /*
103 * Find the next placeholder and add any text before it to the output.
104 */
105 size_t offPlaceholder = mStrScriptFullContent.find(g_szPrefix, offTemplate);
106 size_t cchToCopy = offPlaceholder != RTCString::npos ? offPlaceholder - offTemplate : cchTemplate - offTemplate;
107 if (cchToCopy > 0)
108 {
109 if (fOutputting)
110 {
111 try
112 {
113 rStrDst.append(mStrScriptFullContent, offTemplate , cchToCopy);
114 }
115 catch (std::bad_alloc &)
116 {
117 hrc = E_OUTOFMEMORY;
118 break;
119 }
120 }
121 offTemplate += cchToCopy;
122 }
123
124 /*
125 * Process placeholder.
126 */
127 if (offPlaceholder != RTCString::npos)
128 {
129 /*
130 * First we must find the end of the placeholder string.
131 */
132 size_t const cchMaxPlaceholder = RT_MIN(cchTemplate - offPlaceholder, _1K);
133 const char *pszPlaceholder = mStrScriptFullContent.c_str() + offPlaceholder;
134 size_t cchPlaceholder = sizeof(g_szPrefix) - 1;
135 char ch;
136 while ( cchPlaceholder < cchMaxPlaceholder
137 && (ch = pszPlaceholder[cchPlaceholder]) != '\0'
138 && (RT_C_IS_PRINT(ch) || RT_C_IS_SPACE(ch))
139 && ch != '@')
140 cchPlaceholder++;
141
142 if ( offPlaceholder + cchPlaceholder < cchTemplate
143 && pszPlaceholder[cchPlaceholder] == '@')
144 {
145 cchPlaceholder++;
146 if ( offPlaceholder + cchPlaceholder < cchTemplate
147 && pszPlaceholder[cchPlaceholder] == '@')
148 cchPlaceholder++;
149 }
150
151 if ( pszPlaceholder[cchPlaceholder - 1] != '@'
152 || pszPlaceholder[cchPlaceholder - 2] != '@'
153 || ( strncmp(pszPlaceholder, RT_STR_TUPLE(g_szPrefixInsert)) != 0
154 && strncmp(pszPlaceholder, RT_STR_TUPLE(g_szPrefixCond)) != 0
155 && strncmp(pszPlaceholder, RT_STR_TUPLE(g_szPrefixSplitter)) != 0 ) )
156 {
157 hrc = mpSetError->setError(E_FAIL, tr("Malformed or too long template placeholder '%.*s'"),
158 cchPlaceholder, pszPlaceholder);
159 break;
160 }
161
162 offTemplate += cchPlaceholder;
163
164 /*
165 * @@VBOX_INSERT_XXX@@:
166 */
167 if (strncmp(pszPlaceholder, RT_STR_TUPLE(g_szPrefixInsertXxx)) == 0)
168 {
169 /*
170 * Get the placeholder value and add it to the output.
171 */
172 RTCString strValue;
173 hrc = getReplacement(pszPlaceholder, cchPlaceholder, fOutputting, strValue);
174 if (SUCCEEDED(hrc))
175 {
176 if (fOutputting)
177 {
178 try
179 {
180 rStrDst.append(strValue);
181 }
182 catch (std::bad_alloc &)
183 {
184 hrc = E_OUTOFMEMORY;
185 break;
186 }
187 }
188 }
189 else
190 break;
191 }
192 /*
193 * @@VBOX_INSERT[expr]@@:
194 * @@VBOX_INSERT[expr]SH@@:
195 * @@VBOX_INSERT[expr]ELEMENT@@:
196 * @@VBOX_INSERT[expr]ATTRIB_DQ@@:
197 */
198 else if (strncmp(pszPlaceholder, RT_STR_TUPLE(g_szPrefixInsertExpr)) == 0)
199 {
200 /*
201 * Get the placeholder value and add it to the output.
202 */
203 char *pszValue = NULL;
204 hrc = getReplacementForExpr(hEvaluator, pszPlaceholder, cchPlaceholder, fOutputting, &pszValue);
205 if (SUCCEEDED(hrc))
206 {
207 if (fOutputting && pszValue)
208 {
209 try
210 {
211 rStrDst.append(pszValue);
212 }
213 catch (std::bad_alloc &)
214 {
215 hrc = E_OUTOFMEMORY;
216 break;
217 }
218 }
219 RTStrFree(pszValue);
220 }
221 else
222 break;
223 }
224 /*
225 * @@VBOX_COND_END@@: Pop one item of the conditional stack.
226 */
227 else if (strncmp(pszPlaceholder, RT_STR_TUPLE(g_szPrefixCondEnd)) == 0)
228 {
229 if (cConds > 0)
230 {
231 cConds--;
232 fOutputting = aConds[cConds].fSavedOutputting;
233 }
234 else
235 {
236 hrc = mpSetError->setErrorBoth(E_FAIL, VERR_PARSE_ERROR,
237 tr("%s without @@VBOX_COND_XXX@@ at offset %zu (%#zx)"),
238 g_szPrefixCondEnd, offPlaceholder, offPlaceholder);
239 break;
240 }
241 }
242 /*
243 * @@VBOX_COND_ELSE@@: Flip the output setting of the current condition.
244 */
245 else if (strncmp(pszPlaceholder, RT_STR_TUPLE(g_szPrefixCondElse)) == 0)
246 {
247 if (cConds > 0)
248 fOutputting = !fOutputting;
249 else
250 {
251 hrc = mpSetError->setErrorBoth(E_FAIL, VERR_PARSE_ERROR,
252 tr("%s without @@VBOX_COND_XXX@@ at offset %zu (%#zx)"),
253 g_szPrefixCondElse, offPlaceholder, offPlaceholder);
254 break;
255 }
256 }
257 /*
258 * @@VBOX_COND_XXX@@: Push the previous outputting state and combine it with the
259 * one from the condition.
260 */
261 else if (strncmp(pszPlaceholder, RT_STR_TUPLE(g_szPrefixCondXxx)) == 0)
262 {
263 if (cConds + 1 < RT_ELEMENTS(aConds))
264 {
265 aConds[cConds].fSavedOutputting = fOutputting;
266 bool fNewOutputting = fOutputting;
267 hrc = getConditional(pszPlaceholder, cchPlaceholder, &fNewOutputting);
268 if (SUCCEEDED(hrc))
269 fOutputting = fOutputting && fNewOutputting;
270 else
271 break;
272 cConds++;
273 }
274 else
275 {
276 hrc = mpSetError->setErrorBoth(E_FAIL, VERR_PARSE_ERROR,
277 tr("Too deep conditional nesting at offset %zu (%#zx)"),
278 offPlaceholder, offPlaceholder);
279 break;
280 }
281 }
282 /*
283 * @@VBOX_COND[expr]@@: Push the previous outputting state and combine it with the
284 * one from the condition.
285 */
286 else if (strncmp(pszPlaceholder, RT_STR_TUPLE(g_szPrefixCondExpr)) == 0)
287 {
288 if (cConds + 1 < RT_ELEMENTS(aConds))
289 {
290 aConds[cConds].fSavedOutputting = fOutputting;
291 bool fNewOutputting = fOutputting;
292 hrc = resolveConditionalExpr(hEvaluator, pszPlaceholder, cchPlaceholder, &fNewOutputting);
293 if (SUCCEEDED(hrc))
294 fOutputting = fOutputting && fNewOutputting;
295 else
296 break;
297 cConds++;
298 }
299 else
300 {
301 hrc = mpSetError->setErrorBoth(E_FAIL, VERR_PARSE_ERROR,
302 tr("Too deep conditional nesting at offset %zu (%#zx)"),
303 offPlaceholder, offPlaceholder);
304 break;
305 }
306 }
307 /*
308 * @@VBOX_SPLITTER_START/END[filename]@@: Ignored in this pass.
309 */
310 else
311 {
312 Assert(strncmp(pszPlaceholder, RT_STR_TUPLE(g_szPrefixSplitter)) == 0);
313 if (fOutputting)
314 {
315 try
316 {
317 rStrDst.append(pszPlaceholder, cchPlaceholder);
318 }
319 catch (std::bad_alloc &)
320 {
321 hrc = E_OUTOFMEMORY;
322 break;
323 }
324 }
325 }
326 }
327
328 /*
329 * Done?
330 */
331 if (offTemplate >= cchTemplate)
332 {
333 if (cConds == 0)
334 {
335 RTExprEvalRelease(hEvaluator);
336 return S_OK;
337 }
338 if (cConds == 1)
339 hrc = mpSetError->setErrorBoth(E_FAIL, VERR_PARSE_ERROR, tr("Missing @@VBOX_COND_END@@"));
340 else
341 hrc = mpSetError->setErrorBoth(E_FAIL, VERR_PARSE_ERROR, tr("Missing %u @@VBOX_COND_END@@"), cConds);
342 break;
343 }
344 }
345
346 /* failed */
347 rStrDst.setNull();
348 RTExprEvalRelease(hEvaluator);
349 return hrc;
350}
351
352HRESULT UnattendedScriptTemplate::getReplacement(const char *pachPlaceholder, size_t cchPlaceholder,
353 bool fOutputting, RTCString &rValue)
354{
355 /*
356 * Check for an escaping suffix. Drop the '@@'.
357 */
358 kEvalEscaping_T enmEscaping;
359#define PLACEHOLDER_ENDS_WITH(a_szSuffix) \
360 ( cchPlaceholder > sizeof(a_szSuffix) - 1U \
361 && memcmp(&pachPlaceholder[cchPlaceholder - sizeof(a_szSuffix) + 1U], a_szSuffix, sizeof(a_szSuffix) - 1U) == 0)
362 if (PLACEHOLDER_ENDS_WITH("_SH@@"))
363 {
364 cchPlaceholder -= 3 + 2;
365 enmEscaping = kValueEscaping_Bourne;
366 }
367 else if (PLACEHOLDER_ENDS_WITH("_ELEMENT@@"))
368 {
369 cchPlaceholder -= 8 + 2;
370 enmEscaping = kValueEscaping_XML_Element;
371 }
372 else if (PLACEHOLDER_ENDS_WITH("_ATTRIB_DQ@@"))
373 {
374 cchPlaceholder -= 10 + 2;
375 enmEscaping = kValueEscaping_XML_Attribute_Double_Quotes;
376 }
377 else
378 {
379 Assert(PLACEHOLDER_ENDS_WITH("@@"));
380 cchPlaceholder -= 2;
381 enmEscaping = kValueEscaping_None;
382 }
383#undef PLACEHOLDER_ENDS_WITH
384
385 /*
386 * Resolve and escape the value.
387 */
388 HRESULT hrc;
389 try
390 {
391 Utf8Str strTmp;
392 const char *pszReadOnlyValue = NULL;
393 int vrc = queryVariable(pachPlaceholder + sizeof(g_szPrefixInsertXxx) - 1,
394 cchPlaceholder - sizeof(g_szPrefixInsertXxx) + 1,
395 strTmp, fOutputting ? &pszReadOnlyValue : NULL);
396 if (RT_SUCCESS(vrc))
397 {
398 if (fOutputting)
399 {
400 Assert(pszReadOnlyValue != NULL);
401 switch (enmEscaping)
402 {
403 case kValueEscaping_None:
404 rValue = pszReadOnlyValue;
405 return S_OK;
406
407 case kValueEscaping_Bourne:
408 case kValueEscaping_XML_Element:
409 case kValueEscaping_XML_Attribute_Double_Quotes:
410 {
411 switch (enmEscaping)
412 {
413 case kValueEscaping_Bourne:
414 {
415 const char * const papszArgs[2] = { pszReadOnlyValue, NULL };
416 char *pszEscaped = NULL;
417 vrc = RTGetOptArgvToString(&pszEscaped, papszArgs, RTGETOPTARGV_CNV_QUOTE_BOURNE_SH);
418 if (RT_SUCCESS(vrc))
419 {
420 try
421 {
422 rValue = pszEscaped;
423 RTStrFree(pszEscaped);
424 return S_OK;
425 }
426 catch (std::bad_alloc &)
427 {
428 hrc = E_OUTOFMEMORY;
429 }
430 RTStrFree(pszEscaped);
431 }
432 else
433 hrc = mpSetError->setErrorVrc(vrc);
434 break;
435 }
436
437 case kValueEscaping_XML_Element:
438 rValue.printf("%RMes", pszReadOnlyValue);
439 return S_OK;
440
441 case kValueEscaping_XML_Attribute_Double_Quotes:
442 {
443 RTCString strTmp2;
444 strTmp2.printf("%RMas", pszReadOnlyValue);
445 rValue = RTCString(strTmp2, 1, strTmp2.length() - 2);
446 return S_OK;
447 }
448
449 default:
450 hrc = E_FAIL;
451 break;
452 }
453 break;
454 }
455
456 default:
457 AssertFailedStmt(hrc = E_FAIL);
458 break;
459 }
460 }
461 else
462 hrc = S_OK;
463 }
464 else
465 hrc = E_FAIL;
466 }
467 catch (std::bad_alloc &)
468 {
469 hrc = E_OUTOFMEMORY;
470 }
471 rValue.setNull();
472 return hrc;
473}
474
475HRESULT UnattendedScriptTemplate::getReplacementForExpr(RTEXPREVAL hEvaluator, const char *pachPlaceholder, size_t cchPlaceholder,
476 bool fOutputting, char **ppszValue) RT_NOEXCEPT
477{
478 /*
479 * Process the tail of the placeholder to figure out the escaping rules.
480 *
481 * @@VBOX_INSERT[expr]@@:
482 * @@VBOX_INSERT[expr]SH@@:
483 * @@VBOX_INSERT[expr]ELEMENT@@:
484 * @@VBOX_INSERT[expr]ATTRIB_DQ@@:
485 */
486 kEvalEscaping_T enmEscaping;
487#define PLACEHOLDER_ENDS_WITH(a_szSuffix) \
488 ( cchPlaceholder > sizeof(a_szSuffix) - 1U \
489 && memcmp(&pachPlaceholder[cchPlaceholder - sizeof(a_szSuffix) + 1U], a_szSuffix, sizeof(a_szSuffix) - 1U) == 0)
490 if (PLACEHOLDER_ENDS_WITH("]SH@@"))
491 {
492 cchPlaceholder -= sizeof("]SH@@") - 1;
493 enmEscaping = kValueEscaping_Bourne;
494 }
495 else if (PLACEHOLDER_ENDS_WITH("]ELEMENT@@"))
496 {
497 cchPlaceholder -= sizeof("]ELEMENT@@") - 1;
498 enmEscaping = kValueEscaping_XML_Element;
499 }
500 else if (PLACEHOLDER_ENDS_WITH("]ATTRIB_DQ@@"))
501 {
502 cchPlaceholder -= sizeof("]ATTRIB_DQ@@") - 1;
503 enmEscaping = kValueEscaping_XML_Attribute_Double_Quotes;
504 }
505 else if (PLACEHOLDER_ENDS_WITH("]@@"))
506 {
507 cchPlaceholder -= sizeof("]@@") - 1;
508 enmEscaping = kValueEscaping_None;
509 }
510 else
511 return mpSetError->setErrorBoth(E_FAIL, VERR_PARSE_ERROR, tr("Malformed @@VBOX_INSERT[expr]@@: Missing ']' (%.*s)"),
512 cchPlaceholder, pachPlaceholder);
513#undef PLACEHOLDER_ENDS_WITH
514
515 /* The placeholder prefix length. The expression is from cchPrefix to cchPlaceholder. */
516 size_t const cchPrefix = sizeof(g_szPrefixInsertExpr) - 1;
517 Assert(pachPlaceholder[cchPrefix - 1] == '[');
518
519 /*
520 * Evaluate the expression. We do this regardless of fOutput for now.
521 */
522 RTERRINFOSTATIC ErrInfo;
523 char *pszValue = NULL;
524 int vrc = RTExprEvalToString(hEvaluator, &pachPlaceholder[cchPrefix], cchPlaceholder - cchPrefix, &pszValue,
525 RTErrInfoInitStatic(&ErrInfo));
526 LogFlowFunc(("RTExprEvalToString(%.*s) -> %Rrc pszValue=%s\n",
527 cchPlaceholder - cchPrefix, &pachPlaceholder[cchPrefix], vrc, pszValue));
528 if (RT_SUCCESS(vrc))
529 {
530 if (fOutputting)
531 {
532 switch (enmEscaping)
533 {
534 case kValueEscaping_None:
535 *ppszValue = pszValue;
536 pszValue = NULL;
537 break;
538
539 case kValueEscaping_Bourne:
540 {
541 const char * const papszArgs[2] = { pszValue, NULL };
542 vrc = RTGetOptArgvToString(ppszValue, papszArgs, RTGETOPTARGV_CNV_QUOTE_BOURNE_SH);
543 break;
544 }
545
546 case kValueEscaping_XML_Element:
547 vrc = RTStrAPrintf(ppszValue, "%RMes", pszValue);
548 break;
549
550 case kValueEscaping_XML_Attribute_Double_Quotes:
551 vrc = RTStrAPrintf(ppszValue, "%RMas", pszValue);
552 if (RT_SUCCESS(vrc))
553 {
554 /* drop the quotes */
555 char *pszRet = *ppszValue;
556 size_t const cchRet = strlen(pszRet) - 2;
557 memmove(pszRet, &pszRet[1], cchRet);
558 pszRet[cchRet] = '\0';
559 }
560 break;
561
562 default:
563 AssertFailedStmt(vrc = VERR_IPE_NOT_REACHED_DEFAULT_CASE);
564 break;
565 }
566 RTStrFree(pszValue);
567 if (RT_FAILURE(vrc))
568 return mpSetError->setErrorVrc(vrc);
569 }
570 else
571 {
572 *ppszValue = NULL;
573 RTStrFree(pszValue);
574 }
575 }
576 else
577 return mpSetError->setErrorBoth(E_FAIL, vrc, tr("Expression evaluation error for '%.*s': %#RTeic"),
578 cchPlaceholder, pachPlaceholder, &ErrInfo.Core);
579 return S_OK;
580}
581
582HRESULT UnattendedScriptTemplate::resolveConditionalExpr(RTEXPREVAL hEvaluator, const char *pachPlaceholder,
583 size_t cchPlaceholder, bool *pfOutputting) RT_NOEXCEPT
584{
585 /*
586 * Check the placeholder tail: @@VBOX_COND[expr]@@
587 */
588 static const char s_szTail[] = "]@@";
589 if (memcmp(&pachPlaceholder[cchPlaceholder - sizeof(s_szTail) + 1], RT_STR_TUPLE(s_szTail)) != 0)
590 return mpSetError->setErrorBoth(E_FAIL, VERR_PARSE_ERROR, tr("Malformed @@VBOX_COND[expr]@@: Missing ']' (%.*s)"),
591 cchPlaceholder, pachPlaceholder);
592 Assert(pachPlaceholder[sizeof(g_szPrefixCondExpr) - 2 ] == '[');
593
594 /*
595 * Evaluate the expression.
596 */
597 RTERRINFOSTATIC ErrInfo;
598 const char * const pchExpr = &pachPlaceholder[sizeof(g_szPrefixCondExpr) - 1];
599 size_t const cchExpr = cchPlaceholder - sizeof(g_szPrefixCondExpr) + 1 - sizeof(s_szTail) + 1;
600 int vrc = RTExprEvalToBool(hEvaluator, pchExpr, cchExpr, pfOutputting, RTErrInfoInitStatic(&ErrInfo));
601 LogFlowFunc(("RTExprEvalToBool(%.*s) -> %Rrc *pfOutputting=%s\n", cchExpr, pchExpr, vrc, *pfOutputting));
602 if (RT_SUCCESS(vrc))
603 return S_OK;
604 return mpSetError->setErrorBoth(E_FAIL, vrc, tr("Expression evaluation error for '%.*s': %#RTeic"),
605 cchPlaceholder, pachPlaceholder, &ErrInfo.Core);
606}
607
608/*static */ DECLCALLBACK(int)
609UnattendedScriptTemplate::queryVariableForExpr(const char *pchName, size_t cchName, void *pvUser, char **ppszValue) RT_NOEXCEPT
610{
611 UnattendedScriptTemplate *pThis = (UnattendedScriptTemplate *)pvUser;
612 int vrc;
613 try
614 {
615 const char *pszReadOnlyValue = NULL;
616 Utf8Str strTmp;
617 vrc = pThis->queryVariable(pchName, cchName, strTmp, ppszValue ? &pszReadOnlyValue : NULL);
618 if (ppszValue)
619 {
620 if (RT_SUCCESS(vrc))
621 vrc = RTStrDupEx(ppszValue, pszReadOnlyValue);
622 else
623 *ppszValue = NULL;
624 }
625 }
626 catch (std::bad_alloc &)
627 {
628 vrc = VERR_NO_MEMORY;
629 *ppszValue = NULL;
630 }
631 return vrc;
632}
633
634/* static */
635int UnattendedScriptTemplate::shaCryptGenerateSalt(char *pszSalt, size_t cchSalt)
636{
637 AssertPtrReturn(pszSalt, VERR_INVALID_POINTER);
638#ifdef IN_TST_UNATTENDED_SCRIPT
639 /* Use a fixed salt to predict the hashing result with the testcases. */
640 return RTStrPrintf2(pszSalt, cchSalt, "testcase123") > 0 ? VINF_SUCCESS : VERR_BUFFER_OVERFLOW;
641#else
642 return RTCrShaCryptGenerateSalt(pszSalt, cchSalt);
643#endif
644}
645
646int UnattendedScriptTemplate::queryVariable(const char *pchName, size_t cchName, Utf8Str &rstrTmp, const char **ppszValue)
647{
648#define IS_MATCH(a_szMatch) \
649 (cchNameWithoutSuffix == sizeof(a_szMatch) - 1U && memcmp(pchName, a_szMatch, sizeof(a_szMatch) - 1U) == 0)
650#define ENDS_WITH(a_szMatch) \
651 ( cchName \
652 && cchName >= sizeof(a_szMatch) - 1U \
653 && memcmp(&pchName[cchName - (sizeof(a_szMatch) - 1U)], a_szMatch, sizeof(a_szMatch) - 1U) == 0)
654#define CALCULATE_SUFFIX_LEN_IF_ENDS_WITH(a_szSuff) \
655 if (ENDS_WITH(a_szSuff)) \
656 cchNameWithoutSuffix = cchName - (sizeof(a_szSuff) - 1U);
657#define HASH_AND_ASSIGN(a_abData, a_cbData, a_fnHash, a_cbHashSize) \
658 do { \
659 uint8_t abHash[a_cbHashSize]; \
660 a_fnHash(a_abData, a_cbData, abHash); \
661 char szDigest[a_cbHashSize * 4]; \
662 a_fnHash##ToString(abHash, szDigest, sizeof(szDigest)); \
663 pszValue = rstrTmp.assign(szDigest, strlen(szDigest)).c_str(); \
664 } while (0)
665/** Uses the RTCrShaCrypt APIs to hash and crypt data. Uses a randomized salt + (recommended) default rounds. */
666#define SHACRYPT_AND_ASSIGN(a_szKey, a_fnHashAndCrypt, a_cbHashSize) \
667 do { \
668 uint8_t abHash[a_cbHashSize]; \
669 char szSalt[RT_SHACRYPT_MAX_SALT_LEN + 1]; \
670 int vrc = UnattendedScriptTemplate::shaCryptGenerateSalt(szSalt, RT_SHACRYPT_MAX_SALT_LEN); \
671 if (RT_SUCCESS(vrc)) \
672 { \
673 vrc = a_fnHashAndCrypt(a_szKey, szSalt, RT_SHACRYPT_DEFAULT_ROUNDS, abHash); \
674 if (RT_SUCCESS(vrc)) \
675 { \
676 char szDigest[a_cbHashSize * 4]; \
677 vrc = a_fnHashAndCrypt##ToString(abHash, szSalt, RT_SHACRYPT_DEFAULT_ROUNDS, szDigest, sizeof(szDigest)); \
678 if (RT_SUCCESS(vrc)) \
679 pszValue = rstrTmp.assign(szDigest, strlen(szDigest)).c_str(); \
680 } \
681 } \
682 } while (0)
683
684 const char *pszValue = NULL;
685
686 /*
687 * Calculate the variable name length w/o any suffixes we want to handle down below.
688 */
689 size_t cchNameWithoutSuffix = cchName;
690 CALCULATE_SUFFIX_LEN_IF_ENDS_WITH("_SHACRYPT512");
691 CALCULATE_SUFFIX_LEN_IF_ENDS_WITH("_SHACRYPT256");
692 CALCULATE_SUFFIX_LEN_IF_ENDS_WITH("_SHA512");
693 CALCULATE_SUFFIX_LEN_IF_ENDS_WITH("_SHA256");
694 CALCULATE_SUFFIX_LEN_IF_ENDS_WITH("_SHA1");
695 CALCULATE_SUFFIX_LEN_IF_ENDS_WITH("_MD5");
696
697 /*
698 * Variables
699 */
700 if (IS_MATCH("USER_LOGIN"))
701 pszValue = mpUnattended->i_getUser().c_str();
702 else if (IS_MATCH("USER_PASSWORD"))
703 pszValue = mpUnattended->i_getPassword().c_str();
704 else if (IS_MATCH("ROOT_PASSWORD"))
705 pszValue = mpUnattended->i_getPassword().c_str();
706 else if (IS_MATCH("USER_FULL_NAME"))
707 pszValue = mpUnattended->i_getFullUserName().c_str();
708 else if (IS_MATCH("PRODUCT_KEY"))
709 pszValue = mpUnattended->i_getProductKey().c_str();
710 else if (IS_MATCH("POST_INSTALL_COMMAND"))
711 pszValue = mpUnattended->i_getPostInstallCommand().c_str();
712 else if (IS_MATCH("AUXILIARY_INSTALL_DIR"))
713 pszValue = mpUnattended->i_getAuxiliaryInstallDir().c_str();
714 else if (IS_MATCH("IMAGE_INDEX"))
715 pszValue = rstrTmp.printf("%u", mpUnattended->i_getImageIndex()).c_str();
716 else if (IS_MATCH("OS_ARCH"))
717 pszValue = mpUnattended->i_isGuestOs64Bit() ? "amd64" : "x86";
718 else if (IS_MATCH("OS_ARCH2"))
719 pszValue = mpUnattended->i_isGuestOs64Bit() ? "x86_64" : "x86";
720 else if (IS_MATCH("OS_ARCH3"))
721 pszValue = mpUnattended->i_isGuestOs64Bit() ? "x86_64" : "i386";
722 else if (IS_MATCH("OS_ARCH4"))
723 pszValue = mpUnattended->i_isGuestOs64Bit() ? "x86_64" : "i486";
724 else if (IS_MATCH("OS_ARCH6"))
725 pszValue = mpUnattended->i_isGuestOs64Bit() ? "x86_64" : "i686";
726 else if (IS_MATCH("GUEST_OS_VERSION"))
727 pszValue = mpUnattended->i_getDetectedOSVersion().c_str();
728 else if (IS_MATCH("GUEST_OS_MAJOR_VERSION"))
729 {
730 Utf8Str const &rstrOsVer = mpUnattended->i_getDetectedOSVersion();
731 size_t offDot = rstrOsVer.find('.');
732 if (offDot > 0 && offDot != Utf8Str::npos)
733 pszValue = rstrTmp.assign(rstrOsVer, 0, offDot).c_str(); /* caller catches std::bad_alloc */
734 else if (!ppszValue)
735 return VERR_NOT_FOUND;
736 else
737 {
738 mpSetError->setErrorBoth(E_FAIL, VERR_NO_DATA, tr("Unknown guest OS major version '%s'"), rstrOsVer.c_str());
739 return VERR_NO_DATA;
740 }
741 }
742 else if (IS_MATCH("TIME_ZONE_UX"))
743 pszValue = mpUnattended->i_getTimeZoneInfo()
744 ? mpUnattended->i_getTimeZoneInfo()->pszUnixName : mpUnattended->i_getTimeZone().c_str();
745 else if (IS_MATCH("TIME_ZONE_WIN_NAME"))
746 {
747 PCRTTIMEZONEINFO pInfo = mpUnattended->i_getTimeZoneInfo();
748 if (pInfo)
749 pszValue = pInfo->pszWindowsName ? pInfo->pszWindowsName : "GMT";
750 else
751 pszValue = mpUnattended->i_getTimeZone().c_str();
752 }
753 else if (IS_MATCH("TIME_ZONE_WIN_INDEX"))
754 {
755 PCRTTIMEZONEINFO pInfo = mpUnattended->i_getTimeZoneInfo();
756 if (pInfo)
757 pszValue = rstrTmp.printf("%u", pInfo->idxWindows ? pInfo->idxWindows : 85 /*GMT*/).c_str();
758 else
759 pszValue = mpUnattended->i_getTimeZone().c_str();
760 }
761 else if (IS_MATCH("LOCALE"))
762 pszValue = mpUnattended->i_getLocale().c_str();
763 else if (IS_MATCH("DASH_LOCALE"))
764 {
765 Assert(mpUnattended->i_getLocale()[2] == '_');
766 pszValue = rstrTmp.assign(mpUnattended->i_getLocale()).replace(2, 1, "-").c_str();
767 }
768 else if (IS_MATCH("LANGUAGE"))
769 pszValue = mpUnattended->i_getLanguage().c_str();
770 else if (IS_MATCH("COUNTRY"))
771 pszValue = mpUnattended->i_getCountry().c_str();
772 else if (IS_MATCH("HOSTNAME_FQDN"))
773 pszValue = mpUnattended->i_getHostname().c_str();
774 else if (IS_MATCH("HOSTNAME_WITHOUT_DOMAIN"))
775 pszValue = rstrTmp.assign(mpUnattended->i_getHostname(), 0, mpUnattended->i_getHostname().find(".")).c_str();
776 else if (IS_MATCH("HOSTNAME_WITHOUT_DOMAIN_MAX_15"))
777 pszValue = rstrTmp.assign(mpUnattended->i_getHostname(), 0, RT_MIN(mpUnattended->i_getHostname().find("."), 15)).c_str();
778 else if (IS_MATCH("HOSTNAME_DOMAIN"))
779 pszValue = rstrTmp.assign(mpUnattended->i_getHostname(), mpUnattended->i_getHostname().find(".") + 1).c_str();
780 else if (IS_MATCH("PROXY"))
781 pszValue = mpUnattended->i_getProxy().c_str();
782 else if (IS_MATCH("ADDITIONS_INSTALL_PACKAGE_NAME"))
783 pszValue = mpUnattended->i_getAdditionsInstallPackage().c_str();
784 /*
785 * Indicator variables.
786 */
787 else if (IS_MATCH("IS_INSTALLING_ADDITIONS"))
788 pszValue = mpUnattended->i_getInstallGuestAdditions() ? "1" : "0";
789 else if (IS_MATCH("IS_USER_LOGIN_ADMINISTRATOR"))
790 pszValue = mpUnattended->i_getUser().compare("Administrator", RTCString::CaseInsensitive) == 0 ? "1" : "0";
791 else if (IS_MATCH("IS_INSTALLING_TEST_EXEC_SERVICE"))
792 pszValue = mpUnattended->i_getInstallTestExecService() ? "1" : "0";
793 else if (IS_MATCH("HAS_POST_INSTALL_COMMAND"))
794 pszValue = mpUnattended->i_getPostInstallCommand().isNotEmpty() ? "1" : "0";
795 else if (IS_MATCH("HAS_PRODUCT_KEY"))
796 pszValue = mpUnattended->i_getProductKey().isNotEmpty() ? "1" : "0";
797 else if (IS_MATCH("IS_MINIMAL_INSTALLATION"))
798 pszValue = mpUnattended->i_isMinimalInstallation() ? "1" : "0";
799 else if (IS_MATCH("IS_FIRMWARE_UEFI"))
800 pszValue = mpUnattended->i_isFirmwareEFI() ? "1" : "0";
801 else if (IS_MATCH("IS_RTC_USING_UTC"))
802 pszValue = mpUnattended->i_isRtcUsingUtc() ? "1" : "0";
803 else if (IS_MATCH("HAS_PROXY"))
804 pszValue = mpUnattended->i_getProxy().isNotEmpty() ? "1" : "0";
805
806 /*
807 * Hash output, if needed.
808 *
809 * Keep them ordered, strongest first (most likely nowadays).
810 * Add more here once we need them.
811 */
812 if (pszValue)
813 {
814 /*
815 * SHAcrypt stuff.
816 */
817 if (ENDS_WITH("_SHACRYPT512"))
818 SHACRYPT_AND_ASSIGN(pszValue, RTCrShaCrypt512, RTSHA512_HASH_SIZE);
819 else if (ENDS_WITH("_SHACRYPT256"))
820 SHACRYPT_AND_ASSIGN(pszValue, RTCrShaCrypt256, RTSHA256_HASH_SIZE);
821 /*
822 * Regular hashing.
823 */
824 else if (ENDS_WITH("_SHA512"))
825 HASH_AND_ASSIGN(pszValue, strlen(pszValue), RTSha512, RTSHA512_HASH_SIZE);
826 else if (ENDS_WITH("_SHA256"))
827 HASH_AND_ASSIGN(pszValue, strlen(pszValue), RTSha256, RTSHA256_HASH_SIZE);
828 else if (ENDS_WITH("_SHA1"))
829 HASH_AND_ASSIGN(pszValue, strlen(pszValue), RTSha1, RTSHA1_HASH_SIZE);
830 else if (ENDS_WITH("_MD5"))
831 HASH_AND_ASSIGN(pszValue, strlen(pszValue), RTMd5, RTMD5_HASH_SIZE);
832 }
833 /*
834 * Unknown variable.
835 */
836 else if (!ppszValue)
837 return VERR_NOT_FOUND;
838 else
839 {
840 mpSetError->setErrorBoth(E_FAIL, VERR_NOT_FOUND, tr("Unknown variable '%.*s'"), cchName, pchName);
841 return VERR_NO_DATA;
842 }
843 if (ppszValue)
844 *ppszValue = pszValue;
845
846#undef HASH_AND_ASSIGN
847#undef CALCULATE_SUFFIX_LEN_IF_ENDS_WITH
848#undef ENDS_WITH
849#undef IS_MATCH
850
851 return VINF_SUCCESS;
852}
853
854HRESULT UnattendedScriptTemplate::getConditional(const char *pachPlaceholder, size_t cchPlaceholder, bool *pfOutputting)
855{
856#define IS_PLACEHOLDER_MATCH(a_szMatch) \
857 ( cchPlaceholder == sizeof("@@VBOX_COND_" a_szMatch "@@") - 1U \
858 && memcmp(pachPlaceholder, "@@VBOX_COND_" a_szMatch "@@", sizeof("@@VBOX_COND_" a_szMatch "@@") - 1U) == 0)
859
860 /* Install Guest Additions: */
861 if (IS_PLACEHOLDER_MATCH("IS_INSTALLING_ADDITIONS"))
862 *pfOutputting = mpUnattended->i_getInstallGuestAdditions();
863 else if (IS_PLACEHOLDER_MATCH("IS_NOT_INSTALLING_ADDITIONS"))
864 *pfOutputting = !mpUnattended->i_getInstallGuestAdditions();
865 /* User == Administrator: */
866 else if (IS_PLACEHOLDER_MATCH("IS_USER_LOGIN_ADMINISTRATOR"))
867 *pfOutputting = mpUnattended->i_getUser().compare("Administrator", RTCString::CaseInsensitive) == 0;
868 else if (IS_PLACEHOLDER_MATCH("IS_USER_LOGIN_NOT_ADMINISTRATOR"))
869 *pfOutputting = mpUnattended->i_getUser().compare("Administrator", RTCString::CaseInsensitive) != 0;
870 /* Install TXS: */
871 else if (IS_PLACEHOLDER_MATCH("IS_INSTALLING_TEST_EXEC_SERVICE"))
872 *pfOutputting = mpUnattended->i_getInstallTestExecService();
873 else if (IS_PLACEHOLDER_MATCH("IS_NOT_INSTALLING_TEST_EXEC_SERVICE"))
874 *pfOutputting = !mpUnattended->i_getInstallTestExecService();
875 /* Post install command: */
876 else if (IS_PLACEHOLDER_MATCH("HAS_POST_INSTALL_COMMAND"))
877 *pfOutputting = mpUnattended->i_getPostInstallCommand().isNotEmpty();
878 else if (IS_PLACEHOLDER_MATCH("HAS_NO_POST_INSTALL_COMMAND"))
879 *pfOutputting = mpUnattended->i_getPostInstallCommand().isEmpty();
880 /* Product key: */
881 else if (IS_PLACEHOLDER_MATCH("HAS_PRODUCT_KEY"))
882 *pfOutputting = mpUnattended->i_getProductKey().isNotEmpty();
883 else if (IS_PLACEHOLDER_MATCH("HAS_NO_PRODUCT_KEY"))
884 *pfOutputting = mpUnattended->i_getProductKey().isEmpty();
885 /* Minimal installation: */
886 else if (IS_PLACEHOLDER_MATCH("IS_MINIMAL_INSTALLATION"))
887 *pfOutputting = mpUnattended->i_isMinimalInstallation();
888 else if (IS_PLACEHOLDER_MATCH("IS_NOT_MINIMAL_INSTALLATION"))
889 *pfOutputting = !mpUnattended->i_isMinimalInstallation();
890 /* Is firmware UEFI: */
891 else if (IS_PLACEHOLDER_MATCH("IS_FIRMWARE_UEFI"))
892 *pfOutputting = mpUnattended->i_isFirmwareEFI();
893 else if (IS_PLACEHOLDER_MATCH("IS_NOT_FIRMWARE_UEFI"))
894 *pfOutputting = !mpUnattended->i_isFirmwareEFI();
895 /* Is RTC using UTC (i.e. set to UTC time on startup): */
896 else if (IS_PLACEHOLDER_MATCH("IS_RTC_USING_UTC"))
897 *pfOutputting = mpUnattended->i_isRtcUsingUtc();
898 else if (IS_PLACEHOLDER_MATCH("IS_NOT_RTC_USING_UTC"))
899 *pfOutputting = !mpUnattended->i_isRtcUsingUtc();
900 else if (IS_PLACEHOLDER_MATCH("HAS_PROXY"))
901 *pfOutputting = mpUnattended->i_getProxy().isNotEmpty();
902 else if (IS_PLACEHOLDER_MATCH("AVOID_UPDATES_OVER_NETWORK"))
903 *pfOutputting = mpUnattended->i_getAvoidUpdatesOverNetwork();
904 else
905 return mpSetError->setErrorBoth(E_FAIL, VERR_NOT_FOUND, tr("Unknown conditional placeholder '%.*s'"),
906 cchPlaceholder, pachPlaceholder);
907 return S_OK;
908#undef IS_PLACEHOLDER_MATCH
909}
910
911#endif /* VBOX_WITH_UNATTENDED */
912#if 0 /* Keeping this a reference */
913
914
915/*********************************************************************************************************************************
916* UnattendedSUSEXMLScript Implementation *
917*********************************************************************************************************************************/
918
919HRESULT UnattendedSUSEXMLScript::parse()
920{
921 HRESULT hrc = UnattendedXMLScript::parse();
922 if (SUCCEEDED(hrc))
923 {
924 /*
925 * Check that we've got the right root element type.
926 */
927 const xml::ElementNode *pelmRoot = mDoc.getRootElement();
928 if ( pelmRoot
929 && strcmp(pelmRoot->getName(), "profile") == 0)
930 {
931 /*
932 * Work thought the sections.
933 */
934 try
935 {
936 LoopThruSections(pelmRoot);
937 hrc = S_OK;
938 }
939 catch (std::bad_alloc &)
940 {
941 hrc = E_OUTOFMEMORY;
942 }
943 }
944 else if (pelmRoot)
945 hrc = mpSetError->setError(E_FAIL, tr("XML document root element is '%s' instead of 'profile'"),
946 pelmRoot->getName());
947 else
948 hrc = mpSetError->setError(E_FAIL, tr("Missing XML root element"));
949 }
950 return hrc;
951}
952
953HRESULT UnattendedSUSEXMLScript::setFieldInElement(xml::ElementNode *pElement, const DataId enmDataId, const Utf8Str &rStrValue)
954{
955 /*
956 * Don't set empty values.
957 */
958 if (rStrValue.isEmpty())
959 {
960 Utf8Str strProbableValue;
961 try
962 {
963 strProbableValue = createProbableValue(enmDataId, pElement);
964 }
965 catch (std::bad_alloc &)
966 {
967 return E_OUTOFMEMORY;
968 }
969 return UnattendedXMLScript::setFieldInElement(pElement, enmDataId, strProbableValue);
970 }
971 return UnattendedXMLScript::setFieldInElement(pElement, enmDataId, rStrValue);
972}
973
974HRESULT UnattendedSUSEXMLScript::LoopThruSections(const xml::ElementNode *pelmRoot)
975{
976 xml::NodesLoop loopChildren(*pelmRoot);
977 const xml::ElementNode *pelmOuterLoop;
978 while ((pelmOuterLoop = loopChildren.forAllNodes()) != NULL)
979 {
980 const char *pcszElemName = pelmOuterLoop->getName();
981 if (!strcmp(pcszElemName, "users"))
982 {
983 xml::NodesLoop loopUsers(*pelmOuterLoop);
984 const xml::ElementNode *pelmUser;
985 while ((pelmUser = loopUsers.forAllNodes()) != NULL)
986 {
987 HRESULT hrc = HandleUserAccountsSection(pelmUser);
988 if (FAILED(hrc))
989 return hrc;
990 }
991 }
992 }
993 return S_OK;
994}
995
996HRESULT UnattendedSUSEXMLScript::HandleUserAccountsSection(const xml::ElementNode *pelmSection)
997{
998 xml::NodesLoop loopUser(*pelmSection);
999
1000 const xml::ElementNode *pelmCur;
1001 while ((pelmCur = loopUser.forAllNodes()) != NULL)
1002 {
1003 const char *pszValue = pelmCur->getValue();
1004#ifdef LOG_ENABLED
1005 if (!RTStrCmp(pelmCur->getName(), "uid"))
1006 LogRelFunc(("UnattendedSUSEXMLScript::HandleUserAccountsSection profile/users/%s/%s = %s\n",
1007 pelmSection->getName(), pelmCur->getName(), pszValue));
1008#endif
1009
1010 if (!RTStrCmp(pszValue, "$homedir"))
1011 mNodesForCorrectionMap.insert(make_pair(USERHOMEDIR_ID, pelmCur));
1012
1013 if (!RTStrCmp(pszValue, "$user"))
1014 mNodesForCorrectionMap.insert(make_pair(USERNAME_ID, pelmCur));
1015
1016 if (!RTStrCmp(pszValue, "$password"))
1017 mNodesForCorrectionMap.insert(make_pair(USERPASSWORD_ID, pelmCur));
1018 }
1019 return S_OK;
1020}
1021
1022Utf8Str UnattendedSUSEXMLScript::createProbableValue(const DataId enmDataId, const xml::ElementNode *pCurElem)
1023{
1024 const xml::ElementNode *pElem = pCurElem;
1025
1026 switch (enmDataId)
1027 {
1028 case USERHOMEDIR_ID:
1029// if ((pElem = pElem->findChildElement("home")))
1030// {
1031 return createProbableUserHomeDir(pElem);
1032// }
1033 break;
1034 default:
1035 break;
1036 }
1037
1038 return Utf8Str::Empty;
1039}
1040
1041Utf8Str UnattendedSUSEXMLScript::createProbableUserHomeDir(const xml::ElementNode *pCurElem)
1042{
1043 Utf8Str strCalcValue;
1044 const xml::ElementNode *pElem = pCurElem->findNextSibilingElement("username");
1045 if (pElem)
1046 {
1047 const char *pszValue = pElem->getValue();
1048 strCalcValue = "/home/";
1049 strCalcValue.append(pszValue);
1050 }
1051
1052 return strCalcValue;
1053}
1054#endif /* just for reference */
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette