acme.sh 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644
  1. #!/usr/bin/env sh
  2. VER=2.6.6
  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. if [ -z "$LE_CONFIG_HOME" ]; then
  1390. LE_CONFIG_HOME="$LE_WORKING_DIR"
  1391. fi
  1392. _debug "Using config home:$LE_CONFIG_HOME"
  1393. export LE_CONFIG_HOME
  1394. _DEFAULT_ACCOUNT_CONF_PATH="$LE_CONFIG_HOME/account.conf"
  1395. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1396. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
  1397. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1398. fi
  1399. fi
  1400. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1401. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1402. fi
  1403. DEFAULT_LOG_FILE="$LE_CONFIG_HOME/$PROJECT_NAME.log"
  1404. DEFAULT_CA_HOME="$LE_CONFIG_HOME/ca"
  1405. if [ -z "$LE_TEMP_DIR" ]; then
  1406. LE_TEMP_DIR="$LE_CONFIG_HOME/tmp"
  1407. fi
  1408. }
  1409. #[domain] [keylength]
  1410. _initpath() {
  1411. __initHome
  1412. if [ -f "$ACCOUNT_CONF_PATH" ]; then
  1413. . "$ACCOUNT_CONF_PATH"
  1414. fi
  1415. if [ "$IN_CRON" ]; then
  1416. if [ ! "$_USER_PATH_EXPORTED" ]; then
  1417. _USER_PATH_EXPORTED=1
  1418. export PATH="$USER_PATH:$PATH"
  1419. fi
  1420. fi
  1421. if [ -z "$CA_HOME" ]; then
  1422. CA_HOME="$DEFAULT_CA_HOME"
  1423. fi
  1424. if [ -z "$API" ]; then
  1425. if [ -z "$STAGE" ]; then
  1426. API="$DEFAULT_CA"
  1427. else
  1428. API="$STAGE_CA"
  1429. _info "Using stage api:$API"
  1430. fi
  1431. fi
  1432. _API_HOST="$(echo "$API" | cut -d : -f 2 | tr -d '/')"
  1433. CA_DIR="$CA_HOME/$_API_HOST"
  1434. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  1435. if [ -z "$CA_CONF" ]; then
  1436. CA_CONF="$_DEFAULT_CA_CONF"
  1437. fi
  1438. _debug3 CA_CONF "$CA_CONF"
  1439. if [ -f "$CA_CONF" ]; then
  1440. . "$CA_CONF"
  1441. fi
  1442. if [ -z "$ACME_DIR" ]; then
  1443. ACME_DIR="/home/.acme"
  1444. fi
  1445. if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
  1446. APACHE_CONF_BACKUP_DIR="$LE_CONFIG_HOME"
  1447. fi
  1448. if [ -z "$USER_AGENT" ]; then
  1449. USER_AGENT="$DEFAULT_USER_AGENT"
  1450. fi
  1451. if [ -z "$HTTP_HEADER" ]; then
  1452. HTTP_HEADER="$LE_CONFIG_HOME/http.header"
  1453. fi
  1454. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  1455. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  1456. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  1457. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  1458. if [ -z "$ACCOUNT_KEY_PATH" ]; then
  1459. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  1460. fi
  1461. if [ -z "$ACCOUNT_JSON_PATH" ]; then
  1462. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  1463. fi
  1464. _DEFAULT_CERT_HOME="$LE_CONFIG_HOME"
  1465. if [ -z "$CERT_HOME" ]; then
  1466. CERT_HOME="$_DEFAULT_CERT_HOME"
  1467. fi
  1468. if [ -z "$OPENSSL_BIN" ]; then
  1469. OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
  1470. fi
  1471. if [ -z "$1" ]; then
  1472. return 0
  1473. fi
  1474. domain="$1"
  1475. _ilength="$2"
  1476. if [ -z "$DOMAIN_PATH" ]; then
  1477. domainhome="$CERT_HOME/$domain"
  1478. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  1479. DOMAIN_PATH="$domainhome"
  1480. if _isEccKey "$_ilength"; then
  1481. DOMAIN_PATH="$domainhomeecc"
  1482. else
  1483. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
  1484. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  1485. fi
  1486. fi
  1487. _debug DOMAIN_PATH "$DOMAIN_PATH"
  1488. fi
  1489. if [ -z "$DOMAIN_CONF" ]; then
  1490. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  1491. fi
  1492. if [ -z "$DOMAIN_SSL_CONF" ]; then
  1493. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  1494. fi
  1495. if [ -z "$CSR_PATH" ]; then
  1496. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  1497. fi
  1498. if [ -z "$CERT_KEY_PATH" ]; then
  1499. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  1500. fi
  1501. if [ -z "$CERT_PATH" ]; then
  1502. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  1503. fi
  1504. if [ -z "$CA_CERT_PATH" ]; then
  1505. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  1506. fi
  1507. if [ -z "$CERT_FULLCHAIN_PATH" ]; then
  1508. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  1509. fi
  1510. if [ -z "$CERT_PFX_PATH" ]; then
  1511. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  1512. fi
  1513. if [ -z "$TLS_CONF" ]; then
  1514. TLS_CONF="$DOMAIN_PATH/tls.valdation.conf"
  1515. fi
  1516. if [ -z "$TLS_CERT" ]; then
  1517. TLS_CERT="$DOMAIN_PATH/tls.valdation.cert"
  1518. fi
  1519. if [ -z "$TLS_KEY" ]; then
  1520. TLS_KEY="$DOMAIN_PATH/tls.valdation.key"
  1521. fi
  1522. if [ -z "$TLS_CSR" ]; then
  1523. TLS_CSR="$DOMAIN_PATH/tls.valdation.csr"
  1524. fi
  1525. }
  1526. _exec() {
  1527. if [ -z "$_EXEC_TEMP_ERR" ]; then
  1528. _EXEC_TEMP_ERR="$(_mktemp)"
  1529. fi
  1530. if [ "$_EXEC_TEMP_ERR" ]; then
  1531. eval "$@ 2>>$_EXEC_TEMP_ERR"
  1532. else
  1533. eval "$@"
  1534. fi
  1535. }
  1536. _exec_err() {
  1537. [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
  1538. }
  1539. _apachePath() {
  1540. _APACHECTL="apachectl"
  1541. if ! _exists apachectl; then
  1542. if _exists apache2ctl; then
  1543. _APACHECTL="apache2ctl"
  1544. else
  1545. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  1546. _err "Please use webroot mode to try again."
  1547. return 1
  1548. fi
  1549. fi
  1550. if ! _exec $_APACHECTL -V >/dev/null; then
  1551. _exec_err
  1552. return 1
  1553. fi
  1554. if [ "$APACHE_HTTPD_CONF" ]; then
  1555. _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
  1556. httpdconf="$APACHE_HTTPD_CONF"
  1557. httpdconfname="$(basename "$httpdconfname")"
  1558. else
  1559. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
  1560. _debug httpdconfname "$httpdconfname"
  1561. if [ -z "$httpdconfname" ]; then
  1562. _err "Can not read apache config file."
  1563. return 1
  1564. fi
  1565. if _startswith "$httpdconfname" '/'; then
  1566. httpdconf="$httpdconfname"
  1567. httpdconfname="$(basename "$httpdconfname")"
  1568. else
  1569. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
  1570. _debug httpdroot "$httpdroot"
  1571. httpdconf="$httpdroot/$httpdconfname"
  1572. httpdconfname="$(basename "$httpdconfname")"
  1573. fi
  1574. fi
  1575. _debug httpdconf "$httpdconf"
  1576. _debug httpdconfname "$httpdconfname"
  1577. if [ ! -f "$httpdconf" ]; then
  1578. _err "Apache Config file not found" "$httpdconf"
  1579. return 1
  1580. fi
  1581. return 0
  1582. }
  1583. _restoreApache() {
  1584. if [ -z "$usingApache" ]; then
  1585. return 0
  1586. fi
  1587. _initpath
  1588. if ! _apachePath; then
  1589. return 1
  1590. fi
  1591. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
  1592. _debug "No config file to restore."
  1593. return 0
  1594. fi
  1595. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
  1596. _debug "Restored: $httpdconf."
  1597. if ! _exec $_APACHECTL -t; then
  1598. _exec_err
  1599. _err "Sorry, restore apache config error, please contact me."
  1600. return 1
  1601. fi
  1602. _debug "Restored successfully."
  1603. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1604. return 0
  1605. }
  1606. _setApache() {
  1607. _initpath
  1608. if ! _apachePath; then
  1609. return 1
  1610. fi
  1611. #test the conf first
  1612. _info "Checking if there is an error in the apache config file before starting."
  1613. if ! _exec "$_APACHECTL" -t >/dev/null; then
  1614. _exec_err
  1615. _err "The apache config file has error, please fix it first, then try again."
  1616. _err "Don't worry, there is nothing changed to your system."
  1617. return 1
  1618. else
  1619. _info "OK"
  1620. fi
  1621. #backup the conf
  1622. _debug "Backup apache config file" "$httpdconf"
  1623. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
  1624. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  1625. _err "This might be a bug of $PROJECT_NAME , pleae report issue: $PROJECT"
  1626. return 1
  1627. fi
  1628. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1629. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  1630. _info "The backup file will be deleted on success, just forget it."
  1631. #add alias
  1632. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
  1633. _debug "apacheVer" "$apacheVer"
  1634. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  1635. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  1636. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
  1637. echo "
  1638. Alias /.well-known/acme-challenge $ACME_DIR
  1639. <Directory $ACME_DIR >
  1640. Require all granted
  1641. </Directory>
  1642. " >>"$httpdconf"
  1643. else
  1644. echo "
  1645. Alias /.well-known/acme-challenge $ACME_DIR
  1646. <Directory $ACME_DIR >
  1647. Order allow,deny
  1648. Allow from all
  1649. </Directory>
  1650. " >>"$httpdconf"
  1651. fi
  1652. _msg="$($_APACHECTL -t 2>&1)"
  1653. if [ "$?" != "0" ]; then
  1654. _err "Sorry, apache config error"
  1655. if _restoreApache; then
  1656. _err "The apache config file is restored."
  1657. else
  1658. _err "Sorry, The apache config file can not be restored, please report bug."
  1659. fi
  1660. return 1
  1661. fi
  1662. if [ ! -d "$ACME_DIR" ]; then
  1663. mkdir -p "$ACME_DIR"
  1664. chmod 755 "$ACME_DIR"
  1665. fi
  1666. if ! _exec "$_APACHECTL" graceful; then
  1667. _exec_err
  1668. _err "$_APACHECTL graceful error, please contact me."
  1669. _restoreApache
  1670. return 1
  1671. fi
  1672. usingApache="1"
  1673. return 0
  1674. }
  1675. _clearup() {
  1676. _stopserver "$serverproc"
  1677. serverproc=""
  1678. _restoreApache
  1679. _clearupdns
  1680. if [ -z "$DEBUG" ]; then
  1681. rm -f "$TLS_CONF"
  1682. rm -f "$TLS_CERT"
  1683. rm -f "$TLS_KEY"
  1684. rm -f "$TLS_CSR"
  1685. fi
  1686. }
  1687. _clearupdns() {
  1688. _debug "_clearupdns"
  1689. if [ "$dnsadded" != 1 ] || [ -z "$vlist" ]; then
  1690. _debug "Dns not added, skip."
  1691. return
  1692. fi
  1693. ventries=$(echo "$vlist" | tr ',' ' ')
  1694. for ventry in $ventries; do
  1695. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  1696. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  1697. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  1698. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  1699. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _urlencode)"
  1700. _debug txt "$txt"
  1701. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  1702. _info "$d is already verified, skip $vtype."
  1703. continue
  1704. fi
  1705. if [ "$vtype" != "$VTYPE_DNS" ]; then
  1706. _info "Skip $d for $vtype"
  1707. continue
  1708. fi
  1709. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  1710. _debug d_api "$d_api"
  1711. if [ -z "$d_api" ]; then
  1712. _info "Not Found domain api file: $d_api"
  1713. continue
  1714. fi
  1715. (
  1716. if ! . "$d_api"; then
  1717. _err "Load file $d_api error. Please check your api file and try again."
  1718. return 1
  1719. fi
  1720. rmcommand="${_currentRoot}_rm"
  1721. if ! _exists "$rmcommand"; then
  1722. _err "It seems that your api file doesn't define $rmcommand"
  1723. return 1
  1724. fi
  1725. txtdomain="_acme-challenge.$d"
  1726. if ! $rmcommand "$txtdomain" "$txt"; then
  1727. _err "Error removing txt for domain:$txtdomain"
  1728. return 1
  1729. fi
  1730. )
  1731. done
  1732. }
  1733. # webroot removelevel tokenfile
  1734. _clearupwebbroot() {
  1735. __webroot="$1"
  1736. if [ -z "$__webroot" ]; then
  1737. _debug "no webroot specified, skip"
  1738. return 0
  1739. fi
  1740. _rmpath=""
  1741. if [ "$2" = '1' ]; then
  1742. _rmpath="$__webroot/.well-known"
  1743. elif [ "$2" = '2' ]; then
  1744. _rmpath="$__webroot/.well-known/acme-challenge"
  1745. elif [ "$2" = '3' ]; then
  1746. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  1747. else
  1748. _debug "Skip for removelevel:$2"
  1749. fi
  1750. if [ "$_rmpath" ]; then
  1751. if [ "$DEBUG" ]; then
  1752. _debug "Debugging, skip removing: $_rmpath"
  1753. else
  1754. rm -rf "$_rmpath"
  1755. fi
  1756. fi
  1757. return 0
  1758. }
  1759. _on_before_issue() {
  1760. _debug _on_before_issue
  1761. #run pre hook
  1762. if [ "$Le_PreHook" ]; then
  1763. _info "Run pre hook:'$Le_PreHook'"
  1764. if ! (
  1765. cd "$DOMAIN_PATH" && eval "$Le_PreHook"
  1766. ); then
  1767. _err "Error when run pre hook."
  1768. return 1
  1769. fi
  1770. fi
  1771. if _hasfield "$Le_Webroot" "$NO_VALUE"; then
  1772. if ! _exists "nc"; then
  1773. _err "Please install netcat(nc) tools first."
  1774. return 1
  1775. fi
  1776. fi
  1777. _debug Le_LocalAddress "$Le_LocalAddress"
  1778. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
  1779. _index=1
  1780. _currentRoot=""
  1781. _addrIndex=1
  1782. for d in $alldomains; do
  1783. _debug "Check for domain" "$d"
  1784. _currentRoot="$(_getfield "$Le_Webroot" $_index)"
  1785. _debug "_currentRoot" "$_currentRoot"
  1786. _index=$(_math $_index + 1)
  1787. _checkport=""
  1788. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  1789. _info "Standalone mode."
  1790. if [ -z "$Le_HTTPPort" ]; then
  1791. Le_HTTPPort=80
  1792. else
  1793. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  1794. fi
  1795. _checkport="$Le_HTTPPort"
  1796. elif [ "$_currentRoot" = "$W_TLS" ]; then
  1797. _info "Standalone tls mode."
  1798. if [ -z "$Le_TLSPort" ]; then
  1799. Le_TLSPort=443
  1800. else
  1801. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  1802. fi
  1803. _checkport="$Le_TLSPort"
  1804. fi
  1805. if [ "$_checkport" ]; then
  1806. _debug _checkport "$_checkport"
  1807. _checkaddr="$(_getfield "$Le_LocalAddress" $_addrIndex)"
  1808. _debug _checkaddr "$_checkaddr"
  1809. _addrIndex="$(_math $_addrIndex + 1)"
  1810. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  1811. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  1812. if [ -z "$netprc" ]; then
  1813. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  1814. fi
  1815. if [ "$netprc" ]; then
  1816. _err "$netprc"
  1817. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  1818. _err "Please stop it first"
  1819. return 1
  1820. fi
  1821. fi
  1822. done
  1823. if _hasfield "$Le_Webroot" "apache"; then
  1824. if ! _setApache; then
  1825. _err "set up apache error. Report error to me."
  1826. return 1
  1827. fi
  1828. else
  1829. usingApache=""
  1830. fi
  1831. }
  1832. _on_issue_err() {
  1833. _debug _on_issue_err
  1834. if [ "$LOG_FILE" ]; then
  1835. _err "Please check log file for more details: $LOG_FILE"
  1836. else
  1837. _err "Please add '--debug' or '--log' to check more details."
  1838. _err "See: $_DEBUG_WIKI"
  1839. fi
  1840. if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
  1841. _debug "$(_dlg_versions)"
  1842. fi
  1843. #run the post hook
  1844. if [ "$Le_PostHook" ]; then
  1845. _info "Run post hook:'$Le_PostHook'"
  1846. if ! (
  1847. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1848. ); then
  1849. _err "Error when run post hook."
  1850. return 1
  1851. fi
  1852. fi
  1853. }
  1854. _on_issue_success() {
  1855. _debug _on_issue_success
  1856. #run the post hook
  1857. if [ "$Le_PostHook" ]; then
  1858. _info "Run post hook:'$Le_PostHook'"
  1859. if ! (
  1860. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1861. ); then
  1862. _err "Error when run post hook."
  1863. return 1
  1864. fi
  1865. fi
  1866. #run renew hook
  1867. if [ "$IS_RENEW" ] && [ "$Le_RenewHook" ]; then
  1868. _info "Run renew hook:'$Le_RenewHook'"
  1869. if ! (
  1870. cd "$DOMAIN_PATH" && eval "$Le_RenewHook"
  1871. ); then
  1872. _err "Error when run renew hook."
  1873. return 1
  1874. fi
  1875. fi
  1876. }
  1877. updateaccount() {
  1878. _initpath
  1879. _regAccount
  1880. }
  1881. registeraccount() {
  1882. _reg_length="$1"
  1883. _initpath
  1884. _regAccount "$_reg_length"
  1885. }
  1886. __calcAccountKeyHash() {
  1887. [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
  1888. }
  1889. #keylength
  1890. _regAccount() {
  1891. _initpath
  1892. _reg_length="$1"
  1893. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  1894. mkdir -p "$CA_DIR"
  1895. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  1896. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  1897. fi
  1898. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  1899. mkdir -p "$CA_DIR"
  1900. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  1901. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  1902. fi
  1903. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  1904. if ! _create_account_key "$_reg_length"; then
  1905. _err "Create account key error."
  1906. return 1
  1907. fi
  1908. fi
  1909. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  1910. return 1
  1911. fi
  1912. _updateTos=""
  1913. _reg_res="new-reg"
  1914. while true; do
  1915. _debug AGREEMENT "$AGREEMENT"
  1916. regjson='{"resource": "'$_reg_res'", "agreement": "'$AGREEMENT'"}'
  1917. if [ "$ACCOUNT_EMAIL" ]; then
  1918. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  1919. fi
  1920. if [ -z "$_updateTos" ]; then
  1921. _info "Registering account"
  1922. if ! _send_signed_request "$API/acme/new-reg" "$regjson"; then
  1923. _err "Register account Error: $response"
  1924. return 1
  1925. fi
  1926. if [ "$code" = "" ] || [ "$code" = '201' ]; then
  1927. echo "$response" >"$ACCOUNT_JSON_PATH"
  1928. _info "Registered"
  1929. elif [ "$code" = '409' ]; then
  1930. _info "Already registered"
  1931. else
  1932. _err "Register account Error: $response"
  1933. return 1
  1934. fi
  1935. _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  1936. _debug "_accUri" "$_accUri"
  1937. _tos="$(echo "$responseHeaders" | grep "^Link:.*rel=\"terms-of-service\"" | _head_n 1 | _egrep_o "<.*>" | tr -d '<>')"
  1938. _debug "_tos" "$_tos"
  1939. if [ -z "$_tos" ]; then
  1940. _debug "Use default tos: $DEFAULT_AGREEMENT"
  1941. _tos="$DEFAULT_AGREEMENT"
  1942. fi
  1943. if [ "$_tos" != "$AGREEMENT" ]; then
  1944. _updateTos=1
  1945. AGREEMENT="$_tos"
  1946. _reg_res="reg"
  1947. continue
  1948. fi
  1949. else
  1950. _debug "Update tos: $_tos"
  1951. if ! _send_signed_request "$_accUri" "$regjson"; then
  1952. _err "Update tos error."
  1953. return 1
  1954. fi
  1955. if [ "$code" = '202' ]; then
  1956. _info "Update success."
  1957. CA_KEY_HASH="$(__calcAccountKeyHash)"
  1958. _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
  1959. _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
  1960. else
  1961. _err "Update account error."
  1962. return 1
  1963. fi
  1964. fi
  1965. return 0
  1966. done
  1967. }
  1968. # domain folder file
  1969. _findHook() {
  1970. _hookdomain="$1"
  1971. _hookcat="$2"
  1972. _hookname="$3"
  1973. if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
  1974. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
  1975. elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
  1976. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
  1977. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
  1978. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  1979. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
  1980. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  1981. elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
  1982. d_api="$LE_WORKING_DIR/$_hookname"
  1983. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
  1984. d_api="$LE_WORKING_DIR/$_hookname.sh"
  1985. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
  1986. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  1987. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
  1988. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  1989. fi
  1990. printf "%s" "$d_api"
  1991. }
  1992. #domain
  1993. __get_domain_new_authz() {
  1994. _gdnd="$1"
  1995. _info "Getting new-authz for domain" "$_gdnd"
  1996. _Max_new_authz_retry_times=5
  1997. _authz_i=0
  1998. while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
  1999. _debug "Try new-authz for the $_authz_i time."
  2000. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
  2001. _err "Can not get domain new authz."
  2002. return 1
  2003. fi
  2004. if _contains "$response" "No registration exists matching provided key"; then
  2005. _err "It seems there is an error, but it's recovered now, please try again."
  2006. _err "If you see this message for a second time, please report bug: $(__green "$PROJECT")"
  2007. _clearcaconf "CA_KEY_HASH"
  2008. break
  2009. fi
  2010. if ! _contains "$response" "An error occurred while processing your request"; then
  2011. _info "The new-authz request is ok."
  2012. break
  2013. fi
  2014. _authz_i="$(_math "$_authz_i" + 1)"
  2015. _info "The server is busy, Sleep $_authz_i to retry."
  2016. _sleep "$_authz_i"
  2017. done
  2018. if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
  2019. _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
  2020. fi
  2021. if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
  2022. _err "new-authz error: $response"
  2023. return 1
  2024. fi
  2025. }
  2026. #webroot, domain domainlist keylength
  2027. issue() {
  2028. if [ -z "$2" ]; then
  2029. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  2030. return 1
  2031. fi
  2032. Le_Webroot="$1"
  2033. Le_Domain="$2"
  2034. Le_Alt="$3"
  2035. if _contains "$Le_Domain" ","; then
  2036. Le_Domain=$(echo "$2,$3" | cut -d , -f 1)
  2037. Le_Alt=$(echo "$2,$3" | cut -d , -f 2- | sed "s/,${NO_VALUE}$//")
  2038. fi
  2039. Le_Keylength="$4"
  2040. Le_RealCertPath="$5"
  2041. Le_RealKeyPath="$6"
  2042. Le_RealCACertPath="$7"
  2043. Le_ReloadCmd="$8"
  2044. Le_RealFullChainPath="$9"
  2045. Le_PreHook="${10}"
  2046. Le_PostHook="${11}"
  2047. Le_RenewHook="${12}"
  2048. Le_LocalAddress="${13}"
  2049. #remove these later.
  2050. if [ "$Le_Webroot" = "dns-cf" ]; then
  2051. Le_Webroot="dns_cf"
  2052. fi
  2053. if [ "$Le_Webroot" = "dns-dp" ]; then
  2054. Le_Webroot="dns_dp"
  2055. fi
  2056. if [ "$Le_Webroot" = "dns-cx" ]; then
  2057. Le_Webroot="dns_cx"
  2058. fi
  2059. _debug "Using api: $API"
  2060. if [ ! "$IS_RENEW" ]; then
  2061. _initpath "$Le_Domain" "$Le_Keylength"
  2062. mkdir -p "$DOMAIN_PATH"
  2063. fi
  2064. if [ -f "$DOMAIN_CONF" ]; then
  2065. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  2066. _debug Le_NextRenewTime "$Le_NextRenewTime"
  2067. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  2068. _saved_domain=$(_readdomainconf Le_Domain)
  2069. _debug _saved_domain "$_saved_domain"
  2070. _saved_alt=$(_readdomainconf Le_Alt)
  2071. _debug _saved_alt "$_saved_alt"
  2072. if [ "$_saved_domain,$_saved_alt" = "$Le_Domain,$Le_Alt" ]; then
  2073. _info "Domains not changed."
  2074. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  2075. _info "Add '$(__red '--force')' to force to renew."
  2076. return $RENEW_SKIP
  2077. else
  2078. _info "Domains have changed."
  2079. fi
  2080. fi
  2081. fi
  2082. _savedomainconf "Le_Domain" "$Le_Domain"
  2083. _savedomainconf "Le_Alt" "$Le_Alt"
  2084. _savedomainconf "Le_Webroot" "$Le_Webroot"
  2085. _savedomainconf "Le_PreHook" "$Le_PreHook"
  2086. _savedomainconf "Le_PostHook" "$Le_PostHook"
  2087. _savedomainconf "Le_RenewHook" "$Le_RenewHook"
  2088. if [ "$Le_LocalAddress" ]; then
  2089. _savedomainconf "Le_LocalAddress" "$Le_LocalAddress"
  2090. else
  2091. _cleardomainconf "Le_LocalAddress"
  2092. fi
  2093. Le_API="$API"
  2094. _savedomainconf "Le_API" "$Le_API"
  2095. if [ "$Le_Alt" = "$NO_VALUE" ]; then
  2096. Le_Alt=""
  2097. fi
  2098. if [ "$Le_Keylength" = "$NO_VALUE" ]; then
  2099. Le_Keylength=""
  2100. fi
  2101. if ! _on_before_issue; then
  2102. _err "_on_before_issue."
  2103. return 1
  2104. fi
  2105. _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
  2106. _debug2 _saved_account_key_hash "$_saved_account_key_hash"
  2107. if [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
  2108. if ! _regAccount "$_accountkeylength"; then
  2109. _on_issue_err
  2110. return 1
  2111. fi
  2112. else
  2113. _debug "_saved_account_key_hash is not changed, skip register account."
  2114. fi
  2115. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
  2116. _info "Signing from existing CSR."
  2117. else
  2118. _key=$(_readdomainconf Le_Keylength)
  2119. _debug "Read key length:$_key"
  2120. if [ ! -f "$CERT_KEY_PATH" ] || [ "$Le_Keylength" != "$_key" ]; then
  2121. if ! createDomainKey "$Le_Domain" "$Le_Keylength"; then
  2122. _err "Create domain key error."
  2123. _clearup
  2124. _on_issue_err
  2125. return 1
  2126. fi
  2127. fi
  2128. if ! _createcsr "$Le_Domain" "$Le_Alt" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
  2129. _err "Create CSR error."
  2130. _clearup
  2131. _on_issue_err
  2132. return 1
  2133. fi
  2134. fi
  2135. _savedomainconf "Le_Keylength" "$Le_Keylength"
  2136. vlist="$Le_Vlist"
  2137. _info "Getting domain auth token for each domain"
  2138. sep='#'
  2139. if [ -z "$vlist" ]; then
  2140. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
  2141. _index=1
  2142. _currentRoot=""
  2143. for d in $alldomains; do
  2144. _info "Getting webroot for domain" "$d"
  2145. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  2146. _info _w "$_w"
  2147. if [ "$_w" ]; then
  2148. _currentRoot="$_w"
  2149. fi
  2150. _debug "_currentRoot" "$_currentRoot"
  2151. _index=$(_math $_index + 1)
  2152. vtype="$VTYPE_HTTP"
  2153. if _startswith "$_currentRoot" "dns"; then
  2154. vtype="$VTYPE_DNS"
  2155. fi
  2156. if [ "$_currentRoot" = "$W_TLS" ]; then
  2157. vtype="$VTYPE_TLS"
  2158. fi
  2159. if ! __get_domain_new_authz "$d"; then
  2160. _clearup
  2161. _on_issue_err
  2162. return 1
  2163. fi
  2164. if [ -z "$thumbprint" ]; then
  2165. accountkey_json=$(printf "%s" "$jwk" | tr -d ' ')
  2166. thumbprint=$(printf "%s" "$accountkey_json" | _digest "sha256" | _urlencode)
  2167. fi
  2168. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  2169. _debug entry "$entry"
  2170. if [ -z "$entry" ]; then
  2171. _err "Error, can not get domain token $d"
  2172. _clearup
  2173. _on_issue_err
  2174. return 1
  2175. fi
  2176. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  2177. _debug token "$token"
  2178. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
  2179. _debug uri "$uri"
  2180. keyauthorization="$token.$thumbprint"
  2181. _debug keyauthorization "$keyauthorization"
  2182. if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  2183. _info "$d is already verified, skip."
  2184. keyauthorization="$STATE_VERIFIED"
  2185. _debug keyauthorization "$keyauthorization"
  2186. fi
  2187. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  2188. _debug dvlist "$dvlist"
  2189. vlist="$vlist$dvlist,"
  2190. done
  2191. #add entry
  2192. dnsadded=""
  2193. ventries=$(echo "$vlist" | tr ',' ' ')
  2194. for ventry in $ventries; do
  2195. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2196. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2197. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2198. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2199. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2200. _info "$d is already verified, skip $vtype."
  2201. continue
  2202. fi
  2203. if [ "$vtype" = "$VTYPE_DNS" ]; then
  2204. dnsadded='0'
  2205. txtdomain="_acme-challenge.$d"
  2206. _debug txtdomain "$txtdomain"
  2207. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _urlencode)"
  2208. _debug txt "$txt"
  2209. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  2210. _debug d_api "$d_api"
  2211. if [ "$d_api" ]; then
  2212. _info "Found domain api file: $d_api"
  2213. else
  2214. _err "Add the following TXT record:"
  2215. _err "Domain: '$(__green "$txtdomain")'"
  2216. _err "TXT value: '$(__green "$txt")'"
  2217. _err "Please be aware that you prepend _acme-challenge. before your domain"
  2218. _err "so the resulting subdomain will be: $txtdomain"
  2219. continue
  2220. fi
  2221. (
  2222. if ! . "$d_api"; then
  2223. _err "Load file $d_api error. Please check your api file and try again."
  2224. return 1
  2225. fi
  2226. addcommand="${_currentRoot}_add"
  2227. if ! _exists "$addcommand"; then
  2228. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  2229. return 1
  2230. fi
  2231. if ! $addcommand "$txtdomain" "$txt"; then
  2232. _err "Error add txt for domain:$txtdomain"
  2233. return 1
  2234. fi
  2235. )
  2236. if [ "$?" != "0" ]; then
  2237. _clearup
  2238. _on_issue_err
  2239. return 1
  2240. fi
  2241. dnsadded='1'
  2242. fi
  2243. done
  2244. if [ "$dnsadded" = '0' ]; then
  2245. _savedomainconf "Le_Vlist" "$vlist"
  2246. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  2247. _err "Please add the TXT records to the domains, and retry again."
  2248. _clearup
  2249. _on_issue_err
  2250. return 1
  2251. fi
  2252. fi
  2253. if [ "$dnsadded" = '1' ]; then
  2254. if [ -z "$Le_DNSSleep" ]; then
  2255. Le_DNSSleep="$DEFAULT_DNS_SLEEP"
  2256. else
  2257. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  2258. fi
  2259. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  2260. _sleep "$Le_DNSSleep"
  2261. fi
  2262. _debug "ok, let's start to verify"
  2263. _ncIndex=1
  2264. ventries=$(echo "$vlist" | tr ',' ' ')
  2265. for ventry in $ventries; do
  2266. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2267. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2268. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  2269. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2270. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2271. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2272. _info "$d is already verified, skip $vtype."
  2273. continue
  2274. fi
  2275. _info "Verifying:$d"
  2276. _debug "d" "$d"
  2277. _debug "keyauthorization" "$keyauthorization"
  2278. _debug "uri" "$uri"
  2279. removelevel=""
  2280. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  2281. _debug "_currentRoot" "$_currentRoot"
  2282. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  2283. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2284. _info "Standalone mode server"
  2285. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
  2286. _ncIndex="$(_math $_ncIndex + 1)"
  2287. _startserver "$keyauthorization" "$_ncaddr" &
  2288. if [ "$?" != "0" ]; then
  2289. _clearup
  2290. _on_issue_err
  2291. return 1
  2292. fi
  2293. serverproc="$!"
  2294. sleep 1
  2295. _debug serverproc "$serverproc"
  2296. else
  2297. if [ "$_currentRoot" = "apache" ]; then
  2298. wellknown_path="$ACME_DIR"
  2299. else
  2300. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  2301. if [ ! -d "$_currentRoot/.well-known" ]; then
  2302. removelevel='1'
  2303. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
  2304. removelevel='2'
  2305. else
  2306. removelevel='3'
  2307. fi
  2308. fi
  2309. _debug wellknown_path "$wellknown_path"
  2310. _debug "writing token:$token to $wellknown_path/$token"
  2311. mkdir -p "$wellknown_path"
  2312. if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
  2313. _err "$d:Can not write token to file : $wellknown_path/$token"
  2314. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2315. _clearup
  2316. _on_issue_err
  2317. return 1
  2318. fi
  2319. if [ ! "$usingApache" ]; then
  2320. if webroot_owner=$(_stat "$_currentRoot"); then
  2321. _debug "Changing owner/group of .well-known to $webroot_owner"
  2322. chown -R "$webroot_owner" "$_currentRoot/.well-known"
  2323. else
  2324. _debug "not chaning owner/group of webroot"
  2325. fi
  2326. fi
  2327. fi
  2328. elif [ "$vtype" = "$VTYPE_TLS" ]; then
  2329. #create A
  2330. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  2331. #_debug2 _hash_A "$_hash_A"
  2332. #_x="$(echo $_hash_A | cut -c 1-32)"
  2333. #_debug2 _x "$_x"
  2334. #_y="$(echo $_hash_A | cut -c 33-64)"
  2335. #_debug2 _y "$_y"
  2336. #_SAN_A="$_x.$_y.token.acme.invalid"
  2337. #_debug2 _SAN_A "$_SAN_A"
  2338. #create B
  2339. _hash_B="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
  2340. _debug2 _hash_B "$_hash_B"
  2341. _x="$(echo "$_hash_B" | cut -c 1-32)"
  2342. _debug2 _x "$_x"
  2343. _y="$(echo "$_hash_B" | cut -c 33-64)"
  2344. _debug2 _y "$_y"
  2345. #_SAN_B="$_x.$_y.ka.acme.invalid"
  2346. _SAN_B="$_x.$_y.acme.invalid"
  2347. _debug2 _SAN_B "$_SAN_B"
  2348. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
  2349. _ncIndex="$(_math "$_ncIndex" + 1)"
  2350. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" "$_ncaddr"; then
  2351. _err "Start tls server error."
  2352. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2353. _clearup
  2354. _on_issue_err
  2355. return 1
  2356. fi
  2357. fi
  2358. if ! _send_signed_request "$uri" "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"; then
  2359. _err "$d:Can not get challenge: $response"
  2360. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2361. _clearup
  2362. _on_issue_err
  2363. return 1
  2364. fi
  2365. if [ ! -z "$code" ] && [ ! "$code" = '202' ]; then
  2366. _err "$d:Challenge error: $response"
  2367. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2368. _clearup
  2369. _on_issue_err
  2370. return 1
  2371. fi
  2372. waittimes=0
  2373. if [ -z "$MAX_RETRY_TIMES" ]; then
  2374. MAX_RETRY_TIMES=30
  2375. fi
  2376. while true; do
  2377. waittimes=$(_math "$waittimes" + 1)
  2378. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
  2379. _err "$d:Timeout"
  2380. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2381. _clearup
  2382. _on_issue_err
  2383. return 1
  2384. fi
  2385. _debug "sleep 2 secs to verify"
  2386. sleep 2
  2387. _debug "checking"
  2388. response="$(_get "$uri")"
  2389. if [ "$?" != "0" ]; then
  2390. _err "$d:Verify error:$response"
  2391. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2392. _clearup
  2393. _on_issue_err
  2394. return 1
  2395. fi
  2396. _debug2 original "$response"
  2397. response="$(echo "$response" | _normalizeJson)"
  2398. _debug2 response "$response"
  2399. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  2400. if [ "$status" = "valid" ]; then
  2401. _info "$(__green Success)"
  2402. _stopserver "$serverproc"
  2403. serverproc=""
  2404. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2405. break
  2406. fi
  2407. if [ "$status" = "invalid" ]; then
  2408. error="$(echo "$response" | tr -d "\r\n" | _egrep_o '"error":\{[^\}]*')"
  2409. _debug2 error "$error"
  2410. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  2411. _debug2 errordetail "$errordetail"
  2412. if [ "$errordetail" ]; then
  2413. _err "$d:Verify error:$errordetail"
  2414. else
  2415. _err "$d:Verify error:$error"
  2416. fi
  2417. if [ "$DEBUG" ]; then
  2418. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  2419. _debug "Debug: get token url."
  2420. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  2421. fi
  2422. fi
  2423. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2424. _clearup
  2425. _on_issue_err
  2426. return 1
  2427. fi
  2428. if [ "$status" = "pending" ]; then
  2429. _info "Pending"
  2430. else
  2431. _err "$d:Verify error:$response"
  2432. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2433. _clearup
  2434. _on_issue_err
  2435. return 1
  2436. fi
  2437. done
  2438. done
  2439. _clearup
  2440. _info "Verify finished, start to sign."
  2441. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  2442. if ! _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"; then
  2443. _err "Sign failed."
  2444. _on_issue_err
  2445. return 1
  2446. fi
  2447. _rcert="$response"
  2448. Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _head_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  2449. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  2450. if [ "$Le_LinkCert" ]; then
  2451. echo "$BEGIN_CERT" >"$CERT_PATH"
  2452. #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  2453. # _debug "Get cert failed. Let's try last response."
  2454. # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  2455. #fi
  2456. if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
  2457. _debug "Try cert link."
  2458. _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
  2459. fi
  2460. echo "$END_CERT" >>"$CERT_PATH"
  2461. _info "$(__green "Cert success.")"
  2462. cat "$CERT_PATH"
  2463. _info "Your cert is in $(__green " $CERT_PATH ")"
  2464. if [ -f "$CERT_KEY_PATH" ]; then
  2465. _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
  2466. fi
  2467. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  2468. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ]; then
  2469. USER_PATH="$PATH"
  2470. _saveaccountconf "USER_PATH" "$USER_PATH"
  2471. fi
  2472. fi
  2473. if [ -z "$Le_LinkCert" ]; then
  2474. response="$(echo "$response" | _dbase64 "multiline" | _normalizeJson)"
  2475. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  2476. _on_issue_err
  2477. return 1
  2478. fi
  2479. _cleardomainconf "Le_Vlist"
  2480. Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
  2481. if ! _contains "$Le_LinkIssuer" ":"; then
  2482. Le_LinkIssuer="$API$Le_LinkIssuer"
  2483. fi
  2484. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  2485. if [ "$Le_LinkIssuer" ]; then
  2486. echo "$BEGIN_CERT" >"$CA_CERT_PATH"
  2487. _get "$Le_LinkIssuer" | _base64 "multiline" >>"$CA_CERT_PATH"
  2488. echo "$END_CERT" >>"$CA_CERT_PATH"
  2489. _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
  2490. cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
  2491. _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
  2492. fi
  2493. Le_CertCreateTime=$(_time)
  2494. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  2495. Le_CertCreateTimeStr=$(date -u)
  2496. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  2497. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ]; then
  2498. Le_RenewalDays="$MAX_RENEW"
  2499. else
  2500. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  2501. fi
  2502. if [ "$CA_BUNDLE" ]; then
  2503. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  2504. else
  2505. _clearaccountconf "CA_BUNDLE"
  2506. fi
  2507. if [ "$HTTPS_INSECURE" ]; then
  2508. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  2509. else
  2510. _clearaccountconf "HTTPS_INSECURE"
  2511. fi
  2512. if [ "$Le_Listen_V4" ]; then
  2513. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  2514. _cleardomainconf Le_Listen_V6
  2515. elif [ "$Le_Listen_V6" ]; then
  2516. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  2517. _cleardomainconf Le_Listen_V4
  2518. fi
  2519. Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
  2520. Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
  2521. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  2522. Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
  2523. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  2524. _on_issue_success
  2525. if [ "$Le_RealCertPath$Le_RealKeyPath$Le_RealCACertPath$Le_ReloadCmd$Le_RealFullChainPath" ]; then
  2526. _installcert
  2527. fi
  2528. }
  2529. #domain [isEcc]
  2530. renew() {
  2531. Le_Domain="$1"
  2532. if [ -z "$Le_Domain" ]; then
  2533. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  2534. return 1
  2535. fi
  2536. _isEcc="$2"
  2537. _initpath "$Le_Domain" "$_isEcc"
  2538. _info "$(__green "Renew: '$Le_Domain'")"
  2539. if [ ! -f "$DOMAIN_CONF" ]; then
  2540. _info "'$Le_Domain' is not a issued domain, skip."
  2541. return 0
  2542. fi
  2543. if [ "$Le_RenewalDays" ]; then
  2544. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  2545. fi
  2546. . "$DOMAIN_CONF"
  2547. if [ "$Le_API" ]; then
  2548. API="$Le_API"
  2549. #reload ca configs
  2550. ACCOUNT_KEY_PATH=""
  2551. ACCOUNT_JSON_PATH=""
  2552. CA_CONF=""
  2553. _debug3 "initpath again."
  2554. _initpath "$Le_Domain" "$_isEcc"
  2555. fi
  2556. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  2557. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  2558. _info "Add '$(__red '--force')' to force to renew."
  2559. return "$RENEW_SKIP"
  2560. fi
  2561. IS_RENEW="1"
  2562. 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"
  2563. res="$?"
  2564. if [ "$res" != "0" ]; then
  2565. return "$res"
  2566. fi
  2567. if [ "$Le_DeployHook" ]; then
  2568. deploy "$Le_Domain" "$Le_DeployHook" "$Le_Keylength"
  2569. res="$?"
  2570. fi
  2571. IS_RENEW=""
  2572. return "$res"
  2573. }
  2574. #renewAll [stopRenewOnError]
  2575. renewAll() {
  2576. _initpath
  2577. _stopRenewOnError="$1"
  2578. _debug "_stopRenewOnError" "$_stopRenewOnError"
  2579. _ret="0"
  2580. for di in "${CERT_HOME}"/*.*/; do
  2581. _debug di "$di"
  2582. if ! [ -d "$di" ]; then
  2583. _debug "Not directory, skip: $di"
  2584. continue
  2585. fi
  2586. d=$(basename "$di")
  2587. _debug d "$d"
  2588. (
  2589. if _endswith "$d" "$ECC_SUFFIX"; then
  2590. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  2591. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  2592. fi
  2593. renew "$d" "$_isEcc"
  2594. )
  2595. rc="$?"
  2596. _debug "Return code: $rc"
  2597. if [ "$rc" != "0" ]; then
  2598. if [ "$rc" = "$RENEW_SKIP" ]; then
  2599. _info "Skipped $d"
  2600. elif [ "$_stopRenewOnError" ]; then
  2601. _err "Error renew $d, stop now."
  2602. return "$rc"
  2603. else
  2604. _ret="$rc"
  2605. _err "Error renew $d, Go ahead to next one."
  2606. fi
  2607. fi
  2608. done
  2609. return "$_ret"
  2610. }
  2611. #csr webroot
  2612. signcsr() {
  2613. _csrfile="$1"
  2614. _csrW="$2"
  2615. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  2616. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  2617. return 1
  2618. fi
  2619. _initpath
  2620. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2621. if [ "$?" != "0" ]; then
  2622. _err "Can not read subject from csr: $_csrfile"
  2623. return 1
  2624. fi
  2625. _debug _csrsubj "$_csrsubj"
  2626. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2627. if [ "$?" != "0" ]; then
  2628. _err "Can not read domain list from csr: $_csrfile"
  2629. return 1
  2630. fi
  2631. _debug "_csrdomainlist" "$_csrdomainlist"
  2632. if [ -z "$_csrsubj" ]; then
  2633. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  2634. _debug _csrsubj "$_csrsubj"
  2635. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  2636. _debug "_csrdomainlist" "$_csrdomainlist"
  2637. fi
  2638. if [ -z "$_csrsubj" ]; then
  2639. _err "Can not read subject from csr: $_csrfile"
  2640. return 1
  2641. fi
  2642. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2643. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  2644. _err "Can not read key length from csr: $_csrfile"
  2645. return 1
  2646. fi
  2647. _initpath "$_csrsubj" "$_csrkeylength"
  2648. mkdir -p "$DOMAIN_PATH"
  2649. _info "Copy csr to: $CSR_PATH"
  2650. cp "$_csrfile" "$CSR_PATH"
  2651. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength"
  2652. }
  2653. showcsr() {
  2654. _csrfile="$1"
  2655. _csrd="$2"
  2656. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  2657. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  2658. return 1
  2659. fi
  2660. _initpath
  2661. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2662. if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
  2663. _err "Can not read subject from csr: $_csrfile"
  2664. return 1
  2665. fi
  2666. _info "Subject=$_csrsubj"
  2667. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2668. if [ "$?" != "0" ]; then
  2669. _err "Can not read domain list from csr: $_csrfile"
  2670. return 1
  2671. fi
  2672. _debug "_csrdomainlist" "$_csrdomainlist"
  2673. _info "SubjectAltNames=$_csrdomainlist"
  2674. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2675. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  2676. _err "Can not read key length from csr: $_csrfile"
  2677. return 1
  2678. fi
  2679. _info "KeyLength=$_csrkeylength"
  2680. }
  2681. list() {
  2682. _raw="$1"
  2683. _initpath
  2684. _sep="|"
  2685. if [ "$_raw" ]; then
  2686. printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew"
  2687. for di in "${CERT_HOME}"/*.*/; do
  2688. if ! [ -d "$di" ]; then
  2689. _debug "Not directory, skip: $di"
  2690. continue
  2691. fi
  2692. d=$(basename "$di")
  2693. _debug d "$d"
  2694. (
  2695. if _endswith "$d" "$ECC_SUFFIX"; then
  2696. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  2697. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  2698. fi
  2699. _initpath "$d" "$_isEcc"
  2700. if [ -f "$DOMAIN_CONF" ]; then
  2701. . "$DOMAIN_CONF"
  2702. printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
  2703. fi
  2704. )
  2705. done
  2706. else
  2707. if _exists column; then
  2708. list "raw" | column -t -s "$_sep"
  2709. else
  2710. list "raw" | tr "$_sep" '\t'
  2711. fi
  2712. fi
  2713. }
  2714. deploy() {
  2715. Le_Domain="$1"
  2716. Le_DeployHook="$2"
  2717. _isEcc="$3"
  2718. if [ -z "$Le_DeployHook" ]; then
  2719. _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
  2720. return 1
  2721. fi
  2722. _initpath "$Le_Domain" "$_isEcc"
  2723. if [ ! -d "$DOMAIN_PATH" ]; then
  2724. _err "Domain is not valid:'$Le_Domain'"
  2725. return 1
  2726. fi
  2727. _deployApi="$(_findHook "$Le_Domain" deploy "$Le_DeployHook")"
  2728. if [ -z "$_deployApi" ]; then
  2729. _err "The deploy hook $Le_DeployHook is not found."
  2730. return 1
  2731. fi
  2732. _debug _deployApi "$_deployApi"
  2733. _savedomainconf Le_DeployHook "$Le_DeployHook"
  2734. if ! (
  2735. if ! . "$_deployApi"; then
  2736. _err "Load file $_deployApi error. Please check your api file and try again."
  2737. return 1
  2738. fi
  2739. d_command="${Le_DeployHook}_deploy"
  2740. if ! _exists "$d_command"; then
  2741. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  2742. return 1
  2743. fi
  2744. if ! $d_command "$Le_Domain" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
  2745. _err "Error deploy for domain:$Le_Domain"
  2746. _on_issue_err
  2747. return 1
  2748. fi
  2749. ); then
  2750. _err "Deploy error."
  2751. return 1
  2752. else
  2753. _info "$(__green Success)"
  2754. fi
  2755. }
  2756. installcert() {
  2757. Le_Domain="$1"
  2758. if [ -z "$Le_Domain" ]; then
  2759. _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]"
  2760. return 1
  2761. fi
  2762. Le_RealCertPath="$2"
  2763. Le_RealKeyPath="$3"
  2764. Le_RealCACertPath="$4"
  2765. Le_ReloadCmd="$5"
  2766. Le_RealFullChainPath="$6"
  2767. _isEcc="$7"
  2768. _initpath "$Le_Domain" "$_isEcc"
  2769. if [ ! -d "$DOMAIN_PATH" ]; then
  2770. _err "Domain is not valid:'$Le_Domain'"
  2771. return 1
  2772. fi
  2773. _installcert
  2774. }
  2775. _installcert() {
  2776. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  2777. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  2778. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  2779. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  2780. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  2781. if [ "$Le_RealCertPath" = "$NO_VALUE" ]; then
  2782. Le_RealCertPath=""
  2783. fi
  2784. if [ "$Le_RealKeyPath" = "$NO_VALUE" ]; then
  2785. Le_RealKeyPath=""
  2786. fi
  2787. if [ "$Le_RealCACertPath" = "$NO_VALUE" ]; then
  2788. Le_RealCACertPath=""
  2789. fi
  2790. if [ "$Le_ReloadCmd" = "$NO_VALUE" ]; then
  2791. Le_ReloadCmd=""
  2792. fi
  2793. if [ "$Le_RealFullChainPath" = "$NO_VALUE" ]; then
  2794. Le_RealFullChainPath=""
  2795. fi
  2796. if [ "$Le_RealCertPath" ]; then
  2797. _info "Installing cert to:$Le_RealCertPath"
  2798. if [ -f "$Le_RealCertPath" ] && [ ! "$IS_RENEW" ]; then
  2799. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  2800. fi
  2801. cat "$CERT_PATH" >"$Le_RealCertPath"
  2802. fi
  2803. if [ "$Le_RealCACertPath" ]; then
  2804. _info "Installing CA to:$Le_RealCACertPath"
  2805. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ]; then
  2806. echo "" >>"$Le_RealCACertPath"
  2807. cat "$CA_CERT_PATH" >>"$Le_RealCACertPath"
  2808. else
  2809. if [ -f "$Le_RealCACertPath" ] && [ ! "$IS_RENEW" ]; then
  2810. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  2811. fi
  2812. cat "$CA_CERT_PATH" >"$Le_RealCACertPath"
  2813. fi
  2814. fi
  2815. if [ "$Le_RealKeyPath" ]; then
  2816. _info "Installing key to:$Le_RealKeyPath"
  2817. if [ -f "$Le_RealKeyPath" ] && [ ! "$IS_RENEW" ]; then
  2818. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  2819. fi
  2820. cat "$CERT_KEY_PATH" >"$Le_RealKeyPath"
  2821. fi
  2822. if [ "$Le_RealFullChainPath" ]; then
  2823. _info "Installing full chain to:$Le_RealFullChainPath"
  2824. if [ -f "$Le_RealFullChainPath" ] && [ ! "$IS_RENEW" ]; then
  2825. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  2826. fi
  2827. cat "$CERT_FULLCHAIN_PATH" >"$Le_RealFullChainPath"
  2828. fi
  2829. if [ "$Le_ReloadCmd" ]; then
  2830. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  2831. if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd"); then
  2832. _info "$(__green "Reload success")"
  2833. else
  2834. _err "Reload error for :$Le_Domain"
  2835. fi
  2836. fi
  2837. }
  2838. #confighome
  2839. installcronjob() {
  2840. _c_home="$1"
  2841. _initpath
  2842. if ! _exists "crontab"; then
  2843. _err "crontab doesn't exist, so, we can not install cron jobs."
  2844. _err "All your certs will not be renewed automatically."
  2845. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  2846. return 1
  2847. fi
  2848. _info "Installing cron job"
  2849. if ! crontab -l | grep "$PROJECT_ENTRY --cron"; then
  2850. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
  2851. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  2852. else
  2853. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  2854. return 1
  2855. fi
  2856. if [ "$_c_home" ]; then
  2857. _c_entry="--config-home \"$_c_home\" "
  2858. fi
  2859. _t=$(_time)
  2860. random_minute=$(_math $_t % 60)
  2861. if _exists uname && uname -a | grep SunOS >/dev/null; then
  2862. crontab -l | {
  2863. cat
  2864. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  2865. } | crontab --
  2866. else
  2867. crontab -l | {
  2868. cat
  2869. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  2870. } | crontab -
  2871. fi
  2872. fi
  2873. if [ "$?" != "0" ]; then
  2874. _err "Install cron job failed. You need to manually renew your certs."
  2875. _err "Or you can add cronjob by yourself:"
  2876. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2877. return 1
  2878. fi
  2879. }
  2880. uninstallcronjob() {
  2881. if ! _exists "crontab"; then
  2882. return
  2883. fi
  2884. _info "Removing cron job"
  2885. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  2886. if [ "$cr" ]; then
  2887. if _exists uname && uname -a | grep solaris >/dev/null; then
  2888. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab --
  2889. else
  2890. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  2891. fi
  2892. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  2893. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  2894. if _contains "$cr" "--config-home"; then
  2895. LE_CONFIG_HOME="$(echo "$cr" | cut -d ' ' -f 11 | tr -d '"')"
  2896. _debug LE_CONFIG_HOME "$LE_CONFIG_HOME"
  2897. fi
  2898. fi
  2899. _initpath
  2900. }
  2901. revoke() {
  2902. Le_Domain="$1"
  2903. if [ -z "$Le_Domain" ]; then
  2904. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com [--ecc]"
  2905. return 1
  2906. fi
  2907. _isEcc="$2"
  2908. _initpath "$Le_Domain" "$_isEcc"
  2909. if [ ! -f "$DOMAIN_CONF" ]; then
  2910. _err "$Le_Domain is not a issued domain, skip."
  2911. return 1
  2912. fi
  2913. if [ ! -f "$CERT_PATH" ]; then
  2914. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  2915. return 1
  2916. fi
  2917. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _urlencode)"
  2918. if [ -z "$cert" ]; then
  2919. _err "Cert for $Le_Domain is empty found, skip."
  2920. return 1
  2921. fi
  2922. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  2923. uri="$API/acme/revoke-cert"
  2924. if [ -f "$CERT_KEY_PATH" ]; then
  2925. _info "Try domain key first."
  2926. if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
  2927. if [ -z "$response" ]; then
  2928. _info "Revoke success."
  2929. rm -f "$CERT_PATH"
  2930. return 0
  2931. else
  2932. _err "Revoke error by domain key."
  2933. _err "$response"
  2934. fi
  2935. fi
  2936. else
  2937. _info "Domain key file doesn't exists."
  2938. fi
  2939. _info "Try account key."
  2940. if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
  2941. if [ -z "$response" ]; then
  2942. _info "Revoke success."
  2943. rm -f "$CERT_PATH"
  2944. return 0
  2945. else
  2946. _err "Revoke error."
  2947. _debug "$response"
  2948. fi
  2949. fi
  2950. return 1
  2951. }
  2952. #domain ecc
  2953. remove() {
  2954. Le_Domain="$1"
  2955. if [ -z "$Le_Domain" ]; then
  2956. _usage "Usage: $PROJECT_ENTRY --remove -d domain.com [--ecc]"
  2957. return 1
  2958. fi
  2959. _isEcc="$2"
  2960. _initpath "$Le_Domain" "$_isEcc"
  2961. _removed_conf="$DOMAIN_CONF.removed"
  2962. if [ ! -f "$DOMAIN_CONF" ]; then
  2963. if [ -f "$_removed_conf" ]; then
  2964. _err "$Le_Domain is already removed, You can remove the folder by yourself: $DOMAIN_PATH"
  2965. else
  2966. _err "$Le_Domain is not a issued domain, skip."
  2967. fi
  2968. return 1
  2969. fi
  2970. if mv "$DOMAIN_CONF" "$_removed_conf"; then
  2971. _info "$Le_Domain is removed, the key and cert files are in $(__green $DOMAIN_PATH )"
  2972. _info "You can remove them by yourself."
  2973. return 0
  2974. else
  2975. _err "Remove $Le_Domain failed."
  2976. return 1
  2977. fi
  2978. }
  2979. #domain vtype
  2980. _deactivate() {
  2981. _d_domain="$1"
  2982. _d_type="$2"
  2983. _initpath
  2984. _d_i=0
  2985. _d_max_retry=9
  2986. while [ "$_d_i" -lt "$_d_max_retry" ]; do
  2987. _info "Deactivate: $_d_domain"
  2988. _d_i="$(_math $_d_i + 1)"
  2989. if ! __get_domain_new_authz "$_d_domain"; then
  2990. _err "Can not get domain new authz token."
  2991. return 1
  2992. fi
  2993. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2994. _debug "authzUri" "$authzUri"
  2995. if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
  2996. _err "new-authz error: $response"
  2997. return 1
  2998. fi
  2999. entry="$(printf "%s\n" "$response" | _egrep_o '{"type":"[^"]*","status":"valid","uri"[^}]*')"
  3000. _debug entry "$entry"
  3001. if [ -z "$entry" ]; then
  3002. _info "No more valid entry found."
  3003. break
  3004. fi
  3005. _vtype="$(printf "%s\n" "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  3006. _debug _vtype "$_vtype"
  3007. _info "Found $_vtype"
  3008. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
  3009. _debug uri "$uri"
  3010. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
  3011. _info "Skip $_vtype"
  3012. continue
  3013. fi
  3014. _info "Deactivate: $_vtype"
  3015. if ! _send_signed_request "$authzUri" "{\"resource\": \"authz\", \"status\":\"deactivated\"}"; then
  3016. _err "Can not deactivate $_vtype."
  3017. return 1
  3018. fi
  3019. _info "Deactivate: $_vtype success."
  3020. done
  3021. _debug "$_d_i"
  3022. if [ "$_d_i" -lt "$_d_max_retry" ]; then
  3023. _info "Deactivated success!"
  3024. else
  3025. _err "Deactivate failed."
  3026. fi
  3027. }
  3028. deactivate() {
  3029. _d_domain_list="$1"
  3030. _d_type="$2"
  3031. _initpath
  3032. _debug _d_domain_list "$_d_domain_list"
  3033. if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
  3034. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  3035. return 1
  3036. fi
  3037. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
  3038. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
  3039. continue
  3040. fi
  3041. if ! _deactivate "$_d_dm" "$_d_type"; then
  3042. return 1
  3043. fi
  3044. done
  3045. }
  3046. # Detect profile file if not specified as environment variable
  3047. _detect_profile() {
  3048. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  3049. echo "$PROFILE"
  3050. return
  3051. fi
  3052. DETECTED_PROFILE=''
  3053. SHELLTYPE="$(basename "/$SHELL")"
  3054. if [ "$SHELLTYPE" = "bash" ]; then
  3055. if [ -f "$HOME/.bashrc" ]; then
  3056. DETECTED_PROFILE="$HOME/.bashrc"
  3057. elif [ -f "$HOME/.bash_profile" ]; then
  3058. DETECTED_PROFILE="$HOME/.bash_profile"
  3059. fi
  3060. elif [ "$SHELLTYPE" = "zsh" ]; then
  3061. DETECTED_PROFILE="$HOME/.zshrc"
  3062. fi
  3063. if [ -z "$DETECTED_PROFILE" ]; then
  3064. if [ -f "$HOME/.profile" ]; then
  3065. DETECTED_PROFILE="$HOME/.profile"
  3066. elif [ -f "$HOME/.bashrc" ]; then
  3067. DETECTED_PROFILE="$HOME/.bashrc"
  3068. elif [ -f "$HOME/.bash_profile" ]; then
  3069. DETECTED_PROFILE="$HOME/.bash_profile"
  3070. elif [ -f "$HOME/.zshrc" ]; then
  3071. DETECTED_PROFILE="$HOME/.zshrc"
  3072. fi
  3073. fi
  3074. if [ ! -z "$DETECTED_PROFILE" ]; then
  3075. echo "$DETECTED_PROFILE"
  3076. fi
  3077. }
  3078. _initconf() {
  3079. _initpath
  3080. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  3081. echo "#ACCOUNT_CONF_PATH=xxxx
  3082. #ACCOUNT_EMAIL=aaa@example.com # the account email used to register account.
  3083. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  3084. #CERT_HOME=\"/path/to/cert/home\"
  3085. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  3086. #LOG_LEVEL=1
  3087. #AUTO_UPGRADE=\"1\"
  3088. #NO_TIMESTAMP=1
  3089. #OPENSSL_BIN=openssl
  3090. #USER_AGENT=\"$USER_AGENT\"
  3091. #USER_PATH=
  3092. " >"$ACCOUNT_CONF_PATH"
  3093. fi
  3094. }
  3095. # nocron
  3096. _precheck() {
  3097. _nocron="$1"
  3098. if ! _exists "curl" && ! _exists "wget"; then
  3099. _err "Please install curl or wget first, we need to access http resources."
  3100. return 1
  3101. fi
  3102. if [ -z "$_nocron" ]; then
  3103. if ! _exists "crontab"; then
  3104. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  3105. _err "We need to set cron job to renew the certs automatically."
  3106. _err "Otherwise, your certs will not be able to be renewed automatically."
  3107. if [ -z "$FORCE" ]; then
  3108. _err "Please add '--force' and try install again to go without crontab."
  3109. _err "./$PROJECT_ENTRY --install --force"
  3110. return 1
  3111. fi
  3112. fi
  3113. fi
  3114. if ! _exists "$OPENSSL_BIN"; then
  3115. _err "Please install openssl first."
  3116. _err "We need openssl to generate keys."
  3117. return 1
  3118. fi
  3119. if ! _exists "nc"; then
  3120. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  3121. _err "We use nc for standalone server if you use standalone mode."
  3122. _err "If you don't use standalone mode, just ignore this warning."
  3123. fi
  3124. return 0
  3125. }
  3126. _setShebang() {
  3127. _file="$1"
  3128. _shebang="$2"
  3129. if [ -z "$_shebang" ]; then
  3130. _usage "Usage: file shebang"
  3131. return 1
  3132. fi
  3133. cp "$_file" "$_file.tmp"
  3134. echo "$_shebang" >"$_file"
  3135. sed -n 2,99999p "$_file.tmp" >>"$_file"
  3136. rm -f "$_file.tmp"
  3137. }
  3138. #confighome
  3139. _installalias() {
  3140. _c_home="$1"
  3141. _initpath
  3142. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  3143. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
  3144. echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
  3145. echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
  3146. echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
  3147. fi
  3148. if [ "$_c_home" ]; then
  3149. _c_entry=" --config-home '$_c_home'"
  3150. fi
  3151. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  3152. if [ "$_c_home" ]; then
  3153. _setopt "$_envfile" "export LE_CONFIG_HOME" "=" "\"$LE_CONFIG_HOME\""
  3154. fi
  3155. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  3156. _profile="$(_detect_profile)"
  3157. if [ "$_profile" ]; then
  3158. _debug "Found profile: $_profile"
  3159. _info "Installing alias to '$_profile'"
  3160. _setopt "$_profile" ". \"$_envfile\""
  3161. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  3162. else
  3163. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  3164. fi
  3165. #for csh
  3166. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  3167. _csh_profile="$HOME/.cshrc"
  3168. if [ -f "$_csh_profile" ]; then
  3169. _info "Installing alias to '$_csh_profile'"
  3170. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  3171. if [ "$_c_home" ]; then
  3172. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  3173. fi
  3174. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  3175. _setopt "$_csh_profile" "source \"$_cshfile\""
  3176. fi
  3177. #for tcsh
  3178. _tcsh_profile="$HOME/.tcshrc"
  3179. if [ -f "$_tcsh_profile" ]; then
  3180. _info "Installing alias to '$_tcsh_profile'"
  3181. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  3182. if [ "$_c_home" ]; then
  3183. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  3184. fi
  3185. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  3186. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  3187. fi
  3188. }
  3189. # nocron confighome
  3190. install() {
  3191. if [ -z "$LE_WORKING_DIR" ]; then
  3192. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  3193. fi
  3194. _nocron="$1"
  3195. _c_home="$2"
  3196. if ! _initpath; then
  3197. _err "Install failed."
  3198. return 1
  3199. fi
  3200. if [ "$_nocron" ]; then
  3201. _debug "Skip install cron job"
  3202. fi
  3203. if ! _precheck "$_nocron"; then
  3204. _err "Pre-check failed, can not install."
  3205. return 1
  3206. fi
  3207. #convert from le
  3208. if [ -d "$HOME/.le" ]; then
  3209. for envfile in "le.env" "le.sh.env"; do
  3210. if [ -f "$HOME/.le/$envfile" ]; then
  3211. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
  3212. _upgrading="1"
  3213. _info "You are upgrading from le.sh"
  3214. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  3215. mv "$HOME/.le" "$LE_WORKING_DIR"
  3216. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  3217. break
  3218. fi
  3219. fi
  3220. done
  3221. fi
  3222. _info "Installing to $LE_WORKING_DIR"
  3223. if ! mkdir -p "$LE_WORKING_DIR"; then
  3224. _err "Can not create working dir: $LE_WORKING_DIR"
  3225. return 1
  3226. fi
  3227. chmod 700 "$LE_WORKING_DIR"
  3228. if ! mkdir -p "$LE_CONFIG_HOME"; then
  3229. _err "Can not create config dir: $LE_CONFIG_HOME"
  3230. return 1
  3231. fi
  3232. chmod 700 "$LE_CONFIG_HOME"
  3233. cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  3234. if [ "$?" != "0" ]; then
  3235. _err "Install failed, can not copy $PROJECT_ENTRY"
  3236. return 1
  3237. fi
  3238. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  3239. _installalias "$_c_home"
  3240. for subf in $_SUB_FOLDERS; do
  3241. if [ -d "$subf" ]; then
  3242. mkdir -p "$LE_WORKING_DIR/$subf"
  3243. cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
  3244. fi
  3245. done
  3246. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  3247. _initconf
  3248. fi
  3249. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
  3250. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  3251. fi
  3252. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
  3253. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  3254. fi
  3255. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
  3256. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  3257. fi
  3258. if [ -z "$_nocron" ]; then
  3259. installcronjob "$_c_home"
  3260. fi
  3261. if [ -z "$NO_DETECT_SH" ]; then
  3262. #Modify shebang
  3263. if _exists bash; then
  3264. _info "Good, bash is found, so change the shebang to use bash as preferred."
  3265. _shebang='#!/usr/bin/env bash'
  3266. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  3267. for subf in $_SUB_FOLDERS; do
  3268. if [ -d "$LE_WORKING_DIR/$subf" ]; then
  3269. for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
  3270. _setShebang "$_apifile" "$_shebang"
  3271. done
  3272. fi
  3273. done
  3274. fi
  3275. fi
  3276. _info OK
  3277. }
  3278. # nocron
  3279. uninstall() {
  3280. _nocron="$1"
  3281. if [ -z "$_nocron" ]; then
  3282. uninstallcronjob
  3283. fi
  3284. _initpath
  3285. _uninstallalias
  3286. rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
  3287. _info "The keys and certs are in \"$(__green "$LE_CONFIG_HOME")\", you can remove them by yourself."
  3288. }
  3289. _uninstallalias() {
  3290. _initpath
  3291. _profile="$(_detect_profile)"
  3292. if [ "$_profile" ]; then
  3293. _info "Uninstalling alias from: '$_profile'"
  3294. text="$(cat "$_profile")"
  3295. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
  3296. fi
  3297. _csh_profile="$HOME/.cshrc"
  3298. if [ -f "$_csh_profile" ]; then
  3299. _info "Uninstalling alias from: '$_csh_profile'"
  3300. text="$(cat "$_csh_profile")"
  3301. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
  3302. fi
  3303. _tcsh_profile="$HOME/.tcshrc"
  3304. if [ -f "$_tcsh_profile" ]; then
  3305. _info "Uninstalling alias from: '$_csh_profile'"
  3306. text="$(cat "$_tcsh_profile")"
  3307. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
  3308. fi
  3309. }
  3310. cron() {
  3311. IN_CRON=1
  3312. _initpath
  3313. if [ "$AUTO_UPGRADE" = "1" ]; then
  3314. export LE_WORKING_DIR
  3315. (
  3316. if ! upgrade; then
  3317. _err "Cron:Upgrade failed!"
  3318. return 1
  3319. fi
  3320. )
  3321. . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
  3322. if [ -t 1 ]; then
  3323. __INTERACTIVE="1"
  3324. fi
  3325. _info "Auto upgraded to: $VER"
  3326. fi
  3327. renewAll
  3328. _ret="$?"
  3329. IN_CRON=""
  3330. exit $_ret
  3331. }
  3332. version() {
  3333. echo "$PROJECT"
  3334. echo "v$VER"
  3335. }
  3336. showhelp() {
  3337. _initpath
  3338. version
  3339. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  3340. Commands:
  3341. --help, -h Show this help message.
  3342. --version, -v Show version info.
  3343. --install Install $PROJECT_NAME to your system.
  3344. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  3345. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT .
  3346. --issue Issue a cert.
  3347. --signcsr Issue a cert from an existing csr.
  3348. --deploy Deploy the cert to your server.
  3349. --install-cert Install the issued cert to apache/nginx or any other server.
  3350. --renew, -r Renew a cert.
  3351. --renew-all Renew all the certs.
  3352. --revoke Revoke a cert.
  3353. --remove Remove the cert from $PROJECT
  3354. --list List all the certs.
  3355. --showcsr Show the content of a csr.
  3356. --install-cronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  3357. --uninstall-cronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  3358. --cron Run cron job to renew all the certs.
  3359. --toPkcs Export the certificate and key to a pfx file.
  3360. --update-account Update account info.
  3361. --register-account Register account key.
  3362. --createAccountKey, -cak Create an account private key, professional use.
  3363. --createDomainKey, -cdk Create an domain private key, professional use.
  3364. --createCSR, -ccsr Create CSR , professional use.
  3365. --deactivate Deactivate the domain authz, professional use.
  3366. Parameters:
  3367. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  3368. --force, -f Used to force to install or force to renew a cert immediately.
  3369. --staging, --test Use staging server, just for test.
  3370. --debug Output debug info.
  3371. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  3372. --standalone Use standalone mode.
  3373. --tls Use standalone tls mode.
  3374. --apache Use apache mode.
  3375. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  3376. --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.
  3377. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  3378. --accountkeylength, -ak [2048] Specifies the account key length.
  3379. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  3380. --log-level 1|2 Specifies the log level, default is 1.
  3381. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  3382. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  3383. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  3384. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  3385. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  3386. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  3387. --accountconf Specifies a customized account config file.
  3388. --home Specifies the home dir for $PROJECT_NAME .
  3389. --cert-home Specifies the home dir to save all the certs, only valid for '--install' command.
  3390. --config-home Specifies the home dir to save all the configurations.
  3391. --useragent Specifies the user agent string. it will be saved for future use too.
  3392. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  3393. --accountkey Specifies the account key path, Only valid for the '--install' command.
  3394. --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
  3395. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3396. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3397. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  3398. --listraw Only used for '--list' command, list the certs in raw format.
  3399. --stopRenewOnError, -se Only valid for '--renew-all' command. Stop if one cert has error in renewal.
  3400. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  3401. --ca-bundle Specifices the path to the CA certificate bundle to verify api server's certificate.
  3402. --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.
  3403. --ecc Specifies to use the ECC cert. Valid for '--install-cert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  3404. --csr Specifies the input csr.
  3405. --pre-hook Command to be run before obtaining any certificates.
  3406. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obain/renew is success or failed.
  3407. --renew-hook Command to be run once for each successfully renewed certificate.
  3408. --deploy-hook The hook file to deploy cert
  3409. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  3410. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  3411. --listen-v4 Force standalone/tls server to listen at ipv4.
  3412. --listen-v6 Force standalone/tls server to listen at ipv6.
  3413. --openssl-bin Specifies a custom openssl bin location.
  3414. "
  3415. }
  3416. # nocron
  3417. _installOnline() {
  3418. _info "Installing from online archive."
  3419. _nocron="$1"
  3420. if [ ! "$BRANCH" ]; then
  3421. BRANCH="master"
  3422. fi
  3423. target="$PROJECT/archive/$BRANCH.tar.gz"
  3424. _info "Downloading $target"
  3425. localname="$BRANCH.tar.gz"
  3426. if ! _get "$target" >$localname; then
  3427. _err "Download error."
  3428. return 1
  3429. fi
  3430. (
  3431. _info "Extracting $localname"
  3432. if ! (tar xzf $localname || gtar xzf $localname); then
  3433. _err "Extraction error."
  3434. exit 1
  3435. fi
  3436. cd "$PROJECT_NAME-$BRANCH"
  3437. chmod +x $PROJECT_ENTRY
  3438. if ./$PROJECT_ENTRY install "$_nocron"; then
  3439. _info "Install success!"
  3440. fi
  3441. cd ..
  3442. rm -rf "$PROJECT_NAME-$BRANCH"
  3443. rm -f "$localname"
  3444. )
  3445. }
  3446. upgrade() {
  3447. if (
  3448. _initpath
  3449. export LE_WORKING_DIR
  3450. cd "$LE_WORKING_DIR"
  3451. _installOnline "nocron"
  3452. ); then
  3453. _info "Upgrade success!"
  3454. exit 0
  3455. else
  3456. _err "Upgrade failed!"
  3457. exit 1
  3458. fi
  3459. }
  3460. _processAccountConf() {
  3461. if [ "$_useragent" ]; then
  3462. _saveaccountconf "USER_AGENT" "$_useragent"
  3463. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
  3464. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  3465. fi
  3466. if [ "$_accountemail" ]; then
  3467. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  3468. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
  3469. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  3470. fi
  3471. if [ "$_openssl_bin" ]; then
  3472. _saveaccountconf "OPENSSL_BIN" "$_openssl_bin"
  3473. elif [ "$OPENSSL_BIN" ] && [ "$OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
  3474. _saveaccountconf "OPENSSL_BIN" "$OPENSSL_BIN"
  3475. fi
  3476. if [ "$_auto_upgrade" ]; then
  3477. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  3478. elif [ "$AUTO_UPGRADE" ]; then
  3479. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  3480. fi
  3481. }
  3482. _process() {
  3483. _CMD=""
  3484. _domain=""
  3485. _altdomains="$NO_VALUE"
  3486. _webroot=""
  3487. _keylength=""
  3488. _accountkeylength=""
  3489. _certpath=""
  3490. _keypath=""
  3491. _capath=""
  3492. _fullchainpath=""
  3493. _reloadcmd=""
  3494. _password=""
  3495. _accountconf=""
  3496. _useragent=""
  3497. _accountemail=""
  3498. _accountkey=""
  3499. _certhome=""
  3500. _confighome=""
  3501. _httpport=""
  3502. _tlsport=""
  3503. _dnssleep=""
  3504. _listraw=""
  3505. _stopRenewOnError=""
  3506. #_insecure=""
  3507. _ca_bundle=""
  3508. _nocron=""
  3509. _ecc=""
  3510. _csr=""
  3511. _pre_hook=""
  3512. _post_hook=""
  3513. _renew_hook=""
  3514. _deploy_hook=""
  3515. _logfile=""
  3516. _log=""
  3517. _local_address=""
  3518. _log_level=""
  3519. _auto_upgrade=""
  3520. _listen_v4=""
  3521. _listen_v6=""
  3522. _openssl_bin=""
  3523. while [ ${#} -gt 0 ]; do
  3524. case "${1}" in
  3525. --help | -h)
  3526. showhelp
  3527. return
  3528. ;;
  3529. --version | -v)
  3530. version
  3531. return
  3532. ;;
  3533. --install)
  3534. _CMD="install"
  3535. ;;
  3536. --uninstall)
  3537. _CMD="uninstall"
  3538. ;;
  3539. --upgrade)
  3540. _CMD="upgrade"
  3541. ;;
  3542. --issue)
  3543. _CMD="issue"
  3544. ;;
  3545. --deploy)
  3546. _CMD="deploy"
  3547. ;;
  3548. --signcsr)
  3549. _CMD="signcsr"
  3550. ;;
  3551. --showcsr)
  3552. _CMD="showcsr"
  3553. ;;
  3554. --installcert | -i | --install-cert)
  3555. _CMD="installcert"
  3556. ;;
  3557. --renew | -r)
  3558. _CMD="renew"
  3559. ;;
  3560. --renewAll | --renewall | --renew-all)
  3561. _CMD="renewAll"
  3562. ;;
  3563. --revoke)
  3564. _CMD="revoke"
  3565. ;;
  3566. --remove)
  3567. _CMD="remove"
  3568. ;;
  3569. --list)
  3570. _CMD="list"
  3571. ;;
  3572. --installcronjob | --install-cronjob)
  3573. _CMD="installcronjob"
  3574. ;;
  3575. --uninstallcronjob | --uninstall-cronjob)
  3576. _CMD="uninstallcronjob"
  3577. ;;
  3578. --cron)
  3579. _CMD="cron"
  3580. ;;
  3581. --toPkcs)
  3582. _CMD="toPkcs"
  3583. ;;
  3584. --createAccountKey | --createaccountkey | -cak)
  3585. _CMD="createAccountKey"
  3586. ;;
  3587. --createDomainKey | --createdomainkey | -cdk)
  3588. _CMD="createDomainKey"
  3589. ;;
  3590. --createCSR | --createcsr | -ccr)
  3591. _CMD="createCSR"
  3592. ;;
  3593. --deactivate)
  3594. _CMD="deactivate"
  3595. ;;
  3596. --updateaccount | --update-account)
  3597. _CMD="updateaccount"
  3598. ;;
  3599. --registeraccount | --register-account)
  3600. _CMD="registeraccount"
  3601. ;;
  3602. --domain | -d)
  3603. _dvalue="$2"
  3604. if [ "$_dvalue" ]; then
  3605. if _startswith "$_dvalue" "-"; then
  3606. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  3607. return 1
  3608. fi
  3609. if _is_idn "$_dvalue" && ! _exists idn; then
  3610. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  3611. return 1
  3612. fi
  3613. if [ -z "$_domain" ]; then
  3614. _domain="$_dvalue"
  3615. else
  3616. if [ "$_altdomains" = "$NO_VALUE" ]; then
  3617. _altdomains="$_dvalue"
  3618. else
  3619. _altdomains="$_altdomains,$_dvalue"
  3620. fi
  3621. fi
  3622. fi
  3623. shift
  3624. ;;
  3625. --force | -f)
  3626. FORCE="1"
  3627. ;;
  3628. --staging | --test)
  3629. STAGE="1"
  3630. ;;
  3631. --debug)
  3632. if [ -z "$2" ] || _startswith "$2" "-"; then
  3633. DEBUG="1"
  3634. else
  3635. DEBUG="$2"
  3636. shift
  3637. fi
  3638. ;;
  3639. --webroot | -w)
  3640. wvalue="$2"
  3641. if [ -z "$_webroot" ]; then
  3642. _webroot="$wvalue"
  3643. else
  3644. _webroot="$_webroot,$wvalue"
  3645. fi
  3646. shift
  3647. ;;
  3648. --standalone)
  3649. wvalue="$NO_VALUE"
  3650. if [ -z "$_webroot" ]; then
  3651. _webroot="$wvalue"
  3652. else
  3653. _webroot="$_webroot,$wvalue"
  3654. fi
  3655. ;;
  3656. --local-address)
  3657. lvalue="$2"
  3658. _local_address="$_local_address$lvalue,"
  3659. shift
  3660. ;;
  3661. --apache)
  3662. wvalue="apache"
  3663. if [ -z "$_webroot" ]; then
  3664. _webroot="$wvalue"
  3665. else
  3666. _webroot="$_webroot,$wvalue"
  3667. fi
  3668. ;;
  3669. --tls)
  3670. wvalue="$W_TLS"
  3671. if [ -z "$_webroot" ]; then
  3672. _webroot="$wvalue"
  3673. else
  3674. _webroot="$_webroot,$wvalue"
  3675. fi
  3676. ;;
  3677. --dns)
  3678. wvalue="dns"
  3679. if ! _startswith "$2" "-"; then
  3680. wvalue="$2"
  3681. shift
  3682. fi
  3683. if [ -z "$_webroot" ]; then
  3684. _webroot="$wvalue"
  3685. else
  3686. _webroot="$_webroot,$wvalue"
  3687. fi
  3688. ;;
  3689. --dnssleep)
  3690. _dnssleep="$2"
  3691. Le_DNSSleep="$_dnssleep"
  3692. shift
  3693. ;;
  3694. --keylength | -k)
  3695. _keylength="$2"
  3696. shift
  3697. ;;
  3698. --accountkeylength | -ak)
  3699. _accountkeylength="$2"
  3700. shift
  3701. ;;
  3702. --certpath)
  3703. _certpath="$2"
  3704. shift
  3705. ;;
  3706. --keypath)
  3707. _keypath="$2"
  3708. shift
  3709. ;;
  3710. --capath)
  3711. _capath="$2"
  3712. shift
  3713. ;;
  3714. --fullchainpath)
  3715. _fullchainpath="$2"
  3716. shift
  3717. ;;
  3718. --reloadcmd | --reloadCmd)
  3719. _reloadcmd="$2"
  3720. shift
  3721. ;;
  3722. --password)
  3723. _password="$2"
  3724. shift
  3725. ;;
  3726. --accountconf)
  3727. _accountconf="$2"
  3728. ACCOUNT_CONF_PATH="$_accountconf"
  3729. shift
  3730. ;;
  3731. --home)
  3732. LE_WORKING_DIR="$2"
  3733. shift
  3734. ;;
  3735. --certhome | --cert-home)
  3736. _certhome="$2"
  3737. CERT_HOME="$_certhome"
  3738. shift
  3739. ;;
  3740. --config-home)
  3741. _confighome="$2"
  3742. LE_CONFIG_HOME="$_confighome"
  3743. shift
  3744. ;;
  3745. --useragent)
  3746. _useragent="$2"
  3747. USER_AGENT="$_useragent"
  3748. shift
  3749. ;;
  3750. --accountemail)
  3751. _accountemail="$2"
  3752. ACCOUNT_EMAIL="$_accountemail"
  3753. shift
  3754. ;;
  3755. --accountkey)
  3756. _accountkey="$2"
  3757. ACCOUNT_KEY_PATH="$_accountkey"
  3758. shift
  3759. ;;
  3760. --days)
  3761. _days="$2"
  3762. Le_RenewalDays="$_days"
  3763. shift
  3764. ;;
  3765. --httpport)
  3766. _httpport="$2"
  3767. Le_HTTPPort="$_httpport"
  3768. shift
  3769. ;;
  3770. --tlsport)
  3771. _tlsport="$2"
  3772. Le_TLSPort="$_tlsport"
  3773. shift
  3774. ;;
  3775. --listraw)
  3776. _listraw="raw"
  3777. ;;
  3778. --stopRenewOnError | --stoprenewonerror | -se)
  3779. _stopRenewOnError="1"
  3780. ;;
  3781. --insecure)
  3782. #_insecure="1"
  3783. HTTPS_INSECURE="1"
  3784. ;;
  3785. --ca-bundle)
  3786. _ca_bundle="$(readlink -f "$2")"
  3787. CA_BUNDLE="$_ca_bundle"
  3788. shift
  3789. ;;
  3790. --nocron)
  3791. _nocron="1"
  3792. ;;
  3793. --ecc)
  3794. _ecc="isEcc"
  3795. ;;
  3796. --csr)
  3797. _csr="$2"
  3798. shift
  3799. ;;
  3800. --pre-hook)
  3801. _pre_hook="$2"
  3802. shift
  3803. ;;
  3804. --post-hook)
  3805. _post_hook="$2"
  3806. shift
  3807. ;;
  3808. --renew-hook)
  3809. _renew_hook="$2"
  3810. shift
  3811. ;;
  3812. --deploy-hook)
  3813. _deploy_hook="$2"
  3814. shift
  3815. ;;
  3816. --ocsp-must-staple | --ocsp)
  3817. Le_OCSP_Staple="1"
  3818. ;;
  3819. --log | --logfile)
  3820. _log="1"
  3821. _logfile="$2"
  3822. if _startswith "$_logfile" '-'; then
  3823. _logfile=""
  3824. else
  3825. shift
  3826. fi
  3827. LOG_FILE="$_logfile"
  3828. if [ -z "$LOG_LEVEL" ]; then
  3829. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  3830. fi
  3831. ;;
  3832. --log-level)
  3833. _log_level="$2"
  3834. LOG_LEVEL="$_log_level"
  3835. shift
  3836. ;;
  3837. --auto-upgrade)
  3838. _auto_upgrade="$2"
  3839. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
  3840. _auto_upgrade="1"
  3841. else
  3842. shift
  3843. fi
  3844. AUTO_UPGRADE="$_auto_upgrade"
  3845. ;;
  3846. --listen-v4)
  3847. _listen_v4="1"
  3848. Le_Listen_V4="$_listen_v4"
  3849. ;;
  3850. --listen-v6)
  3851. _listen_v6="1"
  3852. Le_Listen_V6="$_listen_v6"
  3853. ;;
  3854. --openssl-bin)
  3855. _openssl_bin="$2"
  3856. OPENSSL_BIN="$_openssl_bin"
  3857. ;;
  3858. *)
  3859. _err "Unknown parameter : $1"
  3860. return 1
  3861. ;;
  3862. esac
  3863. shift 1
  3864. done
  3865. if [ "${_CMD}" != "install" ]; then
  3866. __initHome
  3867. if [ "$_log" ]; then
  3868. if [ -z "$_logfile" ]; then
  3869. _logfile="$DEFAULT_LOG_FILE"
  3870. fi
  3871. fi
  3872. if [ "$_logfile" ]; then
  3873. _saveaccountconf "LOG_FILE" "$_logfile"
  3874. LOG_FILE="$_logfile"
  3875. fi
  3876. if [ "$_log_level" ]; then
  3877. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3878. LOG_LEVEL="$_log_level"
  3879. fi
  3880. _processAccountConf
  3881. fi
  3882. _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
  3883. if [ "$DEBUG" ]; then
  3884. version
  3885. fi
  3886. case "${_CMD}" in
  3887. install) install "$_nocron" "$_confighome" ;;
  3888. uninstall) uninstall "$_nocron" ;;
  3889. upgrade) upgrade ;;
  3890. issue)
  3891. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address"
  3892. ;;
  3893. deploy)
  3894. deploy "$_domain" "$_deploy_hook" "$_ecc"
  3895. ;;
  3896. signcsr)
  3897. signcsr "$_csr" "$_webroot"
  3898. ;;
  3899. showcsr)
  3900. showcsr "$_csr" "$_domain"
  3901. ;;
  3902. installcert)
  3903. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_ecc"
  3904. ;;
  3905. renew)
  3906. renew "$_domain" "$_ecc"
  3907. ;;
  3908. renewAll)
  3909. renewAll "$_stopRenewOnError"
  3910. ;;
  3911. revoke)
  3912. revoke "$_domain" "$_ecc"
  3913. ;;
  3914. remove)
  3915. remove "$_domain" "$_ecc"
  3916. ;;
  3917. deactivate)
  3918. deactivate "$_domain,$_altdomains"
  3919. ;;
  3920. registeraccount)
  3921. registeraccount "$_accountkeylength"
  3922. ;;
  3923. updateaccount)
  3924. updateaccount
  3925. ;;
  3926. list)
  3927. list "$_listraw"
  3928. ;;
  3929. installcronjob) installcronjob "$_confighome" ;;
  3930. uninstallcronjob) uninstallcronjob ;;
  3931. cron) cron ;;
  3932. toPkcs)
  3933. toPkcs "$_domain" "$_password" "$_ecc"
  3934. ;;
  3935. createAccountKey)
  3936. createAccountKey "$_accountkeylength"
  3937. ;;
  3938. createDomainKey)
  3939. createDomainKey "$_domain" "$_keylength"
  3940. ;;
  3941. createCSR)
  3942. createCSR "$_domain" "$_altdomains" "$_ecc"
  3943. ;;
  3944. *)
  3945. if [ "$_CMD" ]; then
  3946. _err "Invalid command: $_CMD"
  3947. fi
  3948. showhelp
  3949. return 1
  3950. ;;
  3951. esac
  3952. _ret="$?"
  3953. if [ "$_ret" != "0" ]; then
  3954. return $_ret
  3955. fi
  3956. if [ "${_CMD}" = "install" ]; then
  3957. if [ "$_log" ]; then
  3958. if [ -z "$LOG_FILE" ]; then
  3959. LOG_FILE="$DEFAULT_LOG_FILE"
  3960. fi
  3961. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  3962. fi
  3963. if [ "$_log_level" ]; then
  3964. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3965. fi
  3966. _processAccountConf
  3967. fi
  3968. }
  3969. if [ "$INSTALLONLINE" ]; then
  3970. INSTALLONLINE=""
  3971. _installOnline
  3972. exit
  3973. fi
  3974. main() {
  3975. [ -z "$1" ] && showhelp && return
  3976. if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
  3977. }
  3978. main "$@"