acme.sh 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545
  1. #!/usr/bin/env sh
  2. VER=2.6.5
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
  7. _SCRIPT_="$0"
  8. _SUB_FOLDERS="dnsapi deploy"
  9. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  10. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"
  11. DEFAULT_USER_AGENT="$PROJECT_NAME/$VER ($PROJECT)"
  12. DEFAULT_ACCOUNT_EMAIL=""
  13. DEFAULT_ACCOUNT_KEY_LENGTH=2048
  14. DEFAULT_DOMAIN_KEY_LENGTH=2048
  15. DEFAULT_OPENSSL_BIN="openssl"
  16. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  17. VTYPE_HTTP="http-01"
  18. VTYPE_DNS="dns-01"
  19. VTYPE_TLS="tls-sni-01"
  20. #VTYPE_TLS2="tls-sni-02"
  21. LOCAL_ANY_ADDRESS="0.0.0.0"
  22. MAX_RENEW=60
  23. DEFAULT_DNS_SLEEP=120
  24. NO_VALUE="no"
  25. W_TLS="tls"
  26. STATE_VERIFIED="verified_ok"
  27. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  28. END_CSR="-----END CERTIFICATE REQUEST-----"
  29. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  30. END_CERT="-----END CERTIFICATE-----"
  31. RENEW_SKIP=2
  32. ECC_SEP="_"
  33. ECC_SUFFIX="${ECC_SEP}ecc"
  34. LOG_LEVEL_1=1
  35. LOG_LEVEL_2=2
  36. LOG_LEVEL_3=3
  37. DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
  38. _DEBUG_WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-debug-acme.sh"
  39. __INTERACTIVE=""
  40. if [ -t 1 ]; then
  41. __INTERACTIVE="1"
  42. fi
  43. __green() {
  44. if [ "$__INTERACTIVE" ]; then
  45. printf '\033[1;31;32m'
  46. fi
  47. printf -- "$1"
  48. if [ "$__INTERACTIVE" ]; then
  49. printf '\033[0m'
  50. fi
  51. }
  52. __red() {
  53. if [ "$__INTERACTIVE" ]; then
  54. printf '\033[1;31;40m'
  55. fi
  56. printf -- "$1"
  57. if [ "$__INTERACTIVE" ]; then
  58. printf '\033[0m'
  59. fi
  60. }
  61. _printargs() {
  62. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  63. printf -- "%s" "[$(date)] "
  64. fi
  65. if [ -z "$2" ]; then
  66. printf -- "%s" "$1"
  67. else
  68. printf -- "%s" "$1='$2'"
  69. fi
  70. printf "\n"
  71. }
  72. _dlg_versions() {
  73. echo "Diagnosis versions: "
  74. echo "openssl:$OPENSSL_BIN"
  75. if _exists "$OPENSSL_BIN"; then
  76. $OPENSSL_BIN version 2>&1
  77. else
  78. echo "$OPENSSL_BIN doesn't exists."
  79. fi
  80. echo "apache:"
  81. if [ "$_APACHECTL" ] && _exists "$_APACHECTL"; then
  82. _APACHECTL -V 2>&1
  83. else
  84. echo "apache doesn't exists."
  85. fi
  86. echo "nc:"
  87. if _exists "nc"; then
  88. nc -h 2>&1
  89. else
  90. _debug "nc doesn't exists."
  91. fi
  92. }
  93. _log() {
  94. [ -z "$LOG_FILE" ] && return
  95. _printargs "$@" >>"$LOG_FILE"
  96. }
  97. _info() {
  98. _log "$@"
  99. _printargs "$@"
  100. }
  101. _err() {
  102. _log "$@"
  103. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  104. printf -- "%s" "[$(date)] " >&2
  105. fi
  106. if [ -z "$2" ]; then
  107. __red "$1" >&2
  108. else
  109. __red "$1='$2'" >&2
  110. fi
  111. printf "\n" >&2
  112. return 1
  113. }
  114. _usage() {
  115. __red "$@" >&2
  116. printf "\n" >&2
  117. }
  118. _debug() {
  119. if [ -z "$LOG_LEVEL" ] || [ "$LOG_LEVEL" -ge "$LOG_LEVEL_1" ]; then
  120. _log "$@"
  121. fi
  122. if [ -z "$DEBUG" ]; then
  123. return
  124. fi
  125. _printargs "$@" >&2
  126. }
  127. _debug2() {
  128. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_2" ]; then
  129. _log "$@"
  130. fi
  131. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  132. _debug "$@"
  133. fi
  134. }
  135. _debug3() {
  136. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_3" ]; then
  137. _log "$@"
  138. fi
  139. if [ "$DEBUG" ] && [ "$DEBUG" -ge "3" ]; then
  140. _debug "$@"
  141. fi
  142. }
  143. _startswith() {
  144. _str="$1"
  145. _sub="$2"
  146. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  147. }
  148. _endswith() {
  149. _str="$1"
  150. _sub="$2"
  151. echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
  152. }
  153. _contains() {
  154. _str="$1"
  155. _sub="$2"
  156. echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
  157. }
  158. _hasfield() {
  159. _str="$1"
  160. _field="$2"
  161. _sep="$3"
  162. if [ -z "$_field" ]; then
  163. _usage "Usage: str field [sep]"
  164. return 1
  165. fi
  166. if [ -z "$_sep" ]; then
  167. _sep=","
  168. fi
  169. for f in $(echo "$_str" | tr ',' ' '); do
  170. if [ "$f" = "$_field" ]; then
  171. _debug2 "'$_str' contains '$_field'"
  172. return 0 #contains ok
  173. fi
  174. done
  175. _debug2 "'$_str' does not contain '$_field'"
  176. return 1 #not contains
  177. }
  178. _getfield() {
  179. _str="$1"
  180. _findex="$2"
  181. _sep="$3"
  182. if [ -z "$_findex" ]; then
  183. _usage "Usage: str field [sep]"
  184. return 1
  185. fi
  186. if [ -z "$_sep" ]; then
  187. _sep=","
  188. fi
  189. _ffi="$_findex"
  190. while [ "$_ffi" -gt "0" ]; do
  191. _fv="$(echo "$_str" | cut -d "$_sep" -f "$_ffi")"
  192. if [ "$_fv" ]; then
  193. printf -- "%s" "$_fv"
  194. return 0
  195. fi
  196. _ffi="$(_math "$_ffi" - 1)"
  197. done
  198. printf -- "%s" "$_str"
  199. }
  200. _exists() {
  201. cmd="$1"
  202. if [ -z "$cmd" ]; then
  203. _usage "Usage: _exists cmd"
  204. return 1
  205. fi
  206. if eval type type >/dev/null 2>&1; then
  207. eval type "$cmd" >/dev/null 2>&1
  208. elif command >/dev/null 2>&1; then
  209. command -v "$cmd" >/dev/null 2>&1
  210. else
  211. which "$cmd" >/dev/null 2>&1
  212. fi
  213. ret="$?"
  214. _debug3 "$cmd exists=$ret"
  215. return $ret
  216. }
  217. #a + b
  218. _math() {
  219. _m_opts="$@"
  220. printf "%s" "$(($_m_opts))"
  221. }
  222. _h_char_2_dec() {
  223. _ch=$1
  224. case "${_ch}" in
  225. a | A)
  226. printf "10"
  227. ;;
  228. b | B)
  229. printf "11"
  230. ;;
  231. c | C)
  232. printf "12"
  233. ;;
  234. d | D)
  235. printf "13"
  236. ;;
  237. e | E)
  238. printf "14"
  239. ;;
  240. f | F)
  241. printf "15"
  242. ;;
  243. *)
  244. printf "%s" "$_ch"
  245. ;;
  246. esac
  247. }
  248. _URGLY_PRINTF=""
  249. if [ "$(printf '\x41')" != 'A' ]; then
  250. _URGLY_PRINTF=1
  251. fi
  252. _h2b() {
  253. hex=$(cat)
  254. i=1
  255. j=2
  256. _debug3 _URGLY_PRINTF "$_URGLY_PRINTF"
  257. while true; do
  258. if [ -z "$_URGLY_PRINTF" ]; then
  259. h="$(printf "%s" "$hex" | cut -c $i-$j)"
  260. if [ -z "$h" ]; then
  261. break
  262. fi
  263. printf "\x$h%s"
  264. else
  265. ic="$(printf "%s" "$hex" | cut -c $i)"
  266. jc="$(printf "%s" "$hex" | cut -c $j)"
  267. if [ -z "$ic$jc" ]; then
  268. break
  269. fi
  270. ic="$(_h_char_2_dec "$ic")"
  271. jc="$(_h_char_2_dec "$jc")"
  272. printf '\'"$(printf "%o" "$(_math "$ic" \* 16 + $jc)")""%s"
  273. fi
  274. i="$(_math "$i" + 2)"
  275. j="$(_math "$j" + 2)"
  276. done
  277. }
  278. #hex string
  279. _hex() {
  280. _str="$1"
  281. _str_len=${#_str}
  282. _h_i=1
  283. while [ "$_h_i" -le "$_str_len" ]; do
  284. _str_c="$(printf "%s" "$_str" | cut -c "$_h_i")"
  285. printf "%02x" "'$_str_c"
  286. _h_i="$(_math "$_h_i" + 1)"
  287. done
  288. }
  289. #options file
  290. _sed_i() {
  291. options="$1"
  292. filename="$2"
  293. if [ -z "$filename" ]; then
  294. _usage "Usage:_sed_i options filename"
  295. return 1
  296. fi
  297. _debug2 options "$options"
  298. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  299. _debug "Using sed -i"
  300. sed -i "$options" "$filename"
  301. else
  302. _debug "No -i support in sed"
  303. text="$(cat "$filename")"
  304. echo "$text" | sed "$options" >"$filename"
  305. fi
  306. }
  307. _egrep_o() {
  308. if ! egrep -o "$1" 2>/dev/null; then
  309. sed -n 's/.*\('"$1"'\).*/\1/p'
  310. fi
  311. }
  312. #Usage: file startline endline
  313. _getfile() {
  314. filename="$1"
  315. startline="$2"
  316. endline="$3"
  317. if [ -z "$endline" ]; then
  318. _usage "Usage: file startline endline"
  319. return 1
  320. fi
  321. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  322. if [ -z "$i" ]; then
  323. _err "Can not find start line: $startline"
  324. return 1
  325. fi
  326. i="$(_math "$i" + 1)"
  327. _debug i "$i"
  328. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  329. if [ -z "$j" ]; then
  330. _err "Can not find end line: $endline"
  331. return 1
  332. fi
  333. j="$(_math "$j" - 1)"
  334. _debug j "$j"
  335. sed -n "$i,${j}p" "$filename"
  336. }
  337. #Usage: multiline
  338. _base64() {
  339. [ "" ] #urgly
  340. if [ "$1" ]; then
  341. _debug3 "base64 multiline:'$1'"
  342. $OPENSSL_BIN base64 -e
  343. else
  344. _debug3 "base64 single line."
  345. $OPENSSL_BIN base64 -e | tr -d '\r\n'
  346. fi
  347. }
  348. #Usage: multiline
  349. _dbase64() {
  350. if [ "$1" ]; then
  351. $OPENSSL_BIN base64 -d -A
  352. else
  353. $OPENSSL_BIN base64 -d
  354. fi
  355. }
  356. #Usage: hashalg [outputhex]
  357. #Output Base64-encoded digest
  358. _digest() {
  359. alg="$1"
  360. if [ -z "$alg" ]; then
  361. _usage "Usage: _digest hashalg"
  362. return 1
  363. fi
  364. outputhex="$2"
  365. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ] || [ "$alg" = "md5" ]; then
  366. if [ "$outputhex" ]; then
  367. $OPENSSL_BIN dgst -"$alg" -hex | cut -d = -f 2 | tr -d ' '
  368. else
  369. $OPENSSL_BIN dgst -"$alg" -binary | _base64
  370. fi
  371. else
  372. _err "$alg is not supported yet"
  373. return 1
  374. fi
  375. }
  376. #Usage: hashalg secret_hex [outputhex]
  377. #Output binary hmac
  378. _hmac() {
  379. alg="$1"
  380. secret_hex="$2"
  381. outputhex="$3"
  382. if [ -z "$secret_hex" ]; then
  383. _usage "Usage: _hmac hashalg secret [outputhex]"
  384. return 1
  385. fi
  386. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
  387. if [ "$outputhex" ]; then
  388. $OPENSSL_BIN dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" | cut -d = -f 2 | tr -d ' '
  389. else
  390. $OPENSSL_BIN dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" -binary
  391. fi
  392. else
  393. _err "$alg is not supported yet"
  394. return 1
  395. fi
  396. }
  397. #Usage: keyfile hashalg
  398. #Output: Base64-encoded signature value
  399. _sign() {
  400. keyfile="$1"
  401. alg="$2"
  402. if [ -z "$alg" ]; then
  403. _usage "Usage: _sign keyfile hashalg"
  404. return 1
  405. fi
  406. _sign_openssl="$OPENSSL_BIN dgst -sign $keyfile "
  407. if [ "$alg" = "sha256" ]; then
  408. _sign_openssl="$_sign_openssl -$alg"
  409. else
  410. _err "$alg is not supported yet"
  411. return 1
  412. fi
  413. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  414. $_sign_openssl | _base64
  415. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  416. if ! _signedECText="$($_sign_openssl | $OPENSSL_BIN asn1parse -inform DER)"; then
  417. _err "Sign failed: $_sign_openssl"
  418. _err "Key file: $keyfile"
  419. _err "Key content:$(wc -l <"$keyfile") lises"
  420. return 1
  421. fi
  422. _debug3 "_signedECText" "$_signedECText"
  423. _ec_r="$(echo "$_signedECText" | _head_n 2 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  424. _debug3 "_ec_r" "$_ec_r"
  425. _ec_s="$(echo "$_signedECText" | _head_n 3 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  426. _debug3 "_ec_s" "$_ec_s"
  427. printf "%s" "$_ec_r$_ec_s" | _h2b | _base64
  428. else
  429. _err "Unknown key file format."
  430. return 1
  431. fi
  432. }
  433. #keylength
  434. _isEccKey() {
  435. _length="$1"
  436. if [ -z "$_length" ]; then
  437. return 1
  438. fi
  439. [ "$_length" != "1024" ] \
  440. && [ "$_length" != "2048" ] \
  441. && [ "$_length" != "3072" ] \
  442. && [ "$_length" != "4096" ] \
  443. && [ "$_length" != "8192" ]
  444. }
  445. # _createkey 2048|ec-256 file
  446. _createkey() {
  447. length="$1"
  448. f="$2"
  449. _debug2 "_createkey for file:$f"
  450. eccname="$length"
  451. if _startswith "$length" "ec-"; then
  452. length=$(printf "%s" "$length" | cut -d '-' -f 2-100)
  453. if [ "$length" = "256" ]; then
  454. eccname="prime256v1"
  455. fi
  456. if [ "$length" = "384" ]; then
  457. eccname="secp384r1"
  458. fi
  459. if [ "$length" = "521" ]; then
  460. eccname="secp521r1"
  461. fi
  462. fi
  463. if [ -z "$length" ]; then
  464. length=2048
  465. fi
  466. _debug "Use length $length"
  467. if _isEccKey "$length"; then
  468. _debug "Using ec name: $eccname"
  469. $OPENSSL_BIN ecparam -name "$eccname" -genkey 2>/dev/null >"$f"
  470. else
  471. _debug "Using RSA: $length"
  472. $OPENSSL_BIN genrsa "$length" 2>/dev/null >"$f"
  473. fi
  474. if [ "$?" != "0" ]; then
  475. _err "Create key error."
  476. return 1
  477. fi
  478. }
  479. #domain
  480. _is_idn() {
  481. _is_idn_d="$1"
  482. _debug2 _is_idn_d "$_is_idn_d"
  483. _idn_temp=$(printf "%s" "$_is_idn_d" | tr -d '[0-9]' | tr -d '[a-z]' | tr -d '[A-Z]' | tr -d '.,-')
  484. _debug2 _idn_temp "$_idn_temp"
  485. [ "$_idn_temp" ]
  486. }
  487. #aa.com
  488. #aa.com,bb.com,cc.com
  489. _idn() {
  490. __idn_d="$1"
  491. if ! _is_idn "$__idn_d"; then
  492. printf "%s" "$__idn_d"
  493. return 0
  494. fi
  495. if _exists idn; then
  496. if _contains "$__idn_d" ','; then
  497. _i_first="1"
  498. for f in $(echo "$__idn_d" | tr ',' ' '); do
  499. [ -z "$f" ] && continue
  500. if [ -z "$_i_first" ]; then
  501. printf "%s" ","
  502. else
  503. _i_first=""
  504. fi
  505. idn --quiet "$f" | tr -d "\r\n"
  506. done
  507. else
  508. idn "$__idn_d" | tr -d "\r\n"
  509. fi
  510. else
  511. _err "Please install idn to process IDN names."
  512. fi
  513. }
  514. #_createcsr cn san_list keyfile csrfile conf
  515. _createcsr() {
  516. _debug _createcsr
  517. domain="$1"
  518. domainlist="$2"
  519. csrkey="$3"
  520. csr="$4"
  521. csrconf="$5"
  522. _debug2 domain "$domain"
  523. _debug2 domainlist "$domainlist"
  524. _debug2 csrkey "$csrkey"
  525. _debug2 csr "$csr"
  526. _debug2 csrconf "$csrconf"
  527. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment" >"$csrconf"
  528. if [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
  529. #single domain
  530. _info "Single domain" "$domain"
  531. else
  532. domainlist="$(_idn "$domainlist")"
  533. _debug2 domainlist "$domainlist"
  534. if _contains "$domainlist" ","; then
  535. alt="DNS:$(echo "$domainlist" | sed "s/,/,DNS:/g")"
  536. else
  537. alt="DNS:$domainlist"
  538. fi
  539. #multi
  540. _info "Multi domain" "$alt"
  541. printf -- "\nsubjectAltName=$alt" >>"$csrconf"
  542. fi
  543. if [ "$Le_OCSP_Staple" ] || [ "$Le_OCSP_Stable" ]; then
  544. _savedomainconf Le_OCSP_Staple "$Le_OCSP_Staple"
  545. _cleardomainconf Le_OCSP_Stable
  546. printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >>"$csrconf"
  547. fi
  548. _csr_cn="$(_idn "$domain")"
  549. _debug2 _csr_cn "$_csr_cn"
  550. $OPENSSL_BIN req -new -sha256 -key "$csrkey" -subj "/CN=$_csr_cn" -config "$csrconf" -out "$csr"
  551. }
  552. #_signcsr key csr conf cert
  553. _signcsr() {
  554. key="$1"
  555. csr="$2"
  556. conf="$3"
  557. cert="$4"
  558. _debug "_signcsr"
  559. _msg="$($OPENSSL_BIN x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  560. _ret="$?"
  561. _debug "$_msg"
  562. return $_ret
  563. }
  564. #_csrfile
  565. _readSubjectFromCSR() {
  566. _csrfile="$1"
  567. if [ -z "$_csrfile" ]; then
  568. _usage "_readSubjectFromCSR mycsr.csr"
  569. return 1
  570. fi
  571. $OPENSSL_BIN req -noout -in "$_csrfile" -subject | _egrep_o "CN=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d '\n'
  572. }
  573. #_csrfile
  574. #echo comma separated domain list
  575. _readSubjectAltNamesFromCSR() {
  576. _csrfile="$1"
  577. if [ -z "$_csrfile" ]; then
  578. _usage "_readSubjectAltNamesFromCSR mycsr.csr"
  579. return 1
  580. fi
  581. _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
  582. _debug _csrsubj "$_csrsubj"
  583. _dnsAltnames="$($OPENSSL_BIN req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
  584. _debug _dnsAltnames "$_dnsAltnames"
  585. if _contains "$_dnsAltnames," "DNS:$_csrsubj,"; then
  586. _debug "AltNames contains subject"
  587. _dnsAltnames="$(printf "%s" "$_dnsAltnames," | sed "s/DNS:$_csrsubj,//g")"
  588. else
  589. _debug "AltNames doesn't contain subject"
  590. fi
  591. printf "%s" "$_dnsAltnames" | sed "s/DNS://g"
  592. }
  593. #_csrfile
  594. _readKeyLengthFromCSR() {
  595. _csrfile="$1"
  596. if [ -z "$_csrfile" ]; then
  597. _usage "_readKeyLengthFromCSR mycsr.csr"
  598. return 1
  599. fi
  600. _outcsr="$($OPENSSL_BIN req -noout -text -in "$_csrfile")"
  601. if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey"; then
  602. _debug "ECC CSR"
  603. echo "$_outcsr" | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
  604. else
  605. _debug "RSA CSR"
  606. echo "$_outcsr" | _egrep_o "^ *Public-Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
  607. fi
  608. }
  609. _ss() {
  610. _port="$1"
  611. if _exists "ss"; then
  612. _debug "Using: ss"
  613. ss -ntpl | grep ":$_port "
  614. return 0
  615. fi
  616. if _exists "netstat"; then
  617. _debug "Using: netstat"
  618. if netstat -h 2>&1 | grep "\-p proto" >/dev/null; then
  619. #for windows version netstat tool
  620. netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
  621. else
  622. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null; then
  623. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  624. elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null; then
  625. #for solaris
  626. netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
  627. else
  628. netstat -ntpl | grep ":$_port "
  629. fi
  630. fi
  631. return 0
  632. fi
  633. return 1
  634. }
  635. #domain [password] [isEcc]
  636. toPkcs() {
  637. domain="$1"
  638. pfxPassword="$2"
  639. if [ -z "$domain" ]; then
  640. _usage "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  641. return 1
  642. fi
  643. _isEcc="$3"
  644. _initpath "$domain" "$_isEcc"
  645. if [ "$pfxPassword" ]; then
  646. $OPENSSL_BIN pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  647. else
  648. $OPENSSL_BIN pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  649. fi
  650. if [ "$?" = "0" ]; then
  651. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  652. fi
  653. }
  654. #[2048]
  655. createAccountKey() {
  656. _info "Creating account key"
  657. if [ -z "$1" ]; then
  658. _usage "Usage: $PROJECT_ENTRY --createAccountKey --accountkeylength 2048"
  659. return
  660. fi
  661. length=$1
  662. _create_account_key "$length"
  663. }
  664. _create_account_key() {
  665. length=$1
  666. if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ]; then
  667. _debug "Use default length $DEFAULT_ACCOUNT_KEY_LENGTH"
  668. length="$DEFAULT_ACCOUNT_KEY_LENGTH"
  669. fi
  670. _debug length "$length"
  671. _initpath
  672. mkdir -p "$CA_DIR"
  673. if [ -f "$ACCOUNT_KEY_PATH" ]; then
  674. _info "Account key exists, skip"
  675. return
  676. else
  677. #generate account key
  678. _createkey "$length" "$ACCOUNT_KEY_PATH"
  679. fi
  680. }
  681. #domain [length]
  682. createDomainKey() {
  683. _info "Creating domain key"
  684. if [ -z "$1" ]; then
  685. _usage "Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]"
  686. return
  687. fi
  688. domain=$1
  689. length=$2
  690. if [ -z "$length" ]; then
  691. _debug "Use DEFAULT_DOMAIN_KEY_LENGTH=$DEFAULT_DOMAIN_KEY_LENGTH"
  692. length="$DEFAULT_DOMAIN_KEY_LENGTH"
  693. fi
  694. _initpath "$domain" "$length"
  695. if [ ! -f "$CERT_KEY_PATH" ] || ([ "$FORCE" ] && ! [ "$IS_RENEW" ]); then
  696. _createkey "$length" "$CERT_KEY_PATH"
  697. else
  698. if [ "$IS_RENEW" ]; then
  699. _info "Domain key exists, skip"
  700. return 0
  701. else
  702. _err "Domain key exists, do you want to overwrite the key?"
  703. _err "Add '--force', and try again."
  704. return 1
  705. fi
  706. fi
  707. }
  708. # domain domainlist isEcc
  709. createCSR() {
  710. _info "Creating csr"
  711. if [ -z "$1" ]; then
  712. _usage "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
  713. return
  714. fi
  715. domain="$1"
  716. domainlist="$2"
  717. _isEcc="$3"
  718. _initpath "$domain" "$_isEcc"
  719. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  720. _info "CSR exists, skip"
  721. return
  722. fi
  723. if [ ! -f "$CERT_KEY_PATH" ]; then
  724. _err "The key file is not found: $CERT_KEY_PATH"
  725. _err "Please create the key file first."
  726. return 1
  727. fi
  728. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  729. }
  730. _urlencode() {
  731. tr '/+' '_-' | tr -d '= '
  732. }
  733. _time2str() {
  734. #BSD
  735. if date -u -d@"$1" 2>/dev/null; then
  736. return
  737. fi
  738. #Linux
  739. if date -u -r "$1" 2>/dev/null; then
  740. return
  741. fi
  742. #Soaris
  743. if _exists adb; then
  744. _t_s_a=$(echo "0t${1}=Y" | adb)
  745. echo "$_t_s_a"
  746. fi
  747. }
  748. _normalizeJson() {
  749. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  750. }
  751. _stat() {
  752. #Linux
  753. if stat -c '%U:%G' "$1" 2>/dev/null; then
  754. return
  755. fi
  756. #BSD
  757. if stat -f '%Su:%Sg' "$1" 2>/dev/null; then
  758. return
  759. fi
  760. return 1 #error, 'stat' not found
  761. }
  762. #keyfile
  763. _calcjwk() {
  764. keyfile="$1"
  765. if [ -z "$keyfile" ]; then
  766. _usage "Usage: _calcjwk keyfile"
  767. return 1
  768. fi
  769. if [ "$JWK_HEADER" ] && [ "$__CACHED_JWK_KEY_FILE" = "$keyfile" ]; then
  770. _debug2 "Use cached jwk for file: $__CACHED_JWK_KEY_FILE"
  771. return 0
  772. fi
  773. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  774. _debug "RSA key"
  775. pub_exp=$($OPENSSL_BIN rsa -in "$keyfile" -noout -text | grep "^publicExponent:" | cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  776. if [ "${#pub_exp}" = "5" ]; then
  777. pub_exp=0$pub_exp
  778. fi
  779. _debug3 pub_exp "$pub_exp"
  780. e=$(echo "$pub_exp" | _h2b | _base64)
  781. _debug3 e "$e"
  782. modulus=$($OPENSSL_BIN rsa -in "$keyfile" -modulus -noout | cut -d '=' -f 2)
  783. _debug3 modulus "$modulus"
  784. n="$(printf "%s" "$modulus" | _h2b | _base64 | _urlencode)"
  785. _debug3 n "$n"
  786. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  787. _debug3 jwk "$jwk"
  788. JWK_HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  789. JWK_HEADERPLACE_PART1='{"nonce": "'
  790. JWK_HEADERPLACE_PART2='", "alg": "RS256", "jwk": '$jwk'}'
  791. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  792. _debug "EC key"
  793. crv="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  794. _debug3 crv "$crv"
  795. if [ -z "$crv" ]; then
  796. _debug "Let's try ASN1 OID"
  797. crv_oid="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep "^ASN1 OID:" | cut -d ":" -f 2 | tr -d " \r\n")"
  798. _debug3 crv_oid "$crv_oid"
  799. case "${crv_oid}" in
  800. "prime256v1")
  801. crv="P-256"
  802. ;;
  803. "secp384r1")
  804. crv="P-384"
  805. ;;
  806. "secp521r1")
  807. crv="P-521"
  808. ;;
  809. *)
  810. _err "ECC oid : $crv_oid"
  811. return 1
  812. ;;
  813. esac
  814. _debug3 crv "$crv"
  815. fi
  816. pubi="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  817. pubi=$(_math "$pubi" + 1)
  818. _debug3 pubi "$pubi"
  819. pubj="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  820. pubj=$(_math "$pubj" - 1)
  821. _debug3 pubj "$pubj"
  822. pubtext="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  823. _debug3 pubtext "$pubtext"
  824. xlen="$(printf "%s" "$pubtext" | tr -d ':' | wc -c)"
  825. xlen=$(_math "$xlen" / 4)
  826. _debug3 xlen "$xlen"
  827. xend=$(_math "$xlen" + 1)
  828. x="$(printf "%s" "$pubtext" | cut -d : -f 2-"$xend")"
  829. _debug3 x "$x"
  830. x64="$(printf "%s" "$x" | tr -d : | _h2b | _base64 | _urlencode)"
  831. _debug3 x64 "$x64"
  832. xend=$(_math "$xend" + 1)
  833. y="$(printf "%s" "$pubtext" | cut -d : -f "$xend"-10000)"
  834. _debug3 y "$y"
  835. y64="$(printf "%s" "$y" | tr -d : | _h2b | _base64 | _urlencode)"
  836. _debug3 y64 "$y64"
  837. jwk='{"crv": "'$crv'", "kty": "EC", "x": "'$x64'", "y": "'$y64'"}'
  838. _debug3 jwk "$jwk"
  839. JWK_HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  840. JWK_HEADERPLACE_PART1='{"nonce": "'
  841. JWK_HEADERPLACE_PART2='", "alg": "ES256", "jwk": '$jwk'}'
  842. else
  843. _err "Only RSA or EC key is supported."
  844. return 1
  845. fi
  846. _debug3 JWK_HEADER "$JWK_HEADER"
  847. __CACHED_JWK_KEY_FILE="$keyfile"
  848. }
  849. _time() {
  850. date -u "+%s"
  851. }
  852. _mktemp() {
  853. if _exists mktemp; then
  854. if mktemp 2>/dev/null; then
  855. return 0
  856. elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null; then
  857. #for Mac osx
  858. return 0
  859. fi
  860. fi
  861. if [ -d "/tmp" ]; then
  862. echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
  863. return 0
  864. elif [ "$LE_TEMP_DIR" ] && mkdir -p "$LE_TEMP_DIR"; then
  865. echo "/$LE_TEMP_DIR/wefADf24sf.$(_time).tmp"
  866. return 0
  867. fi
  868. _err "Can not create temp file."
  869. }
  870. _inithttp() {
  871. if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER"; then
  872. HTTP_HEADER="$(_mktemp)"
  873. _debug2 HTTP_HEADER "$HTTP_HEADER"
  874. fi
  875. if [ "$__HTTP_INITIALIZED" ]; then
  876. if [ "$_ACME_CURL$_ACME_WGET" ]; then
  877. _debug2 "Http already initialized."
  878. return 0
  879. fi
  880. fi
  881. if [ -z "$_ACME_CURL" ] && _exists "curl"; then
  882. _ACME_CURL="curl -L --silent --dump-header $HTTP_HEADER "
  883. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  884. _CURL_DUMP="$(_mktemp)"
  885. _ACME_CURL="$_ACME_CURL --trace-ascii $_CURL_DUMP "
  886. fi
  887. if [ "$CA_BUNDLE" ]; then
  888. _ACME_CURL="$_ACME_CURL --cacert $CA_BUNDLE "
  889. fi
  890. fi
  891. if [ -z "$_ACME_WGET" ] && _exists "wget"; then
  892. _ACME_WGET="wget -q"
  893. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  894. _ACME_WGET="$_ACME_WGET -d "
  895. fi
  896. if [ "$CA_BUNDLE" ]; then
  897. _ACME_WGET="$_ACME_WGET --ca-certificate $CA_BUNDLE "
  898. fi
  899. fi
  900. __HTTP_INITIALIZED=1
  901. }
  902. # body url [needbase64] [POST|PUT]
  903. _post() {
  904. body="$1"
  905. url="$2"
  906. needbase64="$3"
  907. httpmethod="$4"
  908. if [ -z "$httpmethod" ]; then
  909. httpmethod="POST"
  910. fi
  911. _debug $httpmethod
  912. _debug "url" "$url"
  913. _debug2 "body" "$body"
  914. _inithttp
  915. if [ "$_ACME_CURL" ]; then
  916. _CURL="$_ACME_CURL"
  917. if [ "$HTTPS_INSECURE" ]; then
  918. _CURL="$_CURL --insecure "
  919. fi
  920. _debug "_CURL" "$_CURL"
  921. if [ "$needbase64" ]; then
  922. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url" | _base64)"
  923. else
  924. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url")"
  925. fi
  926. _ret="$?"
  927. if [ "$_ret" != "0" ]; then
  928. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  929. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  930. _err "Here is the curl dump log:"
  931. _err "$(cat "$_CURL_DUMP")"
  932. fi
  933. fi
  934. elif [ "$_ACME_WGET" ]; then
  935. _WGET="$_ACME_WGET"
  936. if [ "$HTTPS_INSECURE" ]; then
  937. _WGET="$_WGET --no-check-certificate "
  938. fi
  939. _debug "_WGET" "$_WGET"
  940. if [ "$needbase64" ]; then
  941. if [ "$httpmethod" = "POST" ]; then
  942. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  943. else
  944. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  945. fi
  946. else
  947. if [ "$httpmethod" = "POST" ]; then
  948. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER")"
  949. else
  950. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER")"
  951. fi
  952. fi
  953. _ret="$?"
  954. if [ "$_ret" = "8" ]; then
  955. _ret=0
  956. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  957. fi
  958. if [ "$_ret" != "0" ]; then
  959. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  960. fi
  961. _sed_i "s/^ *//g" "$HTTP_HEADER"
  962. else
  963. _ret="$?"
  964. _err "Neither curl nor wget is found, can not do $httpmethod."
  965. fi
  966. _debug "_ret" "$_ret"
  967. printf "%s" "$response"
  968. return $_ret
  969. }
  970. # url getheader timeout
  971. _get() {
  972. _debug GET
  973. url="$1"
  974. onlyheader="$2"
  975. t="$3"
  976. _debug url "$url"
  977. _debug "timeout" "$t"
  978. _inithttp
  979. if [ "$_ACME_CURL" ]; then
  980. _CURL="$_ACME_CURL"
  981. if [ "$HTTPS_INSECURE" ]; then
  982. _CURL="$_CURL --insecure "
  983. fi
  984. if [ "$t" ]; then
  985. _CURL="$_CURL --connect-timeout $t"
  986. fi
  987. _debug "_CURL" "$_CURL"
  988. if [ "$onlyheader" ]; then
  989. $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  990. else
  991. $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  992. fi
  993. ret=$?
  994. if [ "$ret" != "0" ]; then
  995. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
  996. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  997. _err "Here is the curl dump log:"
  998. _err "$(cat "$_CURL_DUMP")"
  999. fi
  1000. fi
  1001. elif [ "$_ACME_WGET" ]; then
  1002. _WGET="$_ACME_WGET"
  1003. if [ "$HTTPS_INSECURE" ]; then
  1004. _WGET="$_WGET --no-check-certificate "
  1005. fi
  1006. if [ "$t" ]; then
  1007. _WGET="$_WGET --timeout=$t"
  1008. fi
  1009. _debug "_WGET" "$_WGET"
  1010. if [ "$onlyheader" ]; then
  1011. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null "$url" 2>&1 | sed 's/^[ ]*//g'
  1012. else
  1013. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - "$url"
  1014. fi
  1015. ret=$?
  1016. if [ "$_ret" = "8" ]; then
  1017. _ret=0
  1018. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  1019. fi
  1020. if [ "$ret" != "0" ]; then
  1021. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
  1022. fi
  1023. else
  1024. ret=$?
  1025. _err "Neither curl nor wget is found, can not do GET."
  1026. fi
  1027. _debug "ret" "$ret"
  1028. return $ret
  1029. }
  1030. _head_n() {
  1031. head -n "$1"
  1032. }
  1033. _tail_n() {
  1034. if ! tail -n "$1" 2>/dev/null; then
  1035. #fix for solaris
  1036. tail -"$1"
  1037. fi
  1038. }
  1039. # url payload needbase64 keyfile
  1040. _send_signed_request() {
  1041. url=$1
  1042. payload=$2
  1043. needbase64=$3
  1044. keyfile=$4
  1045. if [ -z "$keyfile" ]; then
  1046. keyfile="$ACCOUNT_KEY_PATH"
  1047. fi
  1048. _debug url "$url"
  1049. _debug payload "$payload"
  1050. if ! _calcjwk "$keyfile"; then
  1051. return 1
  1052. fi
  1053. payload64=$(printf "%s" "$payload" | _base64 | _urlencode)
  1054. _debug3 payload64 "$payload64"
  1055. if [ -z "$_CACHED_NONCE" ]; then
  1056. _debug2 "Get nonce."
  1057. nonceurl="$API/directory"
  1058. _headers="$(_get "$nonceurl" "onlyheader")"
  1059. if [ "$?" != "0" ]; then
  1060. _err "Can not connect to $nonceurl to get nonce."
  1061. return 1
  1062. fi
  1063. _debug2 _headers "$_headers"
  1064. _CACHED_NONCE="$(echo "$_headers" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1065. _debug2 _CACHED_NONCE "$_CACHED_NONCE"
  1066. else
  1067. _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
  1068. fi
  1069. nonce="$_CACHED_NONCE"
  1070. _debug2 nonce "$nonce"
  1071. protected="$JWK_HEADERPLACE_PART1$nonce$JWK_HEADERPLACE_PART2"
  1072. _debug3 protected "$protected"
  1073. protected64="$(printf "%s" "$protected" | _base64 | _urlencode)"
  1074. _debug3 protected64 "$protected64"
  1075. if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
  1076. _err "Sign request failed."
  1077. return 1
  1078. fi
  1079. _debug3 _sig_t "$_sig_t"
  1080. sig="$(printf "%s" "$_sig_t" | _urlencode)"
  1081. _debug3 sig "$sig"
  1082. body="{\"header\": $JWK_HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  1083. _debug3 body "$body"
  1084. response="$(_post "$body" "$url" "$needbase64")"
  1085. _CACHED_NONCE=""
  1086. if [ "$?" != "0" ]; then
  1087. _err "Can not post to $url"
  1088. return 1
  1089. fi
  1090. _debug2 original "$response"
  1091. response="$(echo "$response" | _normalizeJson)"
  1092. responseHeaders="$(cat "$HTTP_HEADER")"
  1093. _debug2 responseHeaders "$responseHeaders"
  1094. _debug2 response "$response"
  1095. code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  1096. _debug code "$code"
  1097. _CACHED_NONCE="$(echo "$responseHeaders" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1098. }
  1099. #setopt "file" "opt" "=" "value" [";"]
  1100. _setopt() {
  1101. __conf="$1"
  1102. __opt="$2"
  1103. __sep="$3"
  1104. __val="$4"
  1105. __end="$5"
  1106. if [ -z "$__opt" ]; then
  1107. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  1108. return
  1109. fi
  1110. if [ ! -f "$__conf" ]; then
  1111. touch "$__conf"
  1112. fi
  1113. if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
  1114. _debug3 OK
  1115. if _contains "$__val" "&"; then
  1116. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1117. fi
  1118. text="$(cat "$__conf")"
  1119. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1120. elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
  1121. if _contains "$__val" "&"; then
  1122. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1123. fi
  1124. text="$(cat "$__conf")"
  1125. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1126. else
  1127. _debug3 APP
  1128. echo "$__opt$__sep$__val$__end" >>"$__conf"
  1129. fi
  1130. _debug2 "$(grep -n "^$__opt$__sep" "$__conf")"
  1131. }
  1132. #_save_conf file key value
  1133. #save to conf
  1134. _save_conf() {
  1135. _s_c_f="$1"
  1136. _sdkey="$2"
  1137. _sdvalue="$3"
  1138. if [ "$_s_c_f" ]; then
  1139. _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
  1140. else
  1141. _err "config file is empty, can not save $_sdkey=$_sdvalue"
  1142. fi
  1143. }
  1144. #_clear_conf file key
  1145. _clear_conf() {
  1146. _c_c_f="$1"
  1147. _sdkey="$2"
  1148. if [ "$_c_c_f" ]; then
  1149. _conf_data="$(cat "$_c_c_f")"
  1150. echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
  1151. else
  1152. _err "config file is empty, can not clear"
  1153. fi
  1154. }
  1155. #_read_conf file key
  1156. _read_conf() {
  1157. _r_c_f="$1"
  1158. _sdkey="$2"
  1159. if [ -f "$_r_c_f" ]; then
  1160. (
  1161. eval "$(grep "^$_sdkey *=" "$_r_c_f")"
  1162. eval "printf \"%s\" \"\$$_sdkey\""
  1163. )
  1164. else
  1165. _debug "config file is empty, can not read $_sdkey"
  1166. fi
  1167. }
  1168. #_savedomainconf key value
  1169. #save to domain.conf
  1170. _savedomainconf() {
  1171. _save_conf "$DOMAIN_CONF" "$1" "$2"
  1172. }
  1173. #_cleardomainconf key
  1174. _cleardomainconf() {
  1175. _clear_conf "$DOMAIN_CONF" "$1"
  1176. }
  1177. #_readdomainconf key
  1178. _readdomainconf() {
  1179. _read_conf "$DOMAIN_CONF" "$1"
  1180. }
  1181. #_saveaccountconf key value
  1182. _saveaccountconf() {
  1183. _save_conf "$ACCOUNT_CONF_PATH" "$1" "$2"
  1184. }
  1185. #_clearaccountconf key
  1186. _clearaccountconf() {
  1187. _clear_conf "$ACCOUNT_CONF_PATH" "$1"
  1188. }
  1189. #_savecaconf key value
  1190. _savecaconf() {
  1191. _save_conf "$CA_CONF" "$1" "$2"
  1192. }
  1193. #_readcaconf key
  1194. _readcaconf() {
  1195. _read_conf "$CA_CONF" "$1"
  1196. }
  1197. #_clearaccountconf key
  1198. _clearcaconf() {
  1199. _clear_conf "$CA_CONF" "$1"
  1200. }
  1201. # content localaddress
  1202. _startserver() {
  1203. content="$1"
  1204. ncaddr="$2"
  1205. _debug "ncaddr" "$ncaddr"
  1206. _debug "startserver: $$"
  1207. nchelp="$(nc -h 2>&1)"
  1208. _debug Le_HTTPPort "$Le_HTTPPort"
  1209. _debug Le_Listen_V4 "$Le_Listen_V4"
  1210. _debug Le_Listen_V6 "$Le_Listen_V6"
  1211. _NC="nc"
  1212. if [ "$Le_Listen_V4" ]; then
  1213. _NC="$_NC -4"
  1214. elif [ "$Le_Listen_V6" ]; then
  1215. _NC="$_NC -6"
  1216. fi
  1217. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null; then
  1218. _NC="$_NC -q 1 -l $ncaddr"
  1219. else
  1220. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null; then
  1221. _NC="$_NC -c -l $ncaddr"
  1222. elif echo "$nchelp" | grep "\-N" | grep "Shutdown the network socket after EOF on stdin" >/dev/null; then
  1223. _NC="$_NC -N -l $ncaddr"
  1224. else
  1225. _NC="$_NC -l $ncaddr"
  1226. fi
  1227. fi
  1228. _debug "_NC" "$_NC"
  1229. #for centos ncat
  1230. if _contains "$nchelp" "nmap.org"; then
  1231. _debug "Using ncat: nmap.org"
  1232. if ! _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC \"$Le_HTTPPort\" >&2"; then
  1233. _exec_err
  1234. return 1
  1235. fi
  1236. if [ "$DEBUG" ]; then
  1237. _exec_err
  1238. fi
  1239. return
  1240. fi
  1241. # while true ; do
  1242. if ! _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC -p \"$Le_HTTPPort\" >&2"; then
  1243. _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC \"$Le_HTTPPort\" >&2"
  1244. fi
  1245. if [ "$?" != "0" ]; then
  1246. _err "nc listen error."
  1247. _exec_err
  1248. exit 1
  1249. fi
  1250. if [ "$DEBUG" ]; then
  1251. _exec_err
  1252. fi
  1253. # done
  1254. }
  1255. _stopserver() {
  1256. pid="$1"
  1257. _debug "pid" "$pid"
  1258. if [ -z "$pid" ]; then
  1259. return
  1260. fi
  1261. _debug2 "Le_HTTPPort" "$Le_HTTPPort"
  1262. if [ "$Le_HTTPPort" ]; then
  1263. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ]; then
  1264. _get "http://localhost:$Le_HTTPPort" "" 1
  1265. else
  1266. _get "http://localhost:$Le_HTTPPort" "" 1 >/dev/null 2>&1
  1267. fi
  1268. fi
  1269. _debug2 "Le_TLSPort" "$Le_TLSPort"
  1270. if [ "$Le_TLSPort" ]; then
  1271. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ]; then
  1272. _get "https://localhost:$Le_TLSPort" "" 1
  1273. _get "https://localhost:$Le_TLSPort" "" 1
  1274. else
  1275. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1276. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1277. fi
  1278. fi
  1279. }
  1280. # sleep sec
  1281. _sleep() {
  1282. _sleep_sec="$1"
  1283. if [ "$__INTERACTIVE" ]; then
  1284. _sleep_c="$_sleep_sec"
  1285. while [ "$_sleep_c" -ge "0" ]; do
  1286. printf "\r \r"
  1287. __green "$_sleep_c"
  1288. _sleep_c="$(_math "$_sleep_c" - 1)"
  1289. sleep 1
  1290. done
  1291. printf "\r"
  1292. else
  1293. sleep "$_sleep_sec"
  1294. fi
  1295. }
  1296. # _starttlsserver san_a san_b port content _ncaddr
  1297. _starttlsserver() {
  1298. _info "Starting tls server."
  1299. san_a="$1"
  1300. san_b="$2"
  1301. port="$3"
  1302. content="$4"
  1303. opaddr="$5"
  1304. _debug san_a "$san_a"
  1305. _debug san_b "$san_b"
  1306. _debug port "$port"
  1307. #create key TLS_KEY
  1308. if ! _createkey "2048" "$TLS_KEY"; then
  1309. _err "Create tls validation key error."
  1310. return 1
  1311. fi
  1312. #create csr
  1313. alt="$san_a"
  1314. if [ "$san_b" ]; then
  1315. alt="$alt,$san_b"
  1316. fi
  1317. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF"; then
  1318. _err "Create tls validation csr error."
  1319. return 1
  1320. fi
  1321. #self signed
  1322. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
  1323. _err "Create tls validation cert error."
  1324. return 1
  1325. fi
  1326. __S_OPENSSL="$OPENSSL_BIN s_server -cert $TLS_CERT -key $TLS_KEY "
  1327. if [ "$opaddr" ]; then
  1328. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1329. else
  1330. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1331. fi
  1332. _debug Le_Listen_V4 "$Le_Listen_V4"
  1333. _debug Le_Listen_V6 "$Le_Listen_V6"
  1334. if [ "$Le_Listen_V4" ]; then
  1335. __S_OPENSSL="$__S_OPENSSL -4"
  1336. elif [ "$Le_Listen_V6" ]; then
  1337. __S_OPENSSL="$__S_OPENSSL -6"
  1338. fi
  1339. _debug "$__S_OPENSSL"
  1340. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1341. (printf "%s\r\n\r\n%s" "HTTP/1.1 200 OK" "$content" | $__S_OPENSSL -tlsextdebug) &
  1342. else
  1343. (printf "%s\r\n\r\n%s" "HTTP/1.1 200 OK" "$content" | $__S_OPENSSL >/dev/null 2>&1) &
  1344. fi
  1345. serverproc="$!"
  1346. sleep 1
  1347. _debug serverproc "$serverproc"
  1348. }
  1349. #file
  1350. _readlink() {
  1351. _rf="$1"
  1352. if ! readlink -f "$_rf" 2>/dev/null; then
  1353. if _startswith "$_rf" "\./$PROJECT_ENTRY"; then
  1354. printf -- "%s" "$(pwd)/$PROJECT_ENTRY"
  1355. return 0
  1356. fi
  1357. readlink "$_rf"
  1358. fi
  1359. }
  1360. __initHome() {
  1361. if [ -z "$_SCRIPT_HOME" ]; then
  1362. if _exists readlink && _exists dirname; then
  1363. _debug "Lets find script dir."
  1364. _debug "_SCRIPT_" "$_SCRIPT_"
  1365. _script="$(_readlink "$_SCRIPT_")"
  1366. _debug "_script" "$_script"
  1367. _script_home="$(dirname "$_script")"
  1368. _debug "_script_home" "$_script_home"
  1369. if [ -d "$_script_home" ]; then
  1370. _SCRIPT_HOME="$_script_home"
  1371. else
  1372. _err "It seems the script home is not correct:$_script_home"
  1373. fi
  1374. fi
  1375. fi
  1376. # if [ -z "$LE_WORKING_DIR" ]; then
  1377. # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
  1378. # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  1379. # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1380. # else
  1381. # LE_WORKING_DIR="$_SCRIPT_HOME"
  1382. # fi
  1383. # fi
  1384. if [ -z "$LE_WORKING_DIR" ]; then
  1385. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  1386. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1387. fi
  1388. export LE_WORKING_DIR
  1389. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  1390. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1391. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
  1392. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1393. fi
  1394. fi
  1395. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1396. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1397. fi
  1398. DEFAULT_LOG_FILE="$LE_WORKING_DIR/$PROJECT_NAME.log"
  1399. DEFAULT_CA_HOME="$LE_WORKING_DIR/ca"
  1400. if [ -z "$LE_TEMP_DIR" ]; then
  1401. LE_TEMP_DIR="$LE_WORKING_DIR/tmp"
  1402. fi
  1403. }
  1404. #[domain] [keylength]
  1405. _initpath() {
  1406. __initHome
  1407. if [ -f "$ACCOUNT_CONF_PATH" ]; then
  1408. . "$ACCOUNT_CONF_PATH"
  1409. fi
  1410. if [ "$IN_CRON" ]; then
  1411. if [ ! "$_USER_PATH_EXPORTED" ]; then
  1412. _USER_PATH_EXPORTED=1
  1413. export PATH="$USER_PATH:$PATH"
  1414. fi
  1415. fi
  1416. if [ -z "$CA_HOME" ]; then
  1417. CA_HOME="$DEFAULT_CA_HOME"
  1418. fi
  1419. if [ -z "$API" ]; then
  1420. if [ -z "$STAGE" ]; then
  1421. API="$DEFAULT_CA"
  1422. else
  1423. API="$STAGE_CA"
  1424. _info "Using stage api:$API"
  1425. fi
  1426. fi
  1427. _API_HOST="$(echo "$API" | cut -d : -f 2 | tr -d '/')"
  1428. CA_DIR="$CA_HOME/$_API_HOST"
  1429. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  1430. if [ -z "$CA_CONF" ]; then
  1431. CA_CONF="$_DEFAULT_CA_CONF"
  1432. fi
  1433. _debug3 CA_CONF "$CA_CONF"
  1434. if [ -f "$CA_CONF" ]; then
  1435. . "$CA_CONF"
  1436. fi
  1437. if [ -z "$ACME_DIR" ]; then
  1438. ACME_DIR="/home/.acme"
  1439. fi
  1440. if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
  1441. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  1442. fi
  1443. if [ -z "$USER_AGENT" ]; then
  1444. USER_AGENT="$DEFAULT_USER_AGENT"
  1445. fi
  1446. if [ -z "$HTTP_HEADER" ]; then
  1447. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  1448. fi
  1449. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  1450. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  1451. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  1452. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  1453. if [ -z "$ACCOUNT_KEY_PATH" ]; then
  1454. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  1455. fi
  1456. if [ -z "$ACCOUNT_JSON_PATH" ]; then
  1457. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  1458. fi
  1459. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  1460. if [ -z "$CERT_HOME" ]; then
  1461. CERT_HOME="$_DEFAULT_CERT_HOME"
  1462. fi
  1463. if [ -z "$OPENSSL_BIN" ]; then
  1464. OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
  1465. fi
  1466. if [ -z "$1" ]; then
  1467. return 0
  1468. fi
  1469. domain="$1"
  1470. _ilength="$2"
  1471. if [ -z "$DOMAIN_PATH" ]; then
  1472. domainhome="$CERT_HOME/$domain"
  1473. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  1474. DOMAIN_PATH="$domainhome"
  1475. if _isEccKey "$_ilength"; then
  1476. DOMAIN_PATH="$domainhomeecc"
  1477. else
  1478. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
  1479. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  1480. fi
  1481. fi
  1482. _debug DOMAIN_PATH "$DOMAIN_PATH"
  1483. fi
  1484. if [ -z "$DOMAIN_CONF" ]; then
  1485. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  1486. fi
  1487. if [ -z "$DOMAIN_SSL_CONF" ]; then
  1488. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  1489. fi
  1490. if [ -z "$CSR_PATH" ]; then
  1491. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  1492. fi
  1493. if [ -z "$CERT_KEY_PATH" ]; then
  1494. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  1495. fi
  1496. if [ -z "$CERT_PATH" ]; then
  1497. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  1498. fi
  1499. if [ -z "$CA_CERT_PATH" ]; then
  1500. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  1501. fi
  1502. if [ -z "$CERT_FULLCHAIN_PATH" ]; then
  1503. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  1504. fi
  1505. if [ -z "$CERT_PFX_PATH" ]; then
  1506. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  1507. fi
  1508. if [ -z "$TLS_CONF" ]; then
  1509. TLS_CONF="$DOMAIN_PATH/tls.valdation.conf"
  1510. fi
  1511. if [ -z "$TLS_CERT" ]; then
  1512. TLS_CERT="$DOMAIN_PATH/tls.valdation.cert"
  1513. fi
  1514. if [ -z "$TLS_KEY" ]; then
  1515. TLS_KEY="$DOMAIN_PATH/tls.valdation.key"
  1516. fi
  1517. if [ -z "$TLS_CSR" ]; then
  1518. TLS_CSR="$DOMAIN_PATH/tls.valdation.csr"
  1519. fi
  1520. }
  1521. _exec() {
  1522. if [ -z "$_EXEC_TEMP_ERR" ]; then
  1523. _EXEC_TEMP_ERR="$(_mktemp)"
  1524. fi
  1525. if [ "$_EXEC_TEMP_ERR" ]; then
  1526. eval "$@ 2>>$_EXEC_TEMP_ERR"
  1527. else
  1528. eval "$@"
  1529. fi
  1530. }
  1531. _exec_err() {
  1532. [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
  1533. }
  1534. _apachePath() {
  1535. _APACHECTL="apachectl"
  1536. if ! _exists apachectl; then
  1537. if _exists apache2ctl; then
  1538. _APACHECTL="apache2ctl"
  1539. else
  1540. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  1541. _err "Please use webroot mode to try again."
  1542. return 1
  1543. fi
  1544. fi
  1545. if ! _exec $_APACHECTL -V >/dev/null; then
  1546. _exec_err
  1547. return 1
  1548. fi
  1549. if [ "$APACHE_HTTPD_CONF" ]; then
  1550. _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
  1551. httpdconf="$APACHE_HTTPD_CONF"
  1552. httpdconfname="$(basename "$httpdconfname")"
  1553. else
  1554. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
  1555. _debug httpdconfname "$httpdconfname"
  1556. if [ -z "$httpdconfname" ]; then
  1557. _err "Can not read apache config file."
  1558. return 1
  1559. fi
  1560. if _startswith "$httpdconfname" '/'; then
  1561. httpdconf="$httpdconfname"
  1562. httpdconfname="$(basename "$httpdconfname")"
  1563. else
  1564. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
  1565. _debug httpdroot "$httpdroot"
  1566. httpdconf="$httpdroot/$httpdconfname"
  1567. httpdconfname="$(basename "$httpdconfname")"
  1568. fi
  1569. fi
  1570. _debug httpdconf "$httpdconf"
  1571. _debug httpdconfname "$httpdconfname"
  1572. if [ ! -f "$httpdconf" ]; then
  1573. _err "Apache Config file not found" "$httpdconf"
  1574. return 1
  1575. fi
  1576. return 0
  1577. }
  1578. _restoreApache() {
  1579. if [ -z "$usingApache" ]; then
  1580. return 0
  1581. fi
  1582. _initpath
  1583. if ! _apachePath; then
  1584. return 1
  1585. fi
  1586. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
  1587. _debug "No config file to restore."
  1588. return 0
  1589. fi
  1590. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
  1591. _debug "Restored: $httpdconf."
  1592. if ! _exec $_APACHECTL -t; then
  1593. _exec_err
  1594. _err "Sorry, restore apache config error, please contact me."
  1595. return 1
  1596. fi
  1597. _debug "Restored successfully."
  1598. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1599. return 0
  1600. }
  1601. _setApache() {
  1602. _initpath
  1603. if ! _apachePath; then
  1604. return 1
  1605. fi
  1606. #test the conf first
  1607. _info "Checking if there is an error in the apache config file before starting."
  1608. if ! _exec "$_APACHECTL" -t >/dev/null; then
  1609. _exec_err
  1610. _err "The apache config file has error, please fix it first, then try again."
  1611. _err "Don't worry, there is nothing changed to your system."
  1612. return 1
  1613. else
  1614. _info "OK"
  1615. fi
  1616. #backup the conf
  1617. _debug "Backup apache config file" "$httpdconf"
  1618. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
  1619. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  1620. _err "This might be a bug of $PROJECT_NAME , pleae report issue: $PROJECT"
  1621. return 1
  1622. fi
  1623. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1624. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  1625. _info "The backup file will be deleted on success, just forget it."
  1626. #add alias
  1627. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
  1628. _debug "apacheVer" "$apacheVer"
  1629. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  1630. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  1631. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
  1632. echo "
  1633. Alias /.well-known/acme-challenge $ACME_DIR
  1634. <Directory $ACME_DIR >
  1635. Require all granted
  1636. </Directory>
  1637. " >>"$httpdconf"
  1638. else
  1639. echo "
  1640. Alias /.well-known/acme-challenge $ACME_DIR
  1641. <Directory $ACME_DIR >
  1642. Order allow,deny
  1643. Allow from all
  1644. </Directory>
  1645. " >>"$httpdconf"
  1646. fi
  1647. _msg="$($_APACHECTL -t 2>&1)"
  1648. if [ "$?" != "0" ]; then
  1649. _err "Sorry, apache config error"
  1650. if _restoreApache; then
  1651. _err "The apache config file is restored."
  1652. else
  1653. _err "Sorry, The apache config file can not be restored, please report bug."
  1654. fi
  1655. return 1
  1656. fi
  1657. if [ ! -d "$ACME_DIR" ]; then
  1658. mkdir -p "$ACME_DIR"
  1659. chmod 755 "$ACME_DIR"
  1660. fi
  1661. if ! _exec "$_APACHECTL" graceful; then
  1662. _exec_err
  1663. _err "$_APACHECTL graceful error, please contact me."
  1664. _restoreApache
  1665. return 1
  1666. fi
  1667. usingApache="1"
  1668. return 0
  1669. }
  1670. _clearup() {
  1671. _stopserver "$serverproc"
  1672. serverproc=""
  1673. _restoreApache
  1674. _clearupdns
  1675. if [ -z "$DEBUG" ]; then
  1676. rm -f "$TLS_CONF"
  1677. rm -f "$TLS_CERT"
  1678. rm -f "$TLS_KEY"
  1679. rm -f "$TLS_CSR"
  1680. fi
  1681. }
  1682. _clearupdns() {
  1683. _debug "_clearupdns"
  1684. if [ "$dnsadded" != 1 ] || [ -z "$vlist" ]; then
  1685. _debug "Dns not added, skip."
  1686. return
  1687. fi
  1688. ventries=$(echo "$vlist" | tr ',' ' ')
  1689. for ventry in $ventries; do
  1690. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  1691. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  1692. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  1693. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  1694. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _urlencode)"
  1695. _debug txt "$txt"
  1696. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  1697. _info "$d is already verified, skip $vtype."
  1698. continue
  1699. fi
  1700. if [ "$vtype" != "$VTYPE_DNS" ]; then
  1701. _info "Skip $d for $vtype"
  1702. continue
  1703. fi
  1704. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  1705. _debug d_api "$d_api"
  1706. if [ -z "$d_api" ]; then
  1707. _info "Not Found domain api file: $d_api"
  1708. continue
  1709. fi
  1710. (
  1711. if ! . "$d_api"; then
  1712. _err "Load file $d_api error. Please check your api file and try again."
  1713. return 1
  1714. fi
  1715. rmcommand="${_currentRoot}_rm"
  1716. if ! _exists "$rmcommand"; then
  1717. _err "It seems that your api file doesn't define $rmcommand"
  1718. return 1
  1719. fi
  1720. txtdomain="_acme-challenge.$d"
  1721. if ! $rmcommand "$txtdomain" "$txt"; then
  1722. _err "Error removing txt for domain:$txtdomain"
  1723. return 1
  1724. fi
  1725. )
  1726. done
  1727. }
  1728. # webroot removelevel tokenfile
  1729. _clearupwebbroot() {
  1730. __webroot="$1"
  1731. if [ -z "$__webroot" ]; then
  1732. _debug "no webroot specified, skip"
  1733. return 0
  1734. fi
  1735. _rmpath=""
  1736. if [ "$2" = '1' ]; then
  1737. _rmpath="$__webroot/.well-known"
  1738. elif [ "$2" = '2' ]; then
  1739. _rmpath="$__webroot/.well-known/acme-challenge"
  1740. elif [ "$2" = '3' ]; then
  1741. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  1742. else
  1743. _debug "Skip for removelevel:$2"
  1744. fi
  1745. if [ "$_rmpath" ]; then
  1746. if [ "$DEBUG" ]; then
  1747. _debug "Debugging, skip removing: $_rmpath"
  1748. else
  1749. rm -rf "$_rmpath"
  1750. fi
  1751. fi
  1752. return 0
  1753. }
  1754. _on_before_issue() {
  1755. _debug _on_before_issue
  1756. if _hasfield "$Le_Webroot" "$NO_VALUE"; then
  1757. if ! _exists "nc"; then
  1758. _err "Please install netcat(nc) tools first."
  1759. return 1
  1760. fi
  1761. fi
  1762. _debug Le_LocalAddress "$Le_LocalAddress"
  1763. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
  1764. _index=1
  1765. _currentRoot=""
  1766. _addrIndex=1
  1767. for d in $alldomains; do
  1768. _debug "Check for domain" "$d"
  1769. _currentRoot="$(_getfield "$Le_Webroot" $_index)"
  1770. _debug "_currentRoot" "$_currentRoot"
  1771. _index=$(_math $_index + 1)
  1772. _checkport=""
  1773. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  1774. _info "Standalone mode."
  1775. if [ -z "$Le_HTTPPort" ]; then
  1776. Le_HTTPPort=80
  1777. else
  1778. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  1779. fi
  1780. _checkport="$Le_HTTPPort"
  1781. elif [ "$_currentRoot" = "$W_TLS" ]; then
  1782. _info "Standalone tls mode."
  1783. if [ -z "$Le_TLSPort" ]; then
  1784. Le_TLSPort=443
  1785. else
  1786. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  1787. fi
  1788. _checkport="$Le_TLSPort"
  1789. fi
  1790. if [ "$_checkport" ]; then
  1791. _debug _checkport "$_checkport"
  1792. _checkaddr="$(_getfield "$Le_LocalAddress" $_addrIndex)"
  1793. _debug _checkaddr "$_checkaddr"
  1794. _addrIndex="$(_math $_addrIndex + 1)"
  1795. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  1796. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  1797. if [ -z "$netprc" ]; then
  1798. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  1799. fi
  1800. if [ "$netprc" ]; then
  1801. _err "$netprc"
  1802. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  1803. _err "Please stop it first"
  1804. return 1
  1805. fi
  1806. fi
  1807. done
  1808. if _hasfield "$Le_Webroot" "apache"; then
  1809. if ! _setApache; then
  1810. _err "set up apache error. Report error to me."
  1811. return 1
  1812. fi
  1813. else
  1814. usingApache=""
  1815. fi
  1816. #run pre hook
  1817. if [ "$Le_PreHook" ]; then
  1818. _info "Run pre hook:'$Le_PreHook'"
  1819. if ! (
  1820. cd "$DOMAIN_PATH" && eval "$Le_PreHook"
  1821. ); then
  1822. _err "Error when run pre hook."
  1823. return 1
  1824. fi
  1825. fi
  1826. }
  1827. _on_issue_err() {
  1828. _debug _on_issue_err
  1829. if [ "$LOG_FILE" ]; then
  1830. _err "Please check log file for more details: $LOG_FILE"
  1831. else
  1832. _err "Please add '--debug' or '--log' to check more details."
  1833. _err "See: $_DEBUG_WIKI"
  1834. fi
  1835. if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
  1836. _debug "$(_dlg_versions)"
  1837. fi
  1838. #run the post hook
  1839. if [ "$Le_PostHook" ]; then
  1840. _info "Run post hook:'$Le_PostHook'"
  1841. if ! (
  1842. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1843. ); then
  1844. _err "Error when run post hook."
  1845. return 1
  1846. fi
  1847. fi
  1848. }
  1849. _on_issue_success() {
  1850. _debug _on_issue_success
  1851. #run the post hook
  1852. if [ "$Le_PostHook" ]; then
  1853. _info "Run post hook:'$Le_PostHook'"
  1854. if ! (
  1855. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1856. ); then
  1857. _err "Error when run post hook."
  1858. return 1
  1859. fi
  1860. fi
  1861. #run renew hook
  1862. if [ "$IS_RENEW" ] && [ "$Le_RenewHook" ]; then
  1863. _info "Run renew hook:'$Le_RenewHook'"
  1864. if ! (
  1865. cd "$DOMAIN_PATH" && eval "$Le_RenewHook"
  1866. ); then
  1867. _err "Error when run renew hook."
  1868. return 1
  1869. fi
  1870. fi
  1871. }
  1872. updateaccount() {
  1873. _initpath
  1874. _regAccount
  1875. }
  1876. registeraccount() {
  1877. _reg_length="$1"
  1878. _initpath
  1879. _regAccount "$_reg_length"
  1880. }
  1881. __calcAccountKeyHash() {
  1882. [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
  1883. }
  1884. #keylength
  1885. _regAccount() {
  1886. _initpath
  1887. _reg_length="$1"
  1888. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  1889. mkdir -p "$CA_DIR"
  1890. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  1891. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  1892. fi
  1893. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  1894. mkdir -p "$CA_DIR"
  1895. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  1896. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  1897. fi
  1898. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  1899. if ! _create_account_key "$_reg_length"; then
  1900. _err "Create account key error."
  1901. return 1
  1902. fi
  1903. fi
  1904. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  1905. return 1
  1906. fi
  1907. _updateTos=""
  1908. _reg_res="new-reg"
  1909. while true; do
  1910. _debug AGREEMENT "$AGREEMENT"
  1911. regjson='{"resource": "'$_reg_res'", "agreement": "'$AGREEMENT'"}'
  1912. if [ "$ACCOUNT_EMAIL" ]; then
  1913. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  1914. fi
  1915. if [ -z "$_updateTos" ]; then
  1916. _info "Registering account"
  1917. if ! _send_signed_request "$API/acme/new-reg" "$regjson"; then
  1918. _err "Register account Error: $response"
  1919. return 1
  1920. fi
  1921. if [ "$code" = "" ] || [ "$code" = '201' ]; then
  1922. echo "$response" >"$ACCOUNT_JSON_PATH"
  1923. _info "Registered"
  1924. elif [ "$code" = '409' ]; then
  1925. _info "Already registered"
  1926. else
  1927. _err "Register account Error: $response"
  1928. return 1
  1929. fi
  1930. _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  1931. _debug "_accUri" "$_accUri"
  1932. _tos="$(echo "$responseHeaders" | grep "^Link:.*rel=\"terms-of-service\"" | _head_n 1 | _egrep_o "<.*>" | tr -d '<>')"
  1933. _debug "_tos" "$_tos"
  1934. if [ -z "$_tos" ]; then
  1935. _debug "Use default tos: $DEFAULT_AGREEMENT"
  1936. _tos="$DEFAULT_AGREEMENT"
  1937. fi
  1938. if [ "$_tos" != "$AGREEMENT" ]; then
  1939. _updateTos=1
  1940. AGREEMENT="$_tos"
  1941. _reg_res="reg"
  1942. continue
  1943. fi
  1944. else
  1945. _debug "Update tos: $_tos"
  1946. if ! _send_signed_request "$_accUri" "$regjson"; then
  1947. _err "Update tos error."
  1948. return 1
  1949. fi
  1950. if [ "$code" = '202' ]; then
  1951. _info "Update success."
  1952. CA_KEY_HASH="$(__calcAccountKeyHash)"
  1953. _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
  1954. _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
  1955. else
  1956. _err "Update account error."
  1957. return 1
  1958. fi
  1959. fi
  1960. return 0
  1961. done
  1962. }
  1963. # domain folder file
  1964. _findHook() {
  1965. _hookdomain="$1"
  1966. _hookcat="$2"
  1967. _hookname="$3"
  1968. if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
  1969. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
  1970. elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
  1971. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
  1972. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
  1973. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  1974. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
  1975. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  1976. elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
  1977. d_api="$LE_WORKING_DIR/$_hookname"
  1978. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
  1979. d_api="$LE_WORKING_DIR/$_hookname.sh"
  1980. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
  1981. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  1982. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
  1983. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  1984. fi
  1985. printf "%s" "$d_api"
  1986. }
  1987. #domain
  1988. __get_domain_new_authz() {
  1989. _gdnd="$1"
  1990. _info "Getting new-authz for domain" "$_gdnd"
  1991. _Max_new_authz_retry_times=5
  1992. _authz_i=0
  1993. while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
  1994. _debug "Try new-authz for the $_authz_i time."
  1995. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
  1996. _err "Can not get domain new authz."
  1997. return 1
  1998. fi
  1999. if ! _contains "$response" "An error occurred while processing your request"; then
  2000. _info "The new-authz request is ok."
  2001. break
  2002. fi
  2003. _authz_i="$(_math "$_authz_i" + 1)"
  2004. _info "The server is busy, Sleep $_authz_i to retry."
  2005. _sleep "$_authz_i"
  2006. done
  2007. if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
  2008. _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
  2009. fi
  2010. if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
  2011. _err "new-authz error: $response"
  2012. return 1
  2013. fi
  2014. }
  2015. #webroot, domain domainlist keylength
  2016. issue() {
  2017. if [ -z "$2" ]; then
  2018. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  2019. return 1
  2020. fi
  2021. Le_Webroot="$1"
  2022. Le_Domain="$2"
  2023. Le_Alt="$3"
  2024. Le_Keylength="$4"
  2025. Le_RealCertPath="$5"
  2026. Le_RealKeyPath="$6"
  2027. Le_RealCACertPath="$7"
  2028. Le_ReloadCmd="$8"
  2029. Le_RealFullChainPath="$9"
  2030. Le_PreHook="${10}"
  2031. Le_PostHook="${11}"
  2032. Le_RenewHook="${12}"
  2033. Le_LocalAddress="${13}"
  2034. #remove these later.
  2035. if [ "$Le_Webroot" = "dns-cf" ]; then
  2036. Le_Webroot="dns_cf"
  2037. fi
  2038. if [ "$Le_Webroot" = "dns-dp" ]; then
  2039. Le_Webroot="dns_dp"
  2040. fi
  2041. if [ "$Le_Webroot" = "dns-cx" ]; then
  2042. Le_Webroot="dns_cx"
  2043. fi
  2044. _debug "Using api: $API"
  2045. if [ ! "$IS_RENEW" ]; then
  2046. _initpath "$Le_Domain" "$Le_Keylength"
  2047. mkdir -p "$DOMAIN_PATH"
  2048. fi
  2049. if [ -f "$DOMAIN_CONF" ]; then
  2050. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  2051. _debug Le_NextRenewTime "$Le_NextRenewTime"
  2052. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  2053. _saved_domain=$(_readdomainconf Le_Domain)
  2054. _debug _saved_domain "$_saved_domain"
  2055. _saved_alt=$(_readdomainconf Le_Alt)
  2056. _debug _saved_alt "$_saved_alt"
  2057. if [ "$_saved_domain,$_saved_alt" = "$Le_Domain,$Le_Alt" ]; then
  2058. _info "Domains not changed."
  2059. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  2060. _info "Add '$(__red '--force')' to force to renew."
  2061. return $RENEW_SKIP
  2062. else
  2063. _info "Domains have changed."
  2064. fi
  2065. fi
  2066. fi
  2067. _savedomainconf "Le_Domain" "$Le_Domain"
  2068. _savedomainconf "Le_Alt" "$Le_Alt"
  2069. _savedomainconf "Le_Webroot" "$Le_Webroot"
  2070. _savedomainconf "Le_PreHook" "$Le_PreHook"
  2071. _savedomainconf "Le_PostHook" "$Le_PostHook"
  2072. _savedomainconf "Le_RenewHook" "$Le_RenewHook"
  2073. if [ "$Le_LocalAddress" ]; then
  2074. _savedomainconf "Le_LocalAddress" "$Le_LocalAddress"
  2075. else
  2076. _cleardomainconf "Le_LocalAddress"
  2077. fi
  2078. Le_API="$API"
  2079. _savedomainconf "Le_API" "$Le_API"
  2080. if [ "$Le_Alt" = "$NO_VALUE" ]; then
  2081. Le_Alt=""
  2082. fi
  2083. if [ "$Le_Keylength" = "$NO_VALUE" ]; then
  2084. Le_Keylength=""
  2085. fi
  2086. if ! _on_before_issue; then
  2087. _err "_on_before_issue."
  2088. return 1
  2089. fi
  2090. _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
  2091. _debug2 _saved_account_key_hash "$_saved_account_key_hash"
  2092. if [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
  2093. if ! _regAccount "$_accountkeylength"; then
  2094. _on_issue_err
  2095. return 1
  2096. fi
  2097. else
  2098. _debug "_saved_account_key_hash is not changed, skip register account."
  2099. fi
  2100. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
  2101. _info "Signing from existing CSR."
  2102. else
  2103. _key=$(_readdomainconf Le_Keylength)
  2104. _debug "Read key length:$_key"
  2105. if [ ! -f "$CERT_KEY_PATH" ] || [ "$Le_Keylength" != "$_key" ]; then
  2106. if ! createDomainKey "$Le_Domain" "$Le_Keylength"; then
  2107. _err "Create domain key error."
  2108. _clearup
  2109. _on_issue_err
  2110. return 1
  2111. fi
  2112. fi
  2113. if ! _createcsr "$Le_Domain" "$Le_Alt" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
  2114. _err "Create CSR error."
  2115. _clearup
  2116. _on_issue_err
  2117. return 1
  2118. fi
  2119. fi
  2120. _savedomainconf "Le_Keylength" "$Le_Keylength"
  2121. vlist="$Le_Vlist"
  2122. _info "Getting domain auth token for each domain"
  2123. sep='#'
  2124. if [ -z "$vlist" ]; then
  2125. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
  2126. _index=1
  2127. _currentRoot=""
  2128. for d in $alldomains; do
  2129. _info "Getting webroot for domain" "$d"
  2130. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  2131. _info _w "$_w"
  2132. if [ "$_w" ]; then
  2133. _currentRoot="$_w"
  2134. fi
  2135. _debug "_currentRoot" "$_currentRoot"
  2136. _index=$(_math $_index + 1)
  2137. vtype="$VTYPE_HTTP"
  2138. if _startswith "$_currentRoot" "dns"; then
  2139. vtype="$VTYPE_DNS"
  2140. fi
  2141. if [ "$_currentRoot" = "$W_TLS" ]; then
  2142. vtype="$VTYPE_TLS"
  2143. fi
  2144. if ! __get_domain_new_authz "$d"; then
  2145. _clearup
  2146. _on_issue_err
  2147. return 1
  2148. fi
  2149. if [ -z "$thumbprint" ]; then
  2150. accountkey_json=$(printf "%s" "$jwk" | tr -d ' ')
  2151. thumbprint=$(printf "%s" "$accountkey_json" | _digest "sha256" | _urlencode)
  2152. fi
  2153. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  2154. _debug entry "$entry"
  2155. if [ -z "$entry" ]; then
  2156. _err "Error, can not get domain token $d"
  2157. _clearup
  2158. _on_issue_err
  2159. return 1
  2160. fi
  2161. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  2162. _debug token "$token"
  2163. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
  2164. _debug uri "$uri"
  2165. keyauthorization="$token.$thumbprint"
  2166. _debug keyauthorization "$keyauthorization"
  2167. if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  2168. _info "$d is already verified, skip."
  2169. keyauthorization="$STATE_VERIFIED"
  2170. _debug keyauthorization "$keyauthorization"
  2171. fi
  2172. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  2173. _debug dvlist "$dvlist"
  2174. vlist="$vlist$dvlist,"
  2175. done
  2176. #add entry
  2177. dnsadded=""
  2178. ventries=$(echo "$vlist" | tr ',' ' ')
  2179. for ventry in $ventries; do
  2180. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2181. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2182. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2183. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2184. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2185. _info "$d is already verified, skip $vtype."
  2186. continue
  2187. fi
  2188. if [ "$vtype" = "$VTYPE_DNS" ]; then
  2189. dnsadded='0'
  2190. txtdomain="_acme-challenge.$d"
  2191. _debug txtdomain "$txtdomain"
  2192. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _urlencode)"
  2193. _debug txt "$txt"
  2194. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  2195. _debug d_api "$d_api"
  2196. if [ "$d_api" ]; then
  2197. _info "Found domain api file: $d_api"
  2198. else
  2199. _err "Add the following TXT record:"
  2200. _err "Domain: '$(__green "$txtdomain")'"
  2201. _err "TXT value: '$(__green "$txt")'"
  2202. _err "Please be aware that you prepend _acme-challenge. before your domain"
  2203. _err "so the resulting subdomain will be: $txtdomain"
  2204. continue
  2205. fi
  2206. (
  2207. if ! . "$d_api"; then
  2208. _err "Load file $d_api error. Please check your api file and try again."
  2209. return 1
  2210. fi
  2211. addcommand="${_currentRoot}_add"
  2212. if ! _exists "$addcommand"; then
  2213. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  2214. return 1
  2215. fi
  2216. if ! $addcommand "$txtdomain" "$txt"; then
  2217. _err "Error add txt for domain:$txtdomain"
  2218. return 1
  2219. fi
  2220. )
  2221. if [ "$?" != "0" ]; then
  2222. _clearup
  2223. _on_issue_err
  2224. return 1
  2225. fi
  2226. dnsadded='1'
  2227. fi
  2228. done
  2229. if [ "$dnsadded" = '0' ]; then
  2230. _savedomainconf "Le_Vlist" "$vlist"
  2231. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  2232. _err "Please add the TXT records to the domains, and retry again."
  2233. _clearup
  2234. _on_issue_err
  2235. return 1
  2236. fi
  2237. fi
  2238. if [ "$dnsadded" = '1' ]; then
  2239. if [ -z "$Le_DNSSleep" ]; then
  2240. Le_DNSSleep="$DEFAULT_DNS_SLEEP"
  2241. else
  2242. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  2243. fi
  2244. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  2245. _sleep "$Le_DNSSleep"
  2246. fi
  2247. _debug "ok, let's start to verify"
  2248. _ncIndex=1
  2249. ventries=$(echo "$vlist" | tr ',' ' ')
  2250. for ventry in $ventries; do
  2251. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2252. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2253. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  2254. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2255. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2256. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2257. _info "$d is already verified, skip $vtype."
  2258. continue
  2259. fi
  2260. _info "Verifying:$d"
  2261. _debug "d" "$d"
  2262. _debug "keyauthorization" "$keyauthorization"
  2263. _debug "uri" "$uri"
  2264. removelevel=""
  2265. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  2266. _debug "_currentRoot" "$_currentRoot"
  2267. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  2268. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2269. _info "Standalone mode server"
  2270. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
  2271. _ncIndex="$(_math $_ncIndex + 1)"
  2272. _startserver "$keyauthorization" "$_ncaddr" &
  2273. if [ "$?" != "0" ]; then
  2274. _clearup
  2275. _on_issue_err
  2276. return 1
  2277. fi
  2278. serverproc="$!"
  2279. sleep 1
  2280. _debug serverproc "$serverproc"
  2281. else
  2282. if [ "$_currentRoot" = "apache" ]; then
  2283. wellknown_path="$ACME_DIR"
  2284. else
  2285. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  2286. if [ ! -d "$_currentRoot/.well-known" ]; then
  2287. removelevel='1'
  2288. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
  2289. removelevel='2'
  2290. else
  2291. removelevel='3'
  2292. fi
  2293. fi
  2294. _debug wellknown_path "$wellknown_path"
  2295. _debug "writing token:$token to $wellknown_path/$token"
  2296. mkdir -p "$wellknown_path"
  2297. if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
  2298. _err "$d:Can not write token to file : $wellknown_path/$token"
  2299. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2300. _clearup
  2301. _on_issue_err
  2302. return 1
  2303. fi
  2304. if [ ! "$usingApache" ]; then
  2305. if webroot_owner=$(_stat "$_currentRoot"); then
  2306. _debug "Changing owner/group of .well-known to $webroot_owner"
  2307. chown -R "$webroot_owner" "$_currentRoot/.well-known"
  2308. else
  2309. _debug "not chaning owner/group of webroot"
  2310. fi
  2311. fi
  2312. fi
  2313. elif [ "$vtype" = "$VTYPE_TLS" ]; then
  2314. #create A
  2315. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  2316. #_debug2 _hash_A "$_hash_A"
  2317. #_x="$(echo $_hash_A | cut -c 1-32)"
  2318. #_debug2 _x "$_x"
  2319. #_y="$(echo $_hash_A | cut -c 33-64)"
  2320. #_debug2 _y "$_y"
  2321. #_SAN_A="$_x.$_y.token.acme.invalid"
  2322. #_debug2 _SAN_A "$_SAN_A"
  2323. #create B
  2324. _hash_B="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
  2325. _debug2 _hash_B "$_hash_B"
  2326. _x="$(echo "$_hash_B" | cut -c 1-32)"
  2327. _debug2 _x "$_x"
  2328. _y="$(echo "$_hash_B" | cut -c 33-64)"
  2329. _debug2 _y "$_y"
  2330. #_SAN_B="$_x.$_y.ka.acme.invalid"
  2331. _SAN_B="$_x.$_y.acme.invalid"
  2332. _debug2 _SAN_B "$_SAN_B"
  2333. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
  2334. _ncIndex="$(_math "$_ncIndex" + 1)"
  2335. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" "$_ncaddr"; then
  2336. _err "Start tls server error."
  2337. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2338. _clearup
  2339. _on_issue_err
  2340. return 1
  2341. fi
  2342. fi
  2343. if ! _send_signed_request "$uri" "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"; then
  2344. _err "$d:Can not get challenge: $response"
  2345. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2346. _clearup
  2347. _on_issue_err
  2348. return 1
  2349. fi
  2350. if [ ! -z "$code" ] && [ ! "$code" = '202' ]; then
  2351. _err "$d:Challenge error: $response"
  2352. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2353. _clearup
  2354. _on_issue_err
  2355. return 1
  2356. fi
  2357. waittimes=0
  2358. if [ -z "$MAX_RETRY_TIMES" ]; then
  2359. MAX_RETRY_TIMES=30
  2360. fi
  2361. while true; do
  2362. waittimes=$(_math "$waittimes" + 1)
  2363. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
  2364. _err "$d:Timeout"
  2365. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2366. _clearup
  2367. _on_issue_err
  2368. return 1
  2369. fi
  2370. _debug "sleep 2 secs to verify"
  2371. sleep 2
  2372. _debug "checking"
  2373. response="$(_get "$uri")"
  2374. if [ "$?" != "0" ]; then
  2375. _err "$d:Verify error:$response"
  2376. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2377. _clearup
  2378. _on_issue_err
  2379. return 1
  2380. fi
  2381. _debug2 original "$response"
  2382. response="$(echo "$response" | _normalizeJson)"
  2383. _debug2 response "$response"
  2384. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  2385. if [ "$status" = "valid" ]; then
  2386. _info "$(__green Success)"
  2387. _stopserver "$serverproc"
  2388. serverproc=""
  2389. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2390. break
  2391. fi
  2392. if [ "$status" = "invalid" ]; then
  2393. error="$(echo "$response" | tr -d "\r\n" | _egrep_o '"error":\{[^\}]*')"
  2394. _debug2 error "$error"
  2395. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  2396. _debug2 errordetail "$errordetail"
  2397. if [ "$errordetail" ]; then
  2398. _err "$d:Verify error:$errordetail"
  2399. else
  2400. _err "$d:Verify error:$error"
  2401. fi
  2402. if [ "$DEBUG" ]; then
  2403. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  2404. _debug "Debug: get token url."
  2405. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  2406. fi
  2407. fi
  2408. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2409. _clearup
  2410. _on_issue_err
  2411. return 1
  2412. fi
  2413. if [ "$status" = "pending" ]; then
  2414. _info "Pending"
  2415. else
  2416. _err "$d:Verify error:$response"
  2417. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2418. _clearup
  2419. _on_issue_err
  2420. return 1
  2421. fi
  2422. done
  2423. done
  2424. _clearup
  2425. _info "Verify finished, start to sign."
  2426. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  2427. if ! _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"; then
  2428. _err "Sign failed."
  2429. _on_issue_err
  2430. return 1
  2431. fi
  2432. _rcert="$response"
  2433. Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _head_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  2434. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  2435. if [ "$Le_LinkCert" ]; then
  2436. echo "$BEGIN_CERT" >"$CERT_PATH"
  2437. #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  2438. # _debug "Get cert failed. Let's try last response."
  2439. # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  2440. #fi
  2441. if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
  2442. _debug "Try cert link."
  2443. _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
  2444. fi
  2445. echo "$END_CERT" >>"$CERT_PATH"
  2446. _info "$(__green "Cert success.")"
  2447. cat "$CERT_PATH"
  2448. _info "Your cert is in $(__green " $CERT_PATH ")"
  2449. if [ -f "$CERT_KEY_PATH" ]; then
  2450. _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
  2451. fi
  2452. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  2453. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ]; then
  2454. USER_PATH="$PATH"
  2455. _saveaccountconf "USER_PATH" "$USER_PATH"
  2456. fi
  2457. fi
  2458. if [ -z "$Le_LinkCert" ]; then
  2459. response="$(echo "$response" | _dbase64 "multiline" | _normalizeJson)"
  2460. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  2461. _on_issue_err
  2462. return 1
  2463. fi
  2464. _cleardomainconf "Le_Vlist"
  2465. Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
  2466. if ! _contains "$Le_LinkIssuer" ":"; then
  2467. Le_LinkIssuer="$API$Le_LinkIssuer"
  2468. fi
  2469. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  2470. if [ "$Le_LinkIssuer" ]; then
  2471. echo "$BEGIN_CERT" >"$CA_CERT_PATH"
  2472. _get "$Le_LinkIssuer" | _base64 "multiline" >>"$CA_CERT_PATH"
  2473. echo "$END_CERT" >>"$CA_CERT_PATH"
  2474. _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
  2475. cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
  2476. _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
  2477. fi
  2478. Le_CertCreateTime=$(_time)
  2479. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  2480. Le_CertCreateTimeStr=$(date -u)
  2481. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  2482. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ]; then
  2483. Le_RenewalDays="$MAX_RENEW"
  2484. else
  2485. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  2486. fi
  2487. if [ "$CA_BUNDLE" ]; then
  2488. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  2489. else
  2490. _clearaccountconf "CA_BUNDLE"
  2491. fi
  2492. if [ "$HTTPS_INSECURE" ]; then
  2493. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  2494. else
  2495. _clearaccountconf "HTTPS_INSECURE"
  2496. fi
  2497. if [ "$Le_Listen_V4" ]; then
  2498. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  2499. _cleardomainconf Le_Listen_V6
  2500. elif [ "$Le_Listen_V6" ]; then
  2501. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  2502. _cleardomainconf Le_Listen_V4
  2503. fi
  2504. Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
  2505. Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
  2506. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  2507. Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
  2508. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  2509. _on_issue_success
  2510. if [ "$Le_RealCertPath$Le_RealKeyPath$Le_RealCACertPath$Le_ReloadCmd$Le_RealFullChainPath" ]; then
  2511. _installcert
  2512. fi
  2513. }
  2514. #domain [isEcc]
  2515. renew() {
  2516. Le_Domain="$1"
  2517. if [ -z "$Le_Domain" ]; then
  2518. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  2519. return 1
  2520. fi
  2521. _isEcc="$2"
  2522. _initpath "$Le_Domain" "$_isEcc"
  2523. _info "$(__green "Renew: '$Le_Domain'")"
  2524. if [ ! -f "$DOMAIN_CONF" ]; then
  2525. _info "'$Le_Domain' is not a issued domain, skip."
  2526. return 0
  2527. fi
  2528. if [ "$Le_RenewalDays" ]; then
  2529. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  2530. fi
  2531. . "$DOMAIN_CONF"
  2532. if [ "$Le_API" ]; then
  2533. API="$Le_API"
  2534. #reload ca configs
  2535. ACCOUNT_KEY_PATH=""
  2536. ACCOUNT_JSON_PATH=""
  2537. CA_CONF=""
  2538. _debug3 "initpath again."
  2539. _initpath "$Le_Domain" "$_isEcc"
  2540. fi
  2541. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  2542. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  2543. _info "Add '$(__red '--force')' to force to renew."
  2544. return "$RENEW_SKIP"
  2545. fi
  2546. IS_RENEW="1"
  2547. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" "$Le_PreHook" "$Le_PostHook" "$Le_RenewHook" "$Le_LocalAddress"
  2548. res="$?"
  2549. if [ "$res" != "0" ]; then
  2550. return "$res"
  2551. fi
  2552. if [ "$Le_DeployHook" ]; then
  2553. deploy "$Le_Domain" "$Le_DeployHook" "$Le_Keylength"
  2554. res="$?"
  2555. fi
  2556. IS_RENEW=""
  2557. return "$res"
  2558. }
  2559. #renewAll [stopRenewOnError]
  2560. renewAll() {
  2561. _initpath
  2562. _stopRenewOnError="$1"
  2563. _debug "_stopRenewOnError" "$_stopRenewOnError"
  2564. _ret="0"
  2565. for di in "${CERT_HOME}"/*.*/; do
  2566. _debug di "$di"
  2567. if ! [ -d "$di" ]; then
  2568. _debug "Not directory, skip: $di"
  2569. continue
  2570. fi
  2571. d=$(basename "$di")
  2572. _debug d "$d"
  2573. (
  2574. if _endswith "$d" "$ECC_SUFFIX"; then
  2575. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  2576. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  2577. fi
  2578. renew "$d" "$_isEcc"
  2579. )
  2580. rc="$?"
  2581. _debug "Return code: $rc"
  2582. if [ "$rc" != "0" ]; then
  2583. if [ "$rc" = "$RENEW_SKIP" ]; then
  2584. _info "Skipped $d"
  2585. elif [ "$_stopRenewOnError" ]; then
  2586. _err "Error renew $d, stop now."
  2587. return "$rc"
  2588. else
  2589. _ret="$rc"
  2590. _err "Error renew $d, Go ahead to next one."
  2591. fi
  2592. fi
  2593. done
  2594. return "$_ret"
  2595. }
  2596. #csr webroot
  2597. signcsr() {
  2598. _csrfile="$1"
  2599. _csrW="$2"
  2600. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  2601. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  2602. return 1
  2603. fi
  2604. _initpath
  2605. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2606. if [ "$?" != "0" ]; then
  2607. _err "Can not read subject from csr: $_csrfile"
  2608. return 1
  2609. fi
  2610. _debug _csrsubj "$_csrsubj"
  2611. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2612. if [ "$?" != "0" ]; then
  2613. _err "Can not read domain list from csr: $_csrfile"
  2614. return 1
  2615. fi
  2616. _debug "_csrdomainlist" "$_csrdomainlist"
  2617. if [ -z "$_csrsubj" ]; then
  2618. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  2619. _debug _csrsubj "$_csrsubj"
  2620. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  2621. _debug "_csrdomainlist" "$_csrdomainlist"
  2622. fi
  2623. if [ -z "$_csrsubj" ]; then
  2624. _err "Can not read subject from csr: $_csrfile"
  2625. return 1
  2626. fi
  2627. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2628. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  2629. _err "Can not read key length from csr: $_csrfile"
  2630. return 1
  2631. fi
  2632. _initpath "$_csrsubj" "$_csrkeylength"
  2633. mkdir -p "$DOMAIN_PATH"
  2634. _info "Copy csr to: $CSR_PATH"
  2635. cp "$_csrfile" "$CSR_PATH"
  2636. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength"
  2637. }
  2638. showcsr() {
  2639. _csrfile="$1"
  2640. _csrd="$2"
  2641. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  2642. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  2643. return 1
  2644. fi
  2645. _initpath
  2646. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2647. if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
  2648. _err "Can not read subject from csr: $_csrfile"
  2649. return 1
  2650. fi
  2651. _info "Subject=$_csrsubj"
  2652. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2653. if [ "$?" != "0" ]; then
  2654. _err "Can not read domain list from csr: $_csrfile"
  2655. return 1
  2656. fi
  2657. _debug "_csrdomainlist" "$_csrdomainlist"
  2658. _info "SubjectAltNames=$_csrdomainlist"
  2659. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2660. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  2661. _err "Can not read key length from csr: $_csrfile"
  2662. return 1
  2663. fi
  2664. _info "KeyLength=$_csrkeylength"
  2665. }
  2666. list() {
  2667. _raw="$1"
  2668. _initpath
  2669. _sep="|"
  2670. if [ "$_raw" ]; then
  2671. printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew"
  2672. for di in "${CERT_HOME}"/*.*/; do
  2673. if ! [ -d "$di" ]; then
  2674. _debug "Not directory, skip: $di"
  2675. continue
  2676. fi
  2677. d=$(basename "$di")
  2678. _debug d "$d"
  2679. (
  2680. if _endswith "$d" "$ECC_SUFFIX"; then
  2681. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  2682. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  2683. fi
  2684. _initpath "$d" "$_isEcc"
  2685. if [ -f "$DOMAIN_CONF" ]; then
  2686. . "$DOMAIN_CONF"
  2687. printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
  2688. fi
  2689. )
  2690. done
  2691. else
  2692. if _exists column; then
  2693. list "raw" | column -t -s "$_sep"
  2694. else
  2695. list "raw" | tr "$_sep" '\t'
  2696. fi
  2697. fi
  2698. }
  2699. deploy() {
  2700. Le_Domain="$1"
  2701. Le_DeployHook="$2"
  2702. _isEcc="$3"
  2703. if [ -z "$Le_DeployHook" ]; then
  2704. _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
  2705. return 1
  2706. fi
  2707. _initpath "$Le_Domain" "$_isEcc"
  2708. if [ ! -d "$DOMAIN_PATH" ]; then
  2709. _err "Domain is not valid:'$Le_Domain'"
  2710. return 1
  2711. fi
  2712. _deployApi="$(_findHook "$Le_Domain" deploy "$Le_DeployHook")"
  2713. if [ -z "$_deployApi" ]; then
  2714. _err "The deploy hook $Le_DeployHook is not found."
  2715. return 1
  2716. fi
  2717. _debug _deployApi "$_deployApi"
  2718. _savedomainconf Le_DeployHook "$Le_DeployHook"
  2719. if ! (
  2720. if ! . "$_deployApi"; then
  2721. _err "Load file $_deployApi error. Please check your api file and try again."
  2722. return 1
  2723. fi
  2724. d_command="${Le_DeployHook}_deploy"
  2725. if ! _exists "$d_command"; then
  2726. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  2727. return 1
  2728. fi
  2729. if ! $d_command "$Le_Domain" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
  2730. _err "Error deploy for domain:$Le_Domain"
  2731. _on_issue_err
  2732. return 1
  2733. fi
  2734. ); then
  2735. _err "Deploy error."
  2736. return 1
  2737. else
  2738. _info "$(__green Success)"
  2739. fi
  2740. }
  2741. installcert() {
  2742. Le_Domain="$1"
  2743. if [ -z "$Le_Domain" ]; then
  2744. _usage "Usage: $PROJECT_ENTRY --installcert -d domain.com [--ecc] [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  2745. return 1
  2746. fi
  2747. Le_RealCertPath="$2"
  2748. Le_RealKeyPath="$3"
  2749. Le_RealCACertPath="$4"
  2750. Le_ReloadCmd="$5"
  2751. Le_RealFullChainPath="$6"
  2752. _isEcc="$7"
  2753. _initpath "$Le_Domain" "$_isEcc"
  2754. if [ ! -d "$DOMAIN_PATH" ]; then
  2755. _err "Domain is not valid:'$Le_Domain'"
  2756. return 1
  2757. fi
  2758. _installcert
  2759. }
  2760. _installcert() {
  2761. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  2762. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  2763. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  2764. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  2765. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  2766. if [ "$Le_RealCertPath" = "$NO_VALUE" ]; then
  2767. Le_RealCertPath=""
  2768. fi
  2769. if [ "$Le_RealKeyPath" = "$NO_VALUE" ]; then
  2770. Le_RealKeyPath=""
  2771. fi
  2772. if [ "$Le_RealCACertPath" = "$NO_VALUE" ]; then
  2773. Le_RealCACertPath=""
  2774. fi
  2775. if [ "$Le_ReloadCmd" = "$NO_VALUE" ]; then
  2776. Le_ReloadCmd=""
  2777. fi
  2778. if [ "$Le_RealFullChainPath" = "$NO_VALUE" ]; then
  2779. Le_RealFullChainPath=""
  2780. fi
  2781. if [ "$Le_RealCertPath" ]; then
  2782. _info "Installing cert to:$Le_RealCertPath"
  2783. if [ -f "$Le_RealCertPath" ] && [ ! "$IS_RENEW" ]; then
  2784. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  2785. fi
  2786. cat "$CERT_PATH" >"$Le_RealCertPath"
  2787. fi
  2788. if [ "$Le_RealCACertPath" ]; then
  2789. _info "Installing CA to:$Le_RealCACertPath"
  2790. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ]; then
  2791. echo "" >>"$Le_RealCACertPath"
  2792. cat "$CA_CERT_PATH" >>"$Le_RealCACertPath"
  2793. else
  2794. if [ -f "$Le_RealCACertPath" ] && [ ! "$IS_RENEW" ]; then
  2795. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  2796. fi
  2797. cat "$CA_CERT_PATH" >"$Le_RealCACertPath"
  2798. fi
  2799. fi
  2800. if [ "$Le_RealKeyPath" ]; then
  2801. _info "Installing key to:$Le_RealKeyPath"
  2802. if [ -f "$Le_RealKeyPath" ] && [ ! "$IS_RENEW" ]; then
  2803. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  2804. fi
  2805. cat "$CERT_KEY_PATH" >"$Le_RealKeyPath"
  2806. fi
  2807. if [ "$Le_RealFullChainPath" ]; then
  2808. _info "Installing full chain to:$Le_RealFullChainPath"
  2809. if [ -f "$Le_RealFullChainPath" ] && [ ! "$IS_RENEW" ]; then
  2810. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  2811. fi
  2812. cat "$CERT_FULLCHAIN_PATH" >"$Le_RealFullChainPath"
  2813. fi
  2814. if [ "$Le_ReloadCmd" ]; then
  2815. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  2816. if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd"); then
  2817. _info "$(__green "Reload success")"
  2818. else
  2819. _err "Reload error for :$Le_Domain"
  2820. fi
  2821. fi
  2822. }
  2823. installcronjob() {
  2824. _initpath
  2825. if ! _exists "crontab"; then
  2826. _err "crontab doesn't exist, so, we can not install cron jobs."
  2827. _err "All your certs will not be renewed automatically."
  2828. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  2829. return 1
  2830. fi
  2831. _info "Installing cron job"
  2832. if ! crontab -l | grep "$PROJECT_ENTRY --cron"; then
  2833. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
  2834. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  2835. else
  2836. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  2837. return 1
  2838. fi
  2839. if _exists uname && uname -a | grep SunOS >/dev/null; then
  2840. crontab -l | {
  2841. cat
  2842. echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2843. } | crontab --
  2844. else
  2845. crontab -l | {
  2846. cat
  2847. echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2848. } | crontab -
  2849. fi
  2850. fi
  2851. if [ "$?" != "0" ]; then
  2852. _err "Install cron job failed. You need to manually renew your certs."
  2853. _err "Or you can add cronjob by yourself:"
  2854. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2855. return 1
  2856. fi
  2857. }
  2858. uninstallcronjob() {
  2859. if ! _exists "crontab"; then
  2860. return
  2861. fi
  2862. _info "Removing cron job"
  2863. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  2864. if [ "$cr" ]; then
  2865. if _exists uname && uname -a | grep solaris >/dev/null; then
  2866. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab --
  2867. else
  2868. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  2869. fi
  2870. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  2871. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  2872. fi
  2873. _initpath
  2874. }
  2875. revoke() {
  2876. Le_Domain="$1"
  2877. if [ -z "$Le_Domain" ]; then
  2878. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  2879. return 1
  2880. fi
  2881. _isEcc="$2"
  2882. _initpath "$Le_Domain" "$_isEcc"
  2883. if [ ! -f "$DOMAIN_CONF" ]; then
  2884. _err "$Le_Domain is not a issued domain, skip."
  2885. return 1
  2886. fi
  2887. if [ ! -f "$CERT_PATH" ]; then
  2888. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  2889. return 1
  2890. fi
  2891. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _urlencode)"
  2892. if [ -z "$cert" ]; then
  2893. _err "Cert for $Le_Domain is empty found, skip."
  2894. return 1
  2895. fi
  2896. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  2897. uri="$API/acme/revoke-cert"
  2898. if [ -f "$CERT_KEY_PATH" ]; then
  2899. _info "Try domain key first."
  2900. if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
  2901. if [ -z "$response" ]; then
  2902. _info "Revoke success."
  2903. rm -f "$CERT_PATH"
  2904. return 0
  2905. else
  2906. _err "Revoke error by domain key."
  2907. _err "$response"
  2908. fi
  2909. fi
  2910. else
  2911. _info "Domain key file doesn't exists."
  2912. fi
  2913. _info "Try account key."
  2914. if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
  2915. if [ -z "$response" ]; then
  2916. _info "Revoke success."
  2917. rm -f "$CERT_PATH"
  2918. return 0
  2919. else
  2920. _err "Revoke error."
  2921. _debug "$response"
  2922. fi
  2923. fi
  2924. return 1
  2925. }
  2926. #domain vtype
  2927. _deactivate() {
  2928. _d_domain="$1"
  2929. _d_type="$2"
  2930. _initpath
  2931. _d_i=0
  2932. _d_max_retry=9
  2933. while [ "$_d_i" -lt "$_d_max_retry" ]; do
  2934. _info "Deactivate: $_d_domain"
  2935. _d_i="$(_math $_d_i + 1)"
  2936. if ! __get_domain_new_authz "$_d_domain"; then
  2937. _err "Can not get domain new authz token."
  2938. return 1
  2939. fi
  2940. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2941. _debug "authzUri" "$authzUri"
  2942. if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
  2943. _err "new-authz error: $response"
  2944. return 1
  2945. fi
  2946. entry="$(printf "%s\n" "$response" | _egrep_o '{"type":"[^"]*","status":"valid","uri"[^}]*')"
  2947. _debug entry "$entry"
  2948. if [ -z "$entry" ]; then
  2949. _info "No more valid entry found."
  2950. break
  2951. fi
  2952. _vtype="$(printf "%s\n" "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  2953. _debug _vtype "$_vtype"
  2954. _info "Found $_vtype"
  2955. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
  2956. _debug uri "$uri"
  2957. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
  2958. _info "Skip $_vtype"
  2959. continue
  2960. fi
  2961. _info "Deactivate: $_vtype"
  2962. if ! _send_signed_request "$authzUri" "{\"resource\": \"authz\", \"status\":\"deactivated\"}"; then
  2963. _err "Can not deactivate $_vtype."
  2964. return 1
  2965. fi
  2966. _info "Deactivate: $_vtype success."
  2967. done
  2968. _debug "$_d_i"
  2969. if [ "$_d_i" -lt "$_d_max_retry" ]; then
  2970. _info "Deactivated success!"
  2971. else
  2972. _err "Deactivate failed."
  2973. fi
  2974. }
  2975. deactivate() {
  2976. _d_domain_list="$1"
  2977. _d_type="$2"
  2978. _initpath
  2979. _debug _d_domain_list "$_d_domain_list"
  2980. if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
  2981. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  2982. return 1
  2983. fi
  2984. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
  2985. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
  2986. continue
  2987. fi
  2988. if ! _deactivate "$_d_dm" "$_d_type"; then
  2989. return 1
  2990. fi
  2991. done
  2992. }
  2993. # Detect profile file if not specified as environment variable
  2994. _detect_profile() {
  2995. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  2996. echo "$PROFILE"
  2997. return
  2998. fi
  2999. DETECTED_PROFILE=''
  3000. SHELLTYPE="$(basename "/$SHELL")"
  3001. if [ "$SHELLTYPE" = "bash" ]; then
  3002. if [ -f "$HOME/.bashrc" ]; then
  3003. DETECTED_PROFILE="$HOME/.bashrc"
  3004. elif [ -f "$HOME/.bash_profile" ]; then
  3005. DETECTED_PROFILE="$HOME/.bash_profile"
  3006. fi
  3007. elif [ "$SHELLTYPE" = "zsh" ]; then
  3008. DETECTED_PROFILE="$HOME/.zshrc"
  3009. fi
  3010. if [ -z "$DETECTED_PROFILE" ]; then
  3011. if [ -f "$HOME/.profile" ]; then
  3012. DETECTED_PROFILE="$HOME/.profile"
  3013. elif [ -f "$HOME/.bashrc" ]; then
  3014. DETECTED_PROFILE="$HOME/.bashrc"
  3015. elif [ -f "$HOME/.bash_profile" ]; then
  3016. DETECTED_PROFILE="$HOME/.bash_profile"
  3017. elif [ -f "$HOME/.zshrc" ]; then
  3018. DETECTED_PROFILE="$HOME/.zshrc"
  3019. fi
  3020. fi
  3021. if [ ! -z "$DETECTED_PROFILE" ]; then
  3022. echo "$DETECTED_PROFILE"
  3023. fi
  3024. }
  3025. _initconf() {
  3026. _initpath
  3027. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  3028. echo "#ACCOUNT_CONF_PATH=xxxx
  3029. #ACCOUNT_EMAIL=aaa@example.com # the account email used to register account.
  3030. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  3031. #CERT_HOME=\"/path/to/cert/home\"
  3032. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  3033. #LOG_LEVEL=1
  3034. #AUTO_UPGRADE=\"1\"
  3035. #NO_TIMESTAMP=1
  3036. #OPENSSL_BIN=openssl
  3037. #USER_AGENT=\"$USER_AGENT\"
  3038. #USER_PATH=
  3039. " >"$ACCOUNT_CONF_PATH"
  3040. fi
  3041. }
  3042. # nocron
  3043. _precheck() {
  3044. _nocron="$1"
  3045. if ! _exists "curl" && ! _exists "wget"; then
  3046. _err "Please install curl or wget first, we need to access http resources."
  3047. return 1
  3048. fi
  3049. if [ -z "$_nocron" ]; then
  3050. if ! _exists "crontab"; then
  3051. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  3052. _err "We need to set cron job to renew the certs automatically."
  3053. _err "Otherwise, your certs will not be able to be renewed automatically."
  3054. if [ -z "$FORCE" ]; then
  3055. _err "Please add '--force' and try install again to go without crontab."
  3056. _err "./$PROJECT_ENTRY --install --force"
  3057. return 1
  3058. fi
  3059. fi
  3060. fi
  3061. if ! _exists "$OPENSSL_BIN"; then
  3062. _err "Please install openssl first."
  3063. _err "We need openssl to generate keys."
  3064. return 1
  3065. fi
  3066. if ! _exists "nc"; then
  3067. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  3068. _err "We use nc for standalone server if you use standalone mode."
  3069. _err "If you don't use standalone mode, just ignore this warning."
  3070. fi
  3071. return 0
  3072. }
  3073. _setShebang() {
  3074. _file="$1"
  3075. _shebang="$2"
  3076. if [ -z "$_shebang" ]; then
  3077. _usage "Usage: file shebang"
  3078. return 1
  3079. fi
  3080. cp "$_file" "$_file.tmp"
  3081. echo "$_shebang" >"$_file"
  3082. sed -n 2,99999p "$_file.tmp" >>"$_file"
  3083. rm -f "$_file.tmp"
  3084. }
  3085. _installalias() {
  3086. _initpath
  3087. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  3088. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
  3089. echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
  3090. echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
  3091. echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
  3092. fi
  3093. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  3094. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  3095. _profile="$(_detect_profile)"
  3096. if [ "$_profile" ]; then
  3097. _debug "Found profile: $_profile"
  3098. _info "Installing alias to '$_profile'"
  3099. _setopt "$_profile" ". \"$_envfile\""
  3100. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  3101. else
  3102. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  3103. fi
  3104. #for csh
  3105. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  3106. _csh_profile="$HOME/.cshrc"
  3107. if [ -f "$_csh_profile" ]; then
  3108. _info "Installing alias to '$_csh_profile'"
  3109. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  3110. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  3111. _setopt "$_csh_profile" "source \"$_cshfile\""
  3112. fi
  3113. #for tcsh
  3114. _tcsh_profile="$HOME/.tcshrc"
  3115. if [ -f "$_tcsh_profile" ]; then
  3116. _info "Installing alias to '$_tcsh_profile'"
  3117. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  3118. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  3119. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  3120. fi
  3121. }
  3122. # nocron
  3123. install() {
  3124. if [ -z "$LE_WORKING_DIR" ]; then
  3125. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  3126. fi
  3127. _nocron="$1"
  3128. if ! _initpath; then
  3129. _err "Install failed."
  3130. return 1
  3131. fi
  3132. if [ "$_nocron" ]; then
  3133. _debug "Skip install cron job"
  3134. fi
  3135. if ! _precheck "$_nocron"; then
  3136. _err "Pre-check failed, can not install."
  3137. return 1
  3138. fi
  3139. #convert from le
  3140. if [ -d "$HOME/.le" ]; then
  3141. for envfile in "le.env" "le.sh.env"; do
  3142. if [ -f "$HOME/.le/$envfile" ]; then
  3143. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
  3144. _upgrading="1"
  3145. _info "You are upgrading from le.sh"
  3146. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  3147. mv "$HOME/.le" "$LE_WORKING_DIR"
  3148. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  3149. break
  3150. fi
  3151. fi
  3152. done
  3153. fi
  3154. _info "Installing to $LE_WORKING_DIR"
  3155. if ! mkdir -p "$LE_WORKING_DIR"; then
  3156. _err "Can not create working dir: $LE_WORKING_DIR"
  3157. return 1
  3158. fi
  3159. chmod 700 "$LE_WORKING_DIR"
  3160. cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  3161. if [ "$?" != "0" ]; then
  3162. _err "Install failed, can not copy $PROJECT_ENTRY"
  3163. return 1
  3164. fi
  3165. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  3166. _installalias
  3167. for subf in $_SUB_FOLDERS; do
  3168. if [ -d "$subf" ]; then
  3169. mkdir -p "$LE_WORKING_DIR/$subf"
  3170. cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
  3171. fi
  3172. done
  3173. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  3174. _initconf
  3175. fi
  3176. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
  3177. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  3178. fi
  3179. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
  3180. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  3181. fi
  3182. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
  3183. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  3184. fi
  3185. if [ -z "$_nocron" ]; then
  3186. installcronjob
  3187. fi
  3188. if [ -z "$NO_DETECT_SH" ]; then
  3189. #Modify shebang
  3190. if _exists bash; then
  3191. _info "Good, bash is found, so change the shebang to use bash as preferred."
  3192. _shebang='#!/usr/bin/env bash'
  3193. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  3194. for subf in $_SUB_FOLDERS; do
  3195. if [ -d "$LE_WORKING_DIR/$subf" ]; then
  3196. for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
  3197. _setShebang "$_apifile" "$_shebang"
  3198. done
  3199. fi
  3200. done
  3201. fi
  3202. fi
  3203. _info OK
  3204. }
  3205. # nocron
  3206. uninstall() {
  3207. _nocron="$1"
  3208. if [ -z "$_nocron" ]; then
  3209. uninstallcronjob
  3210. fi
  3211. _initpath
  3212. _uninstallalias
  3213. rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
  3214. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  3215. }
  3216. _uninstallalias() {
  3217. _initpath
  3218. _profile="$(_detect_profile)"
  3219. if [ "$_profile" ]; then
  3220. _info "Uninstalling alias from: '$_profile'"
  3221. text="$(cat "$_profile")"
  3222. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
  3223. fi
  3224. _csh_profile="$HOME/.cshrc"
  3225. if [ -f "$_csh_profile" ]; then
  3226. _info "Uninstalling alias from: '$_csh_profile'"
  3227. text="$(cat "$_csh_profile")"
  3228. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
  3229. fi
  3230. _tcsh_profile="$HOME/.tcshrc"
  3231. if [ -f "$_tcsh_profile" ]; then
  3232. _info "Uninstalling alias from: '$_csh_profile'"
  3233. text="$(cat "$_tcsh_profile")"
  3234. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
  3235. fi
  3236. }
  3237. cron() {
  3238. IN_CRON=1
  3239. _initpath
  3240. if [ "$AUTO_UPGRADE" = "1" ]; then
  3241. export LE_WORKING_DIR
  3242. (
  3243. if ! upgrade; then
  3244. _err "Cron:Upgrade failed!"
  3245. return 1
  3246. fi
  3247. )
  3248. . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
  3249. if [ -t 1 ]; then
  3250. __INTERACTIVE="1"
  3251. fi
  3252. _info "Auto upgraded to: $VER"
  3253. fi
  3254. renewAll
  3255. _ret="$?"
  3256. IN_CRON=""
  3257. exit $_ret
  3258. }
  3259. version() {
  3260. echo "$PROJECT"
  3261. echo "v$VER"
  3262. }
  3263. showhelp() {
  3264. _initpath
  3265. version
  3266. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  3267. Commands:
  3268. --help, -h Show this help message.
  3269. --version, -v Show version info.
  3270. --install Install $PROJECT_NAME to your system.
  3271. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  3272. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT .
  3273. --issue Issue a cert.
  3274. --signcsr Issue a cert from an existing csr.
  3275. --deploy Deploy the cert to your server.
  3276. --installcert Install the issued cert to apache/nginx or any other server.
  3277. --renew, -r Renew a cert.
  3278. --renewAll Renew all the certs.
  3279. --revoke Revoke a cert.
  3280. --list List all the certs.
  3281. --showcsr Show the content of a csr.
  3282. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  3283. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  3284. --cron Run cron job to renew all the certs.
  3285. --toPkcs Export the certificate and key to a pfx file.
  3286. --updateaccount Update account info.
  3287. --registeraccount Register account key.
  3288. --createAccountKey, -cak Create an account private key, professional use.
  3289. --createDomainKey, -cdk Create an domain private key, professional use.
  3290. --createCSR, -ccsr Create CSR , professional use.
  3291. --deactivate Deactivate the domain authz, professional use.
  3292. Parameters:
  3293. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  3294. --force, -f Used to force to install or force to renew a cert immediately.
  3295. --staging, --test Use staging server, just for test.
  3296. --debug Output debug info.
  3297. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  3298. --standalone Use standalone mode.
  3299. --tls Use standalone tls mode.
  3300. --apache Use apache mode.
  3301. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  3302. --dnssleep [$DEFAULT_DNS_SLEEP] The time in seconds to wait for all the txt records to take effect in dns api mode. Default $DEFAULT_DNS_SLEEP seconds.
  3303. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  3304. --accountkeylength, -ak [2048] Specifies the account key length.
  3305. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  3306. --log-level 1|2 Specifies the log level, default is 1.
  3307. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  3308. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  3309. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  3310. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  3311. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  3312. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  3313. --accountconf Specifies a customized account config file.
  3314. --home Specifies the home dir for $PROJECT_NAME .
  3315. --certhome Specifies the home dir to save all the certs, only valid for '--install' command.
  3316. --useragent Specifies the user agent string. it will be saved for future use too.
  3317. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  3318. --accountkey Specifies the account key path, Only valid for the '--install' command.
  3319. --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
  3320. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3321. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3322. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  3323. --listraw Only used for '--list' command, list the certs in raw format.
  3324. --stopRenewOnError, -se Only valid for '--renewall' command. Stop if one cert has error in renewal.
  3325. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  3326. --ca-bundle Specifices the path to the CA certificate bundle to verify api server's certificate.
  3327. --nocron Only valid for '--install' command, which means: do not install the default cron job. In this case, the certs will not be renewed automatically.
  3328. --ecc Specifies to use the ECC cert. Valid for '--installcert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  3329. --csr Specifies the input csr.
  3330. --pre-hook Command to be run before obtaining any certificates.
  3331. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obain/renew is success or failed.
  3332. --renew-hook Command to be run once for each successfully renewed certificate.
  3333. --deploy-hook The hook file to deploy cert
  3334. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  3335. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  3336. --listen-v4 Force standalone/tls server to listen at ipv4.
  3337. --listen-v6 Force standalone/tls server to listen at ipv6.
  3338. --openssl-bin Specifies a custom openssl bin location.
  3339. "
  3340. }
  3341. # nocron
  3342. _installOnline() {
  3343. _info "Installing from online archive."
  3344. _nocron="$1"
  3345. if [ ! "$BRANCH" ]; then
  3346. BRANCH="master"
  3347. fi
  3348. target="$PROJECT/archive/$BRANCH.tar.gz"
  3349. _info "Downloading $target"
  3350. localname="$BRANCH.tar.gz"
  3351. if ! _get "$target" >$localname; then
  3352. _err "Download error."
  3353. return 1
  3354. fi
  3355. (
  3356. _info "Extracting $localname"
  3357. if ! (tar xzf $localname || gtar xzf $localname); then
  3358. _err "Extraction error."
  3359. exit 1
  3360. fi
  3361. cd "$PROJECT_NAME-$BRANCH"
  3362. chmod +x $PROJECT_ENTRY
  3363. if ./$PROJECT_ENTRY install "$_nocron"; then
  3364. _info "Install success!"
  3365. fi
  3366. cd ..
  3367. rm -rf "$PROJECT_NAME-$BRANCH"
  3368. rm -f "$localname"
  3369. )
  3370. }
  3371. upgrade() {
  3372. if (
  3373. _initpath
  3374. export LE_WORKING_DIR
  3375. cd "$LE_WORKING_DIR"
  3376. _installOnline "nocron"
  3377. ); then
  3378. _info "Upgrade success!"
  3379. exit 0
  3380. else
  3381. _err "Upgrade failed!"
  3382. exit 1
  3383. fi
  3384. }
  3385. _processAccountConf() {
  3386. if [ "$_useragent" ]; then
  3387. _saveaccountconf "USER_AGENT" "$_useragent"
  3388. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
  3389. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  3390. fi
  3391. if [ "$_accountemail" ]; then
  3392. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  3393. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
  3394. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  3395. fi
  3396. if [ "$_openssl_bin" ]; then
  3397. _saveaccountconf "OPENSSL_BIN" "$_openssl_bin"
  3398. elif [ "$OPENSSL_BIN" ] && [ "$OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
  3399. _saveaccountconf "OPENSSL_BIN" "$OPENSSL_BIN"
  3400. fi
  3401. if [ "$_auto_upgrade" ]; then
  3402. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  3403. elif [ "$AUTO_UPGRADE" ]; then
  3404. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  3405. fi
  3406. }
  3407. _process() {
  3408. _CMD=""
  3409. _domain=""
  3410. _altdomains="$NO_VALUE"
  3411. _webroot=""
  3412. _keylength=""
  3413. _accountkeylength=""
  3414. _certpath=""
  3415. _keypath=""
  3416. _capath=""
  3417. _fullchainpath=""
  3418. _reloadcmd=""
  3419. _password=""
  3420. _accountconf=""
  3421. _useragent=""
  3422. _accountemail=""
  3423. _accountkey=""
  3424. _certhome=""
  3425. _httpport=""
  3426. _tlsport=""
  3427. _dnssleep=""
  3428. _listraw=""
  3429. _stopRenewOnError=""
  3430. #_insecure=""
  3431. _ca_bundle=""
  3432. _nocron=""
  3433. _ecc=""
  3434. _csr=""
  3435. _pre_hook=""
  3436. _post_hook=""
  3437. _renew_hook=""
  3438. _deploy_hook=""
  3439. _logfile=""
  3440. _log=""
  3441. _local_address=""
  3442. _log_level=""
  3443. _auto_upgrade=""
  3444. _listen_v4=""
  3445. _listen_v6=""
  3446. _openssl_bin=""
  3447. while [ ${#} -gt 0 ]; do
  3448. case "${1}" in
  3449. --help | -h)
  3450. showhelp
  3451. return
  3452. ;;
  3453. --version | -v)
  3454. version
  3455. return
  3456. ;;
  3457. --install)
  3458. _CMD="install"
  3459. ;;
  3460. --uninstall)
  3461. _CMD="uninstall"
  3462. ;;
  3463. --upgrade)
  3464. _CMD="upgrade"
  3465. ;;
  3466. --issue)
  3467. _CMD="issue"
  3468. ;;
  3469. --deploy)
  3470. _CMD="deploy"
  3471. ;;
  3472. --signcsr)
  3473. _CMD="signcsr"
  3474. ;;
  3475. --showcsr)
  3476. _CMD="showcsr"
  3477. ;;
  3478. --installcert | -i)
  3479. _CMD="installcert"
  3480. ;;
  3481. --renew | -r)
  3482. _CMD="renew"
  3483. ;;
  3484. --renewAll | --renewall)
  3485. _CMD="renewAll"
  3486. ;;
  3487. --revoke)
  3488. _CMD="revoke"
  3489. ;;
  3490. --list)
  3491. _CMD="list"
  3492. ;;
  3493. --installcronjob)
  3494. _CMD="installcronjob"
  3495. ;;
  3496. --uninstallcronjob)
  3497. _CMD="uninstallcronjob"
  3498. ;;
  3499. --cron)
  3500. _CMD="cron"
  3501. ;;
  3502. --toPkcs)
  3503. _CMD="toPkcs"
  3504. ;;
  3505. --createAccountKey | --createaccountkey | -cak)
  3506. _CMD="createAccountKey"
  3507. ;;
  3508. --createDomainKey | --createdomainkey | -cdk)
  3509. _CMD="createDomainKey"
  3510. ;;
  3511. --createCSR | --createcsr | -ccr)
  3512. _CMD="createCSR"
  3513. ;;
  3514. --deactivate)
  3515. _CMD="deactivate"
  3516. ;;
  3517. --updateaccount)
  3518. _CMD="updateaccount"
  3519. ;;
  3520. --registeraccount)
  3521. _CMD="registeraccount"
  3522. ;;
  3523. --domain | -d)
  3524. _dvalue="$2"
  3525. if [ "$_dvalue" ]; then
  3526. if _startswith "$_dvalue" "-"; then
  3527. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  3528. return 1
  3529. fi
  3530. if _is_idn "$_dvalue" && ! _exists idn; then
  3531. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  3532. return 1
  3533. fi
  3534. if [ -z "$_domain" ]; then
  3535. _domain="$_dvalue"
  3536. else
  3537. if [ "$_altdomains" = "$NO_VALUE" ]; then
  3538. _altdomains="$_dvalue"
  3539. else
  3540. _altdomains="$_altdomains,$_dvalue"
  3541. fi
  3542. fi
  3543. fi
  3544. shift
  3545. ;;
  3546. --force | -f)
  3547. FORCE="1"
  3548. ;;
  3549. --staging | --test)
  3550. STAGE="1"
  3551. ;;
  3552. --debug)
  3553. if [ -z "$2" ] || _startswith "$2" "-"; then
  3554. DEBUG="1"
  3555. else
  3556. DEBUG="$2"
  3557. shift
  3558. fi
  3559. ;;
  3560. --webroot | -w)
  3561. wvalue="$2"
  3562. if [ -z "$_webroot" ]; then
  3563. _webroot="$wvalue"
  3564. else
  3565. _webroot="$_webroot,$wvalue"
  3566. fi
  3567. shift
  3568. ;;
  3569. --standalone)
  3570. wvalue="$NO_VALUE"
  3571. if [ -z "$_webroot" ]; then
  3572. _webroot="$wvalue"
  3573. else
  3574. _webroot="$_webroot,$wvalue"
  3575. fi
  3576. ;;
  3577. --local-address)
  3578. lvalue="$2"
  3579. _local_address="$_local_address$lvalue,"
  3580. shift
  3581. ;;
  3582. --apache)
  3583. wvalue="apache"
  3584. if [ -z "$_webroot" ]; then
  3585. _webroot="$wvalue"
  3586. else
  3587. _webroot="$_webroot,$wvalue"
  3588. fi
  3589. ;;
  3590. --tls)
  3591. wvalue="$W_TLS"
  3592. if [ -z "$_webroot" ]; then
  3593. _webroot="$wvalue"
  3594. else
  3595. _webroot="$_webroot,$wvalue"
  3596. fi
  3597. ;;
  3598. --dns)
  3599. wvalue="dns"
  3600. if ! _startswith "$2" "-"; then
  3601. wvalue="$2"
  3602. shift
  3603. fi
  3604. if [ -z "$_webroot" ]; then
  3605. _webroot="$wvalue"
  3606. else
  3607. _webroot="$_webroot,$wvalue"
  3608. fi
  3609. ;;
  3610. --dnssleep)
  3611. _dnssleep="$2"
  3612. Le_DNSSleep="$_dnssleep"
  3613. shift
  3614. ;;
  3615. --keylength | -k)
  3616. _keylength="$2"
  3617. shift
  3618. ;;
  3619. --accountkeylength | -ak)
  3620. _accountkeylength="$2"
  3621. shift
  3622. ;;
  3623. --certpath)
  3624. _certpath="$2"
  3625. shift
  3626. ;;
  3627. --keypath)
  3628. _keypath="$2"
  3629. shift
  3630. ;;
  3631. --capath)
  3632. _capath="$2"
  3633. shift
  3634. ;;
  3635. --fullchainpath)
  3636. _fullchainpath="$2"
  3637. shift
  3638. ;;
  3639. --reloadcmd | --reloadCmd)
  3640. _reloadcmd="$2"
  3641. shift
  3642. ;;
  3643. --password)
  3644. _password="$2"
  3645. shift
  3646. ;;
  3647. --accountconf)
  3648. _accountconf="$2"
  3649. ACCOUNT_CONF_PATH="$_accountconf"
  3650. shift
  3651. ;;
  3652. --home)
  3653. LE_WORKING_DIR="$2"
  3654. shift
  3655. ;;
  3656. --certhome)
  3657. _certhome="$2"
  3658. CERT_HOME="$_certhome"
  3659. shift
  3660. ;;
  3661. --useragent)
  3662. _useragent="$2"
  3663. USER_AGENT="$_useragent"
  3664. shift
  3665. ;;
  3666. --accountemail)
  3667. _accountemail="$2"
  3668. ACCOUNT_EMAIL="$_accountemail"
  3669. shift
  3670. ;;
  3671. --accountkey)
  3672. _accountkey="$2"
  3673. ACCOUNT_KEY_PATH="$_accountkey"
  3674. shift
  3675. ;;
  3676. --days)
  3677. _days="$2"
  3678. Le_RenewalDays="$_days"
  3679. shift
  3680. ;;
  3681. --httpport)
  3682. _httpport="$2"
  3683. Le_HTTPPort="$_httpport"
  3684. shift
  3685. ;;
  3686. --tlsport)
  3687. _tlsport="$2"
  3688. Le_TLSPort="$_tlsport"
  3689. shift
  3690. ;;
  3691. --listraw)
  3692. _listraw="raw"
  3693. ;;
  3694. --stopRenewOnError | --stoprenewonerror | -se)
  3695. _stopRenewOnError="1"
  3696. ;;
  3697. --insecure)
  3698. #_insecure="1"
  3699. HTTPS_INSECURE="1"
  3700. ;;
  3701. --ca-bundle)
  3702. _ca_bundle="$(readlink -f "$2")"
  3703. CA_BUNDLE="$_ca_bundle"
  3704. shift
  3705. ;;
  3706. --nocron)
  3707. _nocron="1"
  3708. ;;
  3709. --ecc)
  3710. _ecc="isEcc"
  3711. ;;
  3712. --csr)
  3713. _csr="$2"
  3714. shift
  3715. ;;
  3716. --pre-hook)
  3717. _pre_hook="$2"
  3718. shift
  3719. ;;
  3720. --post-hook)
  3721. _post_hook="$2"
  3722. shift
  3723. ;;
  3724. --renew-hook)
  3725. _renew_hook="$2"
  3726. shift
  3727. ;;
  3728. --deploy-hook)
  3729. _deploy_hook="$2"
  3730. shift
  3731. ;;
  3732. --ocsp-must-staple | --ocsp)
  3733. Le_OCSP_Staple="1"
  3734. ;;
  3735. --log | --logfile)
  3736. _log="1"
  3737. _logfile="$2"
  3738. if _startswith "$_logfile" '-'; then
  3739. _logfile=""
  3740. else
  3741. shift
  3742. fi
  3743. LOG_FILE="$_logfile"
  3744. if [ -z "$LOG_LEVEL" ]; then
  3745. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  3746. fi
  3747. ;;
  3748. --log-level)
  3749. _log_level="$2"
  3750. LOG_LEVEL="$_log_level"
  3751. shift
  3752. ;;
  3753. --auto-upgrade)
  3754. _auto_upgrade="$2"
  3755. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
  3756. _auto_upgrade="1"
  3757. else
  3758. shift
  3759. fi
  3760. AUTO_UPGRADE="$_auto_upgrade"
  3761. ;;
  3762. --listen-v4)
  3763. _listen_v4="1"
  3764. Le_Listen_V4="$_listen_v4"
  3765. ;;
  3766. --listen-v6)
  3767. _listen_v6="1"
  3768. Le_Listen_V6="$_listen_v6"
  3769. ;;
  3770. --openssl-bin)
  3771. _openssl_bin="$2"
  3772. OPENSSL_BIN="$_openssl_bin"
  3773. ;;
  3774. *)
  3775. _err "Unknown parameter : $1"
  3776. return 1
  3777. ;;
  3778. esac
  3779. shift 1
  3780. done
  3781. if [ "${_CMD}" != "install" ]; then
  3782. __initHome
  3783. if [ "$_log" ]; then
  3784. if [ -z "$_logfile" ]; then
  3785. _logfile="$DEFAULT_LOG_FILE"
  3786. fi
  3787. fi
  3788. if [ "$_logfile" ]; then
  3789. _saveaccountconf "LOG_FILE" "$_logfile"
  3790. LOG_FILE="$_logfile"
  3791. fi
  3792. if [ "$_log_level" ]; then
  3793. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3794. LOG_LEVEL="$_log_level"
  3795. fi
  3796. _processAccountConf
  3797. fi
  3798. _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
  3799. if [ "$DEBUG" ]; then
  3800. version
  3801. fi
  3802. case "${_CMD}" in
  3803. install) install "$_nocron" ;;
  3804. uninstall) uninstall "$_nocron" ;;
  3805. upgrade) upgrade ;;
  3806. issue)
  3807. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address"
  3808. ;;
  3809. deploy)
  3810. deploy "$_domain" "$_deploy_hook" "$_ecc"
  3811. ;;
  3812. signcsr)
  3813. signcsr "$_csr" "$_webroot"
  3814. ;;
  3815. showcsr)
  3816. showcsr "$_csr" "$_domain"
  3817. ;;
  3818. installcert)
  3819. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_ecc"
  3820. ;;
  3821. renew)
  3822. renew "$_domain" "$_ecc"
  3823. ;;
  3824. renewAll)
  3825. renewAll "$_stopRenewOnError"
  3826. ;;
  3827. revoke)
  3828. revoke "$_domain" "$_ecc"
  3829. ;;
  3830. deactivate)
  3831. deactivate "$_domain,$_altdomains"
  3832. ;;
  3833. registeraccount)
  3834. registeraccount "$_accountkeylength"
  3835. ;;
  3836. updateaccount)
  3837. updateaccount
  3838. ;;
  3839. list)
  3840. list "$_listraw"
  3841. ;;
  3842. installcronjob) installcronjob ;;
  3843. uninstallcronjob) uninstallcronjob ;;
  3844. cron) cron ;;
  3845. toPkcs)
  3846. toPkcs "$_domain" "$_password" "$_ecc"
  3847. ;;
  3848. createAccountKey)
  3849. createAccountKey "$_accountkeylength"
  3850. ;;
  3851. createDomainKey)
  3852. createDomainKey "$_domain" "$_keylength"
  3853. ;;
  3854. createCSR)
  3855. createCSR "$_domain" "$_altdomains" "$_ecc"
  3856. ;;
  3857. *)
  3858. _err "Invalid command: $_CMD"
  3859. showhelp
  3860. return 1
  3861. ;;
  3862. esac
  3863. _ret="$?"
  3864. if [ "$_ret" != "0" ]; then
  3865. return $_ret
  3866. fi
  3867. if [ "${_CMD}" = "install" ]; then
  3868. if [ "$_log" ]; then
  3869. if [ -z "$LOG_FILE" ]; then
  3870. LOG_FILE="$DEFAULT_LOG_FILE"
  3871. fi
  3872. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  3873. fi
  3874. if [ "$_log_level" ]; then
  3875. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3876. fi
  3877. _processAccountConf
  3878. fi
  3879. }
  3880. if [ "$INSTALLONLINE" ]; then
  3881. INSTALLONLINE=""
  3882. _installOnline $BRANCH
  3883. exit
  3884. fi
  3885. main() {
  3886. [ -z "$1" ] && showhelp && return
  3887. if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
  3888. }
  3889. main "$@"